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  * Copyright 2017 Dmitry Timoshkov
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23 
24 #ifdef __REACTOS__
25 #undef _WIN32_WINNT
26 #define _WIN32_WINNT 0x0600
27 #endif
28 
29 #include <ntstatus.h>
30 #define WIN32_NO_STATUS
31 #include <winsock2.h>
32 #include <windows.h>
33 #include <winternl.h>
34 #include <ws2tcpip.h>
35 #include <wsipx.h>
36 #include <wsnwlink.h>
37 #include <mswsock.h>
38 #include <mstcpip.h>
39 #include <iphlpapi.h>
40 #include <stdio.h>
41 #include "wine/test.h"
42 
43 // ReactOS: Wine has this in mstcpip.h, but it doesn't belong there
44 #define WSA_CMSG_ALIGN(len)     (((len) + sizeof(SIZE_T) - 1) & ~(sizeof(SIZE_T) - 1))
45 
46 #define MAX_CLIENTS 4      /* Max number of clients */
47 #define FIRST_CHAR 'A'     /* First character in transferred pattern */
48 #define BIND_SLEEP 10      /* seconds to wait between attempts to bind() */
49 #define BIND_TRIES 6       /* Number of bind() attempts */
50 #define TEST_TIMEOUT 30    /* seconds to wait before killing child threads
51                               after server initialization, if something hangs */
52 
53 #define NUM_UDP_PEERS 3    /* Number of UDP sockets to create and test > 1 */
54 
55 #define NUM_THREADS 3      /* Number of threads to run getservbyname */
56 #define NUM_QUERIES 250    /* Number of getservbyname queries per thread */
57 
58 #define SERVERIP "127.0.0.1"   /* IP to bind to */
59 #define SERVERPORT 9374        /* Port number to bind to */
60 
61 #define wsa_ok(op, cond, msg) \
62    do { \
63         int tmp, err = 0; \
64         tmp = op; \
65         if ( !(cond tmp) ) err = WSAGetLastError(); \
66         ok ( cond tmp, msg, GetCurrentThreadId(), err); \
67    } while (0);
68 
69 #define make_keepalive(k, enable, time, interval) \
70    k.onoff = enable; \
71    k.keepalivetime = time; \
72    k.keepaliveinterval = interval;
73 
74 /* Function pointers */
75 static void  (WINAPI *pfreeaddrinfo)(struct addrinfo *);
76 static int   (WINAPI *pgetaddrinfo)(LPCSTR,LPCSTR,const struct addrinfo *,struct addrinfo **);
77 static void  (WINAPI *pFreeAddrInfoW)(PADDRINFOW);
78 static void  (WINAPI *pFreeAddrInfoExW)(ADDRINFOEXW *ai);
79 static int   (WINAPI *pGetAddrInfoW)(LPCWSTR,LPCWSTR,const ADDRINFOW *,PADDRINFOW *);
80 static int   (WINAPI *pGetAddrInfoExW)(const WCHAR *name, const WCHAR *servname, DWORD namespace,
81         GUID *namespace_id, const ADDRINFOEXW *hints, ADDRINFOEXW **result,
82         struct timeval *timeout, OVERLAPPED *overlapped,
83         LPLOOKUPSERVICE_COMPLETION_ROUTINE completion_routine, HANDLE *handle);
84 static int   (WINAPI *pGetAddrInfoExOverlappedResult)(OVERLAPPED *overlapped);
85 static PCSTR (WINAPI *pInetNtop)(INT,LPVOID,LPSTR,ULONG);
86 static PCWSTR(WINAPI *pInetNtopW)(INT,LPVOID,LPWSTR,ULONG);
87 static int   (WINAPI *pInetPtonA)(INT,LPCSTR,LPVOID);
88 static int   (WINAPI *pInetPtonW)(INT,LPWSTR,LPVOID);
89 static int   (WINAPI *pWSALookupServiceBeginW)(LPWSAQUERYSETW,DWORD,LPHANDLE);
90 static int   (WINAPI *pWSALookupServiceEnd)(HANDLE);
91 static int   (WINAPI *pWSALookupServiceNextW)(HANDLE,DWORD,LPDWORD,LPWSAQUERYSETW);
92 static int   (WINAPI *pWSAEnumNameSpaceProvidersA)(LPDWORD,LPWSANAMESPACE_INFOA);
93 static int   (WINAPI *pWSAEnumNameSpaceProvidersW)(LPDWORD,LPWSANAMESPACE_INFOW);
94 static int   (WINAPI *pWSAPoll)(WSAPOLLFD *,ULONG,INT);
95 
96 /* Function pointers from ntdll */
97 static NTSTATUS (WINAPI *pNtSetInformationFile)(HANDLE, PIO_STATUS_BLOCK, PVOID, ULONG, FILE_INFORMATION_CLASS);
98 static NTSTATUS (WINAPI *pNtQueryInformationFile)(HANDLE, PIO_STATUS_BLOCK, PVOID, ULONG, FILE_INFORMATION_CLASS);
99 
100 /* Function pointers from iphlpapi */
101 static DWORD (WINAPI *pGetAdaptersInfo)(PIP_ADAPTER_INFO,PULONG);
102 static DWORD (WINAPI *pGetIpForwardTable)(PMIB_IPFORWARDTABLE,PULONG,BOOL);
103 
104 /* Function pointers from ntdll */
105 static DWORD (WINAPI *pNtClose)(HANDLE);
106 
107 /**************** Structs and typedefs ***************/
108 
109 typedef struct thread_info
110 {
111     HANDLE thread;
112     DWORD id;
113 } thread_info;
114 
115 /* Information in the server about open client connections */
116 typedef struct sock_info
117 {
118     SOCKET                 s;
119     struct sockaddr_in     addr;
120     struct sockaddr_in     peer;
121     char                  *buf;
122     int                    n_recvd;
123     int                    n_sent;
124 } sock_info;
125 
126 /* Test parameters for both server & client */
127 typedef struct test_params
128 {
129     int          sock_type;
130     int          sock_prot;
131     const char  *inet_addr;
132     short        inet_port;
133     int          chunk_size;
134     int          n_chunks;
135     int          n_clients;
136 } test_params;
137 
138 /* server-specific test parameters */
139 typedef struct server_params
140 {
141     test_params   *general;
142     DWORD          sock_flags;
143     int            buflen;
144 } server_params;
145 
146 /* client-specific test parameters */
147 typedef struct client_params
148 {
149     test_params   *general;
150     DWORD          sock_flags;
151     int            buflen;
152 } client_params;
153 
154 /* This type combines all information for setting up a test scenario */
155 typedef struct test_setup
156 {
157     test_params              general;
158     LPVOID                   srv;
159     server_params            srv_params;
160     LPVOID                   clt;
161     client_params            clt_params;
162 } test_setup;
163 
164 /* Thread local storage for server */
165 typedef struct server_memory
166 {
167     SOCKET                  s;
168     struct sockaddr_in      addr;
169     sock_info               sock[MAX_CLIENTS];
170 } server_memory;
171 
172 /* Thread local storage for client */
173 typedef struct client_memory
174 {
175     SOCKET s;
176     struct sockaddr_in      addr;
177     char                   *send_buf;
178     char                   *recv_buf;
179 } client_memory;
180 
181 /* SelectReadThread thread parameters */
182 typedef struct select_thread_params
183 {
184     SOCKET s;
185     BOOL ReadKilled;
186 } select_thread_params;
187 
188 /* Tests used in both getaddrinfo and GetAddrInfoW */
189 static const struct addr_hint_tests
190 {
191     int family, socktype, protocol;
192     DWORD error;
193 } hinttests[] = {
194     {AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, 0 },
195     {AF_UNSPEC, SOCK_STREAM, IPPROTO_UDP, 0 },
196     {AF_UNSPEC, SOCK_STREAM, IPPROTO_IPV6,0 },
197     {AF_UNSPEC, SOCK_DGRAM,  IPPROTO_TCP, 0 },
198     {AF_UNSPEC, SOCK_DGRAM,  IPPROTO_UDP, 0 },
199     {AF_UNSPEC, SOCK_DGRAM,  IPPROTO_IPV6,0 },
200     {AF_INET,   SOCK_STREAM, IPPROTO_TCP, 0 },
201     {AF_INET,   SOCK_STREAM, IPPROTO_UDP, 0 },
202     {AF_INET,   SOCK_STREAM, IPPROTO_IPV6,0 },
203     {AF_INET,   SOCK_DGRAM,  IPPROTO_TCP, 0 },
204     {AF_INET,   SOCK_DGRAM,  IPPROTO_UDP, 0 },
205     {AF_INET,   SOCK_DGRAM,  IPPROTO_IPV6,0 },
206     {AF_UNSPEC, 0,           IPPROTO_TCP, 0 },
207     {AF_UNSPEC, 0,           IPPROTO_UDP, 0 },
208     {AF_UNSPEC, 0,           IPPROTO_IPV6,0 },
209     {AF_UNSPEC, SOCK_STREAM, 0,           0 },
210     {AF_UNSPEC, SOCK_DGRAM,  0,           0 },
211     {AF_INET,   0,           IPPROTO_TCP, 0 },
212     {AF_INET,   0,           IPPROTO_UDP, 0 },
213     {AF_INET,   0,           IPPROTO_IPV6,0 },
214     {AF_INET,   SOCK_STREAM, 0,           0 },
215     {AF_INET,   SOCK_DGRAM,  0,           0 },
216     {AF_UNSPEC, 999,         IPPROTO_TCP, WSAESOCKTNOSUPPORT },
217     {AF_UNSPEC, 999,         IPPROTO_UDP, WSAESOCKTNOSUPPORT },
218     {AF_UNSPEC, 999,         IPPROTO_IPV6,WSAESOCKTNOSUPPORT },
219     {AF_INET,   999,         IPPROTO_TCP, WSAESOCKTNOSUPPORT },
220     {AF_INET,   999,         IPPROTO_UDP, WSAESOCKTNOSUPPORT },
221     {AF_INET,   999,         IPPROTO_IPV6,WSAESOCKTNOSUPPORT },
222     {AF_UNSPEC, SOCK_STREAM, 999,         0 },
223     {AF_UNSPEC, SOCK_STREAM, 999,         0 },
224     {AF_INET,   SOCK_DGRAM,  999,         0 },
225     {AF_INET,   SOCK_DGRAM,  999,         0 },
226 };
227 
228 /**************** Static variables ***************/
229 
230 static DWORD      tls;              /* Thread local storage index */
231 static HANDLE     thread[1+MAX_CLIENTS];
232 static DWORD      thread_id[1+MAX_CLIENTS];
233 static HANDLE     server_ready;
234 static HANDLE     client_ready[MAX_CLIENTS];
235 static int        client_id;
236 
237 /**************** General utility functions ***************/
238 
239 static SOCKET setup_server_socket(struct sockaddr_in *addr, int *len);
240 static SOCKET setup_connector_socket(struct sockaddr_in *addr, int len, BOOL nonblock);
241 
242 static int tcp_socketpair(SOCKET *src, SOCKET *dst)
243 {
244     SOCKET server = INVALID_SOCKET;
245     struct sockaddr_in addr;
246     int len;
247     int ret;
248 
249     *src = INVALID_SOCKET;
250     *dst = INVALID_SOCKET;
251 
252     *src = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
253     if (*src == INVALID_SOCKET)
254         goto end;
255 
256     server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
257     if (server == INVALID_SOCKET)
258         goto end;
259 
260     memset(&addr, 0, sizeof(addr));
261     addr.sin_family = AF_INET;
262     addr.sin_addr.s_addr = inet_addr("127.0.0.1");
263     ret = bind(server, (struct sockaddr*)&addr, sizeof(addr));
264     if (ret != 0)
265         goto end;
266 
267     len = sizeof(addr);
268     ret = getsockname(server, (struct sockaddr*)&addr, &len);
269     if (ret != 0)
270         goto end;
271 
272     ret = listen(server, 1);
273     if (ret != 0)
274         goto end;
275 
276     ret = connect(*src, (struct sockaddr*)&addr, sizeof(addr));
277     if (ret != 0)
278         goto end;
279 
280     len = sizeof(addr);
281     *dst = accept(server, (struct sockaddr*)&addr, &len);
282 
283 end:
284     if (server != INVALID_SOCKET)
285         closesocket(server);
286     if (*src != INVALID_SOCKET && *dst != INVALID_SOCKET)
287         return 0;
288     closesocket(*src);
289     closesocket(*dst);
290     return -1;
291 }
292 
293 static int tcp_socketpair_ovl(SOCKET *src, SOCKET *dst)
294 {
295     SOCKET server = INVALID_SOCKET;
296     struct sockaddr_in addr;
297     int len, ret;
298 
299     *src = INVALID_SOCKET;
300     *dst = INVALID_SOCKET;
301 
302     *src = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
303     if (*src == INVALID_SOCKET)
304         goto end;
305 
306     server = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
307     if (server == INVALID_SOCKET)
308         goto end;
309 
310     memset(&addr, 0, sizeof(addr));
311     addr.sin_family = AF_INET;
312     addr.sin_addr.s_addr = inet_addr("127.0.0.1");
313     ret = bind(server, (struct sockaddr *)&addr, sizeof(addr));
314     if (ret != 0)
315         goto end;
316 
317     len = sizeof(addr);
318     ret = getsockname(server, (struct sockaddr *)&addr, &len);
319     if (ret != 0)
320         goto end;
321 
322     ret = listen(server, 1);
323     if (ret != 0)
324         goto end;
325 
326     ret = connect(*src, (struct sockaddr *)&addr, sizeof(addr));
327     if (ret != 0)
328         goto end;
329 
330     len = sizeof(addr);
331     *dst = accept(server, (struct sockaddr *)&addr, &len);
332 
333 end:
334     if (server != INVALID_SOCKET)
335         closesocket(server);
336     if (*src != INVALID_SOCKET && *dst != INVALID_SOCKET)
337         return 0;
338     closesocket(*src);
339     closesocket(*dst);
340     return -1;
341 }
342 
343 static void set_so_opentype ( BOOL overlapped )
344 {
345     int optval = !overlapped, newval, len = sizeof (int);
346 
347     ok ( setsockopt ( INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
348                       (LPVOID) &optval, sizeof (optval) ) == 0,
349          "setting SO_OPENTYPE failed\n" );
350     ok ( getsockopt ( INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
351                       (LPVOID) &newval, &len ) == 0,
352          "getting SO_OPENTYPE failed\n" );
353     ok ( optval == newval, "failed to set SO_OPENTYPE\n" );
354 }
355 
356 static int set_blocking ( SOCKET s, BOOL blocking )
357 {
358     u_long val = !blocking;
359     return ioctlsocket ( s, FIONBIO, &val );
360 }
361 
362 static void fill_buffer ( char *buf, int chunk_size, int n_chunks )
363 {
364     char c, *p;
365     for ( c = FIRST_CHAR, p = buf; c < FIRST_CHAR + n_chunks; c++, p += chunk_size )
366         memset ( p, c, chunk_size );
367 }
368 
369 static int test_buffer ( char *buf, int chunk_size, int n_chunks )
370 {
371     char c, *p;
372     int i;
373     for ( c = FIRST_CHAR, p = buf; c < FIRST_CHAR + n_chunks; c++, p += chunk_size )
374     {
375         for ( i = 0; i < chunk_size; i++ )
376             if ( p[i] != c ) return i;
377     }
378     return -1;
379 }
380 
381 /*
382  * This routine is called when a client / server does not expect any more data,
383  * but needs to acknowledge the closing of the connection (by reading 0 bytes).
384  */
385 static void read_zero_bytes ( SOCKET s )
386 {
387     char buf[256];
388     int tmp, n = 0;
389     while ( ( tmp = recv ( s, buf, 256, 0 ) ) > 0 )
390         n += tmp;
391     ok ( n <= 0, "garbage data received: %d bytes\n", n );
392 }
393 
394 static int do_synchronous_send ( SOCKET s, char *buf, int buflen, int flags, int sendlen )
395 {
396     char* last = buf + buflen, *p;
397     int n = 1;
398     for ( p = buf; n > 0 && p < last; )
399     {
400         n = send ( s, p, min ( sendlen, last - p ), flags );
401         if (n > 0) p += n;
402     }
403     wsa_ok ( n, 0 <=, "do_synchronous_send (%x): error %d\n" );
404     return p - buf;
405 }
406 
407 static int do_synchronous_recv ( SOCKET s, char *buf, int buflen, int flags, int recvlen )
408 {
409     char* last = buf + buflen, *p;
410     int n = 1;
411     for ( p = buf; n > 0 && p < last; )
412     {
413         n = recv ( s, p, min ( recvlen, last - p ), flags );
414         if (n > 0) p += n;
415     }
416     wsa_ok ( n, 0 <=, "do_synchronous_recv (%x): error %d:\n" );
417     return p - buf;
418 }
419 
420 static int do_synchronous_recvfrom ( SOCKET s, char *buf, int buflen, int flags, struct sockaddr *from, int *fromlen, int recvlen )
421 {
422     char* last = buf + buflen, *p;
423     int n = 1;
424     for ( p = buf; n > 0 && p < last; )
425     {
426         n = recvfrom ( s, p, min ( recvlen, last - p ), flags, from, fromlen );
427         if (n > 0) p += n;
428     }
429     wsa_ok ( n, 0 <=, "do_synchronous_recv (%x): error %d:\n" );
430     return p - buf;
431 }
432 
433 /*
434  *  Call this routine right after thread startup.
435  *  SO_OPENTYPE must by 0, regardless what the server did.
436  */
437 static void check_so_opentype (void)
438 {
439     int tmp = 1, len;
440     len = sizeof (tmp);
441     getsockopt ( INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (LPVOID) &tmp, &len );
442     ok ( tmp == 0, "check_so_opentype: wrong startup value of SO_OPENTYPE: %d\n", tmp );
443 }
444 
445 static void compare_addrinfo (ADDRINFO *a, ADDRINFO *b)
446 {
447     for (; a && b ; a = a->ai_next, b = b->ai_next)
448     {
449         ok(a->ai_flags == b->ai_flags,
450            "Wrong flags %d != %d\n", a->ai_flags, b->ai_flags);
451         ok(a->ai_family == b->ai_family,
452            "Wrong family %d != %d\n", a->ai_family, b->ai_family);
453         ok(a->ai_socktype == b->ai_socktype,
454            "Wrong socktype %d != %d\n", a->ai_socktype, b->ai_socktype);
455         ok(a->ai_protocol == b->ai_protocol,
456            "Wrong protocol %d != %d\n", a->ai_protocol, b->ai_protocol);
457         ok(a->ai_addrlen == b->ai_addrlen,
458            "Wrong addrlen %lu != %lu\n", a->ai_addrlen, b->ai_addrlen);
459         ok(!memcmp(a->ai_addr, b->ai_addr, min(a->ai_addrlen, b->ai_addrlen)),
460            "Wrong address data\n");
461         if (a->ai_canonname && b->ai_canonname)
462         {
463             ok(!strcmp(a->ai_canonname, b->ai_canonname), "Wrong canonical name '%s' != '%s'\n",
464                a->ai_canonname, b->ai_canonname);
465         }
466         else
467             ok(!a->ai_canonname && !b->ai_canonname, "Expected both names absent (%p != %p)\n",
468                a->ai_canonname, b->ai_canonname);
469     }
470     ok(!a && !b, "Expected both addresses null (%p != %p)\n", a, b);
471 }
472 
473 static void compare_addrinfow (ADDRINFOW *a, ADDRINFOW *b)
474 {
475     for (; a && b ; a = a->ai_next, b = b->ai_next)
476     {
477         ok(a->ai_flags == b->ai_flags,
478            "Wrong flags %d != %d\n", a->ai_flags, b->ai_flags);
479         ok(a->ai_family == b->ai_family,
480            "Wrong family %d != %d\n", a->ai_family, b->ai_family);
481         ok(a->ai_socktype == b->ai_socktype,
482            "Wrong socktype %d != %d\n", a->ai_socktype, b->ai_socktype);
483         ok(a->ai_protocol == b->ai_protocol,
484            "Wrong protocol %d != %d\n", a->ai_protocol, b->ai_protocol);
485         ok(a->ai_addrlen == b->ai_addrlen,
486            "Wrong addrlen %lu != %lu\n", a->ai_addrlen, b->ai_addrlen);
487         ok(!memcmp(a->ai_addr, b->ai_addr, min(a->ai_addrlen, b->ai_addrlen)),
488            "Wrong address data\n");
489         if (a->ai_canonname && b->ai_canonname)
490         {
491             ok(!lstrcmpW(a->ai_canonname, b->ai_canonname), "Wrong canonical name '%s' != '%s'\n",
492                wine_dbgstr_w(a->ai_canonname), wine_dbgstr_w(b->ai_canonname));
493         }
494         else
495             ok(!a->ai_canonname && !b->ai_canonname, "Expected both names absent (%p != %p)\n",
496                a->ai_canonname, b->ai_canonname);
497     }
498     ok(!a && !b, "Expected both addresses null (%p != %p)\n", a, b);
499 }
500 
501 /**************** Server utility functions ***************/
502 
503 /*
504  *  Even if we have closed our server socket cleanly,
505  *  the OS may mark the address "in use" for some time -
506  *  this happens with native Linux apps, too.
507  */
508 static void do_bind ( SOCKET s, struct sockaddr* addr, int addrlen )
509 {
510     int err, wsaerr = 0, n_try = BIND_TRIES;
511 
512     while ( ( err = bind ( s, addr, addrlen ) ) != 0 &&
513             ( wsaerr = WSAGetLastError () ) == WSAEADDRINUSE &&
514             n_try-- >= 0)
515     {
516         trace ( "address in use, waiting ...\n" );
517         Sleep ( 1000 * BIND_SLEEP );
518     }
519     ok ( err == 0, "failed to bind: %d\n", wsaerr );
520 }
521 
522 static void server_start ( server_params *par )
523 {
524     int i;
525     test_params *gen = par->general;
526     server_memory *mem = LocalAlloc ( LPTR, sizeof ( server_memory ) );
527 
528     TlsSetValue ( tls, mem );
529     mem->s = WSASocketA ( AF_INET, gen->sock_type, gen->sock_prot,
530                           NULL, 0, par->sock_flags );
531     ok ( mem->s != INVALID_SOCKET, "Server: WSASocket failed\n" );
532 
533     mem->addr.sin_family = AF_INET;
534     mem->addr.sin_addr.s_addr = inet_addr ( gen->inet_addr );
535     mem->addr.sin_port = htons ( gen->inet_port );
536 
537     for (i = 0; i < MAX_CLIENTS; i++)
538     {
539         mem->sock[i].s = INVALID_SOCKET;
540         mem->sock[i].buf = LocalAlloc ( LPTR, gen->n_chunks * gen->chunk_size );
541         mem->sock[i].n_recvd = 0;
542         mem->sock[i].n_sent = 0;
543     }
544 
545     if ( gen->sock_type == SOCK_STREAM )
546         do_bind ( mem->s, (struct sockaddr*) &mem->addr, sizeof (mem->addr) );
547 }
548 
549 static void server_stop (void)
550 {
551     int i;
552     server_memory *mem = TlsGetValue ( tls );
553 
554     for (i = 0; i < MAX_CLIENTS; i++ )
555     {
556         LocalFree ( mem->sock[i].buf );
557         if ( mem->sock[i].s != INVALID_SOCKET )
558             closesocket ( mem->sock[i].s );
559     }
560     ok ( closesocket ( mem->s ) == 0, "closesocket failed\n" );
561     LocalFree ( mem );
562     ExitThread ( GetCurrentThreadId () );
563 }
564 
565 /**************** Client utilitiy functions ***************/
566 
567 static void client_start ( client_params *par )
568 {
569     test_params *gen = par->general;
570     client_memory *mem = LocalAlloc (LPTR, sizeof (client_memory));
571 
572     TlsSetValue ( tls, mem );
573 
574     WaitForSingleObject ( server_ready, INFINITE );
575 
576     mem->s = WSASocketA ( AF_INET, gen->sock_type, gen->sock_prot,
577                           NULL, 0, par->sock_flags );
578 
579     mem->addr.sin_family = AF_INET;
580     mem->addr.sin_addr.s_addr = inet_addr ( gen->inet_addr );
581     mem->addr.sin_port = htons ( gen->inet_port );
582 
583     ok ( mem->s != INVALID_SOCKET, "Client: WSASocket failed\n" );
584 
585     mem->send_buf = LocalAlloc ( LPTR, 2 * gen->n_chunks * gen->chunk_size );
586     mem->recv_buf = mem->send_buf + gen->n_chunks * gen->chunk_size;
587     fill_buffer ( mem->send_buf, gen->chunk_size, gen->n_chunks );
588 
589     SetEvent ( client_ready[client_id] );
590     /* Wait for the other clients to come up */
591     WaitForMultipleObjects ( min ( gen->n_clients, MAX_CLIENTS ), client_ready, TRUE, INFINITE );
592 }
593 
594 static void client_stop (void)
595 {
596     client_memory *mem = TlsGetValue ( tls );
597     wsa_ok ( closesocket ( mem->s ), 0 ==, "closesocket error (%x): %d\n" );
598     LocalFree ( mem->send_buf );
599     LocalFree ( mem );
600     ExitThread(0);
601 }
602 
603 /**************** Servers ***************/
604 
605 /*
606  * simple_server: A very basic server doing synchronous IO.
607  */
608 static VOID WINAPI simple_server ( server_params *par )
609 {
610     test_params *gen = par->general;
611     server_memory *mem;
612     int pos, n_recvd, n_sent, n_expected = gen->n_chunks * gen->chunk_size, tmp, i,
613         id = GetCurrentThreadId();
614 
615     trace ( "simple_server (%x) starting\n", id );
616 
617     set_so_opentype ( FALSE ); /* non-overlapped */
618     server_start ( par );
619     mem = TlsGetValue ( tls );
620 
621     wsa_ok ( set_blocking ( mem->s, TRUE ), 0 ==, "simple_server (%x): failed to set blocking mode: %d\n");
622     wsa_ok ( listen ( mem->s, SOMAXCONN ), 0 ==, "simple_server (%x): listen failed: %d\n");
623 
624     trace ( "simple_server (%x) ready\n", id );
625     SetEvent ( server_ready ); /* notify clients */
626 
627     for ( i = 0; i < min ( gen->n_clients, MAX_CLIENTS ); i++ )
628     {
629         trace ( "simple_server (%x): waiting for client\n", id );
630 
631         /* accept a single connection */
632         tmp = sizeof ( mem->sock[0].peer );
633         mem->sock[0].s = accept ( mem->s, (struct sockaddr*) &mem->sock[0].peer, &tmp );
634         wsa_ok ( mem->sock[0].s, INVALID_SOCKET !=, "simple_server (%x): accept failed: %d\n" );
635 
636         ok ( mem->sock[0].peer.sin_addr.s_addr == inet_addr ( gen->inet_addr ),
637              "simple_server (%x): strange peer address\n", id );
638 
639         /* Receive data & check it */
640         n_recvd = do_synchronous_recv ( mem->sock[0].s, mem->sock[0].buf, n_expected, 0, par->buflen );
641         ok ( n_recvd == n_expected,
642              "simple_server (%x): received less data than expected: %d of %d\n", id, n_recvd, n_expected );
643         pos = test_buffer ( mem->sock[0].buf, gen->chunk_size, gen->n_chunks );
644         ok ( pos == -1, "simple_server (%x): test pattern error: %d\n", id, pos);
645 
646         /* Echo data back */
647         n_sent = do_synchronous_send ( mem->sock[0].s, mem->sock[0].buf, n_expected, 0, par->buflen );
648         ok ( n_sent == n_expected,
649              "simple_server (%x): sent less data than expected: %d of %d\n", id, n_sent, n_expected );
650 
651         /* cleanup */
652         read_zero_bytes ( mem->sock[0].s );
653         wsa_ok ( closesocket ( mem->sock[0].s ),  0 ==, "simple_server (%x): closesocket error: %d\n" );
654         mem->sock[0].s = INVALID_SOCKET;
655     }
656 
657     trace ( "simple_server (%x) exiting\n", id );
658     server_stop ();
659 }
660 
661 /*
662  * oob_server: A very basic server receiving out-of-band data.
663  */
664 static VOID WINAPI oob_server ( server_params *par )
665 {
666     test_params *gen = par->general;
667     server_memory *mem;
668     u_long atmark = 0;
669     int pos, n_sent, n_recvd, n_expected = gen->n_chunks * gen->chunk_size, tmp,
670         id = GetCurrentThreadId();
671 
672     trace ( "oob_server (%x) starting\n", id );
673 
674     set_so_opentype ( FALSE ); /* non-overlapped */
675     server_start ( par );
676     mem = TlsGetValue ( tls );
677 
678     wsa_ok ( set_blocking ( mem->s, TRUE ), 0 ==, "oob_server (%x): failed to set blocking mode: %d\n");
679     wsa_ok ( listen ( mem->s, SOMAXCONN ), 0 ==, "oob_server (%x): listen failed: %d\n");
680 
681     trace ( "oob_server (%x) ready\n", id );
682     SetEvent ( server_ready ); /* notify clients */
683 
684     trace ( "oob_server (%x): waiting for client\n", id );
685 
686     /* accept a single connection */
687     tmp = sizeof ( mem->sock[0].peer );
688     mem->sock[0].s = accept ( mem->s, (struct sockaddr*) &mem->sock[0].peer, &tmp );
689     wsa_ok ( mem->sock[0].s, INVALID_SOCKET !=, "oob_server (%x): accept failed: %d\n" );
690 
691     ok ( mem->sock[0].peer.sin_addr.s_addr == inet_addr ( gen->inet_addr ),
692          "oob_server (%x): strange peer address\n", id );
693 
694     /* check initial atmark state */
695     ioctlsocket ( mem->sock[0].s, SIOCATMARK, &atmark );
696     ok ( atmark == 1, "oob_server (%x): unexpectedly at the OOB mark: %i\n", id, atmark );
697 
698     /* Receive normal data */
699     n_recvd = do_synchronous_recv ( mem->sock[0].s, mem->sock[0].buf, n_expected, 0, par->buflen );
700     ok ( n_recvd == n_expected,
701          "oob_server (%x): received less data than expected: %d of %d\n", id, n_recvd, n_expected );
702     pos = test_buffer ( mem->sock[0].buf, gen->chunk_size, gen->n_chunks );
703     ok ( pos == -1, "oob_server (%x): test pattern error: %d\n", id, pos);
704 
705     /* check atmark state */
706     ioctlsocket ( mem->sock[0].s, SIOCATMARK, &atmark );
707     ok ( atmark == 1, "oob_server (%x): unexpectedly at the OOB mark: %i\n", id, atmark );
708 
709     /* Echo data back */
710     n_sent = do_synchronous_send ( mem->sock[0].s, mem->sock[0].buf, n_expected, 0, par->buflen );
711     ok ( n_sent == n_expected,
712          "oob_server (%x): sent less data than expected: %d of %d\n", id, n_sent, n_expected );
713 
714     /* Receive a part of the out-of-band data and print atmark state */
715     n_recvd = do_synchronous_recv ( mem->sock[0].s, mem->sock[0].buf, 8, 0, par->buflen );
716     ok ( n_recvd == 8,
717          "oob_server (%x): received less data than expected: %d of %d\n", id, n_recvd, 8 );
718     n_expected -= 8;
719 
720     ioctlsocket ( mem->sock[0].s, SIOCATMARK, &atmark );
721     trace( "oob_server (%x): %s the OOB mark: %i\n", id, atmark == 1 ? "not at" : "at", atmark );
722 
723     /* Receive the rest of the out-of-band data and check atmark state */
724     do_synchronous_recv ( mem->sock[0].s, mem->sock[0].buf, n_expected, 0, par->buflen );
725 
726     ioctlsocket ( mem->sock[0].s, SIOCATMARK, &atmark );
727     todo_wine ok ( atmark == 0, "oob_server (%x): not at the OOB mark: %i\n", id, atmark );
728 
729     /* cleanup */
730     wsa_ok ( closesocket ( mem->sock[0].s ),  0 ==, "oob_server (%x): closesocket error: %d\n" );
731     mem->sock[0].s = INVALID_SOCKET;
732 
733     trace ( "oob_server (%x) exiting\n", id );
734     server_stop ();
735 }
736 
737 /*
738  * select_server: A non-blocking server.
739  */
740 static VOID WINAPI select_server ( server_params *par )
741 {
742     test_params *gen = par->general;
743     server_memory *mem;
744     int n_expected = gen->n_chunks * gen->chunk_size, tmp, i,
745         id = GetCurrentThreadId(), n_connections = 0, n_sent, n_recvd,
746         n_set, delta, n_ready;
747     struct timeval timeout = {0,10}; /* wait for 10 milliseconds */
748     fd_set fds_recv, fds_send, fds_openrecv, fds_opensend;
749 
750     trace ( "select_server (%x) starting\n", id );
751 
752     set_so_opentype ( FALSE ); /* non-overlapped */
753     server_start ( par );
754     mem = TlsGetValue ( tls );
755 
756     wsa_ok ( set_blocking ( mem->s, FALSE ), 0 ==, "select_server (%x): failed to set blocking mode: %d\n");
757     wsa_ok ( listen ( mem->s, SOMAXCONN ), 0 ==, "select_server (%x): listen failed: %d\n");
758 
759     trace ( "select_server (%x) ready\n", id );
760     SetEvent ( server_ready ); /* notify clients */
761 
762     FD_ZERO ( &fds_openrecv );
763     FD_ZERO ( &fds_recv );
764     FD_ZERO ( &fds_send );
765     FD_ZERO ( &fds_opensend );
766 
767     FD_SET ( mem->s, &fds_openrecv );
768 
769     while(1)
770     {
771         fds_recv = fds_openrecv;
772         fds_send = fds_opensend;
773 
774         n_set = 0;
775 
776         wsa_ok ( ( n_ready = select ( 0, &fds_recv, &fds_send, NULL, &timeout ) ), SOCKET_ERROR !=,
777             "select_server (%x): select() failed: %d\n" );
778 
779         /* check for incoming requests */
780         if ( FD_ISSET ( mem->s, &fds_recv ) ) {
781             n_set += 1;
782 
783             trace ( "select_server (%x): accepting client connection\n", id );
784 
785             /* accept a single connection */
786             tmp = sizeof ( mem->sock[n_connections].peer );
787             mem->sock[n_connections].s = accept ( mem->s, (struct sockaddr*) &mem->sock[n_connections].peer, &tmp );
788             wsa_ok ( mem->sock[n_connections].s, INVALID_SOCKET !=, "select_server (%x): accept() failed: %d\n" );
789 
790             ok ( mem->sock[n_connections].peer.sin_addr.s_addr == inet_addr ( gen->inet_addr ),
791                 "select_server (%x): strange peer address\n", id );
792 
793             /* add to list of open connections */
794             FD_SET ( mem->sock[n_connections].s, &fds_openrecv );
795             FD_SET ( mem->sock[n_connections].s, &fds_opensend );
796 
797             n_connections++;
798         }
799 
800         /* handle open requests */
801 
802         for ( i = 0; i < n_connections; i++ )
803         {
804             if ( FD_ISSET( mem->sock[i].s, &fds_recv ) ) {
805                 n_set += 1;
806 
807                 if ( mem->sock[i].n_recvd < n_expected ) {
808                     /* Receive data & check it */
809                     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 );
810                     ok ( n_recvd != SOCKET_ERROR, "select_server (%x): error in recv(): %d\n", id, WSAGetLastError() );
811                     mem->sock[i].n_recvd += n_recvd;
812 
813                     if ( mem->sock[i].n_recvd == n_expected ) {
814                         int pos = test_buffer ( mem->sock[i].buf, gen->chunk_size, gen->n_chunks );
815                         ok ( pos == -1, "select_server (%x): test pattern error: %d\n", id, pos );
816                         FD_CLR ( mem->sock[i].s, &fds_openrecv );
817                     }
818 
819                     ok ( mem->sock[i].n_recvd <= n_expected, "select_server (%x): received too many bytes: %d\n", id, mem->sock[i].n_recvd );
820                 }
821             }
822 
823             /* only echo back what we've received */
824             delta = mem->sock[i].n_recvd - mem->sock[i].n_sent;
825 
826             if ( FD_ISSET ( mem->sock[i].s, &fds_send ) ) {
827                 n_set += 1;
828 
829                 if ( ( delta > 0 ) && ( mem->sock[i].n_sent < n_expected ) ) {
830                     /* Echo data back */
831                     n_sent = send ( mem->sock[i].s, mem->sock[i].buf + mem->sock[i].n_sent, min ( delta, par->buflen ), 0 );
832                     ok ( n_sent != SOCKET_ERROR, "select_server (%x): error in send(): %d\n", id, WSAGetLastError() );
833                     mem->sock[i].n_sent += n_sent;
834 
835                     if ( mem->sock[i].n_sent == n_expected ) {
836                         FD_CLR ( mem->sock[i].s, &fds_opensend );
837                     }
838 
839                     ok ( mem->sock[i].n_sent <= n_expected, "select_server (%x): sent too many bytes: %d\n", id, mem->sock[i].n_sent );
840                 }
841             }
842         }
843 
844         /* check that select returned the correct number of ready sockets */
845         ok ( ( n_set == n_ready ), "select_server (%x): select() returns wrong number of ready sockets\n", id );
846 
847         /* check if all clients are done */
848         if ( ( fds_opensend.fd_count == 0 )
849             && ( fds_openrecv.fd_count == 1 ) /* initial socket that accepts clients */
850             && ( n_connections  == min ( gen->n_clients, MAX_CLIENTS ) ) ) {
851             break;
852         }
853     }
854 
855     for ( i = 0; i < min ( gen->n_clients, MAX_CLIENTS ); i++ )
856     {
857         /* cleanup */
858         read_zero_bytes ( mem->sock[i].s );
859         wsa_ok ( closesocket ( mem->sock[i].s ),  0 ==, "select_server (%x): closesocket error: %d\n" );
860         mem->sock[i].s = INVALID_SOCKET;
861     }
862 
863     trace ( "select_server (%x) exiting\n", id );
864     server_stop ();
865 }
866 
867 /**************** Clients ***************/
868 
869 /*
870  * simple_client: A very basic client doing synchronous IO.
871  */
872 static VOID WINAPI simple_client ( client_params *par )
873 {
874     test_params *gen = par->general;
875     client_memory *mem;
876     int pos, n_sent, n_recvd, n_expected = gen->n_chunks * gen->chunk_size, id;
877 
878     id = GetCurrentThreadId();
879     trace ( "simple_client (%x): starting\n", id );
880     /* wait here because we want to call set_so_opentype before creating a socket */
881     WaitForSingleObject ( server_ready, INFINITE );
882     trace ( "simple_client (%x): server ready\n", id );
883 
884     check_so_opentype ();
885     set_so_opentype ( FALSE ); /* non-overlapped */
886     client_start ( par );
887     mem = TlsGetValue ( tls );
888 
889     /* Connect */
890     wsa_ok ( connect ( mem->s, (struct sockaddr*) &mem->addr, sizeof ( mem->addr ) ),
891              0 ==, "simple_client (%x): connect error: %d\n" );
892     ok ( set_blocking ( mem->s, TRUE ) == 0,
893          "simple_client (%x): failed to set blocking mode\n", id );
894     trace ( "simple_client (%x) connected\n", id );
895 
896     /* send data to server */
897     n_sent = do_synchronous_send ( mem->s, mem->send_buf, n_expected, 0, par->buflen );
898     ok ( n_sent == n_expected,
899          "simple_client (%x): sent less data than expected: %d of %d\n", id, n_sent, n_expected );
900 
901     /* shutdown send direction */
902     wsa_ok ( shutdown ( mem->s, SD_SEND ), 0 ==, "simple_client (%x): shutdown failed: %d\n" );
903 
904     /* Receive data echoed back & check it */
905     n_recvd = do_synchronous_recv ( mem->s, mem->recv_buf, n_expected, 0, par->buflen );
906     ok ( n_recvd == n_expected,
907          "simple_client (%x): received less data than expected: %d of %d\n", id, n_recvd, n_expected );
908 
909     /* check data */
910     pos = test_buffer ( mem->recv_buf, gen->chunk_size, gen->n_chunks );
911     ok ( pos == -1, "simple_client (%x): test pattern error: %d\n", id, pos);
912 
913     /* cleanup */
914     read_zero_bytes ( mem->s );
915     trace ( "simple_client (%x) exiting\n", id );
916     client_stop ();
917 }
918 
919 /*
920  * oob_client: A very basic client sending out-of-band data.
921  */
922 static VOID WINAPI oob_client ( client_params *par )
923 {
924     test_params *gen = par->general;
925     client_memory *mem;
926     int pos, n_sent, n_recvd, n_expected = gen->n_chunks * gen->chunk_size, id;
927 
928     id = GetCurrentThreadId();
929     trace ( "oob_client (%x): starting\n", id );
930     /* wait here because we want to call set_so_opentype before creating a socket */
931     WaitForSingleObject ( server_ready, INFINITE );
932     trace ( "oob_client (%x): server ready\n", id );
933 
934     check_so_opentype ();
935     set_so_opentype ( FALSE ); /* non-overlapped */
936     client_start ( par );
937     mem = TlsGetValue ( tls );
938 
939     /* Connect */
940     wsa_ok ( connect ( mem->s, (struct sockaddr*) &mem->addr, sizeof ( mem->addr ) ),
941              0 ==, "oob_client (%x): connect error: %d\n" );
942     ok ( set_blocking ( mem->s, TRUE ) == 0,
943          "oob_client (%x): failed to set blocking mode\n", id );
944     trace ( "oob_client (%x) connected\n", id );
945 
946     /* send data to server */
947     n_sent = do_synchronous_send ( mem->s, mem->send_buf, n_expected, 0, par->buflen );
948     ok ( n_sent == n_expected,
949          "oob_client (%x): sent less data than expected: %d of %d\n", id, n_sent, n_expected );
950 
951     /* Receive data echoed back & check it */
952     n_recvd = do_synchronous_recv ( mem->s, mem->recv_buf, n_expected, 0, par->buflen );
953     ok ( n_recvd == n_expected,
954          "simple_client (%x): received less data than expected: %d of %d\n", id, n_recvd, n_expected );
955     pos = test_buffer ( mem->recv_buf, gen->chunk_size, gen->n_chunks );
956     ok ( pos == -1, "simple_client (%x): test pattern error: %d\n", id, pos);
957 
958     /* send out-of-band data to server */
959     n_sent = do_synchronous_send ( mem->s, mem->send_buf, n_expected, MSG_OOB, par->buflen );
960     ok ( n_sent == n_expected,
961          "oob_client (%x): sent less data than expected: %d of %d\n", id, n_sent, n_expected );
962 
963     /* shutdown send direction */
964     wsa_ok ( shutdown ( mem->s, SD_SEND ), 0 ==, "simple_client (%x): shutdown failed: %d\n" );
965 
966     /* cleanup */
967     read_zero_bytes ( mem->s );
968     trace ( "oob_client (%x) exiting\n", id );
969     client_stop ();
970 }
971 
972 /*
973  * simple_mixed_client: mixing send and recvfrom
974  */
975 static VOID WINAPI simple_mixed_client ( client_params *par )
976 {
977     test_params *gen = par->general;
978     client_memory *mem;
979     int pos, n_sent, n_recvd, n_expected = gen->n_chunks * gen->chunk_size, id;
980     int fromLen = sizeof(mem->addr);
981     struct sockaddr test;
982 
983     id = GetCurrentThreadId();
984     trace ( "simple_client (%x): starting\n", id );
985     /* wait here because we want to call set_so_opentype before creating a socket */
986     WaitForSingleObject ( server_ready, INFINITE );
987     trace ( "simple_client (%x): server ready\n", id );
988 
989     check_so_opentype ();
990     set_so_opentype ( FALSE ); /* non-overlapped */
991     client_start ( par );
992     mem = TlsGetValue ( tls );
993 
994     /* Connect */
995     wsa_ok ( connect ( mem->s, (struct sockaddr*) &mem->addr, sizeof ( mem->addr ) ),
996              0 ==, "simple_client (%x): connect error: %d\n" );
997     ok ( set_blocking ( mem->s, TRUE ) == 0,
998          "simple_client (%x): failed to set blocking mode\n", id );
999     trace ( "simple_client (%x) connected\n", id );
1000 
1001     /* send data to server */
1002     n_sent = do_synchronous_send ( mem->s, mem->send_buf, n_expected, 0, par->buflen );
1003     ok ( n_sent == n_expected,
1004          "simple_client (%x): sent less data than expected: %d of %d\n", id, n_sent, n_expected );
1005 
1006     /* shutdown send direction */
1007     wsa_ok ( shutdown ( mem->s, SD_SEND ), 0 ==, "simple_client (%x): shutdown failed: %d\n" );
1008 
1009     /* this shouldn't change, since lpFrom, is not updated on
1010        connection oriented sockets - exposed by bug 11640
1011     */
1012     ((struct sockaddr_in*)&test)->sin_addr.s_addr = inet_addr("0.0.0.0");
1013 
1014     /* Receive data echoed back & check it */
1015     n_recvd = do_synchronous_recvfrom ( mem->s,
1016 					mem->recv_buf,
1017 					n_expected,
1018 					0,
1019 					(struct sockaddr *)&test,
1020 					&fromLen,
1021 					par->buflen );
1022     ok ( n_recvd == n_expected,
1023          "simple_client (%x): received less data than expected: %d of %d\n", id, n_recvd, n_expected );
1024 
1025     /* check that lpFrom was not updated */
1026     ok(0 ==
1027        strcmp(
1028 	      inet_ntoa(((struct sockaddr_in*)&test)->sin_addr),
1029 	      "0.0.0.0"), "lpFrom shouldn't be updated on connection oriented sockets\n");
1030 
1031     /* check data */
1032     pos = test_buffer ( mem->recv_buf, gen->chunk_size, gen->n_chunks );
1033     ok ( pos == -1, "simple_client (%x): test pattern error: %d\n", id, pos);
1034 
1035     /* cleanup */
1036     read_zero_bytes ( mem->s );
1037     trace ( "simple_client (%x) exiting\n", id );
1038     client_stop ();
1039 }
1040 
1041 /*
1042  * event_client: An event-driven client
1043  */
1044 static void WINAPI event_client ( client_params *par )
1045 {
1046     test_params *gen = par->general;
1047     client_memory *mem;
1048     int id = GetCurrentThreadId(), n_expected = gen->n_chunks * gen->chunk_size,
1049         tmp, err, n;
1050     HANDLE event;
1051     WSANETWORKEVENTS wsa_events;
1052     char *send_last, *recv_last, *send_p, *recv_p;
1053     LONG mask = FD_READ | FD_WRITE | FD_CLOSE;
1054 
1055     trace ( "event_client (%x): starting\n", id );
1056     client_start ( par );
1057     trace ( "event_client (%x): server ready\n", id );
1058 
1059     mem = TlsGetValue ( tls );
1060 
1061     /* Prepare event notification for connect, makes socket nonblocking */
1062     event = WSACreateEvent ();
1063     WSAEventSelect ( mem->s, event, FD_CONNECT );
1064     tmp = connect ( mem->s, (struct sockaddr*) &mem->addr, sizeof ( mem->addr ) );
1065     if ( tmp != 0 ) {
1066         err = WSAGetLastError ();
1067         ok ( err == WSAEWOULDBLOCK, "event_client (%x): connect error: %d\n", id, err );
1068         tmp = WaitForSingleObject ( event, INFINITE );
1069         ok ( tmp == WAIT_OBJECT_0, "event_client (%x): wait for connect event failed: %d\n", id, tmp );
1070         err = WSAEnumNetworkEvents ( mem->s, event, &wsa_events );
1071         ok ( err == 0, "event_client (%x): WSAEnumNetworkEvents error: %d\n", id, err );
1072         err = wsa_events.iErrorCode[ FD_CONNECT_BIT ];
1073         ok ( err == 0, "event_client (%x): connect error: %d\n", id, err );
1074         if ( err ) goto out;
1075     }
1076 
1077     trace ( "event_client (%x) connected\n", id );
1078 
1079     WSAEventSelect ( mem->s, event, mask );
1080 
1081     recv_p = mem->recv_buf;
1082     recv_last = mem->recv_buf + n_expected;
1083     send_p = mem->send_buf;
1084     send_last = mem->send_buf + n_expected;
1085 
1086     while ( TRUE )
1087     {
1088         err = WaitForSingleObject ( event, INFINITE );
1089         ok ( err == WAIT_OBJECT_0, "event_client (%x): wait failed\n", id );
1090 
1091         err = WSAEnumNetworkEvents ( mem->s, event, &wsa_events );
1092         ok( err == 0, "event_client (%x): WSAEnumNetworkEvents error: %d\n", id, err );
1093 
1094         if ( wsa_events.lNetworkEvents & FD_WRITE )
1095         {
1096             err = wsa_events.iErrorCode[ FD_WRITE_BIT ];
1097             ok ( err == 0, "event_client (%x): FD_WRITE error code: %d\n", id, err );
1098 
1099             if ( err== 0 )
1100                 do
1101                 {
1102                     n = send ( mem->s, send_p, min ( send_last - send_p, par->buflen ), 0 );
1103                     if ( n < 0 )
1104                     {
1105                         err = WSAGetLastError ();
1106                         ok ( err == WSAEWOULDBLOCK, "event_client (%x): send error: %d\n", id, err );
1107                     }
1108                     else
1109                         send_p += n;
1110                 }
1111                 while ( n >= 0 && send_p < send_last );
1112 
1113             if ( send_p == send_last )
1114             {
1115                 trace ( "event_client (%x): all data sent - shutdown\n", id );
1116                 shutdown ( mem->s, SD_SEND );
1117                 mask &= ~FD_WRITE;
1118                 WSAEventSelect ( mem->s, event, mask );
1119             }
1120         }
1121         if ( wsa_events.lNetworkEvents & FD_READ )
1122         {
1123             err = wsa_events.iErrorCode[ FD_READ_BIT ];
1124             ok ( err == 0, "event_client (%x): FD_READ error code: %d\n", id, err );
1125             if ( err != 0 ) break;
1126 
1127             /* First read must succeed */
1128             n = recv ( mem->s, recv_p, min ( recv_last - recv_p, par->buflen ), 0 );
1129             wsa_ok ( n, 0 <=, "event_client (%x): recv error: %d\n" );
1130 
1131             while ( n >= 0 ) {
1132                 recv_p += n;
1133                 if ( recv_p == recv_last )
1134                 {
1135                     mask &= ~FD_READ;
1136                     trace ( "event_client (%x): all data received\n", id );
1137                     WSAEventSelect ( mem->s, event, mask );
1138                     break;
1139                 }
1140                 n = recv ( mem->s, recv_p, min ( recv_last - recv_p, par->buflen ), 0 );
1141                 if ( n < 0 && ( err = WSAGetLastError()) != WSAEWOULDBLOCK )
1142                     ok ( 0, "event_client (%x): read error: %d\n", id, err );
1143 
1144             }
1145         }
1146         if ( wsa_events.lNetworkEvents & FD_CLOSE )
1147         {
1148             trace ( "event_client (%x): close event\n", id );
1149             err = wsa_events.iErrorCode[ FD_CLOSE_BIT ];
1150             ok ( err == 0, "event_client (%x): FD_CLOSE error code: %d\n", id, err );
1151             break;
1152         }
1153     }
1154 
1155     n = send_p - mem->send_buf;
1156     ok ( send_p == send_last,
1157          "simple_client (%x): sent less data than expected: %d of %d\n", id, n, n_expected );
1158     n = recv_p - mem->recv_buf;
1159     ok ( recv_p == recv_last,
1160          "simple_client (%x): received less data than expected: %d of %d\n", id, n, n_expected );
1161     n = test_buffer ( mem->recv_buf, gen->chunk_size, gen->n_chunks );
1162     ok ( n == -1, "event_client (%x): test pattern error: %d\n", id, n);
1163 
1164 out:
1165     WSACloseEvent ( event );
1166     trace ( "event_client (%x) exiting\n", id );
1167     client_stop ();
1168 }
1169 
1170 /* Tests for WSAStartup */
1171 static void test_WithoutWSAStartup(void)
1172 {
1173     DWORD err;
1174 
1175     WSASetLastError(0xdeadbeef);
1176     ok(WSASocketA(0, 0, 0, NULL, 0, 0) == INVALID_SOCKET, "WSASocketA should have failed\n");
1177     err = WSAGetLastError();
1178     ok(err == WSANOTINITIALISED, "Expected 10093, received %d\n", err);
1179 
1180     WSASetLastError(0xdeadbeef);
1181     ok(gethostbyname("localhost") == NULL, "gethostbyname() succeeded unexpectedly\n");
1182     err = WSAGetLastError();
1183     ok(err == WSANOTINITIALISED, "Expected 10093, received %d\n", err);
1184 }
1185 
1186 static void test_WithWSAStartup(void)
1187 {
1188     WSADATA data;
1189     WORD version = MAKEWORD( 2, 2 );
1190     INT res, socks, i, j;
1191     SOCKET sock;
1192     LPVOID ptr;
1193     struct
1194     {
1195         SOCKET src, dst, dup_src, dup_dst;
1196     } pairs[32];
1197     DWORD error;
1198 
1199     res = WSAStartup( version, &data );
1200     ok(res == 0, "WSAStartup() failed unexpectedly: %d\n", res);
1201 
1202     ptr = gethostbyname("localhost");
1203     ok(ptr != NULL, "gethostbyname() failed unexpectedly: %d\n", WSAGetLastError());
1204 
1205     /* Alloc some sockets to check if they are destroyed on WSACleanup */
1206     for (socks = 0; socks < sizeof(pairs) / sizeof(pairs[0]); socks++)
1207     {
1208         WSAPROTOCOL_INFOA info;
1209         if (tcp_socketpair(&pairs[socks].src, &pairs[socks].dst)) break;
1210 
1211         memset(&info, 0, sizeof(info));
1212         ok(!WSADuplicateSocketA(pairs[socks].src, GetCurrentProcessId(), &info),
1213            "WSADuplicateSocketA should have worked\n");
1214         pairs[socks].dup_src = WSASocketA(0, 0, 0, &info, 0, 0);
1215         ok(pairs[socks].dup_src != SOCKET_ERROR, "expected != -1\n");
1216 
1217         memset(&info, 0, sizeof(info));
1218         ok(!WSADuplicateSocketA(pairs[socks].dst, GetCurrentProcessId(), &info),
1219            "WSADuplicateSocketA should have worked\n");
1220         pairs[socks].dup_dst = WSASocketA(0, 0, 0, &info, 0, 0);
1221         ok(pairs[socks].dup_dst != SOCKET_ERROR, "expected != -1\n");
1222     }
1223 
1224     res = send(pairs[0].src, "TEST", 4, 0);
1225     ok(res == 4, "send failed with error %d\n", WSAGetLastError());
1226 
1227     WSACleanup();
1228 
1229     res = WSAStartup( version, &data );
1230     ok(res == 0, "WSAStartup() failed unexpectedly: %d\n", res);
1231 
1232     /* show that sockets are destroyed automatically after WSACleanup */
1233     SetLastError(0xdeadbeef);
1234     res = send(pairs[0].src, "TEST", 4, 0);
1235     error = WSAGetLastError();
1236     ok(res == SOCKET_ERROR, "send should have failed\n");
1237     todo_wine ok(error == WSAENOTSOCK, "expected 10038, got %d\n", error);
1238 
1239     SetLastError(0xdeadbeef);
1240     res = send(pairs[0].dst, "TEST", 4, 0);
1241     error = WSAGetLastError();
1242     ok(res == SOCKET_ERROR, "send should have failed\n");
1243     todo_wine ok(error == WSAENOTSOCK, "expected 10038, got %d\n", error);
1244 
1245     /* Check that all sockets were destroyed */
1246     for (i = 0; i < socks; i++)
1247     {
1248         for (j = 0; j < 4; j++)
1249         {
1250             struct sockaddr_in saddr;
1251             int size = sizeof(saddr);
1252             switch(j)
1253             {
1254                 case 0: sock = pairs[i].src; break;
1255                 case 1: sock = pairs[i].dup_src; break;
1256                 case 2: sock = pairs[i].dst; break;
1257                 case 3: sock = pairs[i].dup_dst; break;
1258             }
1259 
1260             SetLastError(0xdeadbeef);
1261             res = getsockname(sock, (struct sockaddr *)&saddr, &size);
1262             error = WSAGetLastError();
1263             ok(res == SOCKET_ERROR, "Test[%d]: getsockname should have failed\n", i);
1264             todo_wine ok(error == WSAENOTSOCK, "Test[%d]: expected 10038, got %d\n", i, error);
1265         }
1266     }
1267 
1268     /* While wine is not fixed, close all sockets manually */
1269     for (i = 0; i < socks; i++)
1270     {
1271         closesocket(pairs[i].src);
1272         closesocket(pairs[i].dst);
1273         closesocket(pairs[i].dup_src);
1274         closesocket(pairs[i].dup_dst);
1275     }
1276 
1277     res = WSACleanup();
1278     ok(res == 0, "expected 0, got %d\n", res);
1279     WSASetLastError(0xdeadbeef);
1280     res = WSACleanup();
1281     error = WSAGetLastError();
1282     ok ( res == SOCKET_ERROR && error ==  WSANOTINITIALISED,
1283             "WSACleanup returned %d WSAGetLastError is %d\n", res, error);
1284 }
1285 
1286 /**************** Main program utility functions ***************/
1287 
1288 static void Init (void)
1289 {
1290     WORD ver = MAKEWORD (2, 2);
1291     WSADATA data;
1292     HMODULE hws2_32 = GetModuleHandleA("ws2_32.dll"), hiphlpapi, ntdll;
1293 
1294     pfreeaddrinfo = (void *)GetProcAddress(hws2_32, "freeaddrinfo");
1295     pgetaddrinfo = (void *)GetProcAddress(hws2_32, "getaddrinfo");
1296     pFreeAddrInfoW = (void *)GetProcAddress(hws2_32, "FreeAddrInfoW");
1297     pFreeAddrInfoExW = (void *)GetProcAddress(hws2_32, "FreeAddrInfoExW");
1298     pGetAddrInfoW = (void *)GetProcAddress(hws2_32, "GetAddrInfoW");
1299     pGetAddrInfoExW = (void *)GetProcAddress(hws2_32, "GetAddrInfoExW");
1300     pGetAddrInfoExOverlappedResult = (void *)GetProcAddress(hws2_32, "GetAddrInfoExOverlappedResult");
1301     pInetNtop = (void *)GetProcAddress(hws2_32, "inet_ntop");
1302     pInetNtopW = (void *)GetProcAddress(hws2_32, "InetNtopW");
1303     pInetPtonA = (void *)GetProcAddress(hws2_32, "inet_pton");
1304     pInetPtonW = (void *)GetProcAddress(hws2_32, "InetPtonW");
1305     pWSALookupServiceBeginW = (void *)GetProcAddress(hws2_32, "WSALookupServiceBeginW");
1306     pWSALookupServiceEnd = (void *)GetProcAddress(hws2_32, "WSALookupServiceEnd");
1307     pWSALookupServiceNextW = (void *)GetProcAddress(hws2_32, "WSALookupServiceNextW");
1308     pWSAEnumNameSpaceProvidersA = (void *)GetProcAddress(hws2_32, "WSAEnumNameSpaceProvidersA");
1309     pWSAEnumNameSpaceProvidersW = (void *)GetProcAddress(hws2_32, "WSAEnumNameSpaceProvidersW");
1310     pWSAPoll = (void *)GetProcAddress(hws2_32, "WSAPoll");
1311 
1312     hiphlpapi = LoadLibraryA("iphlpapi.dll");
1313     if (hiphlpapi)
1314     {
1315         pGetIpForwardTable = (void *)GetProcAddress(hiphlpapi, "GetIpForwardTable");
1316         pGetAdaptersInfo = (void *)GetProcAddress(hiphlpapi, "GetAdaptersInfo");
1317     }
1318 
1319     ntdll = LoadLibraryA("ntdll.dll");
1320     if (ntdll)
1321     {
1322         pNtClose = (void *)GetProcAddress(ntdll, "NtClose");
1323         pNtSetInformationFile = (void *)GetProcAddress(ntdll, "NtSetInformationFile");
1324         pNtQueryInformationFile = (void *)GetProcAddress(ntdll, "NtQueryInformationFile");
1325     }
1326 
1327     ok ( WSAStartup ( ver, &data ) == 0, "WSAStartup failed\n" );
1328     tls = TlsAlloc();
1329 }
1330 
1331 static void Exit (void)
1332 {
1333     INT ret, err;
1334     TlsFree ( tls );
1335     ret = WSACleanup();
1336     err = WSAGetLastError();
1337     ok ( ret == 0, "WSACleanup failed ret = %d GetLastError is %d\n", ret, err);
1338 }
1339 
1340 static void StartServer (LPTHREAD_START_ROUTINE routine,
1341                          test_params *general, server_params *par)
1342 {
1343     par->general = general;
1344     thread[0] = CreateThread ( NULL, 0, routine, par, 0, &thread_id[0] );
1345     ok ( thread[0] != NULL, "Failed to create server thread\n" );
1346 }
1347 
1348 static void StartClients (LPTHREAD_START_ROUTINE routine,
1349                           test_params *general, client_params *par)
1350 {
1351     int i;
1352     par->general = general;
1353     for ( i = 1; i <= min ( general->n_clients, MAX_CLIENTS ); i++ )
1354     {
1355         client_id = i - 1;
1356         thread[i] = CreateThread ( NULL, 0, routine, par, 0, &thread_id[i] );
1357         ok ( thread[i] != NULL, "Failed to create client thread\n" );
1358         /* Make sure the client is up and running */
1359         WaitForSingleObject ( client_ready[client_id], INFINITE );
1360     };
1361 }
1362 
1363 static void do_test( test_setup *test )
1364 {
1365     DWORD i, n = min (test->general.n_clients, MAX_CLIENTS);
1366     DWORD wait;
1367 
1368     server_ready = CreateEventA ( NULL, TRUE, FALSE, NULL );
1369     for (i = 0; i <= n; i++)
1370         client_ready[i] = CreateEventA ( NULL, TRUE, FALSE, NULL );
1371 
1372     StartServer ( test->srv, &test->general, &test->srv_params );
1373     StartClients ( test->clt, &test->general, &test->clt_params );
1374     WaitForSingleObject ( server_ready, INFINITE );
1375 
1376     wait = WaitForMultipleObjects ( 1 + n, thread, TRUE, 1000 * TEST_TIMEOUT );
1377     ok ( wait <= WAIT_OBJECT_0 + n ,
1378          "some threads have not completed: %x\n", wait );
1379 
1380     if ( ! ( wait <= WAIT_OBJECT_0 + n ) )
1381     {
1382         for (i = 0; i <= n; i++)
1383         {
1384             if ( WaitForSingleObject ( thread[i], 0 ) != WAIT_OBJECT_0 )
1385             {
1386                 trace ("terminating thread %08x\n", thread_id[i]);
1387                 TerminateThread ( thread [i], 0 );
1388             }
1389         }
1390     }
1391     CloseHandle ( server_ready );
1392     for (i = 0; i <= n; i++)
1393         CloseHandle ( client_ready[i] );
1394 }
1395 
1396 /********* some tests for getsockopt(setsockopt(X)) == X ***********/
1397 /* optname = SO_LINGER */
1398 static const LINGER linger_testvals[] = {
1399     {0,0},
1400     {0,73},
1401     {1,0},
1402     {5,189}
1403 };
1404 
1405 /* optname = SO_RCVTIMEO, SOSNDTIMEO */
1406 #define SOCKTIMEOUT1 63000 /* 63 seconds. Do not test fractional part because of a
1407                         bug in the linux kernel (fixed in 2.6.8) */
1408 #define SOCKTIMEOUT2 997000 /* 997 seconds */
1409 
1410 static void test_set_getsockopt(void)
1411 {
1412     SOCKET s, s2;
1413     int i, err, lasterr;
1414     int timeout;
1415     LINGER lingval;
1416     int size;
1417     WSAPROTOCOL_INFOA infoA;
1418     WSAPROTOCOL_INFOW infoW;
1419     char providername[WSAPROTOCOL_LEN + 1];
1420     DWORD value;
1421     struct _prottest
1422     {
1423         int family, type, proto;
1424     } prottest[] = {
1425         {AF_INET, SOCK_STREAM, IPPROTO_TCP},
1426         {AF_INET, SOCK_DGRAM, IPPROTO_UDP},
1427         {AF_INET6, SOCK_STREAM, IPPROTO_TCP},
1428         {AF_INET6, SOCK_DGRAM, IPPROTO_UDP}
1429     };
1430     union _csspace
1431     {
1432         CSADDR_INFO cs;
1433         char space[128];
1434     } csinfoA, csinfoB;
1435 
1436     s = socket(AF_INET, SOCK_STREAM, 0);
1437     ok(s!=INVALID_SOCKET, "socket() failed error: %d\n", WSAGetLastError());
1438     if( s == INVALID_SOCKET) return;
1439     /* SO_RCVTIMEO */
1440     timeout = SOCKTIMEOUT1;
1441     size = sizeof(timeout);
1442     err = setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, size);
1443     if( !err)
1444         err = getsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, &size);
1445     ok( !err, "get/setsockopt(SO_RCVTIMEO) failed error: %d\n", WSAGetLastError());
1446     ok( timeout == SOCKTIMEOUT1, "getsockopt(SO_RCVTIMEO) returned wrong value %d\n", timeout);
1447 
1448     timeout = 0;
1449     size = sizeof(timeout);
1450     err = setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, size);
1451     if( !err)
1452         err = getsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, &size);
1453     ok( !err, "get/setsockopt(SO_RCVTIMEO) failed error: %d\n", WSAGetLastError());
1454     ok( timeout == 0, "getsockopt(SO_RCVTIMEO) returned wrong value %d\n", timeout);
1455 
1456     /* SO_SNDTIMEO */
1457     timeout = SOCKTIMEOUT2; /* 997 seconds. See remark above */
1458     size = sizeof(timeout);
1459     err = setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (char *) &timeout, size);
1460     if( !err)
1461         err = getsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (char *) &timeout, &size);
1462     ok( !err, "get/setsockopt(SO_SNDTIMEO) failed error: %d\n", WSAGetLastError());
1463     ok( timeout == SOCKTIMEOUT2, "getsockopt(SO_SNDTIMEO) returned wrong value %d\n", timeout);
1464 
1465     /* SO_SNDBUF */
1466     value = 4096;
1467     size = sizeof(value);
1468     err = setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&value, size);
1469     ok( !err, "setsockopt(SO_SNDBUF) failed error: %u\n", WSAGetLastError() );
1470     value = 0xdeadbeef;
1471     err = getsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&value, &size);
1472     ok( !err, "getsockopt(SO_SNDBUF) failed error: %u\n", WSAGetLastError() );
1473     ok( value == 4096, "expected 4096, got %u\n", value );
1474 
1475     /* SO_RCVBUF */
1476     value = 4096;
1477     size = sizeof(value);
1478     err = setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&value, size);
1479     ok( !err, "setsockopt(SO_RCVBUF) failed error: %u\n", WSAGetLastError() );
1480     value = 0xdeadbeef;
1481     err = getsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&value, &size);
1482     ok( !err, "getsockopt(SO_RCVBUF) failed error: %u\n", WSAGetLastError() );
1483     ok( value == 4096, "expected 4096, got %u\n", value );
1484 
1485     /* SO_LINGER */
1486     for( i = 0; i < sizeof(linger_testvals)/sizeof(LINGER);i++) {
1487         size =  sizeof(lingval);
1488         lingval = linger_testvals[i];
1489         err = setsockopt(s, SOL_SOCKET, SO_LINGER, (char *) &lingval, size);
1490         if( !err)
1491             err = getsockopt(s, SOL_SOCKET, SO_LINGER, (char *) &lingval, &size);
1492         ok( !err, "get/setsockopt(SO_LINGER) failed error: %d\n", WSAGetLastError());
1493         ok( !lingval.l_onoff == !linger_testvals[i].l_onoff &&
1494                 (lingval.l_linger == linger_testvals[i].l_linger ||
1495                  (!lingval.l_linger && !linger_testvals[i].l_onoff))
1496                 , "getsockopt(SO_LINGER #%d) returned wrong value %d,%d not %d,%d\n", i,
1497                  lingval.l_onoff, lingval.l_linger,
1498                  linger_testvals[i].l_onoff, linger_testvals[i].l_linger);
1499     }
1500 
1501     size =  sizeof(lingval);
1502     err = setsockopt(s, SOL_SOCKET, SO_LINGER, NULL, size);
1503     ok(err == SOCKET_ERROR && WSAGetLastError() == WSAEFAULT,
1504        "got %d with %d (expected SOCKET_ERROR with WSAEFAULT)\n", err, WSAGetLastError());
1505     err = setsockopt(s, SOL_SOCKET, SO_LINGER, NULL, 0);
1506     ok(err == SOCKET_ERROR && WSAGetLastError() == WSAEFAULT,
1507        "got %d with %d (expected SOCKET_ERROR with WSAEFAULT)\n", err, WSAGetLastError());
1508 
1509     size =  sizeof(BOOL);
1510     err = setsockopt(s, SOL_SOCKET, SO_DONTLINGER, NULL, size);
1511     ok(err == SOCKET_ERROR && WSAGetLastError() == WSAEFAULT,
1512        "got %d with %d (expected SOCKET_ERROR with WSAEFAULT)\n", err, WSAGetLastError());
1513     err = setsockopt(s, SOL_SOCKET, SO_DONTLINGER, NULL, 0);
1514     ok(err == SOCKET_ERROR && WSAGetLastError() == WSAEFAULT,
1515        "got %d with %d (expected SOCKET_ERROR with WSAEFAULT)\n", err, WSAGetLastError());
1516 
1517     /* Test for erroneously passing a value instead of a pointer as optval */
1518     size = sizeof(char);
1519     err = setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)1, size);
1520     ok(err == SOCKET_ERROR, "setsockopt with optval being a value passed "
1521                             "instead of failing.\n");
1522     lasterr = WSAGetLastError();
1523     ok(lasterr == WSAEFAULT, "setsockopt with optval being a value "
1524                              "returned 0x%08x, not WSAEFAULT(0x%08x)\n",
1525                              lasterr, WSAEFAULT);
1526 
1527     /* SO_RCVTIMEO with invalid values for level */
1528     size = sizeof(timeout);
1529     timeout = SOCKTIMEOUT1;
1530     SetLastError(0xdeadbeef);
1531     err = setsockopt(s, 0xffffffff, SO_RCVTIMEO, (char *) &timeout, size);
1532     ok( (err == SOCKET_ERROR) && (WSAGetLastError() == WSAEINVAL),
1533         "got %d with %d (expected SOCKET_ERROR with WSAEINVAL)\n",
1534         err, WSAGetLastError());
1535 
1536     timeout = SOCKTIMEOUT1;
1537     SetLastError(0xdeadbeef);
1538     err = setsockopt(s, 0x00008000, SO_RCVTIMEO, (char *) &timeout, size);
1539     ok( (err == SOCKET_ERROR) && (WSAGetLastError() == WSAEINVAL),
1540         "got %d with %d (expected SOCKET_ERROR with WSAEINVAL)\n",
1541         err, WSAGetLastError());
1542 
1543     /* Test SO_ERROR set/get */
1544     SetLastError(0xdeadbeef);
1545     i = 1234;
1546     err = setsockopt(s, SOL_SOCKET, SO_ERROR, (char *) &i, size);
1547 todo_wine
1548     ok( !err && !WSAGetLastError(),
1549         "got %d with %d (expected 0 with 0)\n",
1550         err, WSAGetLastError());
1551 
1552     SetLastError(0xdeadbeef);
1553     i = 4321;
1554     err = getsockopt(s, SOL_SOCKET, SO_ERROR, (char *) &i, &size);
1555 todo_wine
1556     ok( !err && !WSAGetLastError(),
1557         "got %d with %d (expected 0 with 0)\n",
1558         err, WSAGetLastError());
1559 todo_wine
1560     ok (i == 1234, "got %d (expected 1234)\n", i);
1561 
1562     /* Test invalid optlen */
1563     SetLastError(0xdeadbeef);
1564     size = 1;
1565     err = getsockopt(s, SOL_SOCKET, SO_ERROR, (char *) &i, &size);
1566 todo_wine
1567     ok( (err == SOCKET_ERROR) && (WSAGetLastError() == WSAEFAULT),
1568         "got %d with %d (expected SOCKET_ERROR with WSAEFAULT)\n",
1569         err, WSAGetLastError());
1570 
1571     closesocket(s);
1572     /* Test with the closed socket */
1573     SetLastError(0xdeadbeef);
1574     size = sizeof(i);
1575     i = 1234;
1576     err = getsockopt(s, SOL_SOCKET, SO_ERROR, (char *) &i, &size);
1577 todo_wine
1578     ok( (err == SOCKET_ERROR) && (WSAGetLastError() == WSAENOTSOCK),
1579         "got %d with %d (expected SOCKET_ERROR with WSAENOTSOCK)\n",
1580         err, WSAGetLastError());
1581     ok (i == 1234, "expected 1234, got %d\n", i);
1582 
1583     /* Test WS_IP_MULTICAST_TTL with 8, 16, 24 and 32 bits values */
1584     s = socket(AF_INET, SOCK_DGRAM, 0);
1585     ok(s != INVALID_SOCKET, "Failed to create socket\n");
1586     size = sizeof(i);
1587     i = 0x0000000a;
1588     err = setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, (char *) &i, size);
1589     if (!err)
1590     {
1591         for (i = 0; i < 4; i++)
1592         {
1593             int k, j;
1594             const int tests[] = {0xffffff0a, 0xffff000b, 0xff00000c, 0x0000000d};
1595             err = setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, (char *) &tests[i], i + 1);
1596             ok(!err, "Test [%d] Expected 0, got %d\n", i, err);
1597             err = getsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, (char *) &k, &size);
1598             ok(!err, "Test [%d] Expected 0, got %d\n", i, err);
1599             j = i != 3 ? tests[i] & ((1 << (i + 1) * 8) - 1) : tests[i];
1600             ok(k == j, "Test [%d] Expected 0x%x, got 0x%x\n", i, j, k);
1601         }
1602     }
1603     else
1604         win_skip("IP_MULTICAST_TTL is unsupported\n");
1605     closesocket(s);
1606 
1607     /* test SO_PROTOCOL_INFOA invalid parameters */
1608     ok(getsockopt(INVALID_SOCKET, SOL_SOCKET, SO_PROTOCOL_INFOA, NULL, NULL),
1609        "getsockopt should have failed\n");
1610     err = WSAGetLastError();
1611     ok(err == WSAENOTSOCK, "expected 10038, got %d instead\n", err);
1612     size = sizeof(WSAPROTOCOL_INFOA);
1613     ok(getsockopt(INVALID_SOCKET, SOL_SOCKET, SO_PROTOCOL_INFOA, (char *) &infoA, &size),
1614        "getsockopt should have failed\n");
1615     ok(size == sizeof(WSAPROTOCOL_INFOA), "got size %d\n", size);
1616     err = WSAGetLastError();
1617     ok(err == WSAENOTSOCK, "expected 10038, got %d instead\n", err);
1618     s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1619     ok(getsockopt(s, SOL_SOCKET, SO_PROTOCOL_INFOA, NULL, NULL),
1620        "getsockopt should have failed\n");
1621     err = WSAGetLastError();
1622     ok(err == WSAEFAULT, "expected 10014, got %d instead\n", err);
1623     ok(getsockopt(s, SOL_SOCKET, SO_PROTOCOL_INFOA, (char *) &infoA, NULL),
1624        "getsockopt should have failed\n");
1625     err = WSAGetLastError();
1626     ok(err == WSAEFAULT, "expected 10014, got %d instead\n", err);
1627     ok(getsockopt(s, SOL_SOCKET, SO_PROTOCOL_INFOA, NULL, &size),
1628        "getsockopt should have failed\n");
1629     err = WSAGetLastError();
1630     ok(err == WSAEFAULT, "expected 10014, got %d instead\n", err);
1631     size = sizeof(WSAPROTOCOL_INFOA) / 2;
1632     ok(getsockopt(s, SOL_SOCKET, SO_PROTOCOL_INFOA, (char *) &infoA, &size),
1633        "getsockopt should have failed\n");
1634     err = WSAGetLastError();
1635     ok(err == WSAEFAULT, "expected 10014, got %d instead\n", err);
1636     ok(size == sizeof(WSAPROTOCOL_INFOA), "got size %d\n", size);
1637     size = sizeof(WSAPROTOCOL_INFOA) * 2;
1638     err = getsockopt(s, SOL_SOCKET, SO_PROTOCOL_INFOA, (char *) &infoA, &size);
1639     ok(!err,"getsockopt failed with %d\n", WSAGetLastError());
1640     ok(size == sizeof(WSAPROTOCOL_INFOA) * 2, "got size %d\n", size);
1641 
1642     closesocket(s);
1643 
1644     /* test SO_PROTOCOL_INFO structure returned for different protocols */
1645     for (i = 0; i < sizeof(prottest) / sizeof(prottest[0]); i++)
1646     {
1647         int k;
1648 
1649         s = socket(prottest[i].family, prottest[i].type, prottest[i].proto);
1650         if (s == INVALID_SOCKET && prottest[i].family == AF_INET6) continue;
1651 
1652         ok(s != INVALID_SOCKET, "Failed to create socket: %d\n",
1653           WSAGetLastError());
1654 
1655         /* compare both A and W version */
1656         infoA.szProtocol[0] = 0;
1657         size = sizeof(WSAPROTOCOL_INFOA);
1658         err = getsockopt(s, SOL_SOCKET, SO_PROTOCOL_INFOA, (char *) &infoA, &size);
1659         ok(!err,"getsockopt failed with %d\n", WSAGetLastError());
1660         ok(size == sizeof(WSAPROTOCOL_INFOA), "got size %d\n", size);
1661 
1662         infoW.szProtocol[0] = 0;
1663         size = sizeof(WSAPROTOCOL_INFOW);
1664         err = getsockopt(s, SOL_SOCKET, SO_PROTOCOL_INFOW, (char *) &infoW, &size);
1665         ok(!err,"getsockopt failed with %d\n", WSAGetLastError());
1666         ok(size == sizeof(WSAPROTOCOL_INFOW), "got size %d\n", size);
1667 
1668         trace("provider name '%s', family %d, type %d, proto %d\n",
1669               infoA.szProtocol, prottest[i].family, prottest[i].type, prottest[i].proto);
1670 
1671         ok(infoA.szProtocol[0], "WSAPROTOCOL_INFOA was not filled\n");
1672         ok(infoW.szProtocol[0], "WSAPROTOCOL_INFOW was not filled\n");
1673 
1674         WideCharToMultiByte(CP_ACP, 0, infoW.szProtocol, -1,
1675                             providername, sizeof(providername), NULL, NULL);
1676         ok(!strcmp(infoA.szProtocol,providername),
1677            "different provider names '%s' != '%s'\n", infoA.szProtocol, providername);
1678 
1679         ok(!memcmp(&infoA, &infoW, FIELD_OFFSET(WSAPROTOCOL_INFOA, szProtocol)),
1680            "SO_PROTOCOL_INFO[A/W] comparison failed\n");
1681 
1682         /* Remove IF when WSAEnumProtocols support IPV6 data */
1683         todo_wine_if (prottest[i].family == AF_INET6)
1684             ok(infoA.iAddressFamily == prottest[i].family, "socket family invalid, expected %d received %d\n",
1685                prottest[i].family, infoA.iAddressFamily);
1686         ok(infoA.iSocketType == prottest[i].type, "socket type invalid, expected %d received %d\n",
1687            prottest[i].type, infoA.iSocketType);
1688         ok(infoA.iProtocol == prottest[i].proto, "socket protocol invalid, expected %d received %d\n",
1689            prottest[i].proto, infoA.iProtocol);
1690 
1691         /* IP_HDRINCL is supported only on SOCK_RAW but passed to SOCK_DGRAM by Impossible Creatures */
1692         size = sizeof(i);
1693         k = 1;
1694         SetLastError(0xdeadbeef);
1695         err = setsockopt(s, IPPROTO_IP, IP_HDRINCL, (char *) &k, size);
1696         if (err == -1) /* >= Vista */
1697         {
1698             todo_wine {
1699             ok(GetLastError() == WSAEINVAL, "Expected 10022, got %d\n", GetLastError());
1700             k = 99;
1701             SetLastError(0xdeadbeef);
1702             err = getsockopt(s, IPPROTO_IP, IP_HDRINCL, (char *) &k, &size);
1703             ok(err == -1, "Expected -1, got %d\n", err);
1704             ok(GetLastError() == WSAEINVAL, "Expected 10022, got %d\n", GetLastError());
1705             ok(k == 99, "Expected 99, got %d\n", k);
1706 
1707             size = sizeof(k);
1708             k = 0;
1709             SetLastError(0xdeadbeef);
1710             err = setsockopt(s, IPPROTO_IP, IP_HDRINCL, (char *) &k, size);
1711             }
1712             ok(err == -1, "Expected -1, got %d\n", err);
1713             todo_wine {
1714             ok(GetLastError() == WSAEINVAL, "Expected 10022, got %d\n", GetLastError());
1715             k = 99;
1716             SetLastError(0xdeadbeef);
1717             err = getsockopt(s, IPPROTO_IP, IP_HDRINCL, (char *) &k, &size);
1718             ok(err == -1, "Expected -1, got %d\n", err);
1719             ok(GetLastError() == WSAEINVAL, "Expected 10022, got %d\n", GetLastError());
1720             ok(k == 99, "Expected 99, got %d\n", k);
1721             }
1722         }
1723         else /* <= 2003 the tests differ between TCP and UDP, UDP silently accepts */
1724         {
1725             SetLastError(0xdeadbeef);
1726             k = 99;
1727             err = getsockopt(s, IPPROTO_IP, IP_HDRINCL, (char *) &k, &size);
1728             if (prottest[i].type == SOCK_DGRAM)
1729             {
1730                 ok(err == 0, "Expected 0, got %d\n", err);
1731                 ok(k == 1, "Expected 1, got %d\n", k);
1732             }
1733             else
1734             {
1735                 /* contratry to what we could expect the function returns error but k is changed */
1736                 ok(err == -1, "Expected -1, got %d\n", err);
1737                 ok(GetLastError() == WSAENOPROTOOPT, "Expected 10042, got %d\n", GetLastError());
1738                 ok(k == 0, "Expected 0, got %d\n", k);
1739             }
1740 
1741             k = 0;
1742             err = setsockopt(s, IPPROTO_IP, IP_HDRINCL, (char *) &k, size);
1743             ok(err == 0, "Expected 0, got %d\n", err);
1744 
1745             k = 99;
1746             err = getsockopt(s, IPPROTO_IP, IP_HDRINCL, (char *) &k, &size);
1747             if (prottest[i].type == SOCK_DGRAM)
1748             {
1749                 ok(err == 0, "Expected 0, got %d\n", err);
1750                 ok(k == 0, "Expected 0, got %d\n", k);
1751             }
1752             else
1753             {
1754                 /* contratry to what we could expect the function returns error but k is changed */
1755                 ok(err == -1, "Expected -1, got %d\n", err);
1756                 ok(GetLastError() == WSAENOPROTOOPT, "Expected 10042, got %d\n", GetLastError());
1757                 ok(k == 0, "Expected 0, got %d\n", k);
1758             }
1759         }
1760 
1761         closesocket(s);
1762     }
1763 
1764     /* Test SO_BSP_STATE - Present only in >= Win 2008 */
1765     s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1766     ok(s != INVALID_SOCKET, "Failed to create socket\n");
1767     s2 = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1768     ok(s2 != INVALID_SOCKET, "Failed to create socket\n");
1769 
1770     SetLastError(0xdeadbeef);
1771     size = sizeof(csinfoA);
1772     err = getsockopt(s, SOL_SOCKET, SO_BSP_STATE, (char *) &csinfoA, &size);
1773     if (!err)
1774     {
1775         struct sockaddr_in saddr;
1776         memset(&saddr, 0, sizeof(saddr));
1777         saddr.sin_family = AF_INET;
1778         saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
1779 
1780         /* Socket is not bound, no information provided */
1781         ok(!csinfoA.cs.LocalAddr.iSockaddrLength, "Expected 0, got %d\n", csinfoA.cs.LocalAddr.iSockaddrLength);
1782         ok(csinfoA.cs.LocalAddr.lpSockaddr == NULL, "Expected NULL, got %p\n", csinfoA.cs.LocalAddr.lpSockaddr);
1783         /* Socket is not connected, no information provided */
1784         ok(!csinfoA.cs.RemoteAddr.iSockaddrLength, "Expected 0, got %d\n", csinfoA.cs.RemoteAddr.iSockaddrLength);
1785         ok(csinfoA.cs.RemoteAddr.lpSockaddr == NULL, "Expected NULL, got %p\n", csinfoA.cs.RemoteAddr.lpSockaddr);
1786 
1787         err = bind(s, (struct sockaddr*)&saddr, sizeof(saddr));
1788         ok(!err, "Expected 0, got %d\n", err);
1789         size = sizeof(csinfoA);
1790         err = getsockopt(s, SOL_SOCKET, SO_BSP_STATE, (char *) &csinfoA, &size);
1791         ok(!err, "Expected 0, got %d\n", err);
1792 
1793         /* Socket is bound */
1794         ok(csinfoA.cs.LocalAddr.iSockaddrLength, "Expected non-zero\n");
1795         ok(csinfoA.cs.LocalAddr.lpSockaddr != NULL, "Expected non-null\n");
1796         /* Socket is not connected, no information provided */
1797         ok(!csinfoA.cs.RemoteAddr.iSockaddrLength, "Expected 0, got %d\n", csinfoA.cs.RemoteAddr.iSockaddrLength);
1798         ok(csinfoA.cs.RemoteAddr.lpSockaddr == NULL, "Expected NULL, got %p\n", csinfoA.cs.RemoteAddr.lpSockaddr);
1799 
1800         err = bind(s2, (struct sockaddr*)&saddr, sizeof(saddr));
1801         ok(!err, "Expected 0, got %d\n", err);
1802         err = getsockname(s2, (struct sockaddr *)&saddr, &size);
1803         ok(!err, "Expected 0, got %d\n", err);
1804         err = listen(s2, 1);
1805         ok(!err, "Expected 0, got %d\n", err);
1806         err = connect(s, (struct sockaddr*)&saddr, sizeof(saddr));
1807         ok(!err, "Expected 0, got %d\n", err);
1808         size = sizeof(saddr);
1809         err = accept(s2, (struct sockaddr*)&saddr, &size);
1810         ok(err != INVALID_SOCKET, "Failed to accept socket\n");
1811         closesocket(s2);
1812         s2 = err;
1813 
1814         size = sizeof(csinfoA);
1815         err = getsockopt(s, SOL_SOCKET, SO_BSP_STATE, (char *) &csinfoA, &size);
1816         ok(!err, "Expected 0, got %d\n", err);
1817         err = getsockopt(s2, SOL_SOCKET, SO_BSP_STATE, (char *) &csinfoB, &size);
1818         ok(!err, "Expected 0, got %d\n", err);
1819         ok(size == sizeof(csinfoA), "Got %d\n", size);
1820         size = sizeof(saddr);
1821         ok(size == csinfoA.cs.LocalAddr.iSockaddrLength, "Expected %d, got %d\n", size,
1822            csinfoA.cs.LocalAddr.iSockaddrLength);
1823         ok(size == csinfoA.cs.RemoteAddr.iSockaddrLength, "Expected %d, got %d\n", size,
1824            csinfoA.cs.RemoteAddr.iSockaddrLength);
1825         ok(!memcmp(csinfoA.cs.LocalAddr.lpSockaddr, csinfoB.cs.RemoteAddr.lpSockaddr, size),
1826            "Expected matching addresses\n");
1827         ok(!memcmp(csinfoB.cs.LocalAddr.lpSockaddr, csinfoA.cs.RemoteAddr.lpSockaddr, size),
1828            "Expected matching addresses\n");
1829         ok(csinfoA.cs.iSocketType == SOCK_STREAM, "Wrong socket type\n");
1830         ok(csinfoB.cs.iSocketType == SOCK_STREAM, "Wrong socket type\n");
1831         ok(csinfoA.cs.iProtocol == IPPROTO_TCP, "Wrong socket protocol\n");
1832         ok(csinfoB.cs.iProtocol == IPPROTO_TCP, "Wrong socket protocol\n");
1833 
1834         err = getpeername(s, (struct sockaddr *)&saddr, &size);
1835         ok(!err, "Expected 0, got %d\n", err);
1836         ok(!memcmp(&saddr, csinfoA.cs.RemoteAddr.lpSockaddr, size), "Expected matching addresses\n");
1837         ok(!memcmp(&saddr, csinfoB.cs.LocalAddr.lpSockaddr, size), "Expected matching addresses\n");
1838         err = getpeername(s2, (struct sockaddr *)&saddr, &size);
1839         ok(!err, "Expected 0, got %d\n", err);
1840         ok(!memcmp(&saddr, csinfoB.cs.RemoteAddr.lpSockaddr, size), "Expected matching addresses\n");
1841         ok(!memcmp(&saddr, csinfoA.cs.LocalAddr.lpSockaddr, size), "Expected matching addresses\n");
1842         err = getsockname(s, (struct sockaddr *)&saddr, &size);
1843         ok(!err, "Expected 0, got %d\n", err);
1844         ok(!memcmp(&saddr, csinfoA.cs.LocalAddr.lpSockaddr, size), "Expected matching addresses\n");
1845         ok(!memcmp(&saddr, csinfoB.cs.RemoteAddr.lpSockaddr, size), "Expected matching addresses\n");
1846         err = getsockname(s2, (struct sockaddr *)&saddr, &size);
1847         ok(!err, "Expected 0, got %d\n", err);
1848         ok(!memcmp(&saddr, csinfoB.cs.LocalAddr.lpSockaddr, size), "Expected matching addresses\n");
1849         ok(!memcmp(&saddr, csinfoA.cs.RemoteAddr.lpSockaddr, size), "Expected matching addresses\n");
1850 
1851         SetLastError(0xdeadbeef);
1852         size = sizeof(CSADDR_INFO);
1853         err = getsockopt(s, SOL_SOCKET, SO_BSP_STATE, (char *) &csinfoA, &size);
1854         ok(err, "Expected non-zero\n");
1855         ok(size == sizeof(CSADDR_INFO), "Got %d\n", size);
1856         ok(GetLastError() == WSAEFAULT, "Expected 10014, got %d\n", GetLastError());
1857 
1858         /* At least for IPv4 the size is exactly 56 bytes */
1859         size = sizeof(*csinfoA.cs.LocalAddr.lpSockaddr) * 2 + sizeof(csinfoA.cs);
1860         err = getsockopt(s, SOL_SOCKET, SO_BSP_STATE, (char *) &csinfoA, &size);
1861         ok(!err, "Expected 0, got %d\n", err);
1862         size--;
1863         SetLastError(0xdeadbeef);
1864         err = getsockopt(s, SOL_SOCKET, SO_BSP_STATE, (char *) &csinfoA, &size);
1865         ok(err, "Expected non-zero\n");
1866         ok(GetLastError() == WSAEFAULT, "Expected 10014, got %d\n", GetLastError());
1867     }
1868     else
1869         ok(GetLastError() == WSAENOPROTOOPT, "Expected 10042, got %d\n", GetLastError());
1870 
1871     closesocket(s);
1872     closesocket(s2);
1873 
1874     for (i = 0; i < 2; i++)
1875     {
1876         int family, level;
1877 
1878         if (i)
1879         {
1880             family = AF_INET6;
1881             level = IPPROTO_IPV6;
1882         }
1883         else
1884         {
1885             family = AF_INET;
1886             level = IPPROTO_IP;
1887         }
1888 
1889         s = socket(family, SOCK_DGRAM, 0);
1890         if (s == INVALID_SOCKET && i)
1891         {
1892             skip("IPv6 is not supported\n");
1893             break;
1894         }
1895         ok(s != INVALID_SOCKET, "socket failed with error %d\n", GetLastError());
1896 
1897         size = sizeof(value);
1898         value = 0xdead;
1899         err = getsockopt(s, level, IP_DONTFRAGMENT, (char *) &value, &size);
1900         ok(!err, "Expected 0, got %d with error %d\n", err, GetLastError());
1901         ok(value == 0, "Expected 0, got %d\n", value);
1902 
1903         size = sizeof(value);
1904         value = 1;
1905         err = setsockopt(s, level, IP_DONTFRAGMENT, (char *) &value, size);
1906         ok(!err, "Expected 0, got %d with error %d\n", err, GetLastError());
1907 
1908         value = 0xdead;
1909         err = getsockopt(s, level, IP_DONTFRAGMENT, (char *) &value, &size);
1910         ok(!err, "Expected 0, got %d with error %d\n", err, GetLastError());
1911         ok(value == 1, "Expected 1, got %d\n", value);
1912 
1913         size = sizeof(value);
1914         value = 0xdead;
1915         err = setsockopt(s, level, IP_DONTFRAGMENT, (char *) &value, size);
1916         ok(!err, "Expected 0, got %d with error %d\n", err, GetLastError());
1917 
1918         err = getsockopt(s, level, IP_DONTFRAGMENT, (char *) &value, &size);
1919         ok(!err, "Expected 0, got %d with error %d\n", err, GetLastError());
1920         ok(value == 1, "Expected 1, got %d\n", value);
1921 
1922         closesocket(s);
1923     }
1924 }
1925 
1926 static void test_so_reuseaddr(void)
1927 {
1928     struct sockaddr_in saddr;
1929     SOCKET s1,s2;
1930     unsigned int rc,reuse;
1931     int size;
1932     DWORD err;
1933 
1934     saddr.sin_family      = AF_INET;
1935     saddr.sin_port        = htons(SERVERPORT+1);
1936     saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
1937 
1938     s1=socket(AF_INET, SOCK_STREAM, 0);
1939     ok(s1!=INVALID_SOCKET, "socket() failed error: %d\n", WSAGetLastError());
1940     rc = bind(s1, (struct sockaddr*)&saddr, sizeof(saddr));
1941     ok(rc!=SOCKET_ERROR, "bind(s1) failed error: %d\n", WSAGetLastError());
1942 
1943     s2=socket(AF_INET, SOCK_STREAM, 0);
1944     ok(s2!=INVALID_SOCKET, "socket() failed error: %d\n", WSAGetLastError());
1945 
1946     reuse=0x1234;
1947     size=sizeof(reuse);
1948     rc=getsockopt(s2, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, &size );
1949     ok(rc==0 && reuse==0,"wrong result in getsockopt(SO_REUSEADDR): rc=%d reuse=%d\n",rc,reuse);
1950 
1951     rc = bind(s2, (struct sockaddr*)&saddr, sizeof(saddr));
1952     ok(rc==SOCKET_ERROR, "bind() succeeded\n");
1953 
1954     reuse = 1;
1955     rc = setsockopt(s2, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse));
1956     ok(rc==0, "setsockopt() failed error: %d\n", WSAGetLastError());
1957 
1958     /* On Win2k3 and above, all SO_REUSEADDR seems to do is to allow binding to
1959      * a port immediately after closing another socket on that port, so
1960      * basically following the BSD socket semantics here. */
1961     rc = bind(s2, (struct sockaddr*)&saddr, sizeof(saddr));
1962     if(rc==0)
1963     {
1964         int s3=socket(AF_INET, SOCK_STREAM, 0), s4;
1965         trace("<= Win XP behavior of SO_REUSEADDR\n");
1966 
1967         /* If we could bind again in the same port this is Windows version <= XP.
1968          * Lets test if we can really connect to one of them. */
1969         set_blocking(s1, FALSE);
1970         set_blocking(s2, FALSE);
1971         rc = listen(s1, 1);
1972         ok(!rc, "listen() failed with error: %d\n", WSAGetLastError());
1973         rc = listen(s2, 1);
1974         ok(!rc, "listen() failed with error: %d\n", WSAGetLastError());
1975         rc = connect(s3, (struct sockaddr*)&saddr, sizeof(saddr));
1976         ok(!rc, "connecting to accepting socket failed %d\n", WSAGetLastError());
1977 
1978         /* the delivery of the connection is random so we need to try on both sockets */
1979         size = sizeof(saddr);
1980         s4 = accept(s1, (struct sockaddr*)&saddr, &size);
1981         if(s4 == INVALID_SOCKET)
1982             s4 = accept(s2, (struct sockaddr*)&saddr, &size);
1983         ok(s4 != INVALID_SOCKET, "none of the listening sockets could get the connection\n");
1984 
1985         closesocket(s1);
1986         closesocket(s3);
1987         closesocket(s4);
1988     }
1989     else
1990     {
1991         trace(">= Win 2003 behavior of SO_REUSEADDR\n");
1992         err = WSAGetLastError();
1993         ok(err==WSAEACCES, "expected 10013, got %d\n", err);
1994 
1995         closesocket(s1);
1996         rc = bind(s2, (struct sockaddr*)&saddr, sizeof(saddr));
1997         ok(rc==0, "bind() failed error: %d\n", WSAGetLastError());
1998     }
1999 
2000     closesocket(s2);
2001 }
2002 
2003 #define IP_PKTINFO_LEN (sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(sizeof(struct in_pktinfo)))
2004 
2005 static void test_ip_pktinfo(void)
2006 {
2007     ULONG addresses[2] = {inet_addr("127.0.0.1"), htonl(INADDR_ANY)};
2008     char recvbuf[10], pktbuf[512], msg[] = "HELLO";
2009     struct sockaddr_in s1addr, s2addr, s3addr;
2010     GUID WSARecvMsg_GUID = WSAID_WSARECVMSG;
2011     LPFN_WSARECVMSG pWSARecvMsg = NULL;
2012     unsigned int rc, yes = 1;
2013     BOOL foundhdr;
2014     DWORD dwBytes, dwSize, dwFlags;
2015     socklen_t addrlen;
2016     WSACMSGHDR *cmsg;
2017     WSAOVERLAPPED ov;
2018     WSABUF iovec[1];
2019     SOCKET s1, s2;
2020     WSAMSG hdr;
2021     int i, err;
2022 
2023     memset(&ov, 0, sizeof(ov));
2024     ov.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
2025     if (ov.hEvent == INVALID_HANDLE_VALUE)
2026     {
2027         skip("Could not create event object, some tests will be skipped. errno = %d\n", GetLastError());
2028         return;
2029     }
2030 
2031     memset(&hdr, 0x00, sizeof(hdr));
2032     s1addr.sin_family = AF_INET;
2033     s1addr.sin_port   = htons(0);
2034     /* Note: s1addr.sin_addr is set below */
2035     iovec[0].buf      = recvbuf;
2036     iovec[0].len      = sizeof(recvbuf);
2037     hdr.name          = (struct sockaddr*)&s3addr;
2038     hdr.namelen       = sizeof(s3addr);
2039     hdr.lpBuffers     = &iovec[0];
2040     hdr.dwBufferCount = 1;
2041     hdr.Control.buf   = pktbuf;
2042     /* Note: hdr.Control.len is set below */
2043     hdr.dwFlags       = 0;
2044 
2045     for (i=0;i<sizeof(addresses)/sizeof(UINT32);i++)
2046     {
2047         s1addr.sin_addr.s_addr = addresses[i];
2048 
2049         /* Build "server" side socket */
2050         s1=socket(AF_INET, SOCK_DGRAM, 0);
2051         if (s1 == INVALID_SOCKET)
2052         {
2053             skip("socket() failed error, some tests skipped: %d\n", WSAGetLastError());
2054             goto cleanup;
2055         }
2056 
2057         /* Obtain the WSARecvMsg function */
2058         WSAIoctl(s1, SIO_GET_EXTENSION_FUNCTION_POINTER, &WSARecvMsg_GUID, sizeof(WSARecvMsg_GUID),
2059                  &pWSARecvMsg, sizeof(pWSARecvMsg), &dwBytes, NULL, NULL);
2060         if (!pWSARecvMsg)
2061         {
2062             win_skip("WSARecvMsg is unsupported, some tests will be skipped.\n");
2063             closesocket(s1);
2064             goto cleanup;
2065         }
2066 
2067         /* Setup the server side socket */
2068         rc=bind(s1, (struct sockaddr*)&s1addr, sizeof(s1addr));
2069         ok(rc != SOCKET_ERROR, "bind() failed error: %d\n", WSAGetLastError());
2070         rc=setsockopt(s1, IPPROTO_IP, IP_PKTINFO, (const char*)&yes, sizeof(yes));
2071         ok(rc == 0, "failed to set IPPROTO_IP flag IP_PKTINFO!\n");
2072 
2073         /* Build "client" side socket */
2074         addrlen = sizeof(s2addr);
2075         if (getsockname(s1, (struct sockaddr *) &s2addr, &addrlen) != 0)
2076         {
2077             skip("Failed to call getsockname, some tests skipped: %d\n", WSAGetLastError());
2078             closesocket(s1);
2079             goto cleanup;
2080         }
2081         s2addr.sin_addr.s_addr = addresses[0]; /* Always target the local adapter address */
2082         s2=socket(AF_INET, SOCK_DGRAM, 0);
2083         if (s2 == INVALID_SOCKET)
2084         {
2085             skip("socket() failed error, some tests skipped: %d\n", WSAGetLastError());
2086             closesocket(s1);
2087             goto cleanup;
2088         }
2089 
2090         /* Test an empty message header */
2091         rc=pWSARecvMsg(s1, NULL, NULL, NULL, NULL);
2092         err=WSAGetLastError();
2093         ok(rc == SOCKET_ERROR && err == WSAEFAULT, "WSARecvMsg() failed error: %d (ret = %d)\n", err, rc);
2094 
2095         /*
2096          * Send a packet from the client to the server and test for specifying
2097          * a short control header.
2098          */
2099         SetLastError(0xdeadbeef);
2100         rc=sendto(s2, msg, sizeof(msg), 0, (struct sockaddr*)&s2addr, sizeof(s2addr));
2101         ok(rc == sizeof(msg), "sendto() failed error: %d\n", WSAGetLastError());
2102         ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
2103         hdr.Control.len = 1;
2104         rc=pWSARecvMsg(s1, &hdr, &dwSize, NULL, NULL);
2105         err=WSAGetLastError();
2106         ok(rc == SOCKET_ERROR && err == WSAEMSGSIZE && (hdr.dwFlags & MSG_CTRUNC),
2107            "WSARecvMsg() failed error: %d (ret: %d, flags: %d)\n", err, rc, hdr.dwFlags);
2108         hdr.dwFlags = 0; /* Reset flags */
2109 
2110         /* Perform another short control header test, this time with an overlapped receive */
2111         hdr.Control.len = 1;
2112         rc=pWSARecvMsg(s1, &hdr, NULL, &ov, NULL);
2113         err=WSAGetLastError();
2114         ok(rc != 0 && err == WSA_IO_PENDING, "WSARecvMsg() failed error: %d\n", err);
2115         SetLastError(0xdeadbeef);
2116         rc=sendto(s2, msg, sizeof(msg), 0, (struct sockaddr*)&s2addr, sizeof(s2addr));
2117         ok(rc == sizeof(msg), "sendto() failed error: %d\n", WSAGetLastError());
2118         ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
2119         if (WaitForSingleObject(ov.hEvent, 100) != WAIT_OBJECT_0)
2120         {
2121             skip("Server side did not receive packet, some tests skipped.\n");
2122             closesocket(s2);
2123             closesocket(s1);
2124             continue;
2125         }
2126         dwFlags = 0;
2127         WSAGetOverlappedResult(s1, &ov, NULL, FALSE, &dwFlags);
2128         ok(dwFlags == 0,
2129            "WSAGetOverlappedResult() returned unexpected flags %d!\n", dwFlags);
2130         ok(hdr.dwFlags == MSG_CTRUNC,
2131            "WSARecvMsg() overlapped operation set unexpected flags %d.\n", hdr.dwFlags);
2132         hdr.dwFlags = 0; /* Reset flags */
2133 
2134         /*
2135          * Setup an overlapped receive, send a packet, then wait for the packet to be retrieved
2136          * on the server end and check that the returned packet matches what was sent.
2137          */
2138         hdr.Control.len = sizeof(pktbuf);
2139         rc=pWSARecvMsg(s1, &hdr, NULL, &ov, NULL);
2140         err=WSAGetLastError();
2141         ok(rc != 0 && err == WSA_IO_PENDING, "WSARecvMsg() failed error: %d\n", err);
2142         ok(hdr.Control.len == sizeof(pktbuf),
2143            "WSARecvMsg() control length mismatch (%d != sizeof pktbuf).\n", hdr.Control.len);
2144         rc=sendto(s2, msg, sizeof(msg), 0, (struct sockaddr*)&s2addr, sizeof(s2addr));
2145         ok(rc == sizeof(msg), "sendto() failed error: %d\n", WSAGetLastError());
2146         if (WaitForSingleObject(ov.hEvent, 100) != WAIT_OBJECT_0)
2147         {
2148             skip("Server side did not receive packet, some tests skipped.\n");
2149             closesocket(s2);
2150             closesocket(s1);
2151             continue;
2152         }
2153         dwSize = 0;
2154         WSAGetOverlappedResult(s1, &ov, &dwSize, FALSE, NULL);
2155         ok(dwSize == sizeof(msg),
2156            "WSARecvMsg() buffer length does not match transmitted data!\n");
2157         ok(strncmp(iovec[0].buf, msg, sizeof(msg)) == 0,
2158            "WSARecvMsg() buffer does not match transmitted data!\n");
2159         ok(hdr.Control.len == IP_PKTINFO_LEN,
2160            "WSARecvMsg() control length mismatch (%d).\n", hdr.Control.len);
2161 
2162         /* Test for the expected IP_PKTINFO return information. */
2163         foundhdr = FALSE;
2164         for (cmsg = WSA_CMSG_FIRSTHDR(&hdr); cmsg != NULL; cmsg = WSA_CMSG_NXTHDR(&hdr, cmsg))
2165         {
2166             if (cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_PKTINFO)
2167             {
2168                 struct in_pktinfo *pi = (struct in_pktinfo *)WSA_CMSG_DATA(cmsg);
2169 
2170                 ok(pi->ipi_addr.s_addr == s2addr.sin_addr.s_addr, "destination ip mismatch!\n");
2171                 foundhdr = TRUE;
2172             }
2173         }
2174         ok(foundhdr, "IP_PKTINFO header information was not returned!\n");
2175 
2176         closesocket(s2);
2177         closesocket(s1);
2178     }
2179 
2180 cleanup:
2181     CloseHandle(ov.hEvent);
2182 }
2183 
2184 /************* Array containing the tests to run **********/
2185 
2186 #define STD_STREAM_SOCKET \
2187             SOCK_STREAM, \
2188             0, \
2189             SERVERIP, \
2190             SERVERPORT
2191 
2192 static test_setup tests [] =
2193 {
2194     /* Test 0: synchronous client and server */
2195     {
2196         {
2197             STD_STREAM_SOCKET,
2198             2048,
2199             16,
2200             2
2201         },
2202         simple_server,
2203         {
2204             NULL,
2205             0,
2206             64
2207         },
2208         simple_client,
2209         {
2210             NULL,
2211             0,
2212             128
2213         }
2214     },
2215     /* Test 1: event-driven client, synchronous server */
2216     {
2217         {
2218             STD_STREAM_SOCKET,
2219             2048,
2220             16,
2221             2
2222         },
2223         simple_server,
2224         {
2225             NULL,
2226             0,
2227             64
2228         },
2229         event_client,
2230         {
2231             NULL,
2232             WSA_FLAG_OVERLAPPED,
2233             128
2234         }
2235     },
2236     /* Test 2: synchronous client, non-blocking server via select() */
2237     {
2238         {
2239             STD_STREAM_SOCKET,
2240             2048,
2241             16,
2242             2
2243         },
2244         select_server,
2245         {
2246             NULL,
2247             0,
2248             64
2249         },
2250         simple_client,
2251         {
2252             NULL,
2253             0,
2254             128
2255         }
2256     },
2257     /* Test 3: OOB client, OOB server */
2258     {
2259         {
2260             STD_STREAM_SOCKET,
2261             128,
2262             16,
2263             1
2264         },
2265         oob_server,
2266         {
2267             NULL,
2268             0,
2269             128
2270         },
2271         oob_client,
2272         {
2273             NULL,
2274             0,
2275             128
2276         }
2277     },
2278     /* Test 4: synchronous mixed client and server */
2279     {
2280         {
2281             STD_STREAM_SOCKET,
2282             2048,
2283             16,
2284             2
2285         },
2286         simple_server,
2287         {
2288             NULL,
2289             0,
2290             64
2291         },
2292         simple_mixed_client,
2293         {
2294             NULL,
2295             0,
2296             128
2297         }
2298     }
2299 };
2300 
2301 static void test_UDP(void)
2302 {
2303     /* This function tests UDP sendto() and recvfrom(). UDP is unreliable, so it is
2304        possible that this test fails due to dropped packets. */
2305 
2306     /* peer 0 receives data from all other peers */
2307     struct sock_info peer[NUM_UDP_PEERS];
2308     char buf[16];
2309     int ss, i, n_recv, n_sent;
2310 
2311     memset (buf,0,sizeof(buf));
2312     for ( i = NUM_UDP_PEERS - 1; i >= 0; i-- ) {
2313         ok ( ( peer[i].s = socket ( AF_INET, SOCK_DGRAM, 0 ) ) != INVALID_SOCKET, "UDP: socket failed\n" );
2314 
2315         peer[i].addr.sin_family         = AF_INET;
2316         peer[i].addr.sin_addr.s_addr    = inet_addr ( SERVERIP );
2317 
2318         if ( i == 0 ) {
2319             peer[i].addr.sin_port       = htons ( SERVERPORT );
2320         } else {
2321             peer[i].addr.sin_port       = htons ( 0 );
2322         }
2323 
2324         do_bind ( peer[i].s, (struct sockaddr *) &peer[i].addr, sizeof( peer[i].addr ) );
2325 
2326         /* test getsockname() to get peer's port */
2327         ss = sizeof ( peer[i].addr );
2328         ok ( getsockname ( peer[i].s, (struct sockaddr *) &peer[i].addr, &ss ) != SOCKET_ERROR, "UDP: could not getsockname()\n" );
2329         ok ( peer[i].addr.sin_port != htons ( 0 ), "UDP: bind() did not associate port\n" );
2330     }
2331 
2332     /* test getsockname() */
2333     ok ( peer[0].addr.sin_port == htons ( SERVERPORT ), "UDP: getsockname returned incorrect peer port\n" );
2334 
2335     for ( i = 1; i < NUM_UDP_PEERS; i++ ) {
2336         /* send client's ip */
2337         memcpy( buf, &peer[i].addr.sin_port, sizeof(peer[i].addr.sin_port) );
2338         n_sent = sendto ( peer[i].s, buf, sizeof(buf), 0, (struct sockaddr*) &peer[0].addr, sizeof(peer[0].addr) );
2339         ok ( n_sent == sizeof(buf), "UDP: sendto() sent wrong amount of data or socket error: %d\n", n_sent );
2340     }
2341 
2342     for ( i = 1; i < NUM_UDP_PEERS; i++ ) {
2343         n_recv = recvfrom ( peer[0].s, buf, sizeof(buf), 0,(struct sockaddr *) &peer[0].peer, &ss );
2344         ok ( n_recv == sizeof(buf), "UDP: recvfrom() received wrong amount of data or socket error: %d\n", n_recv );
2345         ok ( memcmp ( &peer[0].peer.sin_port, buf, sizeof(peer[0].addr.sin_port) ) == 0, "UDP: port numbers do not match\n" );
2346     }
2347 }
2348 
2349 static DWORD WINAPI do_getservbyname( void *param )
2350 {
2351     struct {
2352         const char *name;
2353         const char *proto;
2354         int port;
2355     } serv[2] = { {"domain", "udp", 53}, {"telnet", "tcp", 23} };
2356 
2357     HANDLE *starttest = param;
2358     int i, j;
2359     struct servent *pserv[2];
2360 
2361     ok ( WaitForSingleObject ( *starttest, TEST_TIMEOUT * 1000 ) != WAIT_TIMEOUT,
2362          "test_getservbyname: timeout waiting for start signal\n" );
2363 
2364     /* ensure that necessary buffer resizes are completed */
2365     for ( j = 0; j < 2; j++) {
2366         pserv[j] = getservbyname ( serv[j].name, serv[j].proto );
2367     }
2368 
2369     for ( i = 0; i < NUM_QUERIES / 2; i++ ) {
2370         for ( j = 0; j < 2; j++ ) {
2371             pserv[j] = getservbyname ( serv[j].name, serv[j].proto );
2372             ok ( pserv[j] != NULL || broken(pserv[j] == NULL) /* win8, fixed in win81 */,
2373                  "getservbyname could not retrieve information for %s: %d\n", serv[j].name, WSAGetLastError() );
2374             if ( !pserv[j] ) continue;
2375             ok ( pserv[j]->s_port == htons(serv[j].port),
2376                  "getservbyname returned the wrong port for %s: %d\n", serv[j].name, ntohs(pserv[j]->s_port) );
2377             ok ( !strcmp ( pserv[j]->s_proto, serv[j].proto ),
2378                  "getservbyname returned the wrong protocol for %s: %s\n", serv[j].name, pserv[j]->s_proto );
2379             ok ( !strcmp ( pserv[j]->s_name, serv[j].name ),
2380                  "getservbyname returned the wrong name for %s: %s\n", serv[j].name, pserv[j]->s_name );
2381         }
2382 
2383         ok ( pserv[0] == pserv[1] || broken(pserv[0] != pserv[1]) /* win8, fixed in win81 */,
2384              "getservbyname: winsock resized servent buffer when not necessary\n" );
2385     }
2386 
2387     return 0;
2388 }
2389 
2390 static void test_getservbyname(void)
2391 {
2392     int i;
2393     HANDLE starttest, thread[NUM_THREADS];
2394     DWORD thread_id[NUM_THREADS];
2395 
2396     starttest = CreateEventA ( NULL, 1, 0, "test_getservbyname_starttest" );
2397 
2398     /* create threads */
2399     for ( i = 0; i < NUM_THREADS; i++ ) {
2400         thread[i] = CreateThread ( NULL, 0, do_getservbyname, &starttest, 0, &thread_id[i] );
2401     }
2402 
2403     /* signal threads to start */
2404     SetEvent ( starttest );
2405 
2406     for ( i = 0; i < NUM_THREADS; i++) {
2407         WaitForSingleObject ( thread[i], TEST_TIMEOUT * 1000 );
2408     }
2409 }
2410 
2411 static void test_WSASocket(void)
2412 {
2413     SOCKET sock = INVALID_SOCKET;
2414     WSAPROTOCOL_INFOA *pi;
2415     int wsaproviders[] = {IPPROTO_TCP, IPPROTO_IP};
2416     int autoprotocols[] = {IPPROTO_TCP, IPPROTO_UDP};
2417     int items, err, size, socktype, i, j;
2418     UINT pi_size;
2419 
2420     SetLastError(0xdeadbeef);
2421     ok(WSASocketA(0, 0, 0, NULL, 0, 0) == INVALID_SOCKET,
2422        "WSASocketA should have failed\n");
2423     err = WSAGetLastError();
2424     ok(err == WSAEINVAL, "Expected 10022, received %d\n", err);
2425 
2426     sock = WSASocketA(AF_INET, 0, 0, NULL, 0, 0);
2427     ok(sock != INVALID_SOCKET, "WSASocketA should have succeeded\n");
2428     closesocket(sock);
2429 
2430     sock = WSASocketA(AF_INET, SOCK_STREAM, 0, NULL, 0, 0);
2431     ok(sock != INVALID_SOCKET, "WSASocketA should have succeeded\n");
2432     closesocket(sock);
2433 
2434     SetLastError(0xdeadbeef);
2435     ok(WSASocketA(0, SOCK_STREAM, -1, NULL, 0, 0) == INVALID_SOCKET,
2436        "WSASocketA should have failed\n");
2437     err = WSAGetLastError();
2438     ok(err == WSAEPROTONOSUPPORT, "Expected 10043, received %d\n", err);
2439 
2440     SetLastError(0xdeadbeef);
2441     ok(WSASocketA(0, -1, IPPROTO_UDP, NULL, 0, 0) == INVALID_SOCKET,
2442        "WSASocketA should have failed\n");
2443     err = WSAGetLastError();
2444     ok(err == WSAESOCKTNOSUPPORT, "Expected 10044, received %d\n", err);
2445 
2446     SetLastError(0xdeadbeef);
2447     ok(WSASocketA(0, -1, 0, NULL, 0, 0) == INVALID_SOCKET,
2448        "WSASocketA should have failed\n");
2449     err = WSAGetLastError();
2450     ok(err == WSAEINVAL, "Expected 10022, received %d\n", err);
2451 
2452     SetLastError(0xdeadbeef);
2453     ok(WSASocketA(AF_INET, -1, 0, NULL, 0, 0) == INVALID_SOCKET,
2454        "WSASocketA should have failed\n");
2455     err = WSAGetLastError();
2456     ok(err == WSAESOCKTNOSUPPORT, "Expected 10044, received %d\n", err);
2457 
2458     SetLastError(0xdeadbeef);
2459     ok(WSASocketA(AF_INET, 0, -1, NULL, 0, 0) == INVALID_SOCKET,
2460        "WSASocketA should have failed\n");
2461     err = WSAGetLastError();
2462     ok(err == WSAEPROTONOSUPPORT, "Expected 10043, received %d\n", err);
2463 
2464     SetLastError(0xdeadbeef);
2465     ok(WSASocketA(0, -1, -1, NULL, 0, 0) == INVALID_SOCKET,
2466        "WSASocketA should have failed\n");
2467     err = WSAGetLastError();
2468     ok(err == WSAESOCKTNOSUPPORT, "Expected 10044, received %d\n", err);
2469 
2470     SetLastError(0xdeadbeef);
2471     ok(WSASocketA(-1, SOCK_STREAM, IPPROTO_UDP, NULL, 0, 0) == INVALID_SOCKET,
2472        "WSASocketA should have failed\n");
2473     err = WSAGetLastError();
2474     ok(err == WSAEAFNOSUPPORT, "Expected 10047, received %d\n", err);
2475 
2476     sock = WSASocketA(AF_INET, 0, IPPROTO_TCP, NULL, 0, 0);
2477     ok(sock != INVALID_SOCKET, "WSASocketA should have succeeded\n");
2478     closesocket(sock);
2479 
2480     SetLastError(0xdeadbeef);
2481     ok(WSASocketA(0, SOCK_STREAM, 0, NULL, 0, 0) == INVALID_SOCKET,
2482        "WSASocketA should have failed\n");
2483     err = WSAGetLastError();
2484     ok(err == WSAEINVAL, "Expected 10022, received %d\n", err);
2485 
2486     SetLastError(0xdeadbeef);
2487     ok(WSASocketA(0, 0, 0xdead, NULL, 0, 0) == INVALID_SOCKET,
2488        "WSASocketA should have failed\n");
2489     err = WSAGetLastError();
2490     ok(err == WSAEPROTONOSUPPORT, "Expected 10043, received %d\n", err);
2491 
2492     SetLastError(0xdeadbeef);
2493     ok(WSASocketA(AF_INET, 0xdead, 0, NULL, 0, 0) == INVALID_SOCKET,
2494        "WSASocketA should have failed\n");
2495     err = WSAGetLastError();
2496     ok(err == WSAESOCKTNOSUPPORT, "Expected 10044, received %d\n", err);
2497 
2498     SetLastError(0xdeadbeef);
2499     ok(WSASocketA(0, 0xdead, 0, NULL, 0, 0) == INVALID_SOCKET,
2500        "WSASocketA should have failed\n");
2501     err = WSAGetLastError();
2502     ok(err == WSAEINVAL, "Expected 10022, received %d\n", err);
2503 
2504     sock = WSASocketA(0, 0, IPPROTO_TCP, NULL, 0, 0);
2505     ok(sock != INVALID_SOCKET, "WSASocketA should have succeeded\n");
2506     closesocket(sock);
2507 
2508     /* SOCK_STREAM does not support IPPROTO_UDP */
2509     SetLastError(0xdeadbeef);
2510     ok(WSASocketA(AF_INET, SOCK_STREAM, IPPROTO_UDP, NULL, 0, 0) == INVALID_SOCKET,
2511        "WSASocketA should have failed\n");
2512     err = WSAGetLastError();
2513     ok(err == WSAEPROTONOSUPPORT, "Expected 10043, received %d\n", err);
2514 
2515     /* SOCK_DGRAM does not support IPPROTO_TCP */
2516     SetLastError(0xdeadbeef);
2517     ok(WSASocketA(AF_INET, SOCK_DGRAM, IPPROTO_TCP, NULL, 0, 0) == INVALID_SOCKET,
2518        "WSASocketA should have failed\n");
2519     err = WSAGetLastError();
2520     ok(err == WSAEPROTONOSUPPORT, "Expected 10043, received %d\n", err);
2521 
2522     /* Set pi_size explicitly to a value below 2*sizeof(WSAPROTOCOL_INFOA)
2523      * to avoid a crash on win98.
2524      */
2525     pi_size = 0;
2526     items = WSAEnumProtocolsA(wsaproviders, NULL, &pi_size);
2527     ok(items == SOCKET_ERROR, "WSAEnumProtocolsA({6,0}, NULL, 0) returned %d\n",
2528             items);
2529     err = WSAGetLastError();
2530     ok(err == WSAENOBUFS, "WSAEnumProtocolsA error is %d, not WSAENOBUFS(%d)\n",
2531             err, WSAENOBUFS);
2532 
2533     pi = HeapAlloc(GetProcessHeap(), 0, pi_size);
2534     ok(pi != NULL, "Failed to allocate memory\n");
2535     if (pi == NULL) {
2536         skip("Can't continue without memory.\n");
2537         return;
2538     }
2539 
2540     items = WSAEnumProtocolsA(wsaproviders, pi, &pi_size);
2541     ok(items != SOCKET_ERROR, "WSAEnumProtocolsA failed, last error is %d\n",
2542             WSAGetLastError());
2543 
2544     if (items == 0) {
2545         skip("No protocols enumerated.\n");
2546         HeapFree(GetProcessHeap(), 0, pi);
2547         return;
2548     }
2549 
2550     sock = WSASocketA(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
2551                       FROM_PROTOCOL_INFO, &pi[0], 0, 0);
2552     ok(sock != INVALID_SOCKET, "Failed to create socket: %d\n",
2553             WSAGetLastError());
2554     closesocket(sock);
2555 
2556     /* find what parameters are used first: plain parameters or protocol info struct */
2557     pi[0].iProtocol = -1;
2558     pi[0].iSocketType = -1;
2559     pi[0].iAddressFamily = -1;
2560     ok(WSASocketA(0, 0, IPPROTO_UDP, &pi[0], 0, 0) == INVALID_SOCKET,
2561        "WSASocketA should have failed\n");
2562     err = WSAGetLastError();
2563     ok(err == WSAEAFNOSUPPORT, "Expected 10047, received %d\n", err);
2564 
2565     pi[0].iProtocol = 0;
2566     pi[0].iSocketType = 0;
2567     pi[0].iAddressFamily = 0;
2568     sock = WSASocketA(0, 0, IPPROTO_UDP, &pi[0], 0, 0);
2569     if(sock != INVALID_SOCKET)
2570     {
2571       win_skip("must work only in OS <= 2003\n");
2572       closesocket(sock);
2573     }
2574     else
2575     {
2576       err = WSAGetLastError();
2577       ok(err == WSAEAFNOSUPPORT, "Expected 10047, received %d\n", err);
2578     }
2579 
2580     pi[0].iProtocol = IPPROTO_UDP;
2581     pi[0].iSocketType = SOCK_DGRAM;
2582     pi[0].iAddressFamily = AF_INET;
2583     sock = WSASocketA(0, 0, 0, &pi[0], 0, 0);
2584     ok(sock != INVALID_SOCKET, "Failed to create socket: %d\n",
2585             WSAGetLastError());
2586     size = sizeof(socktype);
2587     socktype = 0xdead;
2588     err = getsockopt(sock, SOL_SOCKET, SO_TYPE, (char *) &socktype, &size);
2589     ok(!err,"getsockopt failed with %d\n", WSAGetLastError());
2590     ok(socktype == SOCK_DGRAM, "Wrong socket type, expected %d received %d\n",
2591        SOCK_DGRAM, socktype);
2592     closesocket(sock);
2593 
2594     sock = WSASocketA(AF_INET, SOCK_STREAM, IPPROTO_TCP, &pi[0], 0, 0);
2595     ok(sock != INVALID_SOCKET, "Failed to create socket: %d\n",
2596             WSAGetLastError());
2597     size = sizeof(socktype);
2598     socktype = 0xdead;
2599     err = getsockopt(sock, SOL_SOCKET, SO_TYPE, (char *) &socktype, &size);
2600     ok(!err,"getsockopt failed with %d\n", WSAGetLastError());
2601     ok(socktype == SOCK_STREAM, "Wrong socket type, expected %d received %d\n",
2602        SOCK_STREAM, socktype);
2603     closesocket(sock);
2604 
2605     HeapFree(GetProcessHeap(), 0, pi);
2606 
2607     pi_size = 0;
2608     items = WSAEnumProtocolsA(NULL, NULL, &pi_size);
2609     ok(items == SOCKET_ERROR, "WSAEnumProtocolsA(NULL, NULL, 0) returned %d\n",
2610             items);
2611     err = WSAGetLastError();
2612     ok(err == WSAENOBUFS, "WSAEnumProtocolsA error is %d, not WSAENOBUFS(%d)\n",
2613             err, WSAENOBUFS);
2614 
2615     pi = HeapAlloc(GetProcessHeap(), 0, pi_size);
2616     ok(pi != NULL, "Failed to allocate memory\n");
2617     if (pi == NULL) {
2618         skip("Can't continue without memory.\n");
2619         return;
2620     }
2621 
2622     items = WSAEnumProtocolsA(NULL, pi, &pi_size);
2623     ok(items != SOCKET_ERROR, "WSAEnumProtocolsA failed, last error is %d\n",
2624             WSAGetLastError());
2625 
2626     /* when no protocol and socket type are specified the first entry
2627      * from WSAEnumProtocols that has the flag PFL_MATCHES_PROTOCOL_ZERO
2628      * is returned */
2629     sock = WSASocketA(AF_INET, 0, 0, NULL, 0, 0);
2630     ok(sock != INVALID_SOCKET, "Failed to create socket: %d\n",
2631             WSAGetLastError());
2632 
2633     size = sizeof(socktype);
2634     socktype = 0xdead;
2635     err = getsockopt(sock, SOL_SOCKET, SO_TYPE, (char *) &socktype, &size);
2636     ok(!err, "getsockopt failed with %d\n", WSAGetLastError());
2637     for(i = 0; i < items; i++)
2638     {
2639         if(pi[i].dwProviderFlags & PFL_MATCHES_PROTOCOL_ZERO)
2640         {
2641             ok(socktype == pi[i].iSocketType, "Wrong socket type, expected %d received %d\n",
2642                pi[i].iSocketType, socktype);
2643              break;
2644         }
2645     }
2646     ok(i != items, "Creating a socket without protocol and socket type didn't work\n");
2647     closesocket(sock);
2648 
2649     /* when no socket type is specified the first entry from WSAEnumProtocols
2650      * that matches the protocol is returned */
2651     for (i = 0; i < sizeof(autoprotocols) / sizeof(autoprotocols[0]); i++)
2652     {
2653         sock = WSASocketA(0, 0, autoprotocols[i], NULL, 0, 0);
2654         ok(sock != INVALID_SOCKET, "Failed to create socket for protocol %d, received %d\n",
2655                 autoprotocols[i], WSAGetLastError());
2656 
2657         size = sizeof(socktype);
2658         socktype = 0xdead;
2659         err = getsockopt(sock, SOL_SOCKET, SO_TYPE, (char *) &socktype, &size);
2660         ok(!err, "getsockopt failed with %d\n", WSAGetLastError());
2661 
2662         for (err = 1, j = 0; j < items; j++)
2663         {
2664             if (pi[j].iProtocol == autoprotocols[i])
2665             {
2666                 if (socktype == pi[j].iSocketType)
2667                     err = 0;
2668                 else
2669                     ok(0, "Wrong socket type, expected %d received %d\n",
2670                        pi[j].iSocketType, socktype);
2671                 break;
2672             }
2673         }
2674         ok(!err, "Protocol %d not found in WSAEnumProtocols\n", autoprotocols[i]);
2675 
2676         closesocket(sock);
2677     }
2678 
2679     HeapFree(GetProcessHeap(), 0, pi);
2680 
2681     SetLastError(0xdeadbeef);
2682     /* starting on vista the socket function returns error during the socket
2683        creation and no longer in the socket operations (sendto, readfrom) */
2684     sock = WSASocketA(AF_INET, SOCK_RAW, IPPROTO_ICMP, NULL, 0, 0);
2685     if (sock == INVALID_SOCKET)
2686     {
2687         err = WSAGetLastError();
2688         ok(err == WSAEACCES, "Expected 10013, received %d\n", err);
2689         skip("SOCK_RAW is not supported\n");
2690     }
2691     else
2692     {
2693         trace("SOCK_RAW is supported\n");
2694 
2695         size = sizeof(socktype);
2696         socktype = 0xdead;
2697         err = getsockopt(sock, SOL_SOCKET, SO_TYPE, (char *) &socktype, &size);
2698         ok(!err, "getsockopt failed with %d\n", WSAGetLastError());
2699         ok(socktype == SOCK_RAW, "Wrong socket type, expected %d received %d\n",
2700            SOCK_RAW, socktype);
2701         closesocket(sock);
2702 
2703         todo_wine {
2704         sock = WSASocketA(0, 0, IPPROTO_RAW, NULL, 0, 0);
2705         ok(sock != INVALID_SOCKET, "Failed to create socket: %d\n",
2706            WSAGetLastError());
2707         size = sizeof(socktype);
2708         socktype = 0xdead;
2709         err = getsockopt(sock, SOL_SOCKET, SO_TYPE, (char *) &socktype, &size);
2710         ok(!err, "getsockopt failed with %d\n", WSAGetLastError());
2711         ok(socktype == SOCK_RAW, "Wrong socket type, expected %d received %d\n",
2712            SOCK_RAW, socktype);
2713         closesocket(sock);
2714         }
2715 
2716         sock = WSASocketA(AF_INET, SOCK_RAW, IPPROTO_TCP, NULL, 0, 0);
2717         ok(sock != INVALID_SOCKET, "Failed to create socket: %d\n",
2718            WSAGetLastError());
2719         size = sizeof(socktype);
2720         socktype = 0xdead;
2721         err = getsockopt(sock, SOL_SOCKET, SO_TYPE, (char *) &socktype, &size);
2722         ok(!err, "getsockopt failed with %d\n", WSAGetLastError());
2723         ok(socktype == SOCK_RAW, "Wrong socket type, expected %d received %d\n",
2724            SOCK_RAW, socktype);
2725         closesocket(sock);
2726     }
2727 
2728     /* IPX socket tests */
2729 
2730     SetLastError(0xdeadbeef);
2731     sock = WSASocketA(AF_IPX, SOCK_DGRAM, NSPROTO_IPX, NULL, 0, 0);
2732     if (sock == INVALID_SOCKET)
2733     {
2734         err = WSAGetLastError();
2735         todo_wine_if (err == WSAEPROTONOSUPPORT)
2736         ok(err == WSAEAFNOSUPPORT || broken(err == WSAEPROTONOSUPPORT), "Expected 10047, received %d\n", err);
2737         skip("IPX is not supported\n");
2738     }
2739     else
2740     {
2741         WSAPROTOCOL_INFOA info;
2742         closesocket(sock);
2743 
2744         trace("IPX is supported\n");
2745 
2746         sock = WSASocketA(0, 0, NSPROTO_IPX, NULL, 0, 0);
2747         ok(sock != INVALID_SOCKET, "Failed to create socket: %d\n",
2748                 WSAGetLastError());
2749 
2750         size = sizeof(socktype);
2751         socktype = 0xdead;
2752         err = getsockopt(sock, SOL_SOCKET, SO_TYPE, (char *) &socktype, &size);
2753         ok(!err,"getsockopt failed with %d\n", WSAGetLastError());
2754         ok(socktype == SOCK_DGRAM, "Wrong socket type, expected %d received %d\n",
2755            SOCK_DGRAM, socktype);
2756 
2757         /* check socket family, type and protocol */
2758         size = sizeof(WSAPROTOCOL_INFOA);
2759         err = getsockopt(sock, SOL_SOCKET, SO_PROTOCOL_INFOA, (char *) &info, &size);
2760         ok(!err,"getsockopt failed with %d\n", WSAGetLastError());
2761         ok(info.iProtocol == NSPROTO_IPX, "expected protocol %d, received %d\n",
2762            NSPROTO_IPX, info.iProtocol);
2763         ok(info.iAddressFamily == AF_IPX, "expected family %d, received %d\n",
2764            AF_IPX, info.iProtocol);
2765         ok(info.iSocketType == SOCK_DGRAM, "expected type %d, received %d\n",
2766            SOCK_DGRAM, info.iSocketType);
2767         closesocket(sock);
2768 
2769         /* SOCK_STREAM does not support NSPROTO_IPX */
2770         SetLastError(0xdeadbeef);
2771         ok(WSASocketA(AF_IPX, SOCK_STREAM, NSPROTO_IPX, NULL, 0, 0) == INVALID_SOCKET,
2772            "WSASocketA should have failed\n");
2773         err = WSAGetLastError();
2774         ok(err == WSAEPROTONOSUPPORT, "Expected 10043, received %d\n", err);
2775 
2776         /* test extended IPX support - that is adding any number between 0 and 255
2777          * to the IPX protocol value will make it be used as IPX packet type */
2778         for(i = 0;i <= 255;i += 17)
2779         {
2780           SetLastError(0xdeadbeef);
2781           sock = WSASocketA(0, 0, NSPROTO_IPX + i, NULL, 0, 0);
2782           ok(sock != INVALID_SOCKET, "Failed to create socket: %d\n",
2783                   WSAGetLastError());
2784 
2785           size = sizeof(int);
2786           socktype = -1;
2787           err = getsockopt(sock, NSPROTO_IPX, IPX_PTYPE, (char *) &socktype, &size);
2788           ok(!err, "getsockopt failed with %d\n", WSAGetLastError());
2789           ok(socktype == i, "Wrong IPX packet type, expected %d received %d\n",
2790              i, socktype);
2791 
2792           closesocket(sock);
2793         }
2794     }
2795 }
2796 
2797 static void test_WSADuplicateSocket(void)
2798 {
2799     SOCKET source, dupsock;
2800     WSAPROTOCOL_INFOA info;
2801     DWORD err;
2802     struct sockaddr_in addr;
2803     int socktype, size, addrsize, ret;
2804     char teststr[] = "TEST", buffer[16];
2805 
2806     source = WSASocketA(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0);
2807     ok(source != INVALID_SOCKET, "WSASocketA should have succeeded\n");
2808 
2809     /* test invalid parameters */
2810     SetLastError(0xdeadbeef);
2811     ok(WSADuplicateSocketA(0, 0, NULL), "WSADuplicateSocketA should have failed\n");
2812     err = WSAGetLastError();
2813     ok(err == WSAENOTSOCK, "expected 10038, received %d\n", err);
2814 
2815     SetLastError(0xdeadbeef);
2816     ok(WSADuplicateSocketA(source, 0, NULL),
2817        "WSADuplicateSocketA should have failed\n");
2818     err = WSAGetLastError();
2819     ok(err == WSAEINVAL, "expected 10022, received %d\n", err);
2820 
2821     SetLastError(0xdeadbeef);
2822     ok(WSADuplicateSocketA(source, ~0, &info),
2823        "WSADuplicateSocketA should have failed\n");
2824     err = WSAGetLastError();
2825     ok(err == WSAEINVAL, "expected 10022, received %d\n", err);
2826 
2827     SetLastError(0xdeadbeef);
2828     ok(WSADuplicateSocketA(0, GetCurrentProcessId(), &info),
2829        "WSADuplicateSocketA should have failed\n");
2830     err = WSAGetLastError();
2831     ok(err == WSAENOTSOCK, "expected 10038, received %d\n", err);
2832 
2833     SetLastError(0xdeadbeef);
2834     ok(WSADuplicateSocketA(source, GetCurrentProcessId(), NULL),
2835        "WSADuplicateSocketA should have failed\n");
2836     err = WSAGetLastError();
2837     ok(err == WSAEFAULT, "expected 10014, received %d\n", err);
2838 
2839     /* test returned structure */
2840     memset(&info, 0, sizeof(info));
2841     ok(!WSADuplicateSocketA(source, GetCurrentProcessId(), &info),
2842        "WSADuplicateSocketA should have worked\n");
2843 
2844     ok(info.iProtocol == IPPROTO_TCP, "expected protocol %d, received %d\n",
2845        IPPROTO_TCP, info.iProtocol);
2846     ok(info.iAddressFamily == AF_INET, "expected family %d, received %d\n",
2847        AF_INET, info.iProtocol);
2848     ok(info.iSocketType == SOCK_STREAM, "expected type %d, received %d\n",
2849        SOCK_STREAM, info.iSocketType);
2850 
2851     dupsock = WSASocketA(0, 0, 0, &info, 0, 0);
2852     ok(dupsock != INVALID_SOCKET, "WSASocketA should have succeeded\n");
2853 
2854     closesocket(dupsock);
2855     closesocket(source);
2856 
2857     /* create a socket, bind it, duplicate it then send data on source and
2858      * receive in the duplicated socket */
2859     source = WSASocketA(AF_INET, SOCK_DGRAM, IPPROTO_UDP, NULL, 0, 0);
2860     ok(source != INVALID_SOCKET, "WSASocketA should have succeeded\n");
2861 
2862     memset(&info, 0, sizeof(info));
2863     ok(!WSADuplicateSocketA(source, GetCurrentProcessId(), &info),
2864        "WSADuplicateSocketA should have worked\n");
2865 
2866     ok(info.iProtocol == IPPROTO_UDP, "expected protocol %d, received %d\n",
2867        IPPROTO_UDP, info.iProtocol);
2868     ok(info.iAddressFamily == AF_INET, "expected family %d, received %d\n",
2869        AF_INET, info.iProtocol);
2870     ok(info.iSocketType == SOCK_DGRAM, "expected type %d, received %d\n",
2871        SOCK_DGRAM, info.iSocketType);
2872 
2873     memset(&addr, 0, sizeof(addr));
2874     addr.sin_family = AF_INET;
2875     addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2876     ok(!bind(source, (struct sockaddr*)&addr, sizeof(addr)),
2877        "bind should have worked\n");
2878 
2879     /* read address to find out the port number to be used in sendto */
2880     memset(&addr, 0, sizeof(addr));
2881     addrsize = sizeof(addr);
2882     ok(!getsockname(source, (struct sockaddr *) &addr, &addrsize),
2883        "getsockname should have worked\n");
2884     ok(addr.sin_port, "socket port should be != 0\n");
2885 
2886     dupsock = WSASocketA(0, 0, 0, &info, 0, 0);
2887     ok(dupsock != INVALID_SOCKET, "WSASocketA should have succeeded\n");
2888 
2889     size = sizeof(int);
2890     ret = getsockopt(dupsock, SOL_SOCKET, SO_TYPE, (char *) &socktype, &size);
2891     ok(!ret, "getsockopt failed with %d\n", WSAGetLastError());
2892     ok(socktype == SOCK_DGRAM, "Wrong socket type, expected %d received %d\n",
2893        SOCK_DGRAM, socktype);
2894 
2895     set_blocking(source, TRUE);
2896 
2897     /* send data on source socket */
2898     addrsize = sizeof(addr);
2899     size = sendto(source, teststr, sizeof(teststr), 0, (struct sockaddr *) &addr, addrsize);
2900     ok(size == sizeof(teststr), "got %d (err %d)\n", size, WSAGetLastError());
2901 
2902     /* receive on duplicated socket */
2903     addrsize = sizeof(addr);
2904     memset(buffer, 0, sizeof(buffer));
2905     size = recvfrom(dupsock, buffer, sizeof(teststr), 0, (struct sockaddr *) &addr, &addrsize);
2906     ok(size == sizeof(teststr), "got %d (err %d)\n", size, WSAGetLastError());
2907     buffer[sizeof(teststr) - 1] = 0;
2908     ok(!strcmp(buffer, teststr), "expected '%s', received '%s'\n", teststr, buffer);
2909 
2910     closesocket(dupsock);
2911     closesocket(source);
2912 
2913     /* show that the source socket need to be bound before the duplicated
2914      * socket is created */
2915     source = WSASocketA(AF_INET, SOCK_DGRAM, IPPROTO_UDP, NULL, 0, 0);
2916     ok(source != INVALID_SOCKET, "WSASocketA should have succeeded\n");
2917 
2918     memset(&info, 0, sizeof(info));
2919     ok(!WSADuplicateSocketA(source, GetCurrentProcessId(), &info),
2920        "WSADuplicateSocketA should have worked\n");
2921 
2922     dupsock = WSASocketA(0, 0, 0, &info, 0, 0);
2923     ok(dupsock != INVALID_SOCKET, "WSASocketA should have succeeded\n");
2924 
2925     memset(&addr, 0, sizeof(addr));
2926     addr.sin_family = AF_INET;
2927     addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2928     ok(!bind(source, (struct sockaddr*)&addr, sizeof(addr)),
2929        "bind should have worked\n");
2930 
2931     /* read address to find out the port number to be used in sendto */
2932     memset(&addr, 0, sizeof(addr));
2933     addrsize = sizeof(addr);
2934     ok(!getsockname(source, (struct sockaddr *) &addr, &addrsize),
2935        "getsockname should have worked\n");
2936     ok(addr.sin_port, "socket port should be != 0\n");
2937 
2938     set_blocking(source, TRUE);
2939 
2940     addrsize = sizeof(addr);
2941     size = sendto(source, teststr, sizeof(teststr), 0, (struct sockaddr *) &addr, addrsize);
2942     ok(size == sizeof(teststr), "got %d (err %d)\n", size, WSAGetLastError());
2943 
2944     SetLastError(0xdeadbeef);
2945     addrsize = sizeof(addr);
2946     memset(buffer, 0, sizeof(buffer));
2947     todo_wine {
2948     ok(recvfrom(dupsock, buffer, sizeof(teststr), 0, (struct sockaddr *) &addr, &addrsize) == -1,
2949        "recvfrom should have failed\n");
2950     err = WSAGetLastError();
2951     ok(err == WSAEINVAL, "expected 10022, received %d\n", err);
2952     }
2953 
2954     closesocket(dupsock);
2955     closesocket(source);
2956 }
2957 
2958 static void test_WSAEnumNetworkEvents(void)
2959 {
2960     SOCKET s, s2;
2961     int sock_type[] = {SOCK_STREAM, SOCK_DGRAM, SOCK_STREAM}, i, j, k, l;
2962     struct sockaddr_in address;
2963     HANDLE event;
2964     WSANETWORKEVENTS net_events;
2965 
2966     memset(&address, 0, sizeof(address));
2967     address.sin_addr.s_addr = htonl(INADDR_ANY);
2968     address.sin_family = AF_INET;
2969 
2970     /* This test follows the steps from bugs 10204 and 24946 */
2971     for (l = 0; l < 2; l++)
2972     {
2973         for (i = 0; i < sizeof(sock_type) / sizeof(sock_type[0]); i++)
2974         {
2975             if (i == 2)
2976                 ok(!tcp_socketpair(&s, &s2), "Test[%d]: creating socket pair failed\n", i);
2977             else
2978             {
2979                 s = socket(AF_INET, sock_type[i], 0);
2980                 ok (s != SOCKET_ERROR, "Test[%d]: failed to create socket\n", i);
2981                 ok (!bind(s, (struct sockaddr*) &address, sizeof(address)), "Test[%d]: bind failed\n", i);
2982             }
2983             event = WSACreateEvent();
2984             ok (event != NULL, "Test[%d]: failed to create event\n", i);
2985             for (j = 0; j < 5; j++) /* Repeat sometimes and the result must be the same */
2986             {
2987                 /* When the TCP socket is not connected NO events will be returned.
2988                  * When connected and no data pending it will get the write event.
2989                  * UDP sockets don't have connections so as soon as they are bound
2990                  * they can read/write data. Since nobody is sendind us data only
2991                  * the write event will be returned and ONLY once.
2992                  */
2993                 ok (!WSAEventSelect(s, event, FD_READ | FD_WRITE), "Test[%d]: WSAEventSelect failed\n", i);
2994                 memset(&net_events, 0xAB, sizeof(net_events));
2995                 ok (!WSAEnumNetworkEvents(s, l == 0 ? event : NULL, &net_events),
2996                     "Test[%d]: WSAEnumNetworkEvents failed\n", i);
2997                 if (i >= 1 && j == 0) /* FD_WRITE is SET on first try for UDP and connected TCP */
2998                 {
2999                     todo_wine_if (i == 0 || net_events.lNetworkEvents == 0)
3000                         ok (net_events.lNetworkEvents == FD_WRITE, "Test[%d]: expected 2, got %d\n",
3001                             i, net_events.lNetworkEvents);
3002                 }
3003                 else
3004                 {
3005                     todo_wine_if (i != 0 && net_events.lNetworkEvents != 0)
3006                         ok (net_events.lNetworkEvents == 0, "Test[%d]: expected 0, got %d\n",
3007                             i, net_events.lNetworkEvents);
3008                 }
3009                 for (k = 0; k < FD_MAX_EVENTS; k++)
3010                 {
3011                     if (net_events.lNetworkEvents & (1 << k))
3012                     {
3013                         ok (net_events.iErrorCode[k] == 0x0, "Test[%d][%d]: expected 0x0, got 0x%x\n",
3014                             i, k, net_events.iErrorCode[k]);
3015                     }
3016                     else
3017                     {
3018                         /* Bits that are not set in lNetworkEvents MUST not be changed */
3019                         ok (net_events.iErrorCode[k] == 0xABABABAB, "Test[%d][%d]: expected 0xABABABAB, got 0x%x\n",
3020                             i, k, net_events.iErrorCode[k]);
3021                     }
3022                 }
3023             }
3024             closesocket(s);
3025             WSACloseEvent(event);
3026             if (i == 2) closesocket(s2);
3027         }
3028     }
3029 }
3030 
3031 static void test_WSAAddressToStringA(void)
3032 {
3033     SOCKET v6 = INVALID_SOCKET;
3034     INT ret;
3035     DWORD len;
3036     int GLE;
3037     SOCKADDR_IN sockaddr;
3038     CHAR address[22]; /* 12 digits + 3 dots + ':' + 5 digits + '\0' */
3039 
3040     CHAR expect1[] = "0.0.0.0";
3041     CHAR expect2[] = "255.255.255.255";
3042     CHAR expect3[] = "0.0.0.0:65535";
3043     CHAR expect4[] = "255.255.255.255:65535";
3044 
3045     SOCKADDR_IN6 sockaddr6;
3046     CHAR address6[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
3047 
3048     CHAR addr6_1[] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01};
3049     CHAR addr6_2[] = {0x20,0xab,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01};
3050     CHAR addr6_3[] = {0x20,0xab,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x01};
3051 
3052     CHAR expect6_1[] = "::1";
3053     CHAR expect6_2[] = "20ab::1";
3054     CHAR expect6_3[] = "[20ab::2001]:33274";
3055     CHAR expect6_3_2[] = "[20ab::2001%4660]:33274";
3056     CHAR expect6_3_3[] = "20ab::2001%4660";
3057 
3058     len = 0;
3059 
3060     sockaddr.sin_family = AF_INET;
3061     sockaddr.sin_port = 0;
3062     sockaddr.sin_addr.s_addr = 0;
3063 
3064     ret = WSAAddressToStringA( (SOCKADDR*)&sockaddr, sizeof(sockaddr), NULL, address, &len );
3065     GLE = WSAGetLastError();
3066     ok( (ret == SOCKET_ERROR && GLE == WSAEFAULT) || (ret == 0),
3067         "WSAAddressToStringA() failed unexpectedly: WSAGetLastError()=%d, ret=%d\n",
3068         GLE, ret );
3069 
3070     len = sizeof(address);
3071 
3072     sockaddr.sin_family = AF_INET;
3073     sockaddr.sin_port = 0;
3074     sockaddr.sin_addr.s_addr = 0;
3075 
3076     ret = WSAAddressToStringA( (SOCKADDR*)&sockaddr, sizeof(sockaddr), NULL, address, &len );
3077     ok( !ret, "WSAAddressToStringA() failed unexpectedly: %d\n", WSAGetLastError() );
3078 
3079     ok( !strcmp( address, expect1 ), "Expected: %s, got: %s\n", expect1, address );
3080     ok( len == sizeof( expect1 ), "Got size %d\n", len);
3081 
3082     len = sizeof(address);
3083 
3084     sockaddr.sin_family = AF_INET;
3085     sockaddr.sin_port = 0;
3086     sockaddr.sin_addr.s_addr = 0xffffffff;
3087 
3088     ret = WSAAddressToStringA( (SOCKADDR*)&sockaddr, sizeof(sockaddr), NULL, address, &len );
3089     ok( !ret, "WSAAddressToStringA() failed unexpectedly: %d\n", WSAGetLastError() );
3090 
3091     ok( !strcmp( address, expect2 ), "Expected: %s, got: %s\n", expect2, address );
3092 
3093     len = sizeof(address);
3094 
3095     sockaddr.sin_family = AF_INET;
3096     sockaddr.sin_port = 0xffff;
3097     sockaddr.sin_addr.s_addr = 0;
3098 
3099     ret = WSAAddressToStringA( (SOCKADDR*)&sockaddr, sizeof(sockaddr), NULL, address, &len );
3100     ok( !ret, "WSAAddressToStringA() failed unexpectedly: %d\n", WSAGetLastError() );
3101 
3102     ok( !strcmp( address, expect3 ), "Expected: %s, got: %s\n", expect3, address );
3103 
3104     len = sizeof(address);
3105 
3106     sockaddr.sin_family = AF_INET;
3107     sockaddr.sin_port = 0xffff;
3108     sockaddr.sin_addr.s_addr = 0xffffffff;
3109 
3110     ret = WSAAddressToStringA( (SOCKADDR*)&sockaddr, sizeof(sockaddr), NULL, address, &len );
3111     ok( !ret, "WSAAddressToStringA() failed unexpectedly: %d\n", WSAGetLastError() );
3112 
3113     ok( !strcmp( address, expect4 ), "Expected: %s, got: %s\n", expect4, address );
3114     ok( len == sizeof( expect4 ), "Got size %d\n", len);
3115 
3116     /*check to see it IPv6 is available */
3117     v6 = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
3118     if (v6 == INVALID_SOCKET) {
3119         skip("Could not create IPv6 socket (LastError: %d; %d expected if IPv6 not available).\n",
3120             WSAGetLastError(), WSAEAFNOSUPPORT);
3121         goto end;
3122     }
3123     /* Test a short IPv6 address */
3124     len = sizeof(address6);
3125 
3126     sockaddr6.sin6_family = AF_INET6;
3127     sockaddr6.sin6_port = 0x0000;
3128     sockaddr6.sin6_scope_id = 0;
3129     memcpy (sockaddr6.sin6_addr.s6_addr, addr6_1, sizeof(addr6_1));
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_1 ), "Expected: %s, got: %s\n", expect6_1, address6 );
3134     ok( len == sizeof(expect6_1), "Got size %d\n", len);
3135 
3136     /* Test a longer IPv6 address */
3137     len = sizeof(address6);
3138 
3139     sockaddr6.sin6_family = AF_INET6;
3140     sockaddr6.sin6_port = 0x0000;
3141     sockaddr6.sin6_scope_id = 0;
3142     memcpy (sockaddr6.sin6_addr.s6_addr, addr6_2, sizeof(addr6_2));
3143 
3144     ret = WSAAddressToStringA( (SOCKADDR*)&sockaddr6, sizeof(sockaddr6), NULL, address6, &len );
3145     ok( !ret, "WSAAddressToStringA() failed unexpectedly: %d\n", WSAGetLastError() );
3146     ok( !strcmp( address6, expect6_2 ), "Expected: %s, got: %s\n", expect6_2, address6 );
3147     ok( len == sizeof(expect6_2), "Got size %d\n", len);
3148 
3149     /* Test IPv6 address and port number */
3150     len = sizeof(address6);
3151 
3152     sockaddr6.sin6_family = AF_INET6;
3153     sockaddr6.sin6_port = 0xfa81;
3154     sockaddr6.sin6_scope_id = 0;
3155     memcpy (sockaddr6.sin6_addr.s6_addr, addr6_3, sizeof(addr6_3));
3156 
3157     ret = WSAAddressToStringA( (SOCKADDR*)&sockaddr6, sizeof(sockaddr6), NULL, address6, &len );
3158     ok( !ret, "WSAAddressToStringA() failed unexpectedly: %d\n", WSAGetLastError() );
3159     ok( !strcmp( address6, expect6_3 ), "Expected: %s, got: %s\n", expect6_3, address6 );
3160     ok( len == sizeof(expect6_3), "Got size %d\n", len );
3161 
3162     /* Test IPv6 address, port number and scope_id */
3163     len = sizeof(address6);
3164 
3165     sockaddr6.sin6_family = AF_INET6;
3166     sockaddr6.sin6_port = 0xfa81;
3167     sockaddr6.sin6_scope_id = 0x1234;
3168     memcpy (sockaddr6.sin6_addr.s6_addr, addr6_3, sizeof(addr6_3));
3169 
3170     ret = WSAAddressToStringA( (SOCKADDR*)&sockaddr6, sizeof(sockaddr6), NULL, address6, &len );
3171     ok( !ret, "WSAAddressToStringA() failed unexpectedly: %d\n", WSAGetLastError() );
3172     ok( !strcmp( address6, expect6_3_2 ), "Expected: %s, got: %s\n", expect6_3_2, address6 );
3173     ok( len == sizeof(expect6_3_2), "Got size %d\n", len );
3174 
3175     /* Test IPv6 address and scope_id */
3176     len = sizeof(address6);
3177 
3178     sockaddr6.sin6_family = AF_INET6;
3179     sockaddr6.sin6_port = 0x0000;
3180     sockaddr6.sin6_scope_id = 0x1234;
3181     memcpy (sockaddr6.sin6_addr.s6_addr, addr6_3, sizeof(addr6_3));
3182 
3183     ret = WSAAddressToStringA( (SOCKADDR*)&sockaddr6, sizeof(sockaddr6), NULL, address6, &len );
3184     ok( !ret, "WSAAddressToStringA() failed unexpectedly: %d\n", WSAGetLastError() );
3185     ok( !strcmp( address6, expect6_3_3 ), "Expected: %s, got: %s\n", expect6_3_3, address6 );
3186     ok( len == sizeof(expect6_3_3), "Got size %d\n", len );
3187 
3188 end:
3189     if (v6 != INVALID_SOCKET)
3190         closesocket(v6);
3191 }
3192 
3193 static void test_WSAAddressToStringW(void)
3194 {
3195     SOCKET v6 = INVALID_SOCKET;
3196     INT ret;
3197     DWORD len;
3198     int GLE;
3199     SOCKADDR_IN sockaddr;
3200     WCHAR address[22]; /* 12 digits + 3 dots + ':' + 5 digits + '\0' */
3201 
3202     WCHAR expect1[] = { '0','.','0','.','0','.','0', 0 };
3203     WCHAR expect2[] = { '2','5','5','.','2','5','5','.','2','5','5','.','2','5','5', 0 };
3204     WCHAR expect3[] = { '0','.','0','.','0','.','0', ':', '6', '5', '5', '3', '5', 0 };
3205     WCHAR expect4[] = { '2','5','5','.','2','5','5','.','2','5','5','.','2','5','5', ':',
3206                         '6', '5', '5', '3', '5', 0 };
3207 
3208     SOCKADDR_IN6 sockaddr6;
3209     WCHAR address6[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
3210 
3211     CHAR addr6_1[] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01};
3212     CHAR addr6_2[] = {0x20,0xab,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01};
3213     CHAR addr6_3[] = {0x20,0xab,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x01};
3214 
3215     WCHAR expect6_1[] = {':',':','1',0};
3216     WCHAR expect6_2[] = {'2','0','a','b',':',':','1',0};
3217     WCHAR expect6_3[] = {'[','2','0','a','b',':',':','2','0','0','1',']',':','3','3','2','7','4',0};
3218     WCHAR expect6_3_2[] = {'[','2','0','a','b',':',':','2','0','0','1','%','4','6','6','0',']',':','3','3','2','7','4',0};
3219     WCHAR expect6_3_3[] = {'2','0','a','b',':',':','2','0','0','1','%','6','5','5','3','4',0};
3220 
3221     len = 0;
3222 
3223     sockaddr.sin_family = AF_INET;
3224     sockaddr.sin_port = 0;
3225     sockaddr.sin_addr.s_addr = 0;
3226 
3227     ret = WSAAddressToStringW( (SOCKADDR*)&sockaddr, sizeof(sockaddr), NULL, address, &len );
3228     GLE = WSAGetLastError();
3229     ok( (ret == SOCKET_ERROR && GLE == WSAEFAULT) || (ret == 0),
3230         "WSAAddressToStringW() failed unexpectedly: WSAGetLastError()=%d, ret=%d\n",
3231         GLE, ret );
3232 
3233     len = sizeof(address);
3234 
3235     sockaddr.sin_family = AF_INET;
3236     sockaddr.sin_port = 0;
3237     sockaddr.sin_addr.s_addr = 0;
3238 
3239     ret = WSAAddressToStringW( (SOCKADDR*)&sockaddr, sizeof(sockaddr), NULL, address, &len );
3240     ok( !ret, "WSAAddressToStringW() failed unexpectedly: %d\n", WSAGetLastError() );
3241 
3242     ok( !lstrcmpW( address, expect1 ), "Expected different address string\n" );
3243     ok( len == sizeof( expect1 )/sizeof( WCHAR ), "Got size %d\n", len);
3244 
3245     len = sizeof(address);
3246 
3247     sockaddr.sin_family = AF_INET;
3248     sockaddr.sin_port = 0;
3249     sockaddr.sin_addr.s_addr = 0xffffffff;
3250 
3251     ret = WSAAddressToStringW( (SOCKADDR*)&sockaddr, sizeof(sockaddr), NULL, address, &len );
3252     ok( !ret, "WSAAddressToStringW() failed unexpectedly: %d\n", WSAGetLastError() );
3253 
3254     ok( !lstrcmpW( address, expect2 ), "Expected different address string\n" );
3255 
3256     len = sizeof(address);
3257 
3258     sockaddr.sin_family = AF_INET;
3259     sockaddr.sin_port = 0xffff;
3260     sockaddr.sin_addr.s_addr = 0;
3261 
3262     ret = WSAAddressToStringW( (SOCKADDR*)&sockaddr, sizeof(sockaddr), NULL, address, &len );
3263     ok( !ret, "WSAAddressToStringW() failed unexpectedly: %d\n", WSAGetLastError() );
3264 
3265     ok( !lstrcmpW( address, expect3 ), "Expected different address string\n" );
3266 
3267     len = sizeof(address);
3268 
3269     sockaddr.sin_family = AF_INET;
3270     sockaddr.sin_port = 0xffff;
3271     sockaddr.sin_addr.s_addr = 0xffffffff;
3272 
3273     ret = WSAAddressToStringW( (SOCKADDR*)&sockaddr, sizeof(sockaddr), NULL, address, &len );
3274     ok( !ret, "WSAAddressToStringW() failed unexpectedly: %d\n", WSAGetLastError() );
3275 
3276     ok( !lstrcmpW( address, expect4 ), "Expected different address string\n" );
3277     ok( len == sizeof( expect4 )/sizeof( WCHAR ), "Got %d\n", len);
3278 
3279     /*check to see it IPv6 is available */
3280     v6 = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
3281     if (v6 == INVALID_SOCKET) {
3282         skip("Could not create IPv6 socket (LastError: %d; %d expected if IPv6 not available).\n",
3283             WSAGetLastError(), WSAEAFNOSUPPORT);
3284         goto end;
3285     }
3286 
3287     /* Test a short IPv6 address */
3288     len = sizeof(address6)/sizeof(WCHAR);
3289 
3290     sockaddr6.sin6_family = AF_INET6;
3291     sockaddr6.sin6_port = 0x0000;
3292     sockaddr6.sin6_scope_id = 0;
3293     memcpy (sockaddr6.sin6_addr.s6_addr, addr6_1, sizeof(addr6_1));
3294 
3295     ret = WSAAddressToStringW( (SOCKADDR*)&sockaddr6, sizeof(sockaddr6), NULL, address6, &len );
3296     ok( !ret, "WSAAddressToStringW() failed unexpectedly: %d\n", WSAGetLastError() );
3297     ok( !lstrcmpW( address6, expect6_1 ), "Wrong string returned\n" );
3298     ok( len == sizeof(expect6_1)/sizeof(WCHAR), "Got %d\n", len);
3299 
3300     /* Test a longer IPv6 address */
3301     len = sizeof(address6)/sizeof(WCHAR);
3302 
3303     sockaddr6.sin6_family = AF_INET6;
3304     sockaddr6.sin6_port = 0x0000;
3305     sockaddr6.sin6_scope_id = 0;
3306     memcpy (sockaddr6.sin6_addr.s6_addr, addr6_2, sizeof(addr6_2));
3307 
3308     ret = WSAAddressToStringW( (SOCKADDR*)&sockaddr6, sizeof(sockaddr6), NULL, address6, &len );
3309     ok( !ret, "WSAAddressToStringW() failed unexpectedly: %d\n", WSAGetLastError() );
3310 
3311     ok( !lstrcmpW( address6, expect6_2 ), "Wrong string returned\n" );
3312     ok( len == sizeof(expect6_2)/sizeof(WCHAR), "Got %d\n", len);
3313 
3314     /* Test IPv6 address and port number */
3315     len = sizeof(address6)/sizeof(WCHAR);
3316 
3317     sockaddr6.sin6_family = AF_INET6;
3318     sockaddr6.sin6_port = 0xfa81;
3319     sockaddr6.sin6_scope_id = 0;
3320     memcpy (sockaddr6.sin6_addr.s6_addr, addr6_3, sizeof(addr6_3));
3321 
3322     ret = WSAAddressToStringW( (SOCKADDR*)&sockaddr6, sizeof(sockaddr6), NULL, address6, &len );
3323     ok( !ret, "WSAAddressToStringW() failed unexpectedly: %d\n", WSAGetLastError() );
3324     ok( !lstrcmpW( address6, expect6_3 ),
3325         "Expected: %s, got: %s\n", wine_dbgstr_w(expect6_3), wine_dbgstr_w(address6) );
3326     ok( len == sizeof(expect6_3)/sizeof(WCHAR), "Got %d\n", len );
3327 
3328     /* Test IPv6 address, port number and scope_id */
3329     len = sizeof(address6)/sizeof(WCHAR);
3330 
3331     sockaddr6.sin6_family = AF_INET6;
3332     sockaddr6.sin6_port = 0xfa81;
3333     sockaddr6.sin6_scope_id = 0x1234;
3334     memcpy (sockaddr6.sin6_addr.s6_addr, addr6_3, sizeof(addr6_3));
3335 
3336     ret = WSAAddressToStringW( (SOCKADDR*)&sockaddr6, sizeof(sockaddr6), NULL, address6, &len );
3337     ok( !ret, "WSAAddressToStringW() failed unexpectedly: %d\n", WSAGetLastError() );
3338     ok( !lstrcmpW( address6, expect6_3_2 ),
3339         "Expected: %s, got: %s\n", wine_dbgstr_w(expect6_3_2), wine_dbgstr_w(address6) );
3340     ok( len == sizeof(expect6_3_2)/sizeof(WCHAR), "Got %d\n", len );
3341 
3342     /* Test IPv6 address and scope_id */
3343     len = sizeof(address6)/sizeof(WCHAR);
3344 
3345     sockaddr6.sin6_family = AF_INET6;
3346     sockaddr6.sin6_port = 0x0000;
3347     sockaddr6.sin6_scope_id = 0xfffe;
3348     memcpy (sockaddr6.sin6_addr.s6_addr, addr6_3, sizeof(addr6_3));
3349 
3350     ret = WSAAddressToStringW( (SOCKADDR*)&sockaddr6, sizeof(sockaddr6), NULL, address6, &len );
3351     ok( !ret, "WSAAddressToStringW() failed unexpectedly: %d\n", WSAGetLastError() );
3352     ok( !lstrcmpW( address6, expect6_3_3 ),
3353         "Expected: %s, got: %s\n", wine_dbgstr_w(expect6_3_3), wine_dbgstr_w(address6) );
3354     ok( len == sizeof(expect6_3_3)/sizeof(WCHAR), "Got %d\n", len );
3355 
3356 end:
3357     if (v6 != INVALID_SOCKET)
3358         closesocket(v6);
3359 }
3360 
3361 static void test_WSAStringToAddressA(void)
3362 {
3363     INT ret, len;
3364     SOCKADDR_IN sockaddr;
3365     SOCKADDR_IN6 sockaddr6;
3366     int GLE;
3367 
3368     CHAR address1[] = "0.0.0.0";
3369     CHAR address2[] = "127.127.127.127";
3370     CHAR address3[] = "255.255.255.255";
3371     CHAR address4[] = "127.127.127.127:65535";
3372     CHAR address5[] = "255.255.255.255:65535";
3373     CHAR address6[] = "::1";
3374     CHAR address7[] = "[::1]";
3375     CHAR address8[] = "[::1]:65535";
3376     CHAR address9[] = "2001::1";
3377 
3378     len = 0;
3379     sockaddr.sin_family = AF_INET;
3380 
3381     ret = WSAStringToAddressA( address1, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3382     ok( ret == SOCKET_ERROR, "WSAStringToAddressA() succeeded unexpectedly: %d\n",
3383         WSAGetLastError() );
3384 
3385     len = sizeof(sockaddr);
3386     sockaddr.sin_port = 0;
3387     sockaddr.sin_addr.s_addr = 0;
3388 
3389     ret = WSAStringToAddressA( address1, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3390     ok( !ret && sockaddr.sin_addr.s_addr == 0,
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( address2, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3398     ok( !ret && sockaddr.sin_addr.s_addr == 0x7f7f7f7f,
3399         "WSAStringToAddressA() failed unexpectedly: %d\n", WSAGetLastError() );
3400 
3401     len = sizeof(sockaddr);
3402     sockaddr.sin_port = 0;
3403     sockaddr.sin_addr.s_addr = 0;
3404 
3405     ret = WSAStringToAddressA( address3, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3406     GLE = WSAGetLastError();
3407     ok( (ret == 0 && sockaddr.sin_addr.s_addr == 0xffffffff) ||
3408         (ret == SOCKET_ERROR && (GLE == ERROR_INVALID_PARAMETER || GLE == WSAEINVAL)),
3409         "WSAStringToAddressA() failed unexpectedly: %d\n", GLE );
3410 
3411     len = sizeof(sockaddr);
3412     sockaddr.sin_port = 0;
3413     sockaddr.sin_addr.s_addr = 0;
3414 
3415     ret = WSAStringToAddressA( address4, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3416     ok( !ret && sockaddr.sin_addr.s_addr == 0x7f7f7f7f && sockaddr.sin_port == 0xffff,
3417         "WSAStringToAddressA() failed unexpectedly: %d\n", WSAGetLastError() );
3418 
3419     len = sizeof(sockaddr);
3420     sockaddr.sin_port = 0;
3421     sockaddr.sin_addr.s_addr = 0;
3422 
3423     ret = WSAStringToAddressA( address5, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3424     GLE = WSAGetLastError();
3425     ok( (ret == 0 && sockaddr.sin_addr.s_addr == 0xffffffff && sockaddr.sin_port == 0xffff) ||
3426         (ret == SOCKET_ERROR && (GLE == ERROR_INVALID_PARAMETER || GLE == WSAEINVAL)),
3427         "WSAStringToAddressA() failed unexpectedly: %d\n", GLE );
3428 
3429     len = sizeof(sockaddr);
3430 
3431     ret = WSAStringToAddressA( address9, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3432     GLE = WSAGetLastError();
3433     ok( (ret == SOCKET_ERROR && GLE == WSAEINVAL),
3434         "WSAStringToAddressA() should have failed with %d\n", GLE );
3435 
3436     len = sizeof(sockaddr6);
3437     memset(&sockaddr6, 0, len);
3438     sockaddr6.sin6_family = AF_INET6;
3439 
3440     ret = WSAStringToAddressA( address6, AF_INET6, NULL, (SOCKADDR*)&sockaddr6,
3441             &len );
3442     if (ret == SOCKET_ERROR)
3443     {
3444         win_skip("IPv6 not supported\n");
3445         return;
3446     }
3447 
3448     GLE = WSAGetLastError();
3449     ok( ret == 0, "WSAStringToAddressA() failed for IPv6 address: %d\n", GLE);
3450 
3451     len = sizeof(sockaddr6);
3452     memset(&sockaddr6, 0, len);
3453     sockaddr6.sin6_family = AF_INET6;
3454 
3455     ret = WSAStringToAddressA( address7, AF_INET6, NULL, (SOCKADDR*)&sockaddr6,
3456             &len );
3457     GLE = WSAGetLastError();
3458     ok( ret == 0, "WSAStringToAddressA() failed for IPv6 address: %d\n", GLE);
3459 
3460     len = sizeof(sockaddr6);
3461     memset(&sockaddr6, 0, len);
3462     sockaddr6.sin6_family = AF_INET6;
3463 
3464     ret = WSAStringToAddressA( address8, AF_INET6, NULL, (SOCKADDR*)&sockaddr6,
3465             &len );
3466     GLE = WSAGetLastError();
3467     ok( ret == 0 && sockaddr6.sin6_port == 0xffff,
3468         "WSAStringToAddressA() failed for IPv6 address: %d\n", GLE);
3469 
3470     len = sizeof(sockaddr6);
3471 
3472     ret = WSAStringToAddressA( address7 + 1, AF_INET6, NULL, (SOCKADDR*)&sockaddr, &len );
3473     GLE = WSAGetLastError();
3474     ok( (ret == SOCKET_ERROR && GLE == WSAEINVAL),
3475         "WSAStringToAddressW() should have failed with %d\n", GLE );
3476 
3477     len = sizeof(sockaddr6);
3478 
3479     ret = WSAStringToAddressA( address8 + 1, AF_INET6, NULL, (SOCKADDR*)&sockaddr, &len );
3480     GLE = WSAGetLastError();
3481     ok( (ret == SOCKET_ERROR && GLE == WSAEINVAL),
3482         "WSAStringToAddressW() should have failed with %d\n", GLE );
3483 }
3484 
3485 static void test_WSAStringToAddressW(void)
3486 {
3487     INT ret, len;
3488     SOCKADDR_IN sockaddr, *sin;
3489     SOCKADDR_IN6 sockaddr6;
3490     SOCKADDR_STORAGE sockaddr_storage;
3491     int GLE;
3492 
3493     WCHAR address1[] = { '0','.','0','.','0','.','0', 0 };
3494     WCHAR address2[] = { '1','2','7','.','1','2','7','.','1','2','7','.','1','2','7', 0 };
3495     WCHAR address3[] = { '2','5','5','.','2','5','5','.','2','5','5','.','2','5','5', 0 };
3496     WCHAR address4[] = { '1','2','7','.','1','2','7','.','1','2','7','.','1','2','7',
3497                          ':', '6', '5', '5', '3', '5', 0 };
3498     WCHAR address5[] = { '2','5','5','.','2','5','5','.','2','5','5','.','2','5','5', ':',
3499                          '6', '5', '5', '3', '5', 0 };
3500     WCHAR address6[] = {':',':','1','\0'};
3501     WCHAR address7[] = {'[',':',':','1',']','\0'};
3502     WCHAR address8[] = {'[',':',':','1',']',':','6','5','5','3','5','\0'};
3503     WCHAR address9[] = {'2','0','0','1',':',':','1','\0'};
3504 
3505     len = 0;
3506     sockaddr.sin_family = AF_INET;
3507 
3508     ret = WSAStringToAddressW( address1, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3509     ok( ret == SOCKET_ERROR, "WSAStringToAddressW() failed unexpectedly: %d\n",
3510         WSAGetLastError() );
3511 
3512     len = sizeof(sockaddr);
3513     sockaddr.sin_port = 0;
3514     sockaddr.sin_addr.s_addr = 0;
3515 
3516     ret = WSAStringToAddressW( address1, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3517     ok( !ret && sockaddr.sin_addr.s_addr == 0,
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( address2, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3525     ok( !ret && sockaddr.sin_addr.s_addr == 0x7f7f7f7f,
3526         "WSAStringToAddressW() failed unexpectedly: %d\n", WSAGetLastError() );
3527 
3528     len = sizeof(sockaddr);
3529     sockaddr.sin_port = 0;
3530     sockaddr.sin_addr.s_addr = 0;
3531 
3532     ret = WSAStringToAddressW( address3, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3533     GLE = WSAGetLastError();
3534     ok( (ret == 0 && sockaddr.sin_addr.s_addr == 0xffffffff) ||
3535         (ret == SOCKET_ERROR && (GLE == ERROR_INVALID_PARAMETER || GLE == WSAEINVAL)),
3536         "WSAStringToAddressW() failed unexpectedly: %d\n", GLE );
3537 
3538     len = sizeof(sockaddr);
3539     sockaddr.sin_port = 0;
3540     sockaddr.sin_addr.s_addr = 0;
3541 
3542     ret = WSAStringToAddressW( address4, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3543     ok( !ret && sockaddr.sin_addr.s_addr == 0x7f7f7f7f && sockaddr.sin_port == 0xffff,
3544         "WSAStringToAddressW() failed unexpectedly: %d\n", WSAGetLastError() );
3545 
3546     len = sizeof(sockaddr);
3547     sockaddr.sin_port = 0;
3548     sockaddr.sin_addr.s_addr = 0;
3549 
3550     ret = WSAStringToAddressW( address5, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3551     ok( (ret == 0 && sockaddr.sin_addr.s_addr == 0xffffffff && sockaddr.sin_port == 0xffff) ||
3552         (ret == SOCKET_ERROR && (GLE == ERROR_INVALID_PARAMETER || GLE == WSAEINVAL)),
3553         "WSAStringToAddressW() failed unexpectedly: %d\n", GLE );
3554 
3555     /* Test with a larger buffer than necessary */
3556     len = sizeof(sockaddr_storage);
3557     sin = (SOCKADDR_IN *)&sockaddr_storage;
3558     sin->sin_port = 0;
3559     sin->sin_addr.s_addr = 0;
3560 
3561     ret = WSAStringToAddressW( address5, AF_INET, NULL, (SOCKADDR*)sin, &len );
3562     ok( (ret == 0 && sin->sin_addr.s_addr == 0xffffffff && sin->sin_port == 0xffff) ||
3563         (ret == SOCKET_ERROR && (GLE == ERROR_INVALID_PARAMETER || GLE == WSAEINVAL)),
3564         "WSAStringToAddressW() failed unexpectedly: %d\n", GLE );
3565     ok( len == sizeof(SOCKADDR_IN), "unexpected length %d\n", len );
3566 
3567     len = sizeof(sockaddr);
3568 
3569     ret = WSAStringToAddressW( address9, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3570     GLE = WSAGetLastError();
3571     ok( (ret == SOCKET_ERROR && GLE == WSAEINVAL),
3572         "WSAStringToAddressW() should have failed with %d\n", GLE );
3573 
3574     len = sizeof(sockaddr6);
3575     memset(&sockaddr6, 0, len);
3576     sockaddr6.sin6_family = AF_INET6;
3577 
3578     ret = WSAStringToAddressW( address6, AF_INET6, NULL, (SOCKADDR*)&sockaddr6,
3579             &len );
3580     if (ret == SOCKET_ERROR)
3581     {
3582         win_skip("IPv6 not supported\n");
3583         return;
3584     }
3585 
3586     GLE = WSAGetLastError();
3587     ok( ret == 0, "WSAStringToAddressW() failed for IPv6 address: %d\n", GLE);
3588 
3589     len = sizeof(sockaddr6);
3590     memset(&sockaddr6, 0, len);
3591     sockaddr6.sin6_family = AF_INET6;
3592 
3593     ret = WSAStringToAddressW( address7, AF_INET6, NULL, (SOCKADDR*)&sockaddr6,
3594             &len );
3595     GLE = WSAGetLastError();
3596     ok( ret == 0, "WSAStringToAddressW() failed for IPv6 address: %d\n", GLE);
3597 
3598     len = sizeof(sockaddr6);
3599     memset(&sockaddr6, 0, len);
3600     sockaddr6.sin6_family = AF_INET6;
3601 
3602     ret = WSAStringToAddressW( address8, AF_INET6, NULL, (SOCKADDR*)&sockaddr6,
3603             &len );
3604     GLE = WSAGetLastError();
3605     ok( ret == 0 && sockaddr6.sin6_port == 0xffff,
3606         "WSAStringToAddressW() failed for IPv6 address: %d\n", GLE);
3607 
3608     len = sizeof(sockaddr6);
3609 
3610     ret = WSAStringToAddressW( address7 + 1, AF_INET6, NULL, (SOCKADDR*)&sockaddr, &len );
3611     GLE = WSAGetLastError();
3612     ok( (ret == SOCKET_ERROR && GLE == WSAEINVAL),
3613         "WSAStringToAddressW() should have failed with %d\n", GLE );
3614 
3615     len = sizeof(sockaddr6);
3616 
3617     ret = WSAStringToAddressW( address8 + 1, AF_INET6, NULL, (SOCKADDR*)&sockaddr, &len );
3618     GLE = WSAGetLastError();
3619     ok( (ret == SOCKET_ERROR && GLE == WSAEINVAL),
3620         "WSAStringToAddressW() should have failed with %d\n", GLE );
3621 }
3622 
3623 static DWORD WINAPI SelectReadThread(void *param)
3624 {
3625     select_thread_params *par = param;
3626     fd_set readfds;
3627     int ret;
3628     struct sockaddr_in addr;
3629     struct timeval select_timeout;
3630 
3631     memset(&readfds, 0, sizeof(readfds));
3632     FD_ZERO(&readfds);
3633     FD_SET(par->s, &readfds);
3634     select_timeout.tv_sec=5;
3635     select_timeout.tv_usec=0;
3636     addr.sin_family = AF_INET;
3637     addr.sin_addr.s_addr = inet_addr(SERVERIP);
3638     addr.sin_port = htons(SERVERPORT);
3639 
3640     do_bind(par->s, (struct sockaddr *)&addr, sizeof(addr));
3641     wsa_ok(listen(par->s, SOMAXCONN ), 0 ==, "SelectReadThread (%x): listen failed: %d\n");
3642 
3643     SetEvent(server_ready);
3644     ret = select(par->s+1, &readfds, NULL, NULL, &select_timeout);
3645     par->ReadKilled = (ret == 1);
3646 
3647     return 0;
3648 }
3649 
3650 static DWORD WINAPI SelectCloseThread(void *param)
3651 {
3652     SOCKET s = *(SOCKET*)param;
3653     Sleep(500);
3654     closesocket(s);
3655     return 0;
3656 }
3657 
3658 static void test_errors(void)
3659 {
3660     SOCKET sock;
3661     SOCKADDR_IN  SockAddr;
3662     int ret, err;
3663 
3664     WSASetLastError(NO_ERROR);
3665     sock = socket(PF_INET, SOCK_STREAM, 0);
3666     ok( (sock != INVALID_SOCKET), "socket failed unexpectedly: %d\n", WSAGetLastError() );
3667     memset(&SockAddr, 0, sizeof(SockAddr));
3668     SockAddr.sin_family = AF_INET;
3669     SockAddr.sin_port = htons(6924);
3670     SockAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
3671 
3672     ret = connect(sock, (PSOCKADDR)&SockAddr, sizeof(SockAddr));
3673     ok( (ret == SOCKET_ERROR), "expected SOCKET_ERROR, got: %d\n", ret );
3674     if (ret == SOCKET_ERROR)
3675     {
3676         err = WSAGetLastError();
3677         ok( (err == WSAECONNREFUSED), "expected WSAECONNREFUSED, got: %d\n", err );
3678     }
3679 
3680     {
3681         TIMEVAL timeval;
3682         fd_set set = {1, {sock}};
3683 
3684         timeval.tv_sec = 0;
3685         timeval.tv_usec = 50000;
3686 
3687         ret = select(1, NULL, &set, NULL, &timeval);
3688         ok( (ret == 0), "expected 0 (timeout), got: %d\n", ret );
3689     }
3690 
3691     ret = closesocket(sock);
3692     ok ( (ret == 0), "closesocket failed unexpectedly: %d\n", WSAGetLastError());
3693 }
3694 
3695 static void test_listen(void)
3696 {
3697     SOCKET fdA, fdB;
3698     int ret, acceptc, olen = sizeof(acceptc);
3699     struct sockaddr_in address;
3700 
3701     memset(&address, 0, sizeof(address));
3702     address.sin_addr.s_addr = inet_addr("127.0.0.1");
3703     address.sin_family = AF_INET;
3704     address.sin_port = htons(SERVERPORT);
3705 
3706     /* invalid socket tests */
3707     SetLastError(0xdeadbeef);
3708     ok ((listen(0, 0) == SOCKET_ERROR), "listen did not fail\n");
3709     ret = WSAGetLastError();
3710     ok (ret == WSAENOTSOCK, "expected 10038, received %d\n", ret);
3711 
3712     SetLastError(0xdeadbeef);
3713     ok ((listen(0xdeadbeef, 0) == SOCKET_ERROR), "listen did not fail\n");
3714     ret = WSAGetLastError();
3715     ok (ret == WSAENOTSOCK, "expected 10038, received %d\n", ret);
3716 
3717     /* tcp tests */
3718     fdA = socket(AF_INET, SOCK_STREAM, 0);
3719     ok ((fdA != INVALID_SOCKET), "socket failed unexpectedly: %d\n", WSAGetLastError() );
3720 
3721     fdB = socket(AF_INET, SOCK_STREAM, 0);
3722     ok ((fdB != INVALID_SOCKET), "socket failed unexpectedly: %d\n", WSAGetLastError() );
3723 
3724     SetLastError(0xdeadbeef);
3725     ok ((listen(fdA, -2) == SOCKET_ERROR), "listen did not fail\n");
3726     ret = WSAGetLastError();
3727     ok (ret == WSAEINVAL, "expected 10022, received %d\n", ret);
3728 
3729     SetLastError(0xdeadbeef);
3730     ok ((listen(fdA, 1) == SOCKET_ERROR), "listen did not fail\n");
3731     ret = WSAGetLastError();
3732     ok (ret == WSAEINVAL, "expected 10022, received %d\n", ret);
3733 
3734     SetLastError(0xdeadbeef);
3735     ok ((listen(fdA, SOMAXCONN) == SOCKET_ERROR), "listen did not fail\n");
3736     ret = WSAGetLastError();
3737     ok (ret == WSAEINVAL, "expected 10022, received %d\n", ret);
3738 
3739     ok (!bind(fdA, (struct sockaddr*) &address, sizeof(address)), "bind failed\n");
3740 
3741     SetLastError(0xdeadbeef);
3742     ok (bind(fdB, (struct sockaddr*) &address, sizeof(address)), "bind should have failed\n");
3743     ok (ret == WSAEINVAL, "expected 10022, received %d\n", ret);
3744 
3745     acceptc = 0xdead;
3746     ret = getsockopt(fdA, SOL_SOCKET, SO_ACCEPTCONN, (char*)&acceptc, &olen);
3747     ok (!ret, "getsockopt failed\n");
3748     ok (acceptc == 0, "SO_ACCEPTCONN should be 0, received %d\n", acceptc);
3749 
3750     ok (!listen(fdA, 0), "listen failed\n");
3751     ok (!listen(fdA, SOMAXCONN), "double listen failed\n");
3752 
3753     acceptc = 0xdead;
3754     ret = getsockopt(fdA, SOL_SOCKET, SO_ACCEPTCONN, (char*)&acceptc, &olen);
3755     ok (!ret, "getsockopt failed\n");
3756     ok (acceptc == 1, "SO_ACCEPTCONN should be 1, received %d\n", acceptc);
3757 
3758     SetLastError(0xdeadbeef);
3759     ok ((listen(fdB, SOMAXCONN) == SOCKET_ERROR), "listen did not fail\n");
3760     ret = WSAGetLastError();
3761     ok (ret == WSAEINVAL, "expected 10022, received %d\n", ret);
3762 
3763     ret = closesocket(fdB);
3764     ok (ret == 0, "closesocket failed unexpectedly: %d\n", ret);
3765 
3766     fdB = socket(AF_INET, SOCK_STREAM, 0);
3767     ok ((fdB != INVALID_SOCKET), "socket failed unexpectedly: %d\n", WSAGetLastError() );
3768 
3769     SetLastError(0xdeadbeef);
3770     ok (bind(fdB, (struct sockaddr*) &address, sizeof(address)), "bind should have failed\n");
3771     ret = WSAGetLastError();
3772     ok (ret == WSAEADDRINUSE, "expected 10048, received %d\n", ret);
3773 
3774     ret = closesocket(fdA);
3775     ok (ret == 0, "closesocket failed unexpectedly: %d\n", ret);
3776     ret = closesocket(fdB);
3777     ok (ret == 0, "closesocket failed unexpectedly: %d\n", ret);
3778 }
3779 
3780 #define FD_ZERO_ALL() { FD_ZERO(&readfds); FD_ZERO(&writefds); FD_ZERO(&exceptfds); }
3781 #define FD_SET_ALL(s) { FD_SET(s, &readfds); FD_SET(s, &writefds); FD_SET(s, &exceptfds); }
3782 static void test_select(void)
3783 {
3784     static char tmp_buf[1024];
3785 
3786     SOCKET fdListen, fdRead, fdWrite;
3787     fd_set readfds, writefds, exceptfds;
3788     unsigned int maxfd;
3789     int ret, len;
3790     char buffer;
3791     struct timeval select_timeout;
3792     struct sockaddr_in address;
3793     select_thread_params thread_params;
3794     HANDLE thread_handle;
3795     DWORD ticks, id;
3796 
3797     fdRead = socket(AF_INET, SOCK_STREAM, 0);
3798     ok( (fdRead != INVALID_SOCKET), "socket failed unexpectedly: %d\n", WSAGetLastError() );
3799     fdWrite = socket(AF_INET, SOCK_STREAM, 0);
3800     ok( (fdWrite != INVALID_SOCKET), "socket failed unexpectedly: %d\n", WSAGetLastError() );
3801 
3802     maxfd = fdRead;
3803     if (fdWrite > maxfd)
3804         maxfd = fdWrite;
3805 
3806     FD_ZERO_ALL();
3807     FD_SET_ALL(fdRead);
3808     FD_SET_ALL(fdWrite);
3809     select_timeout.tv_sec=0;
3810     select_timeout.tv_usec=0;
3811 
3812     ticks = GetTickCount();
3813     ret = select(maxfd+1, &readfds, &writefds, &exceptfds, &select_timeout);
3814     ticks = GetTickCount() - ticks;
3815     ok(ret == 0, "select should not return any socket handles\n");
3816     ok(ticks < 10, "select was blocking for %u ms, expected < 10 ms\n", ticks);
3817     ok(!FD_ISSET(fdRead, &readfds), "FD should not be set\n");
3818     ok(!FD_ISSET(fdWrite, &writefds), "FD should not be set\n");
3819     ok(!FD_ISSET(fdRead, &exceptfds), "FD should not be set\n");
3820     ok(!FD_ISSET(fdWrite, &exceptfds), "FD should not be set\n");
3821 
3822     FD_ZERO_ALL();
3823     FD_SET_ALL(fdRead);
3824     FD_SET_ALL(fdWrite);
3825     select_timeout.tv_sec=0;
3826     select_timeout.tv_usec=500;
3827 
3828     ret = select(maxfd+1, &readfds, &writefds, &exceptfds, &select_timeout);
3829     ok(ret == 0, "select should not return any socket handles\n");
3830     ok(!FD_ISSET(fdRead, &readfds), "FD should not be set\n");
3831     ok(!FD_ISSET(fdWrite, &writefds), "FD should not be set\n");
3832     ok(!FD_ISSET(fdRead, &exceptfds), "FD should not be set\n");
3833     ok(!FD_ISSET(fdWrite, &exceptfds), "FD should not be set\n");
3834 
3835     ok ((listen(fdWrite, SOMAXCONN) == SOCKET_ERROR), "listen did not fail\n");
3836     ret = closesocket(fdWrite);
3837     ok ( (ret == 0), "closesocket failed unexpectedly: %d\n", ret);
3838 
3839     thread_params.s = fdRead;
3840     thread_params.ReadKilled = FALSE;
3841     server_ready = CreateEventA(NULL, TRUE, FALSE, NULL);
3842     thread_handle = CreateThread (NULL, 0, SelectReadThread, &thread_params, 0, &id );
3843     ok ( (thread_handle != NULL), "CreateThread failed unexpectedly: %d\n", GetLastError());
3844 
3845     WaitForSingleObject (server_ready, INFINITE);
3846     Sleep(200);
3847     ret = closesocket(fdRead);
3848     ok ( (ret == 0), "closesocket failed unexpectedly: %d\n", ret);
3849 
3850     WaitForSingleObject (thread_handle, 1000);
3851     ok ( thread_params.ReadKilled, "closesocket did not wake up select\n");
3852     ret = recv(fdRead, &buffer, 1, MSG_PEEK);
3853     ok( (ret == -1), "peek at closed socket expected -1 got %d\n", ret);
3854 
3855     /* Test selecting invalid handles */
3856     FD_ZERO_ALL();
3857 
3858     SetLastError(0);
3859     ret = select(maxfd+1, 0, 0, 0, &select_timeout);
3860     ok ( (ret == SOCKET_ERROR), "expected SOCKET_ERROR, got %i\n", ret);
3861     ok ( WSAGetLastError() == WSAEINVAL, "expected WSAEINVAL, got %i\n", WSAGetLastError());
3862 
3863     SetLastError(0);
3864     ret = select(maxfd+1, &readfds, &writefds, &exceptfds, &select_timeout);
3865     ok ( (ret == SOCKET_ERROR), "expected SOCKET_ERROR, got %i\n", ret);
3866     ok ( WSAGetLastError() == WSAEINVAL, "expected WSAEINVAL, got %i\n", WSAGetLastError());
3867 
3868     FD_SET(INVALID_SOCKET, &readfds);
3869     SetLastError(0);
3870     ret = select(maxfd+1, &readfds, &writefds, &exceptfds, &select_timeout);
3871     ok ( (ret == SOCKET_ERROR), "expected SOCKET_ERROR, got %i\n", ret);
3872     ok ( WSAGetLastError() == WSAENOTSOCK, "expected WSAENOTSOCK, got %i\n", WSAGetLastError());
3873     ok ( !FD_ISSET(fdRead, &readfds), "FD should not be set\n");
3874 
3875     FD_ZERO(&readfds);
3876     FD_SET(INVALID_SOCKET, &writefds);
3877     SetLastError(0);
3878     ret = select(maxfd+1, &readfds, &writefds, &exceptfds, &select_timeout);
3879     ok ( (ret == SOCKET_ERROR), "expected SOCKET_ERROR, got %i\n", ret);
3880     ok ( WSAGetLastError() == WSAENOTSOCK, "expected WSAENOTSOCK, got %i\n", WSAGetLastError());
3881     ok ( !FD_ISSET(fdRead, &writefds), "FD should not be set\n");
3882 
3883     FD_ZERO(&writefds);
3884     FD_SET(INVALID_SOCKET, &exceptfds);
3885     SetLastError(0);
3886     ret = select(maxfd+1, &readfds, &writefds, &exceptfds, &select_timeout);
3887     ok ( (ret == SOCKET_ERROR), "expected SOCKET_ERROR, got %i\n", ret);
3888     ok ( WSAGetLastError() == WSAENOTSOCK, "expected WSAENOTSOCK, got %i\n", WSAGetLastError());
3889     ok ( !FD_ISSET(fdRead, &exceptfds), "FD should not be set\n");
3890 
3891     ok(!tcp_socketpair(&fdRead, &fdWrite), "creating socket pair failed\n");
3892     maxfd = fdRead;
3893     if(fdWrite > maxfd) maxfd = fdWrite;
3894 
3895     FD_ZERO(&readfds);
3896     FD_SET(fdRead, &readfds);
3897     ret = select(fdRead+1, &readfds, NULL, NULL, &select_timeout);
3898     ok(!ret, "select returned %d\n", ret);
3899 
3900     FD_ZERO(&writefds);
3901     FD_SET(fdWrite, &writefds);
3902     ret = select(fdWrite+1, NULL, &writefds, NULL, &select_timeout);
3903     ok(ret == 1, "select returned %d\n", ret);
3904     ok(FD_ISSET(fdWrite, &writefds), "fdWrite socket is not in the set\n");
3905 
3906     /* tests for overlapping fd_set pointers */
3907     FD_ZERO(&readfds);
3908     FD_SET(fdWrite, &readfds);
3909     ret = select(fdWrite+1, &readfds, &readfds, NULL, &select_timeout);
3910     ok(ret == 1, "select returned %d\n", ret);
3911     ok(FD_ISSET(fdWrite, &readfds), "fdWrite socket is not in the set\n");
3912 
3913     FD_ZERO(&readfds);
3914     FD_SET(fdWrite, &readfds);
3915     FD_SET(fdRead, &readfds);
3916     ret = select(maxfd+1, &readfds, &readfds, NULL, &select_timeout);
3917     ok(ret == 2, "select returned %d\n", ret);
3918     ok(FD_ISSET(fdWrite, &readfds), "fdWrite socket is not in the set\n");
3919     ok(FD_ISSET(fdRead, &readfds), "fdRead socket is not in the set\n");
3920 
3921     ok(send(fdWrite, "test", 4, 0) == 4, "failed to send data\n");
3922     FD_ZERO(&readfds);
3923     FD_SET(fdRead, &readfds);
3924     ret = select(fdRead+1, &readfds, NULL, NULL, &select_timeout);
3925     ok(ret == 1, "select returned %d\n", ret);
3926     ok(FD_ISSET(fdRead, &readfds), "fdRead socket is not in the set\n");
3927 
3928     FD_ZERO(&readfds);
3929     FD_SET(fdWrite, &readfds);
3930     FD_SET(fdRead, &readfds);
3931     ret = select(maxfd+1, &readfds, &readfds, NULL, &select_timeout);
3932     ok(ret == 2, "select returned %d\n", ret);
3933     ok(FD_ISSET(fdWrite, &readfds), "fdWrite socket is not in the set\n");
3934     ok(FD_ISSET(fdRead, &readfds), "fdRead socket is not in the set\n");
3935 
3936 #if ROSTESTS_233_IS_FIXED
3937     while(1) {
3938         FD_ZERO(&writefds);
3939         FD_SET(fdWrite, &writefds);
3940         ret = select(fdWrite+1, NULL, &writefds, NULL, &select_timeout);
3941         if(!ret) break;
3942         ok(send(fdWrite, tmp_buf, sizeof(tmp_buf), 0) > 0, "failed to send data\n");
3943     }
3944 #endif /* ROSTESTS_233_IS_FIXED */
3945 
3946     FD_ZERO(&readfds);
3947     FD_SET(fdWrite, &readfds);
3948     FD_SET(fdRead, &readfds);
3949     ret = select(maxfd+1, &readfds, &readfds, NULL, &select_timeout);
3950     ok(ret == 1, "select returned %d\n", ret);
3951     ok(!FD_ISSET(fdWrite, &readfds), "fdWrite socket is in the set\n");
3952     ok(FD_ISSET(fdRead, &readfds), "fdRead socket is not in the set\n");
3953 
3954     ok(send(fdRead, "test", 4, 0) == 4, "failed to send data\n");
3955     Sleep(100);
3956     FD_ZERO(&readfds);
3957     FD_SET(fdWrite, &readfds);
3958     FD_SET(fdRead, &readfds);
3959     ret = select(maxfd+1, &readfds, &readfds, NULL, &select_timeout);
3960     ok(ret == 2, "select returned %d\n", ret);
3961     ok(FD_ISSET(fdWrite, &readfds), "fdWrite socket is not in the set\n");
3962     ok(FD_ISSET(fdRead, &readfds), "fdRead socket is not in the set\n");
3963 
3964     closesocket(fdRead);
3965     closesocket(fdWrite);
3966 
3967     /* select() works in 3 distinct states:
3968      * - to check if a connection attempt ended with success or error;
3969      * - to check if a pending connection is waiting for acceptance;
3970      * - to check for data to read, availability for write and OOB data
3971      *
3972      * The tests below ensure that all conditions are tested.
3973      */
3974     memset(&address, 0, sizeof(address));
3975     address.sin_addr.s_addr = inet_addr("127.0.0.1");
3976     address.sin_family = AF_INET;
3977     len = sizeof(address);
3978     fdListen = setup_server_socket(&address, &len);
3979     select_timeout.tv_sec = 1;
3980     select_timeout.tv_usec = 250000;
3981 
3982     /* When no events are pending select returns 0 with no error */
3983     FD_ZERO_ALL();
3984     FD_SET_ALL(fdListen);
3985     ret = select(0, &readfds, &writefds, &exceptfds, &select_timeout);
3986     ok(ret == 0, "expected 0, got %d\n", ret);
3987 
3988     /* When a socket is attempting to connect the listening socket receives the read descriptor */
3989     fdWrite = setup_connector_socket(&address, len, TRUE);
3990     FD_ZERO_ALL();
3991     FD_SET_ALL(fdListen);
3992     ret = select(0, &readfds, &writefds, &exceptfds, &select_timeout);
3993     ok(ret == 1, "expected 1, got %d\n", ret);
3994     ok(FD_ISSET(fdListen, &readfds), "fdListen socket is not in the set\n");
3995     len = sizeof(address);
3996     fdRead = accept(fdListen, (struct sockaddr*) &address, &len);
3997     ok(fdRead != INVALID_SOCKET, "expected a valid socket\n");
3998 
3999     /* The connector is signaled through the write descriptor */
4000     FD_ZERO_ALL();
4001     FD_SET_ALL(fdListen);
4002     FD_SET_ALL(fdRead);
4003     FD_SET_ALL(fdWrite);
4004     ret = select(0, &readfds, &writefds, &exceptfds, &select_timeout);
4005     ok(ret == 2, "expected 2, got %d\n", ret);
4006     ok(FD_ISSET(fdWrite, &writefds), "fdWrite socket is not in the set\n");
4007     ok(FD_ISSET(fdRead, &writefds), "fdRead socket is not in the set\n");
4008     len = sizeof(id);
4009     id = 0xdeadbeef;
4010     ret = getsockopt(fdWrite, SOL_SOCKET, SO_ERROR, (char*)&id, &len);
4011     ok(!ret, "getsockopt failed with %d\n", WSAGetLastError());
4012     ok(id == 0, "expected 0, got %d\n", id);
4013 
4014     /* When data is received the receiver gets the read descriptor */
4015     ret = send(fdWrite, "1234", 4, 0);
4016     ok(ret == 4, "expected 4, got %d\n", ret);
4017     FD_ZERO_ALL();
4018     FD_SET_ALL(fdListen);
4019     FD_SET(fdRead, &readfds);
4020     FD_SET(fdRead, &exceptfds);
4021     ret = select(0, &readfds, &writefds, &exceptfds, &select_timeout);
4022     ok(ret == 1, "expected 1, got %d\n", ret);
4023     ok(FD_ISSET(fdRead, &readfds), "fdRead socket is not in the set\n");
4024     ret = recv(fdRead, tmp_buf, sizeof(tmp_buf), 0);
4025     ok(ret == 4, "expected 4, got %d\n", ret);
4026     ok(!strcmp(tmp_buf, "1234"), "data received differs from sent\n");
4027 
4028     /* When OOB data is received the socket is set in the except descriptor */
4029     ret = send(fdWrite, "A", 1, MSG_OOB);
4030     ok(ret == 1, "expected 1, got %d\n", ret);
4031     FD_ZERO_ALL();
4032     FD_SET_ALL(fdListen);
4033     FD_SET(fdRead, &readfds);
4034     FD_SET(fdRead, &exceptfds);
4035     ret = select(0, &readfds, &writefds, &exceptfds, &select_timeout);
4036     ok(ret == 1, "expected 1, got %d\n", ret);
4037     ok(FD_ISSET(fdRead, &exceptfds), "fdRead socket is not in the set\n");
4038     tmp_buf[0] = 0xAF;
4039     ret = recv(fdRead, tmp_buf, sizeof(tmp_buf), MSG_OOB);
4040     ok(ret == 1, "expected 1, got %d\n", ret);
4041     ok(tmp_buf[0] == 'A', "expected 'A', got 0x%02X\n", tmp_buf[0]);
4042 
4043     /* If the socket is OOBINLINED it will not receive the OOB in except fds */
4044     ret = 1;
4045     ret = setsockopt(fdRead, SOL_SOCKET, SO_OOBINLINE, (char*) &ret, sizeof(ret));
4046     ok(ret == 0, "expected 0, got %d\n", ret);
4047     ret = send(fdWrite, "A", 1, MSG_OOB);
4048     ok(ret == 1, "expected 1, got %d\n", ret);
4049     FD_ZERO_ALL();
4050     FD_SET_ALL(fdListen);
4051     FD_SET(fdRead, &readfds);
4052     FD_SET(fdRead, &exceptfds);
4053     ret = select(0, &readfds, &writefds, &exceptfds, &select_timeout);
4054     ok(ret == 1, "expected 1, got %d\n", ret);
4055     ok(FD_ISSET(fdRead, &readfds), "fdRead socket is not in the set\n");
4056     tmp_buf[0] = 0xAF;
4057     SetLastError(0xdeadbeef);
4058     ret = recv(fdRead, tmp_buf, sizeof(tmp_buf), MSG_OOB);
4059     ok(ret == SOCKET_ERROR, "expected SOCKET_ERROR, got %d\n", ret);
4060     ok(GetLastError() == WSAEINVAL, "expected 10022, got %d\n", GetLastError());
4061     ret = recv(fdRead, tmp_buf, sizeof(tmp_buf), 0);
4062     ok(ret == 1, "expected 1, got %d\n", ret);
4063     ok(tmp_buf[0] == 'A', "expected 'A', got 0x%02X\n", tmp_buf[0]);
4064 
4065     /* When the connection is closed the socket is set in the read descriptor */
4066     ret = closesocket(fdRead);
4067     ok(ret == 0, "expected 0, got %d\n", ret);
4068     FD_ZERO_ALL();
4069     FD_SET_ALL(fdListen);
4070     FD_SET(fdWrite, &readfds);
4071     ret = select(0, &readfds, &writefds, &exceptfds, &select_timeout);
4072     ok(ret == 1, "expected 1, got %d\n", ret);
4073     ok(FD_ISSET(fdWrite, &readfds), "fdWrite socket is not in the set\n");
4074     ret = recv(fdWrite, tmp_buf, sizeof(tmp_buf), 0);
4075     ok(ret == 0, "expected 0, got %d\n", ret);
4076 
4077     /* When a connection is attempted to a non-listening socket it will get to the except descriptor */
4078     ret = closesocket(fdWrite);
4079     ok(ret == 0, "expected 0, got %d\n", ret);
4080     ret = closesocket(fdListen);
4081     ok(ret == 0, "expected 0, got %d\n", ret);
4082     len = sizeof(address);
4083     fdWrite = setup_connector_socket(&address, len, TRUE);
4084     FD_ZERO_ALL();
4085     FD_SET(fdWrite, &writefds);
4086     FD_SET(fdWrite, &exceptfds);
4087     select_timeout.tv_sec = 2; /* requires more time to realize it will not connect */
4088     ret = select(0, &readfds, &writefds, &exceptfds, &select_timeout);
4089     ok(ret == 1, "expected 1, got %d\n", ret);
4090     len = sizeof(id);
4091     id = 0xdeadbeef;
4092     ret = getsockopt(fdWrite, SOL_SOCKET, SO_ERROR, (char*)&id, &len);
4093     ok(!ret, "getsockopt failed with %d\n", WSAGetLastError());
4094     ok(id == WSAECONNREFUSED, "expected 10061, got %d\n", id);
4095     ok(FD_ISSET(fdWrite, &exceptfds), "fdWrite socket is not in the set\n");
4096     ok(select_timeout.tv_usec == 250000, "select timeout should not have changed\n");
4097     closesocket(fdWrite);
4098 
4099     /* Try select() on a closed socket after connection */
4100     ok(!tcp_socketpair(&fdRead, &fdWrite), "creating socket pair failed\n");
4101     closesocket(fdRead);
4102     FD_ZERO_ALL();
4103     FD_SET_ALL(fdWrite);
4104     FD_SET_ALL(fdRead);
4105     SetLastError(0xdeadbeef);
4106     ret = select(0, &readfds, NULL, &exceptfds, &select_timeout);
4107     ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
4108 todo_wine
4109     ok(GetLastError() == WSAENOTSOCK, "expected 10038, got %d\n", GetLastError());
4110     /* descriptor sets are unchanged */
4111     ok(readfds.fd_count == 2, "expected 2, got %d\n", readfds.fd_count);
4112     ok(exceptfds.fd_count == 2, "expected 2, got %d\n", exceptfds.fd_count);
4113     closesocket(fdWrite);
4114 
4115 #if ROSTESTS_233_IS_FIXED
4116 
4117     /* Close the socket currently being selected in a thread - bug 38399 */
4118     ok(!tcp_socketpair(&fdRead, &fdWrite), "creating socket pair failed\n");
4119     thread_handle = CreateThread(NULL, 0, SelectCloseThread, &fdWrite, 0, &id);
4120     ok(thread_handle != NULL, "CreateThread failed unexpectedly: %d\n", GetLastError());
4121     FD_ZERO_ALL();
4122     FD_SET_ALL(fdWrite);
4123     ret = select(0, &readfds, NULL, &exceptfds, &select_timeout);
4124     ok(ret == 1, "expected 1, got %d\n", ret);
4125     ok(FD_ISSET(fdWrite, &readfds), "fdWrite socket is not in the set\n");
4126     WaitForSingleObject (thread_handle, 1000);
4127     closesocket(fdRead);
4128     /* test again with only the except descriptor */
4129     ok(!tcp_socketpair(&fdRead, &fdWrite), "creating socket pair failed\n");
4130     thread_handle = CreateThread(NULL, 0, SelectCloseThread, &fdWrite, 0, &id);
4131     ok(thread_handle != NULL, "CreateThread failed unexpectedly: %d\n", GetLastError());
4132     FD_ZERO_ALL();
4133     FD_SET(fdWrite, &exceptfds);
4134     SetLastError(0xdeadbeef);
4135     ret = select(0, NULL, NULL, &exceptfds, &select_timeout);
4136 todo_wine
4137     ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
4138 todo_wine
4139     ok(GetLastError() == WSAENOTSOCK, "expected 10038, got %d\n", GetLastError());
4140     WaitForSingleObject (thread_handle, 1000);
4141     closesocket(fdRead);
4142 
4143 #endif /* ROSTESTS_233_IS_FIXED */
4144 
4145     /* test UDP behavior of unbound sockets */
4146     select_timeout.tv_sec = 0;
4147     select_timeout.tv_usec = 250000;
4148     fdWrite = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
4149     ok(fdWrite != INVALID_SOCKET, "socket call failed\n");
4150     FD_ZERO_ALL();
4151     FD_SET_ALL(fdWrite);
4152     ret = select(0, &readfds, &writefds, &exceptfds, &select_timeout);
4153     ok(ret == 1, "expected 1, got %d\n", ret);
4154     ok(FD_ISSET(fdWrite, &writefds), "fdWrite socket is not in the set\n");
4155     closesocket(fdWrite);
4156 }
4157 #undef FD_SET_ALL
4158 #undef FD_ZERO_ALL
4159 
4160 static DWORD WINAPI AcceptKillThread(void *param)
4161 {
4162     select_thread_params *par = param;
4163     struct sockaddr_in address;
4164     int len = sizeof(address);
4165     SOCKET client_socket;
4166 
4167     SetEvent(server_ready);
4168     client_socket = accept(par->s, (struct sockaddr*) &address, &len);
4169     if (client_socket != INVALID_SOCKET)
4170         closesocket(client_socket);
4171     par->ReadKilled = (client_socket == INVALID_SOCKET);
4172     return 0;
4173 }
4174 
4175 
4176 static int CALLBACK AlwaysDeferConditionFunc(LPWSABUF lpCallerId, LPWSABUF lpCallerData, LPQOS pQos,
4177                                              LPQOS lpGQOS, LPWSABUF lpCalleeId, LPWSABUF lpCalleeData,
4178                                              GROUP *g, DWORD_PTR dwCallbackData)
4179 {
4180     return CF_DEFER;
4181 }
4182 
4183 static SOCKET setup_server_socket(struct sockaddr_in *addr, int *len)
4184 {
4185     int ret, val;
4186     SOCKET server_socket;
4187 
4188     server_socket = socket(AF_INET, SOCK_STREAM, 0);
4189     if (server_socket == INVALID_SOCKET)
4190     {
4191         trace("error creating server socket: %d\n", WSAGetLastError());
4192         return INVALID_SOCKET;
4193     }
4194 
4195     val = 1;
4196     ret = setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&val, sizeof(val));
4197     if (ret)
4198     {
4199         trace("error setting SO_REUSEADDR: %d\n", WSAGetLastError());
4200         closesocket(server_socket);
4201         return INVALID_SOCKET;
4202     }
4203 
4204     ret = bind(server_socket, (struct sockaddr *)addr, *len);
4205     if (ret)
4206     {
4207         trace("error binding server socket: %d\n", WSAGetLastError());
4208     }
4209 
4210     ret = getsockname(server_socket, (struct sockaddr *)addr, len);
4211     if (ret)
4212     {
4213         skip("failed to lookup bind address: %d\n", WSAGetLastError());
4214         closesocket(server_socket);
4215         return INVALID_SOCKET;
4216     }
4217 
4218     ret = listen(server_socket, 5);
4219     if (ret)
4220     {
4221         trace("error making server socket listen: %d\n", WSAGetLastError());
4222         closesocket(server_socket);
4223         return INVALID_SOCKET;
4224     }
4225 
4226     return server_socket;
4227 }
4228 
4229 static SOCKET setup_connector_socket(struct sockaddr_in *addr, int len, BOOL nonblock)
4230 {
4231     int ret;
4232     SOCKET connector;
4233 
4234     connector = socket(AF_INET, SOCK_STREAM, 0);
4235     ok(connector != INVALID_SOCKET, "failed to create connector socket %d\n", WSAGetLastError());
4236 
4237     if (nonblock)
4238         set_blocking(connector, !nonblock);
4239 
4240     ret = connect(connector, (struct sockaddr *)addr, len);
4241     if (!nonblock)
4242         ok(!ret, "connecting to accepting socket failed %d\n", WSAGetLastError());
4243     else if (ret == SOCKET_ERROR)
4244     {
4245         DWORD error = WSAGetLastError();
4246         ok(error == WSAEWOULDBLOCK || error == WSAEINPROGRESS,
4247            "expected 10035 or 10036, got %d\n", error);
4248     }
4249 
4250     return connector;
4251 }
4252 
4253 static void test_accept(void)
4254 {
4255     int ret;
4256     SOCKET server_socket, accepted = INVALID_SOCKET, connector;
4257     struct sockaddr_in address;
4258     SOCKADDR_STORAGE ss, ss_empty;
4259     int socklen;
4260     select_thread_params thread_params;
4261     HANDLE thread_handle = NULL;
4262     DWORD id;
4263 
4264     memset(&address, 0, sizeof(address));
4265     address.sin_addr.s_addr = inet_addr("127.0.0.1");
4266     address.sin_family = AF_INET;
4267 
4268     socklen = sizeof(address);
4269     server_socket = setup_server_socket(&address, &socklen);
4270     if (server_socket == INVALID_SOCKET)
4271     {
4272         trace("error creating server socket: %d\n", WSAGetLastError());
4273         return;
4274     }
4275 
4276     connector = setup_connector_socket(&address, socklen, FALSE);
4277     if (connector == INVALID_SOCKET) goto done;
4278 
4279     trace("Blocking accept next\n");
4280 
4281     accepted = WSAAccept(server_socket, NULL, NULL, AlwaysDeferConditionFunc, 0);
4282     ok(accepted == INVALID_SOCKET && WSAGetLastError() == WSATRY_AGAIN, "Failed to defer connection, %d\n", WSAGetLastError());
4283 
4284     accepted = accept(server_socket, NULL, 0);
4285     ok(accepted != INVALID_SOCKET, "Failed to accept deferred connection, error %d\n", WSAGetLastError());
4286 
4287     server_ready = CreateEventA(NULL, TRUE, FALSE, NULL);
4288     if (server_ready == INVALID_HANDLE_VALUE)
4289     {
4290         trace("error creating event: %d\n", GetLastError());
4291         goto done;
4292     }
4293 
4294     thread_params.s = server_socket;
4295     thread_params.ReadKilled = FALSE;
4296     thread_handle = CreateThread(NULL, 0, AcceptKillThread, &thread_params, 0, &id);
4297     if (thread_handle == NULL)
4298     {
4299         trace("error creating thread: %d\n", GetLastError());
4300         goto done;
4301     }
4302 
4303     WaitForSingleObject(server_ready, INFINITE);
4304     Sleep(200);
4305     ret = closesocket(server_socket);
4306     if (ret != 0)
4307     {
4308         trace("closesocket failed: %d\n", WSAGetLastError());
4309         goto done;
4310     }
4311 
4312     WaitForSingleObject(thread_handle, 1000);
4313     ok(thread_params.ReadKilled, "closesocket did not wake up 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, "getsockname did not zero the sockaddr_in structure\n");
4586 
4587     closesocket(sock);
4588 
4589     h = gethostbyname("");
4590     if (h && h->h_length == 4) /* this test is only meaningful in IPv4 */
4591     {
4592         int i;
4593         for (i = 0; h->h_addr_list[i]; i++)
4594         {
4595             char ipstr[32];
4596             struct in_addr ip;
4597             ip.s_addr = *(ULONG *) h->h_addr_list[i];
4598 
4599             sock = socket(AF_INET, SOCK_DGRAM, 0);
4600             ok(sock != INVALID_SOCKET, "socket failed with %d\n", GetLastError());
4601 
4602             memset(&sa_set, 0, sizeof(sa_set));
4603             sa_set.sin_family = AF_INET;
4604             sa_set.sin_addr.s_addr = ip.s_addr;
4605             /* The same address we bind must be the same address we get */
4606             ret = bind(sock, (struct sockaddr*)&sa_set, sizeof(sa_set));
4607             ok(ret == 0, "bind failed with %d\n", GetLastError());
4608             sa_get_len = sizeof(sa_get);
4609             ret = getsockname(sock, (struct sockaddr*)&sa_get, &sa_get_len);
4610             ok(ret == 0, "getsockname failed with %d\n", GetLastError());
4611             strcpy(ipstr, inet_ntoa(sa_get.sin_addr));
4612             trace("testing bind on interface %s\n", ipstr);
4613             ok(sa_get.sin_addr.s_addr == sa_set.sin_addr.s_addr,
4614                "address does not match: %s != %s\n", ipstr, inet_ntoa(sa_set.sin_addr));
4615 
4616             closesocket(sock);
4617         }
4618     }
4619 
4620     WSACleanup();
4621 }
4622 
4623 static void test_dns(void)
4624 {
4625     struct hostent *h;
4626     union memaddress
4627     {
4628         char *chr;
4629         void *mem;
4630     } addr;
4631     char **ptr;
4632     int acount;
4633 
4634     h = gethostbyname("");
4635     ok(h != NULL, "gethostbyname(\"\") failed with %d\n", h_errno);
4636 
4637     /* Use an address with valid alias names if possible */
4638     h = gethostbyname("source.winehq.org");
4639     if(!h)
4640     {
4641         skip("Can't test the hostent structure because gethostbyname failed\n");
4642         return;
4643     }
4644 
4645     /* The returned struct must be allocated in a very strict way. First we need to
4646      * count how many aliases there are because they must be located right after
4647      * the struct hostent size. Knowing the amount of aliases we know the exact
4648      * location of the first IP returned. Rule valid for >= XP, for older OS's
4649      * it's somewhat the opposite. */
4650     addr.mem = h + 1;
4651     if(h->h_addr_list == addr.mem) /* <= W2K */
4652     {
4653         win_skip("Skipping hostent tests since this OS is unsupported\n");
4654         return;
4655     }
4656 
4657     ok(h->h_aliases == addr.mem,
4658        "hostent->h_aliases should be in %p, it is in %p\n", addr.mem, h->h_aliases);
4659 
4660     for(ptr = h->h_aliases, acount = 1; *ptr; ptr++) acount++;
4661     addr.chr += sizeof(*ptr) * acount;
4662     ok(h->h_addr_list == addr.mem,
4663        "hostent->h_addr_list should be in %p, it is in %p\n", addr.mem, h->h_addr_list);
4664 
4665     for(ptr = h->h_addr_list, acount = 1; *ptr; ptr++) acount++;
4666 
4667     addr.chr += sizeof(*ptr) * acount;
4668     ok(h->h_addr_list[0] == addr.mem,
4669        "hostent->h_addr_list[0] should be in %p, it is in %p\n", addr.mem, h->h_addr_list[0]);
4670 }
4671 
4672 #ifndef __REACTOS__
4673 /* Our winsock headers don't define gethostname because it conflicts with the
4674  * definition in unistd.h. Define it here to get rid of the warning. */
4675 
4676 int WINAPI gethostname(char *name, int namelen);
4677 #endif
4678 
4679 static void test_gethostbyname(void)
4680 {
4681     struct hostent *he;
4682     struct in_addr **addr_list;
4683     char name[256], first_ip[16];
4684     int ret, i, count;
4685     PMIB_IPFORWARDTABLE routes = NULL;
4686     PIP_ADAPTER_INFO adapters = NULL, k;
4687     DWORD adap_size = 0, route_size = 0;
4688     BOOL found_default = FALSE;
4689     BOOL local_ip = FALSE;
4690 
4691     ret = gethostname(name, sizeof(name));
4692     ok(ret == 0, "gethostname() call failed: %d\n", WSAGetLastError());
4693 
4694     he = gethostbyname(name);
4695     ok(he != NULL, "gethostbyname(\"%s\") failed: %d\n", name, WSAGetLastError());
4696 #ifdef __REACTOS__ /* ROSTESTS-233 */
4697     if (he != NULL)
4698     {
4699 #endif
4700         addr_list = (struct in_addr **)he->h_addr_list;
4701         strcpy(first_ip, inet_ntoa(*addr_list[0]));
4702 
4703         trace("List of local IPs:\n");
4704         for(count = 0; addr_list[count] != NULL; count++)
4705         {
4706             char *ip = inet_ntoa(*addr_list[count]);
4707             if (!strcmp(ip, "127.0.0.1"))
4708                 local_ip = TRUE;
4709             trace("%s\n", ip);
4710         }
4711 #ifdef __REACTOS__ /* ROSTESTS-233 */
4712     }
4713 #endif
4714 
4715     if (local_ip)
4716     {
4717         ok (count == 1, "expected 127.0.0.1 to be the only IP returned\n");
4718         skip("Only the loopback address is present, skipping tests\n");
4719         return;
4720     }
4721 
4722     if (!pGetAdaptersInfo || !pGetIpForwardTable)
4723     {
4724         win_skip("GetAdaptersInfo and/or GetIpForwardTable not found, skipping tests\n");
4725         return;
4726     }
4727 
4728     ret = pGetAdaptersInfo(NULL, &adap_size);
4729     ok (ret  == ERROR_BUFFER_OVERFLOW, "GetAdaptersInfo failed with a different error: %d\n", ret);
4730     ret = pGetIpForwardTable(NULL, &route_size, FALSE);
4731     ok (ret == ERROR_INSUFFICIENT_BUFFER, "GetIpForwardTable failed with a different error: %d\n", ret);
4732 
4733     adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
4734     routes = HeapAlloc(GetProcessHeap(), 0, route_size);
4735 
4736     ret = pGetAdaptersInfo(adapters, &adap_size);
4737     ok (ret  == NO_ERROR, "GetAdaptersInfo failed, error: %d\n", ret);
4738     ret = pGetIpForwardTable(routes, &route_size, FALSE);
4739     ok (ret == NO_ERROR, "GetIpForwardTable failed, error: %d\n", ret);
4740 
4741     /* This test only has meaning if there is more than one IP configured */
4742     if (adapters->Next == NULL && count == 1)
4743     {
4744         skip("Only one IP is present, skipping tests\n");
4745         goto cleanup;
4746     }
4747 
4748     for (i = 0; !found_default && i < routes->dwNumEntries; i++)
4749     {
4750         /* default route (ip 0.0.0.0) ? */
4751         if (routes->table[i].dwForwardDest) continue;
4752 
4753         for (k = adapters; k != NULL; k = k->Next)
4754         {
4755             char *ip;
4756 
4757             if (k->Index != routes->table[i].dwForwardIfIndex) continue;
4758 
4759             /* the first IP returned from gethostbyname must be a default route */
4760             ip = k->IpAddressList.IpAddress.String;
4761             if (!strcmp(first_ip, ip))
4762             {
4763                 found_default = TRUE;
4764                 break;
4765             }
4766         }
4767     }
4768     ok (found_default, "failed to find the first IP from gethostbyname!\n");
4769 
4770 cleanup:
4771     HeapFree(GetProcessHeap(), 0, adapters);
4772     HeapFree(GetProcessHeap(), 0, routes);
4773 }
4774 
4775 static void test_gethostbyname_hack(void)
4776 {
4777     struct hostent *he;
4778     char name[256];
4779     static BYTE loopback[] = {127, 0, 0, 1};
4780     static BYTE magic_loopback[] = {127, 12, 34, 56};
4781     int ret;
4782 
4783     ret = gethostname(name, 256);
4784     ok(ret == 0, "gethostname() call failed: %d\n", WSAGetLastError());
4785 
4786     he = gethostbyname("localhost");
4787     ok(he != NULL, "gethostbyname(\"localhost\") failed: %d\n", h_errno);
4788     if(he)
4789     {
4790         if(he->h_length != 4)
4791         {
4792             skip("h_length is %d, not IPv4, skipping test.\n", he->h_length);
4793             return;
4794         }
4795 
4796         ok(memcmp(he->h_addr_list[0], loopback, he->h_length) == 0,
4797            "gethostbyname(\"localhost\") returned %u.%u.%u.%u\n",
4798            he->h_addr_list[0][0], he->h_addr_list[0][1], he->h_addr_list[0][2],
4799            he->h_addr_list[0][3]);
4800     }
4801 
4802     if(strcmp(name, "localhost") == 0)
4803     {
4804         skip("hostname seems to be \"localhost\", skipping test.\n");
4805         return;
4806     }
4807 
4808     he = gethostbyname(name);
4809     ok(he != NULL, "gethostbyname(\"%s\") failed: %d\n", name, h_errno);
4810     if(he)
4811     {
4812         if(he->h_length != 4)
4813         {
4814             skip("h_length is %d, not IPv4, skipping test.\n", he->h_length);
4815             return;
4816         }
4817 
4818         if (he->h_addr_list[0][0] == 127)
4819         {
4820             ok(memcmp(he->h_addr_list[0], magic_loopback, he->h_length) == 0,
4821                "gethostbyname(\"%s\") returned %u.%u.%u.%u not 127.12.34.56\n",
4822                name, he->h_addr_list[0][0], he->h_addr_list[0][1],
4823                he->h_addr_list[0][2], he->h_addr_list[0][3]);
4824         }
4825     }
4826 
4827     gethostbyname("nonexistent.winehq.org");
4828     /* Don't check for the return value, as some braindead ISPs will kindly
4829      * resolve nonexistent host names to addresses of the ISP's spam pages. */
4830 }
4831 
4832 static void test_gethostname(void)
4833 {
4834     struct hostent *he;
4835     char name[256];
4836     int ret, len;
4837 
4838     WSASetLastError(0xdeadbeef);
4839     ret = gethostname(NULL, 256);
4840     ok(ret == -1, "gethostname() returned %d\n", ret);
4841     ok(WSAGetLastError() == WSAEFAULT, "gethostname with null buffer "
4842             "failed with %d, expected %d\n", WSAGetLastError(), WSAEFAULT);
4843 
4844     ret = gethostname(name, sizeof(name));
4845     ok(ret == 0, "gethostname() call failed: %d\n", WSAGetLastError());
4846     he = gethostbyname(name);
4847     ok(he != NULL, "gethostbyname(\"%s\") failed: %d\n", name, WSAGetLastError());
4848 
4849     len = strlen(name);
4850     WSASetLastError(0xdeadbeef);
4851     strcpy(name, "deadbeef");
4852     ret = gethostname(name, len);
4853     ok(ret == -1, "gethostname() returned %d\n", ret);
4854     ok(!strcmp(name, "deadbeef"), "name changed unexpected!\n");
4855     ok(WSAGetLastError() == WSAEFAULT, "gethostname with insufficient length "
4856             "failed with %d, expected %d\n", WSAGetLastError(), WSAEFAULT);
4857 
4858     len++;
4859     ret = gethostname(name, len);
4860     ok(ret == 0, "gethostname() call failed: %d\n", WSAGetLastError());
4861     he = gethostbyname(name);
4862     ok(he != NULL, "gethostbyname(\"%s\") failed: %d\n", name, WSAGetLastError());
4863 }
4864 
4865 static void test_inet_addr(void)
4866 {
4867     u_long addr;
4868 
4869     addr = inet_addr(NULL);
4870     ok(addr == INADDR_NONE, "inet_addr succeeded unexpectedly\n");
4871 }
4872 
4873 static void test_addr_to_print(void)
4874 {
4875     char dst[16];
4876     char dst6[64];
4877     const char * pdst;
4878     struct in_addr in;
4879     struct in6_addr in6;
4880 
4881     u_long addr0_Num = 0x00000000;
4882     PCSTR addr0_Str = "0.0.0.0";
4883     u_long addr1_Num = 0x20201015;
4884     PCSTR addr1_Str = "21.16.32.32";
4885     u_char addr2_Num[16] = {0,0,0,0,0,0,0,0,0,0,0xff,0xfe,0xcC,0x98,0xbd,0x74};
4886     PCSTR addr2_Str = "::fffe:cc98:bd74";
4887     u_char addr3_Num[16] = {0x20,0x30,0xa4,0xb1};
4888     PCSTR addr3_Str = "2030:a4b1::";
4889     u_char addr4_Num[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0xcC,0x98,0xbd,0x74};
4890     PCSTR addr4_Str = "::204.152.189.116";
4891 
4892     /* Test IPv4 addresses */
4893     in.s_addr = addr0_Num;
4894 
4895     pdst = inet_ntoa(*((struct in_addr*)&in.s_addr));
4896     ok(pdst != NULL, "inet_ntoa failed %s\n", dst);
4897     ok(!strcmp(pdst, addr0_Str),"Address %s != %s\n", pdst, addr0_Str);
4898 
4899     /* Test that inet_ntoa and inet_ntop return the same value */
4900     in.S_un.S_addr = addr1_Num;
4901     pdst = inet_ntoa(*((struct in_addr*)&in.s_addr));
4902     ok(pdst != NULL, "inet_ntoa failed %s\n", dst);
4903     ok(!strcmp(pdst, addr1_Str),"Address %s != %s\n", pdst, addr1_Str);
4904 
4905     /* InetNtop became available in Vista and Win2008 */
4906     if (!pInetNtop)
4907     {
4908         win_skip("InetNtop not present, not executing tests\n");
4909         return;
4910     }
4911 
4912     /* Second part of test */
4913     pdst = pInetNtop(AF_INET,(void*)&in.s_addr, dst, sizeof(dst));
4914     ok(pdst != NULL, "InetNtop failed %s\n", dst);
4915     ok(!strcmp(pdst, addr1_Str),"Address %s != %s\n", pdst, addr1_Str);
4916 
4917     /* Test invalid parm conditions */
4918     pdst = pInetNtop(1, (void*)&in.s_addr, dst, sizeof(dst));
4919     ok(pdst == NULL, "The pointer should not be returned (%p)\n", pdst);
4920     ok(WSAGetLastError() == WSAEAFNOSUPPORT, "Should be WSAEAFNOSUPPORT\n");
4921 
4922     /* Test Null destination */
4923     pdst = NULL;
4924     pdst = pInetNtop(AF_INET, (void*)&in.s_addr, NULL, sizeof(dst));
4925     ok(pdst == NULL, "The pointer should not be returned (%p)\n", pdst);
4926     ok(WSAGetLastError() == STATUS_INVALID_PARAMETER || WSAGetLastError() == WSAEINVAL /* Win7 */,
4927        "Should be STATUS_INVALID_PARAMETER or WSAEINVAL not 0x%x\n", WSAGetLastError());
4928 
4929     /* Test zero length passed */
4930     WSASetLastError(0);
4931     pdst = NULL;
4932     pdst = pInetNtop(AF_INET, (void*)&in.s_addr, dst, 0);
4933     ok(pdst == NULL, "The pointer should not be returned (%p)\n", pdst);
4934     ok(WSAGetLastError() == STATUS_INVALID_PARAMETER || WSAGetLastError() == WSAEINVAL /* Win7 */,
4935        "Should be STATUS_INVALID_PARAMETER or WSAEINVAL not 0x%x\n", WSAGetLastError());
4936 
4937     /* Test length one shorter than the address length */
4938     WSASetLastError(0);
4939     pdst = NULL;
4940     pdst = pInetNtop(AF_INET, (void*)&in.s_addr, dst, 6);
4941     ok(pdst == NULL, "The pointer should not be returned (%p)\n", pdst);
4942     ok(WSAGetLastError() == STATUS_INVALID_PARAMETER || WSAGetLastError() == WSAEINVAL /* Win7 */,
4943        "Should be STATUS_INVALID_PARAMETER or WSAEINVAL not 0x%x\n", WSAGetLastError());
4944 
4945     /* Test longer length is ok */
4946     WSASetLastError(0);
4947     pdst = NULL;
4948     pdst = pInetNtop(AF_INET, (void*)&in.s_addr, dst, sizeof(dst)+1);
4949     ok(pdst != NULL, "The pointer should  be returned (%p)\n", pdst);
4950     ok(!strcmp(pdst, addr1_Str),"Address %s != %s\n", pdst, addr1_Str);
4951 
4952     /* Test the IPv6 addresses */
4953 
4954     /* Test an zero prefixed IPV6 address */
4955     memcpy(in6.u.Byte, addr2_Num, sizeof(addr2_Num));
4956     pdst = pInetNtop(AF_INET6,(void*)&in6.s6_addr, dst6, sizeof(dst6));
4957     ok(pdst != NULL, "InetNtop failed %s\n", dst6);
4958     ok(!strcmp(pdst, addr2_Str),"Address %s != %s\n", pdst, addr2_Str);
4959 
4960     /* Test an zero suffixed IPV6 address */
4961     memcpy(in6.s6_addr, addr3_Num, sizeof(addr3_Num));
4962     pdst = pInetNtop(AF_INET6,(void*)&in6.s6_addr, dst6, sizeof(dst6));
4963     ok(pdst != NULL, "InetNtop failed %s\n", dst6);
4964     ok(!strcmp(pdst, addr3_Str),"Address %s != %s\n", pdst, addr3_Str);
4965 
4966     /* Test the IPv6 address contains the IPv4 address in IPv4 notation */
4967     memcpy(in6.s6_addr, addr4_Num, sizeof(addr4_Num));
4968     pdst = pInetNtop(AF_INET6, (void*)&in6.s6_addr, dst6, sizeof(dst6));
4969     ok(pdst != NULL, "InetNtop failed %s\n", dst6);
4970     ok(!strcmp(pdst, addr4_Str),"Address %s != %s\n", pdst, addr4_Str);
4971 
4972     /* Test invalid parm conditions */
4973     memcpy(in6.u.Byte, addr2_Num, sizeof(addr2_Num));
4974 
4975     /* Test Null destination */
4976     pdst = NULL;
4977     pdst = pInetNtop(AF_INET6, (void*)&in6.s6_addr, NULL, sizeof(dst6));
4978     ok(pdst == NULL, "The pointer should not be returned (%p)\n", pdst);
4979     ok(WSAGetLastError() == STATUS_INVALID_PARAMETER || WSAGetLastError() == WSAEINVAL /* Win7 */,
4980        "Should be STATUS_INVALID_PARAMETER or WSAEINVAL not 0x%x\n", WSAGetLastError());
4981 
4982     /* Test zero length passed */
4983     WSASetLastError(0);
4984     pdst = NULL;
4985     pdst = pInetNtop(AF_INET6, (void*)&in6.s6_addr, dst6, 0);
4986     ok(pdst == NULL, "The pointer should not be returned (%p)\n", pdst);
4987     ok(WSAGetLastError() == STATUS_INVALID_PARAMETER || WSAGetLastError() == WSAEINVAL /* Win7 */,
4988        "Should be STATUS_INVALID_PARAMETER or WSAEINVAL not 0x%x\n", WSAGetLastError());
4989 
4990     /* Test length one shorter than the address length */
4991     WSASetLastError(0);
4992     pdst = NULL;
4993     pdst = pInetNtop(AF_INET6, (void*)&in6.s6_addr, dst6, 16);
4994     ok(pdst == NULL, "The pointer should not be returned (%p)\n", pdst);
4995     ok(WSAGetLastError() == STATUS_INVALID_PARAMETER || WSAGetLastError() == WSAEINVAL /* Win7 */,
4996        "Should be STATUS_INVALID_PARAMETER or WSAEINVAL not 0x%x\n", WSAGetLastError());
4997 
4998     /* Test longer length is ok */
4999     WSASetLastError(0);
5000     pdst = NULL;
5001     pdst = pInetNtop(AF_INET6, (void*)&in6.s6_addr, dst6, 18);
5002     ok(pdst != NULL, "The pointer should be returned (%p)\n", pdst);
5003 }
5004 static void test_inet_pton(void)
5005 {
5006     struct TEST_DATA
5007     {
5008         int family, ret;
5009         DWORD err;
5010         const char *printable, *collapsed, *raw_data;
5011     } tests[] = {
5012         {AF_UNSPEC, -1, WSAEFAULT,    /* Test 0 */
5013         NULL, NULL, NULL},
5014         {AF_INET, -1, WSAEFAULT,
5015         NULL, NULL, NULL},
5016         {AF_INET6, -1, WSAEFAULT,
5017         NULL, NULL, NULL},
5018         {AF_UNSPEC, -1, WSAEAFNOSUPPORT,
5019         "127.0.0.1", NULL, NULL},
5020         {AF_INET, 1, 0,
5021         "127.0.0.1", "127.0.0.1",
5022         "\x7f\x00\x00\x01"},
5023         {AF_INET6, 0, 0,
5024         "127.0.0.1", "127.0.0.1", NULL},
5025         {AF_INET, 0, 0,
5026         "::1/128", NULL, NULL},
5027         {AF_INET6, 0, 0,
5028         "::1/128", NULL, NULL},
5029         {AF_UNSPEC, -1, WSAEAFNOSUPPORT,
5030         "broken", NULL, NULL},
5031         {AF_INET, 0, 0,
5032         "broken", NULL, NULL},
5033         {AF_INET6, 0, 0,              /* Test 10 */
5034         "broken", NULL, NULL},
5035         {AF_UNSPEC, -1, WSAEAFNOSUPPORT,
5036         "177.32.45.20", NULL, NULL},
5037         {AF_INET, 1, 0,
5038         "177.32.45.20", "177.32.45.20",
5039         "\xb1\x20\x2d\x14"},
5040         {AF_INET6, 0, 0,
5041         "177.32.45.20", NULL, NULL},
5042         {AF_INET, 0, 0,
5043         "2607:f0d0:1002:51::4", NULL, NULL},
5044         {AF_INET6, 1, 0,
5045         "2607:f0d0:1002:51::4", "2607:f0d0:1002:51::4",
5046         "\x26\x07\xf0\xd0\x10\x02\x00\x51\x00\x00\x00\x00\x00\x00\x00\x04"},
5047         {AF_INET, 0, 0,
5048         "::177.32.45.20", NULL, NULL},
5049         {AF_INET6, 1, 0,
5050         "::177.32.45.20", "::177.32.45.20",
5051         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xb1\x20\x2d\x14"},
5052         {AF_INET, 0, 0,
5053         "fe80::0202:b3ff:fe1e:8329", NULL, NULL},
5054         {AF_INET6, 1, 0,
5055         "fe80::0202:b3ff:fe1e:8329", "fe80::202:b3ff:fe1e:8329",
5056         "\xfe\x80\x00\x00\x00\x00\x00\x00\x02\x02\xb3\xff\xfe\x1e\x83\x29"},
5057         {AF_INET6, 1, 0,              /* Test 20 */
5058         "fe80::202:b3ff:fe1e:8329", "fe80::202:b3ff:fe1e:8329",
5059         "\xfe\x80\x00\x00\x00\x00\x00\x00\x02\x02\xb3\xff\xfe\x1e\x83\x29"},
5060         {AF_INET, 0, 0,
5061         "a", NULL, NULL},
5062         {AF_INET, 0, 0,
5063         "a.b", NULL, NULL},
5064         {AF_INET, 0, 0,
5065         "a.b.c",  NULL, NULL},
5066         {AF_INET, 0, 0,
5067         "a.b.c.d", NULL, NULL},
5068         {AF_INET6, 1, 0,
5069         "2001:cdba:0000:0000:0000:0000:3257:9652", "2001:cdba::3257:9652",
5070         "\x20\x01\xcd\xba\x00\x00\x00\x00\x00\x00\x00\x00\x32\x57\x96\x52"},
5071         {AF_INET6, 1, 0,
5072         "2001:cdba::3257:9652", "2001:cdba::3257:9652",
5073         "\x20\x01\xcd\xba\x00\x00\x00\x00\x00\x00\x00\x00\x32\x57\x96\x52"},
5074         {AF_INET6, 1, 0,
5075         "2001:cdba:0:0:0:0:3257:9652", "2001:cdba::3257:9652",
5076         "\x20\x01\xcd\xba\x00\x00\x00\x00\x00\x00\x00\x00\x32\x57\x96\x52"}
5077     };
5078     int i, ret;
5079     DWORD err;
5080     char buffer[64],str[64];
5081     WCHAR printableW[64], collapsedW[64];
5082     const char *ptr;
5083     const WCHAR *ptrW;
5084 
5085     /* InetNtop and InetPton became available in Vista and Win2008 */
5086     if (!pInetNtop || !pInetNtopW || !pInetPtonA || !pInetPtonW)
5087     {
5088         win_skip("InetNtop and/or InetPton not present, not executing tests\n");
5089         return;
5090     }
5091 
5092     for (i = 0; i < sizeof(tests) / sizeof(tests[0]); i++)
5093     {
5094         WSASetLastError(0xdeadbeef);
5095         ret = pInetPtonA(tests[i].family, tests[i].printable, buffer);
5096         ok (ret == tests[i].ret, "Test [%d]: Expected %d, got %d\n", i, tests[i].ret, ret);
5097         if (tests[i].ret == -1)
5098         {
5099             err = WSAGetLastError();
5100             ok (tests[i].err == err, "Test [%d]: Expected 0x%x, got 0x%x\n", i, tests[i].err, err);
5101         }
5102         if (tests[i].ret != 1) continue;
5103         ok (memcmp(buffer, tests[i].raw_data,
5104             tests[i].family == AF_INET ? sizeof(struct in_addr) : sizeof(struct in6_addr)) == 0,
5105             "Test [%d]: Expected binary data differs\n", i);
5106 
5107         /* Test the result from Pton with Ntop */
5108         strcpy (str, "deadbeef");
5109         ptr = pInetNtop(tests[i].family, buffer, str, sizeof(str));
5110         ok (ptr != NULL, "Test [%d]: Failed with NULL\n", i);
5111         ok (ptr == str, "Test [%d]: Pointers differ (%p != %p)\n", i, ptr, str);
5112         if (!ptr) continue;
5113         ok (strcmp(ptr, tests[i].collapsed) == 0, "Test [%d]: Expected '%s', got '%s'\n",
5114             i, tests[i].collapsed, ptr);
5115     }
5116 
5117     for (i = 0; i < sizeof(tests) / sizeof(tests[0]); i++)
5118     {
5119         if (tests[i].printable)
5120             MultiByteToWideChar(CP_ACP, 0, tests[i].printable, -1, printableW,
5121                                 sizeof(printableW) / sizeof(printableW[0]));
5122         WSASetLastError(0xdeadbeef);
5123         ret = pInetPtonW(tests[i].family, tests[i].printable ? printableW : NULL, buffer);
5124         ok(ret == tests[i].ret, "Test [%d]: Expected %d, got %d\n", i, tests[i].ret, ret);
5125         if (tests[i].ret == -1)
5126         {
5127             err = WSAGetLastError();
5128             ok(tests[i].err == err, "Test [%d]: Expected 0x%x, got 0x%x\n", i, tests[i].err, err);
5129         }
5130         if (tests[i].ret != 1) continue;
5131         ok(memcmp(buffer, tests[i].raw_data,
5132            tests[i].family == AF_INET ? sizeof(struct in_addr) : sizeof(struct in6_addr)) == 0,
5133            "Test [%d]: Expected binary data differs\n", i);
5134 
5135         /* Test the result from Pton with Ntop */
5136         printableW[0] = 0xdead;
5137         ptrW = pInetNtopW(tests[i].family, buffer, printableW, sizeof(printableW) / sizeof(printableW[0]));
5138         ok (ptrW != NULL, "Test [%d]: Failed with NULL\n", i);
5139         ok (ptrW == printableW, "Test [%d]: Pointers differ (%p != %p)\n", i, ptrW, printableW);
5140         if (!ptrW) continue;
5141 
5142         MultiByteToWideChar(CP_ACP, 0, tests[i].collapsed, -1, collapsedW,
5143                             sizeof(collapsedW) / sizeof(collapsedW[0]));
5144         ok (lstrcmpW(ptrW, collapsedW) == 0, "Test [%d]: Expected '%s', got '%s'\n",
5145             i, tests[i].collapsed, wine_dbgstr_w(ptrW));
5146     }
5147 }
5148 
5149 static void test_ioctlsocket(void)
5150 {
5151     SOCKET sock, src, dst;
5152     struct tcp_keepalive kalive;
5153     struct sockaddr_in address;
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     make_keepalive(kalive, 0, 0, 0);
5214     ret = WSAIoctl(sock, SIO_KEEPALIVE_VALS, &kalive, sizeof(struct tcp_keepalive), NULL, 0, &arg, NULL, NULL);
5215     ok(ret == 0, "WSAIoctl failed unexpectedly\n");
5216 
5217     make_keepalive(kalive, 1, 0, 0);
5218     ret = WSAIoctl(sock, SIO_KEEPALIVE_VALS, &kalive, sizeof(struct tcp_keepalive), NULL, 0, &arg, NULL, NULL);
5219     ok(ret == 0, "WSAIoctl failed unexpectedly\n");
5220 
5221     make_keepalive(kalive, 1, 1000, 1000);
5222     ret = WSAIoctl(sock, SIO_KEEPALIVE_VALS, &kalive, sizeof(struct tcp_keepalive), NULL, 0, &arg, NULL, NULL);
5223     ok(ret == 0, "WSAIoctl failed unexpectedly\n");
5224 
5225     make_keepalive(kalive, 1, 10000, 10000);
5226     ret = WSAIoctl(sock, SIO_KEEPALIVE_VALS, &kalive, sizeof(struct tcp_keepalive), NULL, 0, &arg, NULL, NULL);
5227     ok(ret == 0, "WSAIoctl failed unexpectedly\n");
5228 
5229     make_keepalive(kalive, 1, 100, 100);
5230     ret = WSAIoctl(sock, SIO_KEEPALIVE_VALS, &kalive, sizeof(struct tcp_keepalive), NULL, 0, &arg, NULL, NULL);
5231     ok(ret == 0, "WSAIoctl failed unexpectedly\n");
5232 
5233     make_keepalive(kalive, 0, 100, 100);
5234     ret = WSAIoctl(sock, SIO_KEEPALIVE_VALS, &kalive, sizeof(struct tcp_keepalive), NULL, 0, &arg, NULL, NULL);
5235     ok(ret == 0, "WSAIoctl failed unexpectedly\n");
5236 
5237     closesocket(sock);
5238 
5239     sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
5240     ok(sock != INVALID_SOCKET, "Creating the socket failed: %d\n", WSAGetLastError());
5241     if(sock == INVALID_SOCKET)
5242     {
5243         skip("Can't continue without a socket.\n");
5244         return;
5245     }
5246 
5247     /* test FIONREAD with a fresh and non-connected socket */
5248     arg = 0xdeadbeef;
5249     ret = ioctlsocket(sock, FIONREAD, &arg);
5250     ok(ret == 0, "ioctlsocket failed unexpectedly with error %d\n", WSAGetLastError());
5251     ok(arg == 0, "expected 0, got %u\n", arg);
5252 
5253     memset(&address, 0, sizeof(address));
5254     address.sin_family = AF_INET;
5255     address.sin_addr.s_addr = inet_addr( SERVERIP );
5256     address.sin_port = htons( SERVERPORT );
5257     ret = bind(sock, (struct sockaddr *)&address, sizeof(address));
5258     ok(ret == 0, "bind failed unexpectedly with error %d\n", WSAGetLastError());
5259 
5260     ret = listen(sock, SOMAXCONN);
5261     ok(ret == 0, "listen failed unexpectedly with error %d\n", WSAGetLastError());
5262 
5263     /* test FIONREAD with listening socket */
5264     arg = 0xdeadbeef;
5265     ret = ioctlsocket(sock, FIONREAD, &arg);
5266     ok(ret == 0, "ioctlsocket failed unexpectedly with error %d\n", WSAGetLastError());
5267     ok(arg == 0, "expected 0, got %u\n", arg);
5268 
5269     closesocket(sock);
5270 
5271     if (tcp_socketpair(&src, &dst) != 0)
5272     {
5273         ok(0, "creating socket pair failed, skipping test\n");
5274         return;
5275     }
5276 
5277     /* test FIONREAD on TCP sockets */
5278     optval = 0xdeadbeef;
5279     ret = WSAIoctl(dst, FIONREAD, NULL, 0, &optval, sizeof(optval), &arg, NULL, NULL);
5280     ok(ret == 0, "WSAIoctl failed unexpectedly with error %d\n", WSAGetLastError());
5281     ok(optval == 0, "FIONREAD should have returned 0 bytes, got %d instead\n", optval);
5282 
5283     optval = 0xdeadbeef;
5284     ok(send(src, "TEST", 4, 0) == 4, "failed to send test data\n");
5285     Sleep(100);
5286     ret = WSAIoctl(dst, FIONREAD, NULL, 0, &optval, sizeof(optval), &arg, NULL, NULL);
5287     ok(ret == 0, "WSAIoctl failed unexpectedly with error %d\n", WSAGetLastError());
5288     ok(optval == 4, "FIONREAD should have returned 4 bytes, got %d instead\n", optval);
5289 
5290     /* trying to read from an OOB inlined socket with MSG_OOB results in WSAEINVAL */
5291     set_blocking(dst, FALSE);
5292     i = MSG_OOB;
5293     SetLastError(0xdeadbeef);
5294     ret = recv(dst, &data, 1, i);
5295     ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
5296     ret = GetLastError();
5297     ok(ret == WSAEWOULDBLOCK, "expected 10035, got %d\n", ret);
5298     bufs.len = sizeof(char);
5299     bufs.buf = &data;
5300     ret = WSARecv(dst, &bufs, 1, &bytes_rec, &i, NULL, NULL);
5301     ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
5302     ret = GetLastError();
5303     ok(ret == WSAEWOULDBLOCK, "expected 10035, got %d\n", ret);
5304     optval = 1;
5305     ret = setsockopt(dst, SOL_SOCKET, SO_OOBINLINE, (void *)&optval, sizeof(optval));
5306     ok(ret != SOCKET_ERROR, "setsockopt failed unexpectedly\n");
5307     i = MSG_OOB;
5308     SetLastError(0xdeadbeef);
5309     ret = recv(dst, &data, 1, i);
5310     ok(ret == SOCKET_ERROR, "expected SOCKET_ERROR, got %d\n", ret);
5311     ret = GetLastError();
5312     ok(ret == WSAEINVAL, "expected 10022, got %d\n", ret);
5313     bufs.len = sizeof(char);
5314     bufs.buf = &data;
5315     ret = WSARecv(dst, &bufs, 1, &bytes_rec, &i, NULL, NULL);
5316     ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
5317     ret = GetLastError();
5318     ok(ret == WSAEINVAL, "expected 10022, got %d\n", ret);
5319 
5320     closesocket(dst);
5321     optval = 0xdeadbeef;
5322     ret = WSAIoctl(dst, FIONREAD, NULL, 0, &optval, sizeof(optval), &arg, NULL, NULL);
5323     ok(ret == SOCKET_ERROR, "WSAIoctl succeeded unexpectedly\n");
5324     ok(optval == 0xdeadbeef, "FIONREAD should not have changed last error, got %d instead\n", optval);
5325     closesocket(src);
5326 }
5327 
5328 static BOOL drain_pause = FALSE;
5329 static DWORD WINAPI drain_socket_thread(LPVOID arg)
5330 {
5331     char buffer[1024];
5332     SOCKET sock = *(SOCKET*)arg;
5333     int ret;
5334 
5335     while ((ret = recv(sock, buffer, sizeof(buffer), 0)) != 0)
5336     {
5337         if (ret < 0)
5338         {
5339             if (WSAGetLastError() == WSAEWOULDBLOCK)
5340             {
5341                 fd_set readset;
5342                 FD_ZERO(&readset);
5343                 FD_SET(sock, &readset);
5344                 select(sock+1, &readset, NULL, NULL, NULL);
5345                 while (drain_pause)
5346                     Sleep(100);
5347             }
5348             else
5349                 break;
5350         }
5351     }
5352     return 0;
5353 }
5354 
5355 static void test_send(void)
5356 {
5357     SOCKET src = INVALID_SOCKET;
5358     SOCKET dst = INVALID_SOCKET;
5359     HANDLE hThread = NULL;
5360     const int buflen = 1024*1024;
5361     char *buffer = NULL;
5362     int ret, i, zero = 0;
5363     WSABUF buf;
5364     OVERLAPPED ov;
5365     BOOL bret;
5366     DWORD id, bytes_sent, dwRet;
5367     DWORD expected_time, connect_time;
5368     socklen_t optlen;
5369 
5370     memset(&ov, 0, sizeof(ov));
5371 
5372     if (tcp_socketpair(&src, &dst) != 0)
5373     {
5374         ok(0, "creating socket pair failed, skipping test\n");
5375         return;
5376     }
5377     expected_time = GetTickCount();
5378 
5379     set_blocking(dst, FALSE);
5380     /* force disable buffering so we can get a pending overlapped request */
5381     ret = setsockopt(dst, SOL_SOCKET, SO_SNDBUF, (char *) &zero, sizeof(zero));
5382     ok(!ret, "setsockopt SO_SNDBUF failed: %d - %d\n", ret, GetLastError());
5383 
5384     hThread = CreateThread(NULL, 0, drain_socket_thread, &dst, 0, &id);
5385     if (hThread == NULL)
5386     {
5387         ok(0, "CreateThread failed, error %d\n", GetLastError());
5388         goto end;
5389     }
5390 
5391     buffer = HeapAlloc(GetProcessHeap(), 0, buflen);
5392     if (buffer == NULL)
5393     {
5394         ok(0, "HeapAlloc failed, error %d\n", GetLastError());
5395         goto end;
5396     }
5397 
5398     /* fill the buffer with some nonsense */
5399     for (i = 0; i < buflen; ++i)
5400     {
5401         buffer[i] = (char) i;
5402     }
5403 
5404     ret = send(src, buffer, buflen, 0);
5405     if (ret >= 0)
5406         ok(ret == buflen, "send should have sent %d bytes, but it only sent %d\n", buflen, ret);
5407     else
5408         ok(0, "send failed, error %d\n", WSAGetLastError());
5409 
5410     buf.buf = buffer;
5411     buf.len = buflen;
5412 
5413     ov.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
5414     ok(ov.hEvent != NULL, "could not create event object, errno = %d\n", GetLastError());
5415     if (!ov.hEvent)
5416         goto end;
5417 
5418     bytes_sent = 0;
5419     WSASetLastError(12345);
5420     ret = WSASend(dst, &buf, 1, &bytes_sent, 0, &ov, NULL);
5421     ok((ret == SOCKET_ERROR && WSAGetLastError() == ERROR_IO_PENDING) || broken(bytes_sent == buflen),
5422        "Failed to start overlapped send %d - %d - %d/%d\n", ret, WSAGetLastError(), bytes_sent, buflen);
5423 
5424     /* don't check for completion yet, we may need to drain the buffer while still sending */
5425     set_blocking(src, FALSE);
5426     for (i = 0; i < buflen; ++i)
5427     {
5428         int j = 0;
5429 
5430         ret = recv(src, buffer, 1, 0);
5431         while (ret == SOCKET_ERROR && GetLastError() == WSAEWOULDBLOCK && j < 100)
5432         {
5433             j++;
5434             Sleep(50);
5435             ret = recv(src, buffer, 1, 0);
5436         }
5437 
5438         ok(ret == 1, "Failed to receive data %d - %d (got %d/%d)\n", ret, GetLastError(), i, buflen);
5439         if (ret != 1)
5440             break;
5441 
5442         ok(buffer[0] == (char) i, "Received bad data at position %d\n", i);
5443     }
5444 
5445     dwRet = WaitForSingleObject(ov.hEvent, 1000);
5446     ok(dwRet == WAIT_OBJECT_0, "Failed to wait for recv message: %d - %d\n", dwRet, GetLastError());
5447     if (dwRet == WAIT_OBJECT_0)
5448     {
5449         bret = GetOverlappedResult((HANDLE)dst, &ov, &bytes_sent, FALSE);
5450         ok(bret && bytes_sent == buflen,
5451            "Got %d instead of %d (%d - %d)\n", bytes_sent, buflen, bret, GetLastError());
5452     }
5453 
5454     WSASetLastError(12345);
5455     ret = WSASend(INVALID_SOCKET, &buf, 1, NULL, 0, &ov, NULL);
5456     ok(ret == SOCKET_ERROR && WSAGetLastError() == WSAENOTSOCK,
5457        "WSASend failed %d - %d\n", ret, WSAGetLastError());
5458 
5459     WSASetLastError(12345);
5460     ret = WSASend(dst, &buf, 1, NULL, 0, &ov, NULL);
5461     ok(ret == SOCKET_ERROR && WSAGetLastError() == ERROR_IO_PENDING,
5462        "Failed to start overlapped send %d - %d\n", ret, WSAGetLastError());
5463 
5464     expected_time = (GetTickCount() - expected_time) / 1000;
5465 
5466     connect_time = 0xdeadbeef;
5467     optlen = sizeof(connect_time);
5468     ret = getsockopt(dst, SOL_SOCKET, SO_CONNECT_TIME, (char *)&connect_time, &optlen);
5469     ok(!ret, "getsockopt failed %d\n", WSAGetLastError());
5470     ok(connect_time >= expected_time && connect_time <= expected_time + 1,
5471        "unexpected connect time %u, expected %u\n", connect_time, expected_time);
5472 
5473     connect_time = 0xdeadbeef;
5474     optlen = sizeof(connect_time);
5475     ret = getsockopt(src, SOL_SOCKET, SO_CONNECT_TIME, (char *)&connect_time, &optlen);
5476     ok(!ret, "getsockopt failed %d\n", WSAGetLastError());
5477     ok(connect_time >= expected_time && connect_time <= expected_time + 1,
5478        "unexpected connect time %u, expected %u\n", connect_time, expected_time);
5479 
5480 end:
5481     if (src != INVALID_SOCKET)
5482         closesocket(src);
5483     if (dst != INVALID_SOCKET)
5484         closesocket(dst);
5485     if (hThread != NULL)
5486     {
5487         dwRet = WaitForSingleObject(hThread, 500);
5488         ok(dwRet == WAIT_OBJECT_0, "failed to wait for thread termination: %d\n", GetLastError());
5489         CloseHandle(hThread);
5490     }
5491     if (ov.hEvent)
5492         CloseHandle(ov.hEvent);
5493     HeapFree(GetProcessHeap(), 0, buffer);
5494 }
5495 
5496 typedef struct async_message
5497 {
5498     SOCKET socket;
5499     LPARAM lparam;
5500     struct async_message *next;
5501 } async_message;
5502 
5503 static struct async_message *messages_received;
5504 
5505 #define WM_SOCKET (WM_USER+100)
5506 static LRESULT CALLBACK ws2_test_WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
5507 {
5508     struct async_message *message;
5509 
5510     switch (msg)
5511     {
5512     case WM_SOCKET:
5513         message = HeapAlloc(GetProcessHeap(), 0, sizeof(*message));
5514         message->socket = (SOCKET) wparam;
5515         message->lparam = lparam;
5516         message->next = NULL;
5517 
5518         if (messages_received)
5519         {
5520             struct async_message *last = messages_received;
5521             while (last->next) last = last->next;
5522             last->next = message;
5523         }
5524         else
5525             messages_received = message;
5526         return 0;
5527     }
5528 
5529     return DefWindowProcA(hwnd, msg, wparam, lparam);
5530 }
5531 
5532 static void get_event_details(int event, int *bit, char *name)
5533 {
5534     switch (event)
5535     {
5536         case FD_ACCEPT:
5537             if (bit) *bit = FD_ACCEPT_BIT;
5538             if (name) strcpy(name, "FD_ACCEPT");
5539             break;
5540         case FD_CONNECT:
5541             if (bit) *bit = FD_CONNECT_BIT;
5542             if (name) strcpy(name, "FD_CONNECT");
5543             break;
5544         case FD_READ:
5545             if (bit) *bit = FD_READ_BIT;
5546             if (name) strcpy(name, "FD_READ");
5547             break;
5548         case FD_OOB:
5549             if (bit) *bit = FD_OOB_BIT;
5550             if (name) strcpy(name, "FD_OOB");
5551             break;
5552         case FD_WRITE:
5553             if (bit) *bit = FD_WRITE_BIT;
5554             if (name) strcpy(name, "FD_WRITE");
5555             break;
5556         case FD_CLOSE:
5557             if (bit) *bit = FD_CLOSE_BIT;
5558             if (name) strcpy(name, "FD_CLOSE");
5559             break;
5560         default:
5561             if (bit) *bit = -1;
5562             if (name) sprintf(name, "bad%x", event);
5563     }
5564 }
5565 
5566 static const char *dbgstr_event_seq(const LPARAM *seq)
5567 {
5568     static char message[1024];
5569     char name[12];
5570     int len = 1;
5571 
5572     message[0] = '[';
5573     message[1] = 0;
5574     while (*seq)
5575     {
5576         get_event_details(WSAGETSELECTEVENT(*seq), NULL, name);
5577         len += sprintf(message + len, "%s(%d) ", name, WSAGETSELECTERROR(*seq));
5578         seq++;
5579     }
5580     if (len > 1) len--;
5581     strcpy( message + len, "]" );
5582     return message;
5583 }
5584 
5585 static char *dbgstr_event_seq_result(SOCKET s, WSANETWORKEVENTS *netEvents)
5586 {
5587     static char message[1024];
5588     struct async_message *curr = messages_received;
5589     int index, error, bit = 0;
5590     char name[12];
5591     int len = 1;
5592 
5593     message[0] = '[';
5594     message[1] = 0;
5595     while (1)
5596     {
5597         if (netEvents)
5598         {
5599             if (bit >= FD_MAX_EVENTS) break;
5600             if ( !(netEvents->lNetworkEvents & (1 << bit)) )
5601             {
5602                 bit++;
5603                 continue;
5604             }
5605             get_event_details(1 << bit, &index, name);
5606             error = netEvents->iErrorCode[index];
5607             bit++;
5608         }
5609         else
5610         {
5611             if (!curr) break;
5612             if (curr->socket != s)
5613             {
5614                 curr = curr->next;
5615                 continue;
5616             }
5617             get_event_details(WSAGETSELECTEVENT(curr->lparam), NULL, name);
5618             error = WSAGETSELECTERROR(curr->lparam);
5619             curr = curr->next;
5620         }
5621 
5622         len += sprintf(message + len, "%s(%d) ", name, error);
5623     }
5624     if (len > 1) len--;
5625     strcpy( message + len, "]" );
5626     return message;
5627 }
5628 
5629 static void flush_events(SOCKET s, HANDLE hEvent)
5630 {
5631     WSANETWORKEVENTS netEvents;
5632     struct async_message *prev = NULL, *curr = messages_received;
5633     int ret;
5634     DWORD dwRet;
5635 
5636     if (hEvent != INVALID_HANDLE_VALUE)
5637     {
5638         dwRet = WaitForSingleObject(hEvent, 100);
5639         if (dwRet == WAIT_OBJECT_0)
5640         {
5641             ret = WSAEnumNetworkEvents(s, hEvent, &netEvents);
5642             if (ret)
5643                 ok(0, "WSAEnumNetworkEvents failed, error %d\n", ret);
5644         }
5645     }
5646     else
5647     {
5648         while (curr)
5649         {
5650             if (curr->socket == s)
5651             {
5652                 if (prev) prev->next = curr->next;
5653                 else messages_received = curr->next;
5654 
5655                 HeapFree(GetProcessHeap(), 0, curr);
5656 
5657                 if (prev) curr = prev->next;
5658                 else curr = messages_received;
5659             }
5660             else
5661             {
5662                 prev = curr;
5663                 curr = curr->next;
5664             }
5665         }
5666     }
5667 }
5668 
5669 static int match_event_sequence(SOCKET s, WSANETWORKEVENTS *netEvents, const LPARAM *seq)
5670 {
5671     int event, index, error, events;
5672     struct async_message *curr;
5673 
5674     if (netEvents)
5675     {
5676         events = netEvents->lNetworkEvents;
5677         while (*seq)
5678         {
5679             event = WSAGETSELECTEVENT(*seq);
5680             error = WSAGETSELECTERROR(*seq);
5681             get_event_details(event, &index, NULL);
5682 
5683             if (!(events & event) && index != -1)
5684                 return 0;
5685             if (events & event && index != -1)
5686             {
5687                 if (netEvents->iErrorCode[index] != error)
5688                     return 0;
5689             }
5690             events &= ~event;
5691             seq++;
5692         }
5693         if (events)
5694             return 0;
5695     }
5696     else
5697     {
5698         curr = messages_received;
5699         while (curr)
5700         {
5701             if (curr->socket == s)
5702             {
5703                 if (!*seq) return 0;
5704                 if (*seq != curr->lparam) return 0;
5705                 seq++;
5706             }
5707             curr = curr->next;
5708         }
5709         if (*seq)
5710             return 0;
5711     }
5712     return 1;
5713 }
5714 
5715 /* checks for a sequence of events, (order only checked if window is used) */
5716 static void ok_event_sequence(SOCKET s, HANDLE hEvent, const LPARAM *seq, const LPARAM **broken_seqs, int completelyBroken)
5717 {
5718     MSG msg;
5719     WSANETWORKEVENTS events, *netEvents = NULL;
5720     int ret;
5721     DWORD dwRet;
5722 
5723     if (hEvent != INVALID_HANDLE_VALUE)
5724     {
5725         netEvents = &events;
5726 
5727         dwRet = WaitForSingleObject(hEvent, 200);
5728         if (dwRet == WAIT_OBJECT_0)
5729         {
5730             ret = WSAEnumNetworkEvents(s, hEvent, netEvents);
5731             if (ret)
5732             {
5733                 winetest_ok(0, "WSAEnumNetworkEvents failed, error %d\n", ret);
5734                 return;
5735             }
5736         }
5737         else
5738             memset(netEvents, 0, sizeof(*netEvents));
5739     }
5740     else
5741     {
5742         Sleep(200);
5743         /* Run the message loop a little */
5744         while (PeekMessageA( &msg, 0, 0, 0, PM_REMOVE ))
5745         {
5746             DispatchMessageA(&msg);
5747         }
5748     }
5749 
5750     if (match_event_sequence(s, netEvents, seq))
5751     {
5752         winetest_ok(1, "Sequence matches expected: %s\n", dbgstr_event_seq(seq));
5753         flush_events(s, hEvent);
5754         return;
5755     }
5756 
5757     if (broken_seqs)
5758     {
5759         for (; *broken_seqs; broken_seqs++)
5760         {
5761             if (match_event_sequence(s, netEvents, *broken_seqs))
5762             {
5763                 winetest_ok(broken(1), "Sequence matches broken: %s, expected %s\n", dbgstr_event_seq_result(s, netEvents), dbgstr_event_seq(seq));
5764                 flush_events(s, hEvent);
5765                 return;
5766             }
5767         }
5768     }
5769 
5770     winetest_ok(broken(completelyBroken), "Expected event sequence %s, got %s\n", dbgstr_event_seq(seq),
5771                 dbgstr_event_seq_result(s, netEvents));
5772     flush_events(s, hEvent);
5773 }
5774 
5775 #define ok_event_seq (winetest_set_location(__FILE__, __LINE__), 0) ? (void)0 : ok_event_sequence
5776 
5777 static void test_events(int useMessages)
5778 {
5779     SOCKET server = INVALID_SOCKET;
5780     SOCKET src = INVALID_SOCKET, src2 = INVALID_SOCKET;
5781     SOCKET dst = INVALID_SOCKET, dst2 = INVALID_SOCKET;
5782     struct sockaddr_in addr;
5783     HANDLE hThread = NULL;
5784     HANDLE hEvent = INVALID_HANDLE_VALUE, hEvent2 = INVALID_HANDLE_VALUE;
5785     WNDCLASSEXA wndclass;
5786     HWND hWnd = NULL;
5787     char *buffer = NULL;
5788     int bufferSize = 1024*1024;
5789     WSABUF bufs;
5790     OVERLAPPED ov, ov2;
5791     DWORD flags = 0;
5792     DWORD bytesReturned;
5793     DWORD id;
5794     int len;
5795     int ret;
5796     DWORD dwRet;
5797     BOOL bret;
5798     static char szClassName[] = "wstestclass";
5799     const LPARAM *broken_seq[3];
5800     static const LPARAM empty_seq[] = { 0 };
5801     static const LPARAM close_seq[] = { WSAMAKESELECTREPLY(FD_CLOSE, 0), 0 };
5802     static const LPARAM write_seq[] = { WSAMAKESELECTREPLY(FD_WRITE, 0), 0 };
5803     static const LPARAM read_seq[] = { WSAMAKESELECTREPLY(FD_READ, 0), 0 };
5804     static const LPARAM oob_seq[] = { WSAMAKESELECTREPLY(FD_OOB, 0), 0 };
5805     static const LPARAM connect_seq[] = { WSAMAKESELECTREPLY(FD_CONNECT, 0),
5806                                           WSAMAKESELECTREPLY(FD_WRITE, 0), 0 };
5807     static const LPARAM read_read_seq[] = { WSAMAKESELECTREPLY(FD_READ, 0),
5808                                             WSAMAKESELECTREPLY(FD_READ, 0), 0 };
5809     static const LPARAM read_write_seq[] = { WSAMAKESELECTREPLY(FD_READ, 0),
5810                                              WSAMAKESELECTREPLY(FD_WRITE, 0), 0 };
5811     static const LPARAM read_close_seq[] = { WSAMAKESELECTREPLY(FD_READ, 0),
5812                                              WSAMAKESELECTREPLY(FD_CLOSE, 0), 0 };
5813 
5814     memset(&ov, 0, sizeof(ov));
5815     memset(&ov2, 0, sizeof(ov2));
5816 
5817     /* don't use socketpair, we want connection event */
5818     src = socket(AF_INET, SOCK_STREAM, 0);
5819     if (src == INVALID_SOCKET)
5820     {
5821         ok(0, "creating socket pair failed (%d), skipping test\n", GetLastError());
5822         goto end;
5823     }
5824 
5825     ret = set_blocking(src, TRUE);
5826     ok(!ret, "set_blocking failed, error %d\n", WSAGetLastError());
5827 
5828     src2 = socket(AF_INET, SOCK_STREAM, 0);
5829     if (src2 == INVALID_SOCKET)
5830     {
5831         ok(0, "creating socket pair failed (%d), skipping test\n", GetLastError());
5832         goto end;
5833     }
5834 
5835     ret = set_blocking(src2, TRUE);
5836     ok(!ret, "set_blocking failed, error %d\n", WSAGetLastError());
5837 
5838     len = sizeof(BOOL);
5839     if (getsockopt(src, SOL_SOCKET, SO_OOBINLINE, (void *)&bret, &len) == SOCKET_ERROR)
5840     {
5841         ok(0, "failed to get oobinline status, %d\n", GetLastError());
5842         goto end;
5843     }
5844     ok(bret == FALSE, "OOB not inline\n");
5845 
5846     if (useMessages)
5847     {
5848         trace("Event test using messages\n");
5849 
5850         wndclass.cbSize         = sizeof(wndclass);
5851         wndclass.style          = CS_HREDRAW | CS_VREDRAW;
5852         wndclass.lpfnWndProc    = ws2_test_WndProc;
5853         wndclass.cbClsExtra     = 0;
5854         wndclass.cbWndExtra     = 0;
5855         wndclass.hInstance      = GetModuleHandleA(NULL);
5856         wndclass.hIcon          = LoadIconA(NULL, (LPCSTR)IDI_APPLICATION);
5857         wndclass.hIconSm        = LoadIconA(NULL, (LPCSTR)IDI_APPLICATION);
5858         wndclass.hCursor        = LoadCursorA(NULL, (LPCSTR)IDC_ARROW);
5859         wndclass.hbrBackground  = (HBRUSH)(COLOR_WINDOW + 1);
5860         wndclass.lpszClassName  = szClassName;
5861         wndclass.lpszMenuName   = NULL;
5862         RegisterClassExA(&wndclass);
5863 
5864         hWnd = CreateWindowA(szClassName, "WS2Test", WS_OVERLAPPEDWINDOW,
5865                             0, 0, 500, 500, NULL, NULL, GetModuleHandleA(NULL), NULL);
5866         if (!hWnd)
5867         {
5868             ok(0, "failed to create window: %d\n", GetLastError());
5869             return;
5870         }
5871 
5872         ret = WSAAsyncSelect(src, hWnd, WM_SOCKET, FD_CONNECT | FD_READ | FD_OOB | FD_WRITE | FD_CLOSE);
5873         if (ret)
5874         {
5875             ok(0, "WSAAsyncSelect failed, error %d\n", ret);
5876             goto end;
5877         }
5878 
5879         ok(set_blocking(src, TRUE) == SOCKET_ERROR, "set_blocking should failed!\n");
5880         ok(WSAGetLastError() == WSAEINVAL, "expect WSAEINVAL, returned %x\n", WSAGetLastError());
5881 
5882         ret = WSAAsyncSelect(src2, hWnd, WM_SOCKET, FD_CONNECT | FD_READ | FD_OOB | FD_WRITE | FD_CLOSE);
5883         if (ret)
5884         {
5885             ok(0, "WSAAsyncSelect failed, error %d\n", ret);
5886             goto end;
5887         }
5888 
5889         ok(set_blocking(src2, TRUE) == SOCKET_ERROR, "set_blocking should failed!\n");
5890         ok(WSAGetLastError() == WSAEINVAL, "expect WSAEINVAL, returned %x\n", WSAGetLastError());
5891     }
5892     else
5893     {
5894         trace("Event test using events\n");
5895 
5896         hEvent = WSACreateEvent();
5897         if (hEvent == INVALID_HANDLE_VALUE)
5898         {
5899             ok(0, "WSACreateEvent failed, error %d\n", GetLastError());
5900             goto end;
5901         }
5902 
5903         hEvent2 = WSACreateEvent();
5904         if (hEvent2 == INVALID_HANDLE_VALUE)
5905         {
5906             ok(0, "WSACreateEvent failed, error %d\n", GetLastError());
5907             goto end;
5908         }
5909 
5910         ret = WSAEventSelect(src, hEvent, FD_CONNECT | FD_READ | FD_OOB | FD_WRITE | FD_CLOSE);
5911         if (ret)
5912         {
5913             ok(0, "WSAEventSelect failed, error %d\n", ret);
5914             goto end;
5915         }
5916 
5917         ok(set_blocking(src, TRUE) == SOCKET_ERROR, "set_blocking should failed!\n");
5918         ok(WSAGetLastError() == WSAEINVAL, "expect WSAEINVAL, returned %x\n", WSAGetLastError());
5919 
5920         ret = WSAEventSelect(src2, hEvent2, FD_CONNECT | FD_READ | FD_OOB | FD_WRITE | FD_CLOSE);
5921         if (ret)
5922         {
5923             ok(0, "WSAEventSelect failed, error %d\n", ret);
5924             goto end;
5925         }
5926 
5927         ok(set_blocking(src2, TRUE) == SOCKET_ERROR, "set_blocking should failed!\n");
5928         ok(WSAGetLastError() == WSAEINVAL, "expect WSAEINVAL, returned %x\n", WSAGetLastError());
5929     }
5930 
5931     server = socket(AF_INET, SOCK_STREAM, 0);
5932     if (server == INVALID_SOCKET)
5933     {
5934         ok(0, "creating socket pair failed (%d), skipping test\n", GetLastError());
5935         goto end;
5936     }
5937 
5938     memset(&addr, 0, sizeof(addr));
5939     addr.sin_family = AF_INET;
5940     addr.sin_addr.s_addr = inet_addr("127.0.0.1");
5941     ret = bind(server, (struct sockaddr*)&addr, sizeof(addr));
5942     if (ret != 0)
5943     {
5944         ok(0, "creating socket pair failed (%d), skipping test\n", GetLastError());
5945         goto end;
5946     }
5947 
5948     len = sizeof(addr);
5949     ret = getsockname(server, (struct sockaddr*)&addr, &len);
5950     if (ret != 0)
5951     {
5952         ok(0, "creating socket pair failed (%d), skipping test\n", GetLastError());
5953         goto end;
5954     }
5955 
5956     ret = listen(server, 2);
5957     if (ret != 0)
5958     {
5959         ok(0, "creating socket pair failed (%d), skipping test\n", GetLastError());
5960         goto end;
5961     }
5962 
5963     SetLastError(0xdeadbeef);
5964     ret = connect(src, NULL, 0);
5965     ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
5966     ok(GetLastError() == WSAEFAULT, "expected 10014, got %d\n", GetLastError());
5967 
5968     ret = connect(src, (struct sockaddr*)&addr, sizeof(addr));
5969     if (ret == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)
5970     {
5971         ok(0, "creating socket pair failed (%d), skipping test\n", GetLastError());
5972         goto end;
5973     }
5974 
5975     ret = connect(src2, (struct sockaddr*)&addr, sizeof(addr));
5976     if (ret == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)
5977     {
5978         ok(0, "creating socket pair failed (%d), skipping test\n", GetLastError());
5979         goto end;
5980     }
5981 
5982     len = sizeof(addr);
5983     dst = accept(server, (struct sockaddr*)&addr, &len);
5984     if (dst == INVALID_SOCKET)
5985     {
5986         ok(0, "creating socket pair failed (%d), skipping test\n", GetLastError());
5987         goto end;
5988     }
5989 
5990     len = sizeof(addr);
5991     dst2 = accept(server, (struct sockaddr*)&addr, &len);
5992     if (dst2 == INVALID_SOCKET)
5993     {
5994         ok(0, "creating socket pair failed (%d), skipping test\n", GetLastError());
5995         goto end;
5996     }
5997 
5998     closesocket(server);
5999     server = INVALID_SOCKET;
6000 
6001     /* On Windows it seems when a non-blocking socket sends to a
6002        blocking socket on the same host, the send() is BLOCKING,
6003        so make both sockets non-blocking. src is already non-blocking
6004        from the async select */
6005 
6006     if (set_blocking(dst, FALSE))
6007     {
6008         ok(0, "ioctlsocket failed, error %d\n", WSAGetLastError());
6009         goto end;
6010     }
6011 
6012     buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bufferSize);
6013     if (buffer == NULL)
6014     {
6015         ok(0, "could not allocate memory for test\n");
6016         goto end;
6017     }
6018 
6019     ov.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
6020     if (ov.hEvent == NULL)
6021     {
6022         ok(0, "could not create event object, errno = %d\n", GetLastError());
6023         goto end;
6024     }
6025 
6026     ov2.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
6027     if (ov2.hEvent == NULL)
6028     {
6029         ok(0, "could not create event object, errno = %d\n", GetLastError());
6030         goto end;
6031     }
6032 
6033     /* FD_WRITE should be set initially, and allow us to send at least 1 byte */
6034     ok_event_seq(src, hEvent, connect_seq, NULL, 1);
6035     ok_event_seq(src2, hEvent2, connect_seq, NULL, 1);
6036     /* broken on all windows - FD_CONNECT error is garbage */
6037 
6038     /* Test simple send/recv */
6039     SetLastError(0xdeadbeef);
6040     ret = send(dst, buffer, 100, 0);
6041     ok(ret == 100, "Failed to send buffer %d err %d\n", ret, GetLastError());
6042     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6043     ok_event_seq(src, hEvent, read_seq, NULL, 0);
6044 
6045     SetLastError(0xdeadbeef);
6046     ret = recv(src, buffer, 1, MSG_PEEK);
6047     ok(ret == 1, "Failed to peek at recv buffer %d err %d\n", ret, GetLastError());
6048     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6049     ok_event_seq(src, hEvent, read_seq, NULL, 0);
6050 
6051     SetLastError(0xdeadbeef);
6052     ret = recv(src, buffer, 50, 0);
6053     ok(ret == 50, "Failed to recv buffer %d err %d\n", ret, GetLastError());
6054     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6055     ok_event_seq(src, hEvent, read_seq, NULL, 0);
6056 
6057     ret = recv(src, buffer, 50, 0);
6058     ok(ret == 50, "Failed to recv buffer %d err %d\n", ret, GetLastError());
6059     ok_event_seq(src, hEvent, empty_seq, NULL, 0);
6060 
6061     /* fun fact - events are re-enabled even on failure, but only for messages */
6062     ret = send(dst, "1", 1, 0);
6063     ok(ret == 1, "Failed to send buffer %d err %d\n", ret, GetLastError());
6064     ok_event_seq(src, hEvent, read_seq, NULL, 0);
6065 
6066     ret = recv(src, buffer, -1, 0);
6067     ok(ret == SOCKET_ERROR && (GetLastError() == WSAEFAULT || GetLastError() == WSAENOBUFS),
6068        "Failed to recv buffer %d err %d\n", ret, GetLastError());
6069     if (useMessages)
6070     {
6071         broken_seq[0] = empty_seq; /* win9x */
6072         broken_seq[1] = NULL;
6073         todo_wine ok_event_seq(src, hEvent, read_seq, broken_seq, 0);
6074     }
6075     else
6076         ok_event_seq(src, hEvent, empty_seq, NULL, 0);
6077 
6078     SetLastError(0xdeadbeef);
6079     ret = recv(src, buffer, 1, 0);
6080     ok(ret == 1, "Failed to recv buffer %d err %d\n", ret, GetLastError());
6081     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6082     ok_event_seq(src, hEvent, empty_seq, NULL, 0);
6083 
6084     /* Interaction with overlapped */
6085     bufs.len = sizeof(char);
6086     bufs.buf = buffer;
6087     ret = WSARecv(src, &bufs, 1, &bytesReturned, &flags, &ov, NULL);
6088     ok(ret == SOCKET_ERROR && GetLastError() == ERROR_IO_PENDING,
6089        "WSARecv failed - %d error %d\n", ret, GetLastError());
6090 
6091     bufs.len = sizeof(char);
6092     bufs.buf = buffer+1;
6093     ret = WSARecv(src, &bufs, 1, &bytesReturned, &flags, &ov2, NULL);
6094     ok(ret == SOCKET_ERROR && GetLastError() == ERROR_IO_PENDING,
6095        "WSARecv failed - %d error %d\n", ret, GetLastError());
6096 
6097     ret = send(dst, "12", 2, 0);
6098     ok(ret == 2, "Failed to send buffer %d err %d\n", ret, GetLastError());
6099     broken_seq[0] = read_read_seq; /* win9x */
6100     broken_seq[1] = NULL;
6101     ok_event_seq(src, hEvent, empty_seq, broken_seq, 0);
6102 
6103     dwRet = WaitForSingleObject(ov.hEvent, 100);
6104     ok(dwRet == WAIT_OBJECT_0, "Failed to wait for recv message: %d - %d\n", dwRet, GetLastError());
6105     if (dwRet == WAIT_OBJECT_0)
6106     {
6107         bret = GetOverlappedResult((HANDLE)src, &ov, &bytesReturned, FALSE);
6108         ok((bret && bytesReturned == 1) || broken(!bret && GetLastError() == ERROR_IO_INCOMPLETE) /* win9x */,
6109            "Got %d instead of 1 (%d - %d)\n", bytesReturned, bret, GetLastError());
6110         ok(buffer[0] == '1', "Got %c instead of 1\n", buffer[0]);
6111     }
6112 
6113     dwRet = WaitForSingleObject(ov2.hEvent, 100);
6114     ok(dwRet == WAIT_OBJECT_0, "Failed to wait for recv message: %d - %d\n", dwRet, GetLastError());
6115     if (dwRet == WAIT_OBJECT_0)
6116     {
6117         bret = GetOverlappedResult((HANDLE)src, &ov2, &bytesReturned, FALSE);
6118         ok((bret && bytesReturned == 1) || broken(!bret && GetLastError() == ERROR_IO_INCOMPLETE) /* win9x */,
6119            "Got %d instead of 1 (%d - %d)\n", bytesReturned, bret, GetLastError());
6120         ok(buffer[1] == '2', "Got %c instead of 2\n", buffer[1]);
6121     }
6122 
6123     SetLastError(0xdeadbeef);
6124     ret = send(dst, "1", 1, 0);
6125     ok(ret == 1, "Failed to send buffer %d err %d\n", ret, GetLastError());
6126     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6127     ok_event_seq(src, hEvent, read_seq, NULL, 0);
6128 
6129     ret = recv(src, buffer, 1, 0);
6130     ok(ret == 1, "Failed to empty buffer: %d - %d\n", ret, GetLastError());
6131     ok_event_seq(src, hEvent, empty_seq, NULL, 0);
6132 
6133     /* Notifications are delivered as soon as possible, blocked only on
6134      * async requests on the same type */
6135     bufs.len = sizeof(char);
6136     bufs.buf = buffer;
6137     ret = WSARecv(src, &bufs, 1, &bytesReturned, &flags, &ov, NULL);
6138     ok(ret == SOCKET_ERROR && GetLastError() == ERROR_IO_PENDING,
6139        "WSARecv failed - %d error %d\n", ret, GetLastError());
6140 
6141     if (0) {
6142     ret = send(dst, "1", 1, MSG_OOB);
6143     ok(ret == 1, "Failed to send buffer %d err %d\n", ret, GetLastError());
6144     ok_event_seq(src, hEvent, oob_seq, NULL, 0);
6145     }
6146 
6147     dwRet = WaitForSingleObject(ov.hEvent, 100);
6148     ok(dwRet == WAIT_TIMEOUT, "OOB message activated read?: %d - %d\n", dwRet, GetLastError());
6149 
6150     ret = send(dst, "2", 1, 0);
6151     ok(ret == 1, "Failed to send buffer %d err %d\n", ret, GetLastError());
6152     broken_seq[0] = read_seq;  /* win98 */
6153     broken_seq[1] = NULL;
6154     ok_event_seq(src, hEvent, empty_seq, broken_seq, 0);
6155 
6156     dwRet = WaitForSingleObject(ov.hEvent, 100);
6157     ok(dwRet == WAIT_OBJECT_0 || broken(dwRet == WAIT_TIMEOUT),
6158        "Failed to wait for recv message: %d - %d\n", dwRet, GetLastError());
6159     if (dwRet == WAIT_OBJECT_0)
6160     {
6161         bret = GetOverlappedResult((HANDLE)src, &ov, &bytesReturned, FALSE);
6162         ok((bret && bytesReturned == 1) || broken(!bret && GetLastError() == ERROR_IO_INCOMPLETE) /* win9x */,
6163            "Got %d instead of 1 (%d - %d)\n", bytesReturned, bret, GetLastError());
6164         ok(buffer[0] == '2', "Got %c instead of 2\n", buffer[0]);
6165     }
6166 
6167     if (0) {
6168     ret = recv(src, buffer, 1, MSG_OOB);
6169     todo_wine ok(ret == 1, "Failed to empty buffer: %d - %d\n", ret, GetLastError());
6170     /* We get OOB notification, but no data on wine */
6171     ok_event_seq(src, hEvent, empty_seq, NULL, 0);
6172     }
6173 
6174     /* Flood the send queue */
6175     hThread = CreateThread(NULL, 0, drain_socket_thread, &dst, 0, &id);
6176     if (hThread == NULL)
6177     {
6178         ok(0, "CreateThread failed, error %d\n", GetLastError());
6179         goto end;
6180     }
6181 
6182     /* Now FD_WRITE should not be set, because the socket send buffer isn't full yet */
6183     ok_event_seq(src, hEvent, empty_seq, NULL, 0);
6184 
6185     /* Now if we send a ton of data and the 'server' does not drain it fast
6186      * enough (set drain_pause to be sure), the socket send buffer will only
6187      * take some of it, and we will get a short write. This will trigger
6188      * another FD_WRITE event as soon as data is sent and more space becomes
6189      * available, but not any earlier. */
6190     drain_pause = TRUE;
6191     do
6192     {
6193         ret = send(src, buffer, bufferSize, 0);
6194     } while (ret == bufferSize);
6195     drain_pause = FALSE;
6196     if (ret >= 0 || WSAGetLastError() == WSAEWOULDBLOCK)
6197     {
6198         Sleep(400); /* win9x */
6199         broken_seq[0] = read_write_seq;
6200         broken_seq[1] = NULL;
6201         ok_event_seq(src, hEvent, write_seq, broken_seq, 0);
6202     }
6203     else
6204     {
6205         ok(0, "sending a lot of data failed with error %d\n", WSAGetLastError());
6206     }
6207 
6208     /* Test how FD_CLOSE is handled */
6209     ret = send(dst, "12", 2, 0);
6210     ok(ret == 2, "Failed to send buffer %d err %d\n", ret, GetLastError());
6211 
6212     /* Wait a little and let the send complete */
6213     Sleep(100);
6214     closesocket(dst);
6215     dst = INVALID_SOCKET;
6216     Sleep(100);
6217 
6218     /* We can never implement this in wine, best we can hope for is
6219        sending FD_CLOSE after the reads complete */
6220     broken_seq[0] = read_seq;  /* win9x */
6221     broken_seq[1] = NULL;
6222     todo_wine ok_event_seq(src, hEvent, read_close_seq, broken_seq, 0);
6223 
6224     ret = recv(src, buffer, 1, 0);
6225     ok(ret == 1, "Failed to empty buffer: %d - %d\n", ret, GetLastError());
6226     ok_event_seq(src, hEvent, read_seq, NULL, 0);
6227 
6228     ret = recv(src, buffer, 1, 0);
6229     ok(ret == 1, "Failed to empty buffer: %d - %d\n", ret, GetLastError());
6230     /* want it? it's here, but you can't have it */
6231     broken_seq[0] = close_seq;  /* win9x */
6232     broken_seq[1] = NULL;
6233     todo_wine ok_event_seq(src, hEvent, empty_seq, /* wine sends FD_CLOSE here */
6234                            broken_seq, 0);
6235 
6236     /* Test how FD_CLOSE is handled */
6237     ret = send(dst2, "12", 2, 0);
6238     ok(ret == 2, "Failed to send buffer %d err %d\n", ret, GetLastError());
6239 
6240     Sleep(200);
6241     shutdown(dst2, SD_SEND);
6242     Sleep(200);
6243 
6244     /* Some of the below are technically todo_wine, but our event sequence is still valid, so to prevent
6245        regressions, don't mark them as todo_wine, and mark windows as broken */
6246     broken_seq[0] = read_close_seq;
6247     broken_seq[1] = close_seq;
6248     broken_seq[2] = NULL;
6249     ok_event_seq(src2, hEvent2, read_seq, broken_seq, 0);
6250 
6251     ret = recv(src2, buffer, 1, 0);
6252     ok(ret == 1 || broken(!ret), "Failed to empty buffer: %d - %d\n", ret, GetLastError());
6253     broken_seq[0] = close_seq;  /* win98 */
6254     broken_seq[1] = NULL;
6255     ok_event_seq(src2, hEvent2, read_seq, broken_seq, 0);
6256 
6257     ret = recv(src2, buffer, 1, 0);
6258     ok(ret == 1 || broken(!ret), "Failed to empty buffer: %d - %d\n", ret, GetLastError());
6259     broken_seq[0] = empty_seq;
6260     broken_seq[1] = NULL;
6261     ok_event_seq(src2, hEvent2, close_seq, broken_seq, 0);
6262 
6263     ret = send(src2, "1", 1, 0);
6264     ok(ret == 1, "Sending to half-closed socket failed %d err %d\n", ret, GetLastError());
6265     ok_event_seq(src2, hEvent2, empty_seq, NULL, 0);
6266 
6267     ret = send(src2, "1", 1, 0);
6268     ok(ret == 1, "Sending to half-closed socket failed %d err %d\n", ret, GetLastError());
6269     ok_event_seq(src2, hEvent2, empty_seq, NULL, 0);
6270 
6271     if (useMessages)
6272     {
6273         ret = WSAAsyncSelect(src, hWnd, WM_SOCKET, 0);
6274         if (ret)
6275         {
6276             ok(0, "WSAAsyncSelect failed, error %d\n", ret);
6277             goto end;
6278         }
6279 
6280         ret = set_blocking(src, TRUE);
6281         ok(!ret, "set_blocking failed, error %d\n", WSAGetLastError());
6282 
6283         ret = WSAAsyncSelect(src2, hWnd, WM_SOCKET, 0);
6284         if (ret)
6285         {
6286             ok(0, "WSAAsyncSelect failed, error %d\n", ret);
6287             goto end;
6288         }
6289 
6290         ret = set_blocking(src2, TRUE);
6291         ok(!ret, "set_blocking failed, error %d\n", WSAGetLastError());
6292     }
6293     else
6294     {
6295         ret = WSAEventSelect(src, hEvent2, 0);
6296         if (ret)
6297         {
6298             ok(0, "WSAAsyncSelect failed, error %d\n", ret);
6299             goto end;
6300         }
6301 
6302         ret = set_blocking(src, TRUE);
6303         ok(!ret, "set_blocking failed, error %d\n", WSAGetLastError());
6304 
6305         ret = WSAEventSelect(src2, hEvent2, 0);
6306         if (ret)
6307         {
6308             ok(0, "WSAAsyncSelect failed, error %d\n", ret);
6309             goto end;
6310         }
6311 
6312         ret = set_blocking(src2, TRUE);
6313         ok(!ret, "set_blocking failed, error %d\n", WSAGetLastError());
6314     }
6315 
6316 end:
6317     if (src != INVALID_SOCKET)
6318     {
6319         flush_events(src, hEvent);
6320         closesocket(src);
6321     }
6322     if (src2 != INVALID_SOCKET)
6323     {
6324         flush_events(src2, hEvent2);
6325         closesocket(src2);
6326     }
6327     HeapFree(GetProcessHeap(), 0, buffer);
6328     if (server != INVALID_SOCKET)
6329         closesocket(server);
6330     if (dst != INVALID_SOCKET)
6331         closesocket(dst);
6332     if (dst2 != INVALID_SOCKET)
6333         closesocket(dst2);
6334     if (hThread != NULL)
6335         CloseHandle(hThread);
6336     if (hWnd != NULL)
6337         DestroyWindow(hWnd);
6338     if (hEvent != NULL)
6339         CloseHandle(hEvent);
6340     if (hEvent2 != NULL)
6341         CloseHandle(hEvent2);
6342     if (ov.hEvent != NULL)
6343         CloseHandle(ov.hEvent);
6344     if (ov2.hEvent != NULL)
6345         CloseHandle(ov2.hEvent);
6346 }
6347 
6348 static void test_ipv6only(void)
6349 {
6350     SOCKET v4 = INVALID_SOCKET, v6;
6351     struct sockaddr_in sin4;
6352     struct sockaddr_in6 sin6;
6353     int ret, enabled, len = sizeof(enabled);
6354 
6355     memset(&sin4, 0, sizeof(sin4));
6356     sin4.sin_family = AF_INET;
6357     sin4.sin_port = htons(SERVERPORT);
6358 
6359     memset(&sin6, 0, sizeof(sin6));
6360     sin6.sin6_family = AF_INET6;
6361     sin6.sin6_port = htons(SERVERPORT);
6362 
6363     v6 = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
6364     if (v6 == INVALID_SOCKET)
6365     {
6366         skip("Could not create IPv6 socket (LastError: %d)\n", WSAGetLastError());
6367         goto end;
6368     }
6369 
6370     enabled = 2;
6371     ret = getsockopt(v6, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, &len);
6372     ok(!ret, "getsockopt(IPV6_ONLY) failed (LastError: %d)\n", WSAGetLastError());
6373     ok(enabled == 1, "expected 1, got %d\n", enabled);
6374 
6375     ret = bind(v6, (struct sockaddr*)&sin6, sizeof(sin6));
6376     if (ret)
6377     {
6378         skip("Could not bind IPv6 address (LastError: %d)\n", WSAGetLastError());
6379         goto end;
6380     }
6381 
6382     v4 = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
6383     ok(v4 != INVALID_SOCKET, "Could not create IPv4 socket (LastError: %d)\n", WSAGetLastError());
6384 
6385 todo_wine {
6386     enabled = 2;
6387     ret = getsockopt(v4, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, &len);
6388     ok(!ret, "getsockopt(IPV6_ONLY) failed (LastError: %d)\n", WSAGetLastError());
6389     ok(enabled == 1, "expected 1, got %d\n", enabled);
6390 }
6391 
6392     enabled = 0;
6393     len = sizeof(enabled);
6394     ret = setsockopt(v4, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, len);
6395     ok(!ret, "setsockopt(IPV6_ONLY) failed (LastError: %d)\n", WSAGetLastError());
6396 
6397 todo_wine {
6398     enabled = 2;
6399     ret = getsockopt(v4, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, &len);
6400     ok(!ret, "getsockopt(IPV6_ONLY) failed (LastError: %d)\n", WSAGetLastError());
6401     ok(!enabled, "expected 0, got %d\n", enabled);
6402 }
6403 
6404     enabled = 1;
6405     len = sizeof(enabled);
6406     ret = setsockopt(v4, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, len);
6407     ok(!ret, "setsockopt(IPV6_ONLY) failed (LastError: %d)\n", WSAGetLastError());
6408 
6409     /* bind on IPv4 socket should succeed - IPV6_V6ONLY is enabled by default */
6410     ret = bind(v4, (struct sockaddr*)&sin4, sizeof(sin4));
6411     ok(!ret, "Could not bind IPv4 address (LastError: %d)\n", WSAGetLastError());
6412 
6413 todo_wine {
6414     enabled = 2;
6415     ret = getsockopt(v4, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, &len);
6416     ok(!ret, "getsockopt(IPV6_ONLY) failed (LastError: %d)\n", WSAGetLastError());
6417     ok(enabled == 1, "expected 1, got %d\n", enabled);
6418 }
6419 
6420     enabled = 0;
6421     len = sizeof(enabled);
6422     ret = setsockopt(v4, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, len);
6423     ok(ret, "setsockopt(IPV6_ONLY) succeeded (LastError: %d)\n", WSAGetLastError());
6424 
6425 todo_wine {
6426     enabled = 0;
6427     ret = getsockopt(v4, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, &len);
6428     ok(!ret, "getsockopt(IPV6_ONLY) failed (LastError: %d)\n", WSAGetLastError());
6429     ok(enabled == 1, "expected 1, got %d\n", enabled);
6430 }
6431 
6432     enabled = 1;
6433     len = sizeof(enabled);
6434     ret = setsockopt(v4, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, len);
6435     ok(ret, "setsockopt(IPV6_ONLY) succeeded (LastError: %d)\n", WSAGetLastError());
6436 
6437     closesocket(v4);
6438     closesocket(v6);
6439 
6440     /* Test again, this time disabling IPV6_V6ONLY. */
6441     sin4.sin_port = htons(SERVERPORT+2);
6442     sin6.sin6_port = htons(SERVERPORT+2);
6443 
6444     v6 = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
6445     ok(v6 != INVALID_SOCKET, "Could not create IPv6 socket (LastError: %d; %d expected if IPv6 not available).\n",
6446         WSAGetLastError(), WSAEAFNOSUPPORT);
6447 
6448     enabled = 0;
6449     ret = setsockopt(v6, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, len);
6450     ok(!ret, "Could not disable IPV6_V6ONLY (LastError: %d).\n", WSAGetLastError());
6451 
6452     enabled = 2;
6453     ret = getsockopt(v6, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, &len);
6454     ok(!ret, "getsockopt(IPV6_ONLY) failed (LastError: %d)\n", WSAGetLastError());
6455     ok(!enabled, "expected 0, got %d\n", enabled);
6456 
6457     /*
6458         Observaition:
6459         On Windows, bind on both IPv4 and IPv6 with IPV6_V6ONLY disabled succeeds by default.
6460         Application must set SO_EXCLUSIVEADDRUSE on first socket to disallow another successful bind.
6461         In general, a standard application should not use SO_REUSEADDR.
6462         Setting both SO_EXCLUSIVEADDRUSE and SO_REUSEADDR on the same socket is not possible in
6463         either order, the later setsockopt call always fails.
6464     */
6465     enabled = 1;
6466     ret = setsockopt(v6, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char*)&enabled, len);
6467     ok(!ret, "Could not set SO_EXCLUSIVEADDRUSE on IPv6 socket (LastError: %d)\n", WSAGetLastError());
6468 
6469     ret = bind(v6, (struct sockaddr*)&sin6, sizeof(sin6));
6470     ok(!ret, "Could not bind IPv6 address (LastError: %d)\n", WSAGetLastError());
6471 
6472     enabled = 2;
6473     len = sizeof(enabled);
6474     getsockopt(v6, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, &len);
6475     ok(!ret, "getsockopt(IPV6_ONLY) failed (LastError: %d)\n", WSAGetLastError());
6476     ok(!enabled, "IPV6_V6ONLY is enabled after bind\n");
6477 
6478     v4 = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
6479     ok(v4 != INVALID_SOCKET, "Could not create IPv4 socket (LastError: %d)\n", WSAGetLastError());
6480 
6481     enabled = 1;
6482     ret = setsockopt(v4, SOL_SOCKET, SO_REUSEADDR, (char*)&enabled, len);
6483     ok(!ret, "Could not set SO_REUSEADDR on IPv4 socket (LastError: %d)\n", WSAGetLastError());
6484 
6485     WSASetLastError(0xdeadbeef);
6486     ret = bind(v4, (struct sockaddr*)&sin4, sizeof(sin4));
6487     ok(ret, "bind succeeded unexpectedly for the IPv4 socket\n");
6488     ok(WSAGetLastError() == WSAEACCES, "Expected 10013, got %d\n", WSAGetLastError());
6489 
6490 end:
6491     if (v4 != INVALID_SOCKET)
6492         closesocket(v4);
6493     if (v6 != INVALID_SOCKET)
6494         closesocket(v6);
6495 }
6496 
6497 static void test_WSASendMsg(void)
6498 {
6499     SOCKET sock, dst;
6500     struct sockaddr_in sendaddr, sockaddr;
6501     GUID WSASendMsg_GUID = WSAID_WSASENDMSG;
6502     LPFN_WSASENDMSG pWSASendMsg = NULL;
6503     char teststr[12] = "hello world", buffer[32];
6504     WSABUF iovec[2];
6505     WSAMSG msg;
6506     DWORD bytesSent, err;
6507     int ret, addrlen;
6508 
6509     /* FIXME: Missing OVERLAPPED and OVERLAPPED COMPLETION ROUTINE tests */
6510 
6511     sock = socket(AF_INET, SOCK_DGRAM, 0);
6512     ok(sock != INVALID_SOCKET, "socket() failed\n");
6513 
6514     /* Obtain the WSASendMsg function */
6515     WSAIoctl(sock, SIO_GET_EXTENSION_FUNCTION_POINTER, &WSASendMsg_GUID, sizeof(WSASendMsg_GUID),
6516              &pWSASendMsg, sizeof(pWSASendMsg), &err, NULL, NULL);
6517     if (!pWSASendMsg)
6518     {
6519         closesocket(sock);
6520         win_skip("WSASendMsg is unsupported, some tests will be skipped.\n");
6521         return;
6522     }
6523 
6524     /* fake address for now */
6525     sendaddr.sin_family = AF_INET;
6526     sendaddr.sin_port = htons(139);
6527     sendaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
6528 
6529     memset(&msg, 0, sizeof(msg));
6530     iovec[0].buf      = teststr;
6531     iovec[0].len      = sizeof(teststr);
6532     iovec[1].buf      = teststr;
6533     iovec[1].len      = sizeof(teststr) / 2;
6534     msg.name          = (struct sockaddr *) &sendaddr;
6535     msg.namelen       = sizeof(sendaddr);
6536     msg.lpBuffers     = iovec;
6537     msg.dwBufferCount = 1; /* send only one buffer for now */
6538 
6539     WSASetLastError(0xdeadbeef);
6540     ret = pWSASendMsg(INVALID_SOCKET, &msg, 0, NULL, NULL, NULL);
6541     ok(ret == SOCKET_ERROR, "WSASendMsg should have failed\n");
6542     err = WSAGetLastError();
6543     ok(err == WSAENOTSOCK, "expected 10038, got %d instead\n", err);
6544 
6545     WSASetLastError(0xdeadbeef);
6546     ret = pWSASendMsg(sock, NULL, 0, NULL, NULL, NULL);
6547     ok(ret == SOCKET_ERROR, "WSASendMsg should have failed\n");
6548     err = WSAGetLastError();
6549     ok(err == WSAEFAULT, "expected 10014, got %d instead\n", err);
6550 
6551     WSASetLastError(0xdeadbeef);
6552     ret = pWSASendMsg(sock, NULL, 0, &bytesSent, NULL, NULL);
6553     ok(ret == SOCKET_ERROR, "WSASendMsg should have failed\n");
6554     err = WSAGetLastError();
6555     ok(err == WSAEFAULT, "expected 10014, got %d instead\n", err);
6556 
6557     WSASetLastError(0xdeadbeef);
6558     ret = pWSASendMsg(sock, &msg, 0, NULL, NULL, NULL);
6559     ok(ret == SOCKET_ERROR, "WSASendMsg should have failed\n");
6560     err = WSAGetLastError();
6561     ok(err == WSAEFAULT, "expected 10014, got %d instead\n", err);
6562 
6563     closesocket(sock);
6564 
6565     sock = socket(AF_INET, SOCK_DGRAM, 0);
6566     ok(sock != INVALID_SOCKET, "socket() failed\n");
6567 
6568     dst = socket(AF_INET, SOCK_DGRAM, 0);
6569     ok(dst != INVALID_SOCKET, "socket() failed\n");
6570 
6571     memset(&sockaddr, 0, sizeof(sockaddr));
6572     sockaddr.sin_family = AF_INET;
6573     sockaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
6574     ok(!bind(dst, (struct sockaddr*)&sockaddr, sizeof(sockaddr)),
6575        "bind should have worked\n");
6576 
6577     /* read address to find out the port number to be used in send */
6578     memset(&sendaddr, 0, sizeof(sendaddr));
6579     addrlen = sizeof(sendaddr);
6580     ok(!getsockname(dst, (struct sockaddr *) &sendaddr, &addrlen),
6581        "getsockname should have worked\n");
6582     ok(sendaddr.sin_port, "socket port should be != 0\n");
6583 
6584     /* ensure the sending socket is not bound */
6585     WSASetLastError(0xdeadbeef);
6586     addrlen = sizeof(sockaddr);
6587     ret = getsockname(sock, (struct sockaddr*)&sockaddr, &addrlen);
6588     ok(ret == SOCKET_ERROR, "getsockname should have failed\n");
6589     err = WSAGetLastError();
6590     ok(err == WSAEINVAL, "expected 10022, got %d instead\n", err);
6591 
6592     set_blocking(sock, TRUE);
6593 
6594     bytesSent = 0;
6595     SetLastError(0xdeadbeef);
6596     ret = pWSASendMsg(sock, &msg, 0, &bytesSent, NULL, NULL);
6597     ok(!ret, "WSASendMsg should have worked\n");
6598     ok(GetLastError() == 0 || broken(GetLastError() == 0xdeadbeef) /* Win <= 2008 */,
6599        "Expected 0, got %d\n", GetLastError());
6600     ok(bytesSent == iovec[0].len, "incorret bytes sent, expected %d, sent %d\n",
6601        iovec[0].len, bytesSent);
6602 
6603     /* receive data */
6604     addrlen = sizeof(sockaddr);
6605     memset(buffer, 0, sizeof(buffer));
6606     SetLastError(0xdeadbeef);
6607     ret = recvfrom(dst, buffer, sizeof(buffer), 0, (struct sockaddr *) &sockaddr, &addrlen);
6608     ok(ret == bytesSent, "got %d, expected %d\n",
6609        ret, bytesSent);
6610     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6611 
6612     /* A successful call to WSASendMsg must have bound the socket */
6613     addrlen = sizeof(sockaddr);
6614     sockaddr.sin_port = 0;
6615     sockaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
6616     ret = getsockname(sock, (struct sockaddr*)&sockaddr, &addrlen);
6617     ok(!ret, "getsockname should have worked\n");
6618     ok(sockaddr.sin_addr.s_addr == htonl(INADDR_ANY), "expected 0.0.0.0, got %s\n",
6619        inet_ntoa(sockaddr.sin_addr));
6620     ok(sockaddr.sin_port, "sin_port should be != 0\n");
6621 
6622     msg.dwBufferCount = 2; /* send both buffers */
6623 
6624     bytesSent = 0;
6625     SetLastError(0xdeadbeef);
6626     ret = pWSASendMsg(sock, &msg, 0, &bytesSent, NULL, NULL);
6627     ok(!ret, "WSASendMsg should have worked\n");
6628     ok(bytesSent == iovec[0].len + iovec[1].len, "incorret bytes sent, expected %d, sent %d\n",
6629        iovec[0].len + iovec[1].len, bytesSent);
6630     ok(GetLastError() == 0 || broken(GetLastError() == 0xdeadbeef) /* Win <= 2008 */,
6631        "Expected 0, got %d\n", GetLastError());
6632 
6633     /* receive data */
6634     addrlen = sizeof(sockaddr);
6635     memset(buffer, 0, sizeof(buffer));
6636     SetLastError(0xdeadbeef);
6637     ret = recvfrom(dst, buffer, sizeof(buffer), 0, (struct sockaddr *) &sockaddr, &addrlen);
6638     ok(ret == bytesSent, "got %d, expected %d\n",
6639        ret, bytesSent);
6640     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6641 
6642     closesocket(sock);
6643     closesocket(dst);
6644 
6645     /* a bad call to WSASendMsg will also bind the socket */
6646     addrlen = sizeof(sockaddr);
6647     sockaddr.sin_port = 0;
6648     sockaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
6649     sock = socket(AF_INET, SOCK_DGRAM, 0);
6650     ok(sock != INVALID_SOCKET, "socket() failed\n");
6651     ok(pWSASendMsg(sock, &msg, 0, NULL, NULL, NULL) == SOCKET_ERROR, "WSASendMsg should have failed\n");
6652 todo_wine {
6653     ok(!getsockname(sock, (struct sockaddr*)&sockaddr, &addrlen), "getsockname should have worked\n");
6654     ok(sockaddr.sin_addr.s_addr == htonl(INADDR_ANY), "expected 0.0.0.0, got %s\n",
6655        inet_ntoa(sockaddr.sin_addr));
6656     ok(sockaddr.sin_port, "sin_port should be > 0\n");
6657 }
6658     closesocket(sock);
6659 
6660     /* a bad call without msg parameter will not trigger the auto-bind */
6661     sock = socket(AF_INET, SOCK_DGRAM, 0);
6662     ok(sock != INVALID_SOCKET, "socket() failed\n");
6663     ok(pWSASendMsg(sock, NULL, 0, NULL, NULL, NULL) == SOCKET_ERROR, "WSASendMsg should have failed\n");
6664     ok(getsockname(sock, (struct sockaddr*)&sockaddr, &addrlen), "getsockname should have failed\n");
6665     err = WSAGetLastError();
6666     ok(err == WSAEINVAL, "expected 10022, got %d instead\n", err);
6667     closesocket(sock);
6668 
6669     /* SOCK_STREAM sockets are not supported */
6670     bytesSent = 0;
6671     sock = socket(AF_INET, SOCK_STREAM, 0);
6672     ok(sock != INVALID_SOCKET, "socket() failed\n");
6673     SetLastError(0xdeadbeef);
6674     ret = pWSASendMsg(sock, &msg, 0, &bytesSent, NULL, NULL);
6675     ok(ret == SOCKET_ERROR, "WSASendMsg should have failed\n");
6676     err = WSAGetLastError();
6677 todo_wine
6678     ok(err == WSAEINVAL, "expected 10014, got %d instead\n", err);
6679     closesocket(sock);
6680 }
6681 
6682 static void test_WSASendTo(void)
6683 {
6684     SOCKET s;
6685     struct sockaddr_in addr;
6686     char buf[12] = "hello world";
6687     WSABUF data_buf;
6688     DWORD bytesSent;
6689     int ret;
6690 
6691     addr.sin_family = AF_INET;
6692     addr.sin_port = htons(139);
6693     addr.sin_addr.s_addr = inet_addr("127.0.0.1");
6694     data_buf.len = sizeof(buf);
6695     data_buf.buf = buf;
6696 
6697     if( (s = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) {
6698         ok(0, "socket() failed error: %d\n", WSAGetLastError());
6699         return;
6700     }
6701 
6702     WSASetLastError(12345);
6703     ret = WSASendTo(INVALID_SOCKET, &data_buf, 1, NULL, 0, (struct sockaddr*)&addr, sizeof(addr), NULL, NULL);
6704     ok(ret == SOCKET_ERROR && WSAGetLastError() == WSAENOTSOCK,
6705        "WSASendTo() failed: %d/%d\n", ret, WSAGetLastError());
6706 
6707     WSASetLastError(12345);
6708     ret = WSASendTo(s, &data_buf, 1, NULL, 0, (struct sockaddr*)&addr, sizeof(addr), NULL, NULL);
6709     ok(ret == SOCKET_ERROR && WSAGetLastError() == WSAEFAULT,
6710        "WSASendTo() failed: %d/%d\n", ret, WSAGetLastError());
6711 
6712     WSASetLastError(12345);
6713     if(WSASendTo(s, &data_buf, 1, &bytesSent, 0, (struct sockaddr*)&addr, sizeof(addr), NULL, NULL)) {
6714         ok(0, "WSASendTo() failed error: %d\n", WSAGetLastError());
6715         return;
6716     }
6717     ok(!WSAGetLastError(), "WSAGetLastError() should return zero after "
6718             "a successful call to WSASendTo()\n");
6719 }
6720 
6721 static DWORD WINAPI recv_thread(LPVOID arg)
6722 {
6723     SOCKET sock = *(SOCKET *)arg;
6724     char buffer[32];
6725     WSABUF wsa;
6726     WSAOVERLAPPED ov;
6727     DWORD flags = 0;
6728 
6729     wsa.buf = buffer;
6730     wsa.len = sizeof(buffer);
6731     ov.hEvent = WSACreateEvent();
6732     WSARecv(sock, &wsa, 1, NULL, &flags, &ov, NULL);
6733 
6734     WaitForSingleObject(ov.hEvent, 1000);
6735     WSACloseEvent(ov.hEvent);
6736     return 0;
6737 }
6738 
6739 static int completion_called;
6740 
6741 static void WINAPI io_completion(DWORD error, DWORD transferred, WSAOVERLAPPED *overlapped, DWORD flags)
6742 {
6743     completion_called++;
6744 }
6745 
6746 static void test_WSARecv(void)
6747 {
6748     SOCKET src, dest, server = INVALID_SOCKET;
6749     char buf[20];
6750     WSABUF bufs[2];
6751     WSAOVERLAPPED ov;
6752     DWORD bytesReturned, flags, id;
6753     struct linger ling;
6754     struct sockaddr_in addr;
6755     int iret, len;
6756     DWORD dwret;
6757     BOOL bret;
6758     HANDLE thread, event = NULL, io_port;
6759 
6760     tcp_socketpair(&src, &dest);
6761     if (src == INVALID_SOCKET || dest == INVALID_SOCKET)
6762     {
6763         skip("failed to create sockets\n");
6764         goto end;
6765     }
6766 
6767     memset(&ov, 0, sizeof(ov));
6768     flags = 0;
6769     bufs[0].len = 2;
6770     bufs[0].buf = buf;
6771 
6772     /* Send 4 bytes and receive in two calls of 2 */
6773     SetLastError(0xdeadbeef);
6774     iret = send(src, "test", 4, 0);
6775     ok(iret == 4, "Expected 4, got %d\n", iret);
6776     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6777     SetLastError(0xdeadbeef);
6778     bytesReturned = 0xdeadbeef;
6779     iret = WSARecv(dest, bufs, 1, &bytesReturned, &flags, NULL, NULL);
6780     ok(!iret, "Expected 0, got %d\n", iret);
6781     ok(bytesReturned == 2, "Expected 2, got %d\n", bytesReturned);
6782     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6783     SetLastError(0xdeadbeef);
6784     bytesReturned = 0xdeadbeef;
6785     iret = WSARecv(dest, bufs, 1, &bytesReturned, &flags, NULL, NULL);
6786     ok(!iret, "Expected 0, got %d\n", iret);
6787     ok(bytesReturned == 2, "Expected 2, got %d\n", bytesReturned);
6788     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6789 
6790     bufs[0].len = 4;
6791     SetLastError(0xdeadbeef);
6792     iret = send(src, "test", 4, 0);
6793     ok(iret == 4, "Expected 4, got %d\n", iret);
6794     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6795     SetLastError(0xdeadbeef);
6796     bytesReturned = 0xdeadbeef;
6797     iret = WSARecv(dest, bufs, 1, &bytesReturned, &flags, NULL, NULL);
6798     ok(!iret, "Expected 0, got %d\n", iret);
6799     ok(bytesReturned == 4, "Expected 4, got %d\n", bytesReturned);
6800     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6801 
6802     /* Test 2 buffers */
6803     bufs[0].len = 4;
6804     bufs[1].len = 5;
6805     bufs[1].buf = buf + 10;
6806     SetLastError(0xdeadbeef);
6807     iret = send(src, "deadbeefs", 9, 0);
6808     ok(iret == 9, "Expected 9, got %d\n", iret);
6809     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6810     SetLastError(0xdeadbeef);
6811     bytesReturned = 0xdeadbeef;
6812     iret = WSARecv(dest, bufs, 2, &bytesReturned, &flags, NULL, NULL);
6813     ok(!iret, "Expected 0, got %d\n", iret);
6814     ok(bytesReturned == 9, "Expected 9, got %d\n", bytesReturned);
6815     bufs[0].buf[4] = '\0';
6816     bufs[1].buf[5] = '\0';
6817     ok(!strcmp(bufs[0].buf, "dead"), "buf[0] doesn't match: %s != dead\n", bufs[0].buf);
6818     ok(!strcmp(bufs[1].buf, "beefs"), "buf[1] doesn't match: %s != beefs\n", bufs[1].buf);
6819     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6820 
6821     bufs[0].len = sizeof(buf);
6822     ov.hEvent = event = CreateEventA(NULL, FALSE, FALSE, NULL);
6823     ok(ov.hEvent != NULL, "could not create event object, errno = %d\n", GetLastError());
6824     if (!event)
6825         goto end;
6826 
6827     ling.l_onoff = 1;
6828     ling.l_linger = 0;
6829     iret = setsockopt (src, SOL_SOCKET, SO_LINGER, (char *) &ling, sizeof(ling));
6830     ok(!iret, "Failed to set linger %d\n", GetLastError());
6831 
6832     iret = WSARecv(dest, bufs, 1, NULL, &flags, &ov, NULL);
6833     ok(iret == SOCKET_ERROR && GetLastError() == ERROR_IO_PENDING, "WSARecv failed - %d error %d\n", iret, GetLastError());
6834 
6835     iret = WSARecv(dest, bufs, 1, &bytesReturned, &flags, &ov, NULL);
6836     ok(iret == SOCKET_ERROR && GetLastError() == ERROR_IO_PENDING, "WSARecv failed - %d error %d\n", iret, GetLastError());
6837 
6838     closesocket(src);
6839     src = INVALID_SOCKET;
6840 
6841     dwret = WaitForSingleObject(ov.hEvent, 1000);
6842     ok(dwret == WAIT_OBJECT_0, "Waiting for disconnect event failed with %d + errno %d\n", dwret, GetLastError());
6843 
6844     bret = GetOverlappedResult((HANDLE)dest, &ov, &bytesReturned, FALSE);
6845     todo_wine ok(!bret && (GetLastError() == ERROR_NETNAME_DELETED || broken(GetLastError() == ERROR_IO_INCOMPLETE) /* win9x */),
6846         "Did not get disconnect event: %d, error %d\n", bret, GetLastError());
6847     ok(bytesReturned == 0, "Bytes received is %d\n", bytesReturned);
6848     closesocket(dest);
6849     dest = INVALID_SOCKET;
6850 
6851     src = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0);
6852     ok(src != INVALID_SOCKET, "failed to create socket %d\n", WSAGetLastError());
6853     if (src == INVALID_SOCKET) goto end;
6854 
6855     server = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
6856     ok(server != INVALID_SOCKET, "failed to create socket %d\n", WSAGetLastError());
6857     if (server == INVALID_SOCKET) goto end;
6858 
6859     memset(&addr, 0, sizeof(addr));
6860     addr.sin_family = AF_INET;
6861     addr.sin_addr.s_addr = inet_addr("127.0.0.1");
6862     iret = bind(server, (struct sockaddr *)&addr, sizeof(addr));
6863     if (iret) goto end;
6864 
6865     len = sizeof(addr);
6866     iret = getsockname(server, (struct sockaddr *)&addr, &len);
6867     if (iret) goto end;
6868 
6869     iret = listen(server, 1);
6870     if (iret) goto end;
6871 
6872     iret = connect(src, (struct sockaddr *)&addr, sizeof(addr));
6873     if (iret) goto end;
6874 
6875     len = sizeof(addr);
6876     dest = accept(server, (struct sockaddr *)&addr, &len);
6877     ok(dest != INVALID_SOCKET, "failed to create socket %d\n", WSAGetLastError());
6878     if (dest == INVALID_SOCKET) goto end;
6879 
6880     send(src, "test message", sizeof("test message"), 0);
6881     thread = CreateThread(NULL, 0, recv_thread, &dest, 0, &id);
6882     WaitForSingleObject(thread, 3000);
6883     CloseHandle(thread);
6884 
6885     memset(&ov, 0, sizeof(ov));
6886     ov.hEvent = event;
6887     ResetEvent(event);
6888     iret = WSARecv(dest, bufs, 1, NULL, &flags, &ov, io_completion);
6889     ok(iret == SOCKET_ERROR && GetLastError() == ERROR_IO_PENDING, "WSARecv failed - %d error %d\n", iret, GetLastError());
6890     send(src, "test message", sizeof("test message"), 0);
6891 
6892     completion_called = 0;
6893     dwret = SleepEx(1000, TRUE);
6894     ok(dwret == WAIT_IO_COMPLETION, "got %u\n", dwret);
6895     ok(completion_called == 1, "completion not called\n");
6896 
6897     dwret = WaitForSingleObject(event, 1);
6898     ok(dwret == WAIT_TIMEOUT, "got %u\n", dwret);
6899 
6900     io_port = CreateIoCompletionPort( (HANDLE)dest, NULL, 0, 0 );
6901     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
6902 
6903     /* Using completion function on socket associated with completion port is not allowed. */
6904     memset(&ov, 0, sizeof(ov));
6905     completion_called = 0;
6906     iret = WSARecv(dest, bufs, 1, NULL, &flags, &ov, io_completion);
6907     ok(iret == SOCKET_ERROR && GetLastError() == WSAEINVAL, "WSARecv failed - %d error %d\n", iret, GetLastError());
6908     ok(!completion_called, "completion called\n");
6909 
6910     CloseHandle(io_port);
6911 
6912 end:
6913     if (server != INVALID_SOCKET)
6914         closesocket(server);
6915     if (dest != INVALID_SOCKET)
6916         closesocket(dest);
6917     if (src != INVALID_SOCKET)
6918         closesocket(src);
6919     if (event)
6920         WSACloseEvent(event);
6921 }
6922 
6923 struct write_watch_thread_args
6924 {
6925     int func;
6926     SOCKET dest;
6927     void *base;
6928     DWORD size;
6929     const char *expect;
6930 };
6931 
6932 static DWORD CALLBACK write_watch_thread( void *arg )
6933 {
6934     struct write_watch_thread_args *args = arg;
6935     struct sockaddr addr;
6936     int addr_len = sizeof(addr), ret;
6937     DWORD bytes, flags = 0;
6938     WSABUF buf[1];
6939 
6940     switch (args->func)
6941     {
6942     case 0:
6943         ret = recv( args->dest, args->base, args->size, 0 );
6944         ok( ret == strlen(args->expect) + 1, "wrong len %d\n", ret );
6945         ok( !strcmp( args->base, args->expect ), "wrong data\n" );
6946         break;
6947     case 1:
6948         ret = recvfrom( args->dest, args->base, args->size, 0, &addr, &addr_len );
6949         ok( ret == strlen(args->expect) + 1, "wrong len %d\n", ret );
6950         ok( !strcmp( args->base, args->expect ), "wrong data\n" );
6951         break;
6952     case 2:
6953         buf[0].len = args->size;
6954         buf[0].buf = args->base;
6955         ret = WSARecv( args->dest, buf, 1, &bytes, &flags, NULL, NULL );
6956         ok( !ret, "WSARecv failed %u\n", GetLastError() );
6957         ok( bytes == strlen(args->expect) + 1, "wrong len %d\n", bytes );
6958         ok( !strcmp( args->base, args->expect ), "wrong data\n" );
6959         break;
6960     case 3:
6961         buf[0].len = args->size;
6962         buf[0].buf = args->base;
6963         ret = WSARecvFrom( args->dest, buf, 1, &bytes, &flags, &addr, &addr_len, NULL, NULL );
6964         ok( !ret, "WSARecvFrom failed %u\n", GetLastError() );
6965         ok( bytes == strlen(args->expect) + 1, "wrong len %d\n", bytes );
6966         ok( !strcmp( args->base, args->expect ), "wrong data\n" );
6967         break;
6968     }
6969     return 0;
6970 }
6971 
6972 static void test_write_watch(void)
6973 {
6974     SOCKET src, dest;
6975     WSABUF bufs[2];
6976     WSAOVERLAPPED ov;
6977     struct write_watch_thread_args args;
6978     DWORD bytesReturned, flags, size;
6979     struct sockaddr addr;
6980     int addr_len, ret;
6981     HANDLE thread, event;
6982     char *base;
6983     void *results[64];
6984     ULONG_PTR count;
6985     ULONG pagesize;
6986     UINT (WINAPI *pGetWriteWatch)(DWORD,LPVOID,SIZE_T,LPVOID*,ULONG_PTR*,ULONG*);
6987 
6988     pGetWriteWatch = (void *)GetProcAddress( GetModuleHandleA("kernel32.dll"), "GetWriteWatch" );
6989     if (!pGetWriteWatch)
6990     {
6991         win_skip( "write watched not supported\n" );
6992         return;
6993     }
6994 
6995     tcp_socketpair(&src, &dest);
6996     if (src == INVALID_SOCKET || dest == INVALID_SOCKET)
6997     {
6998         skip("failed to create sockets\n");
6999         return;
7000     }
7001 
7002     memset(&ov, 0, sizeof(ov));
7003     ov.hEvent = event = CreateEventA(NULL, FALSE, FALSE, NULL);
7004     ok(ov.hEvent != NULL, "could not create event object, errno = %d\n", GetLastError());
7005 
7006     flags = 0;
7007 
7008     size = 0x10000;
7009     base = VirtualAlloc( 0, size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE );
7010     ok( base != NULL, "VirtualAlloc failed %u\n", GetLastError() );
7011 
7012     memset( base, 0, size );
7013     count = 64;
7014     ret = pGetWriteWatch( WRITE_WATCH_FLAG_RESET, base, size, results, &count, &pagesize );
7015     ok( !ret, "GetWriteWatch failed %u\n", GetLastError() );
7016     ok( count == 16, "wrong count %lu\n", count );
7017 
7018     bufs[0].len = 5;
7019     bufs[0].buf = base;
7020     bufs[1].len = 0x8000;
7021     bufs[1].buf = base + 0x4000;
7022 
7023     ret = WSARecv( dest, bufs, 2, NULL, &flags, &ov, NULL);
7024     ok(ret == SOCKET_ERROR && GetLastError() == ERROR_IO_PENDING,
7025        "WSARecv failed - %d error %d\n", ret, GetLastError());
7026 
7027     count = 64;
7028     ret = pGetWriteWatch( WRITE_WATCH_FLAG_RESET, base, size, results, &count, &pagesize );
7029     ok( !ret, "GetWriteWatch failed %u\n", GetLastError() );
7030     ok( count == 9, "wrong count %lu\n", count );
7031     ok( !base[0], "data set\n" );
7032 
7033     send(src, "test message", sizeof("test message"), 0);
7034 
7035     ret = GetOverlappedResult( (HANDLE)dest, &ov, &bytesReturned, TRUE );
7036     ok( ret, "GetOverlappedResult failed %u\n", GetLastError() );
7037     ok( bytesReturned == sizeof("test message"), "wrong size %u\n", bytesReturned );
7038     ok( !memcmp( base, "test ", 5 ), "wrong data %s\n", base );
7039     ok( !memcmp( base + 0x4000, "message", 8 ), "wrong data %s\n", base + 0x4000 );
7040 
7041     count = 64;
7042     ret = pGetWriteWatch( WRITE_WATCH_FLAG_RESET, base, size, results, &count, &pagesize );
7043     ok( !ret, "GetWriteWatch failed %u\n", GetLastError() );
7044     ok( count == 0, "wrong count %lu\n", count );
7045 
7046     memset( base, 0, size );
7047     count = 64;
7048     ret = pGetWriteWatch( WRITE_WATCH_FLAG_RESET, base, size, results, &count, &pagesize );
7049     ok( !ret, "GetWriteWatch failed %u\n", GetLastError() );
7050     ok( count == 16, "wrong count %lu\n", count );
7051 
7052     bufs[1].len = 0x4000;
7053     bufs[1].buf = base + 0x2000;
7054     ret = WSARecvFrom( dest, bufs, 2, NULL, &flags, &addr, &addr_len, &ov, NULL);
7055     ok(ret == SOCKET_ERROR && GetLastError() == ERROR_IO_PENDING,
7056        "WSARecv failed - %d error %d\n", ret, GetLastError());
7057 
7058     count = 64;
7059     ret = pGetWriteWatch( WRITE_WATCH_FLAG_RESET, base, size, results, &count, &pagesize );
7060     ok( !ret, "GetWriteWatch failed %u\n", GetLastError() );
7061     ok( count == 5, "wrong count %lu\n", count );
7062     ok( !base[0], "data set\n" );
7063 
7064     send(src, "test message", sizeof("test message"), 0);
7065 
7066     ret = GetOverlappedResult( (HANDLE)dest, &ov, &bytesReturned, TRUE );
7067     ok( ret, "GetOverlappedResult failed %u\n", GetLastError() );
7068     ok( bytesReturned == sizeof("test message"), "wrong size %u\n", bytesReturned );
7069     ok( !memcmp( base, "test ", 5 ), "wrong data %s\n", base );
7070     ok( !memcmp( base + 0x2000, "message", 8 ), "wrong data %s\n", base + 0x2000 );
7071 
7072     count = 64;
7073     ret = pGetWriteWatch( WRITE_WATCH_FLAG_RESET, base, size, results, &count, &pagesize );
7074     ok( !ret, "GetWriteWatch failed %u\n", GetLastError() );
7075     ok( count == 0, "wrong count %lu\n", count );
7076 
7077     memset( base, 0, size );
7078     count = 64;
7079     ret = pGetWriteWatch( WRITE_WATCH_FLAG_RESET, base, size, results, &count, &pagesize );
7080     ok( !ret, "GetWriteWatch failed %u\n", GetLastError() );
7081     ok( count == 16, "wrong count %lu\n", count );
7082 
7083     args.dest = dest;
7084     args.base = base;
7085     args.size = 0x7002;
7086     args.expect = "test message";
7087     for (args.func = 0; args.func < 4; args.func++)
7088     {
7089         thread = CreateThread( NULL, 0, write_watch_thread, &args, 0, NULL );
7090         Sleep( 200 );
7091 
7092         count = 64;
7093         ret = pGetWriteWatch( WRITE_WATCH_FLAG_RESET, base, size, results, &count, &pagesize );
7094         ok( !ret, "GetWriteWatch failed %u\n", GetLastError() );
7095         ok( count == 8, "wrong count %lu\n", count );
7096 
7097         send(src, "test message", sizeof("test message"), 0);
7098         WaitForSingleObject( thread, 10000 );
7099         CloseHandle( thread );
7100 
7101         count = 64;
7102         ret = pGetWriteWatch( WRITE_WATCH_FLAG_RESET, base, size, results, &count, &pagesize );
7103         ok( !ret, "GetWriteWatch failed %u\n", GetLastError() );
7104         ok( count == 0, "wrong count %lu\n", count );
7105     }
7106     WSACloseEvent( event );
7107     closesocket( dest );
7108     closesocket( src );
7109     VirtualFree( base, 0, MEM_FREE );
7110 }
7111 
7112 #define POLL_CLEAR() ix = 0
7113 #define POLL_SET(s, ev) {fds[ix].fd = s; fds[ix++].events = ev;}
7114 #define POLL_ISSET(s, rev) poll_isset(fds, ix, s, rev)
7115 static BOOL poll_isset(WSAPOLLFD *fds, int max, SOCKET s, int rev)
7116 {
7117     int k;
7118     for (k = 0; k < max; k++)
7119         if (fds[k].fd == s && (fds[k].revents == rev)) return TRUE;
7120     return FALSE;
7121 }
7122 
7123 static void test_WSAPoll(void)
7124 {
7125     int ix, ret, err, poll_timeout;
7126     SOCKET fdListen, fdRead, fdWrite;
7127     struct sockaddr_in address;
7128     socklen_t len;
7129     static char tmp_buf[1024];
7130     WSAPOLLFD fds[16];
7131     HANDLE thread_handle;
7132     DWORD id;
7133 
7134     if (!pWSAPoll) /* >= Vista */
7135     {
7136         skip("WSAPoll is unsupported, some tests will be skipped.\n");
7137         return;
7138     }
7139 
7140     /* Invalid parameters test */
7141     SetLastError(0xdeadbeef);
7142     ret = pWSAPoll(NULL, 0, 0);
7143     err = GetLastError();
7144     ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
7145     ok(err == WSAEINVAL, "expected 10022, got %d\n", err);
7146     SetLastError(0xdeadbeef);
7147     ret = pWSAPoll(NULL, 1, 0);
7148     err = GetLastError();
7149     ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
7150     ok(err == WSAEFAULT, "expected 10014, got %d\n", err);
7151     SetLastError(0xdeadbeef);
7152     ret = pWSAPoll(NULL, 0, 1);
7153     err = GetLastError();
7154     ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
7155     ok(err == WSAEINVAL, "expected 10022, got %d\n", err);
7156     SetLastError(0xdeadbeef);
7157     ret = pWSAPoll(NULL, 1, 1);
7158     err = GetLastError();
7159     ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
7160     ok(err == WSAEFAULT, "expected 10014, got %d\n", err);
7161 
7162     /* WSAPoll() tries to mime the unix poll() call. The following tests do:
7163      * - check if a connection attempt ended with success or error;
7164      * - check if a pending connection is waiting for acceptance;
7165      * - check for data to read, availability for write and OOB data
7166      */
7167     memset(&address, 0, sizeof(address));
7168     address.sin_addr.s_addr = inet_addr("127.0.0.1");
7169     address.sin_family = AF_INET;
7170     len = sizeof(address);
7171     fdListen = setup_server_socket(&address, &len);
7172     poll_timeout = 100;
7173 
7174     /* When no events are pending poll returns 0 with no error */
7175     POLL_CLEAR();
7176     POLL_SET(fdListen, POLLIN);
7177     ret = pWSAPoll(fds, ix, poll_timeout);
7178     ok(ret == 0, "expected 0, got %d\n", ret);
7179 
7180     /* Test listening socket connection attempt notifications */
7181     fdWrite = setup_connector_socket(&address, len, TRUE);
7182     POLL_CLEAR();
7183     POLL_SET(fdListen, POLLIN | POLLOUT);
7184     ret = pWSAPoll(fds, ix, poll_timeout);
7185     ok(ret == 1, "expected 1, got %d\n", ret);
7186     ok(POLL_ISSET(fdListen, POLLRDNORM), "fdListen socket events incorrect\n");
7187     len = sizeof(address);
7188     fdRead = accept(fdListen, (struct sockaddr*) &address, &len);
7189     ok(fdRead != INVALID_SOCKET, "expected a valid socket\n");
7190 
7191     /* Test client side connection attempt notifications */
7192     POLL_CLEAR();
7193     POLL_SET(fdListen, POLLIN | POLLOUT);
7194     POLL_SET(fdRead, POLLIN | POLLOUT);
7195     POLL_SET(fdWrite, POLLIN | POLLOUT);
7196     ret = pWSAPoll(fds, ix, poll_timeout);
7197     ok(ret == 2, "expected 2, got %d\n", ret);
7198     ok(POLL_ISSET(fdWrite, POLLWRNORM), "fdWrite socket events incorrect\n");
7199     ok(POLL_ISSET(fdRead, POLLWRNORM), "fdRead socket events incorrect\n");
7200     len = sizeof(id);
7201     id = 0xdeadbeef;
7202     err = getsockopt(fdWrite, SOL_SOCKET, SO_ERROR, (char*)&id, &len);
7203     ok(!err, "getsockopt failed with %d\n", WSAGetLastError());
7204     ok(id == 0, "expected 0, got %d\n", id);
7205 
7206     /* Test data receiving notifications */
7207     ret = send(fdWrite, "1234", 4, 0);
7208     ok(ret == 4, "expected 4, got %d\n", ret);
7209     POLL_CLEAR();
7210     POLL_SET(fdListen, POLLIN | POLLOUT);
7211     POLL_SET(fdRead, POLLIN);
7212     ret = pWSAPoll(fds, ix, poll_timeout);
7213     ok(ret == 1, "expected 1, got %d\n", ret);
7214     ok(POLL_ISSET(fdRead, POLLRDNORM), "fdRead socket events incorrect\n");
7215     ret = recv(fdRead, tmp_buf, sizeof(tmp_buf), 0);
7216     ok(ret == 4, "expected 4, got %d\n", ret);
7217     ok(!strcmp(tmp_buf, "1234"), "data received differs from sent\n");
7218 
7219     /* Test OOB data notifications */
7220     ret = send(fdWrite, "A", 1, MSG_OOB);
7221     ok(ret == 1, "expected 1, got %d\n", ret);
7222     POLL_CLEAR();
7223     POLL_SET(fdListen, POLLIN | POLLOUT);
7224     POLL_SET(fdRead, POLLIN);
7225     ret = pWSAPoll(fds, ix, poll_timeout);
7226     ok(ret == 1, "expected 1, got %d\n", ret);
7227     ok(POLL_ISSET(fdRead, POLLRDBAND), "fdRead socket events incorrect\n");
7228     tmp_buf[0] = 0xAF;
7229     ret = recv(fdRead, tmp_buf, sizeof(tmp_buf), MSG_OOB);
7230     ok(ret == 1, "expected 1, got %d\n", ret);
7231     ok(tmp_buf[0] == 'A', "expected 'A', got 0x%02X\n", tmp_buf[0]);
7232 
7233     /* If the socket is OOBINLINED the notification is like normal data */
7234     ret = 1;
7235     ret = setsockopt(fdRead, SOL_SOCKET, SO_OOBINLINE, (char*) &ret, sizeof(ret));
7236     ok(ret == 0, "expected 0, got %d\n", ret);
7237     ret = send(fdWrite, "A", 1, MSG_OOB);
7238     ok(ret == 1, "expected 1, got %d\n", ret);
7239     POLL_CLEAR();
7240     POLL_SET(fdListen, POLLIN | POLLOUT);
7241     POLL_SET(fdRead, POLLIN | POLLOUT);
7242     ret = pWSAPoll(fds, ix, poll_timeout);
7243     ok(ret == 1, "expected 1, got %d\n", ret);
7244     tmp_buf[0] = 0xAF;
7245     SetLastError(0xdeadbeef);
7246     ret = recv(fdRead, tmp_buf, sizeof(tmp_buf), MSG_OOB);
7247     ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
7248     ok(GetLastError() == WSAEINVAL, "expected 10022, got %d\n", GetLastError());
7249     ret = recv(fdRead, tmp_buf, sizeof(tmp_buf), 0);
7250     ok(ret == 1, "expected 1, got %d\n", ret);
7251     ok(tmp_buf[0] == 'A', "expected 'A', got 0x%02X\n", tmp_buf[0]);
7252 
7253     /* Test connection closed notifications */
7254     ret = closesocket(fdRead);
7255     ok(ret == 0, "expected 0, got %d\n", ret);
7256     POLL_CLEAR();
7257     POLL_SET(fdListen, POLLIN | POLLOUT);
7258     POLL_SET(fdWrite, POLLIN);
7259     ret = pWSAPoll(fds, ix, poll_timeout);
7260     ok(ret == 1, "expected 1, got %d\n", ret);
7261     ok(POLL_ISSET(fdWrite, POLLHUP), "fdWrite socket events incorrect\n");
7262     ret = recv(fdWrite, tmp_buf, sizeof(tmp_buf), 0);
7263     ok(ret == 0, "expected 0, got %d\n", ret);
7264 
7265     /* When a connection is attempted to a non-listening socket due to a bug
7266      * in the MS code it will never be notified. This is a long standing issue
7267      * that will never be fixed for compatibility reasons so we have to deal
7268      * with it manually. */
7269     ret = closesocket(fdWrite);
7270     ok(ret == 0, "expected 0, got %d\n", ret);
7271     ret = closesocket(fdListen);
7272     ok(ret == 0, "expected 0, got %d\n", ret);
7273     len = sizeof(address);
7274     fdWrite = setup_connector_socket(&address, len, TRUE);
7275     POLL_CLEAR();
7276     POLL_SET(fdWrite, POLLIN | POLLOUT);
7277     poll_timeout = 2000;
7278     ret = pWSAPoll(fds, ix, poll_timeout);
7279 todo_wine
7280     ok(ret == 0, "expected 0, got %d\n", ret);
7281     len = sizeof(id);
7282     id = 0xdeadbeef;
7283     err = getsockopt(fdWrite, SOL_SOCKET, SO_ERROR, (char*)&id, &len);
7284     ok(!err, "getsockopt failed with %d\n", WSAGetLastError());
7285     ok(id == WSAECONNREFUSED, "expected 10061, got %d\n", id);
7286     closesocket(fdWrite);
7287 
7288     /* Try poll() on a closed socket after connection */
7289     ok(!tcp_socketpair(&fdRead, &fdWrite), "creating socket pair failed\n");
7290     closesocket(fdRead);
7291     POLL_CLEAR();
7292     POLL_SET(fdWrite, POLLIN | POLLOUT);
7293     POLL_SET(fdRead, POLLIN | POLLOUT);
7294     ret = pWSAPoll(fds, ix, poll_timeout);
7295     ok(ret == 1, "expected 1, got %d\n", ret);
7296     ok(POLL_ISSET(fdRead, POLLNVAL), "fdRead socket events incorrect\n");
7297     POLL_CLEAR();
7298     POLL_SET(fdWrite, POLLIN | POLLOUT);
7299     ret = pWSAPoll(fds, ix, poll_timeout);
7300     ok(ret == 1, "expected 1, got %d\n", ret);
7301 todo_wine
7302     ok(POLL_ISSET(fdWrite, POLLWRNORM | POLLHUP) || broken(POLL_ISSET(fdWrite, POLLWRNORM)) /* <= 2008 */,
7303        "fdWrite socket events incorrect\n");
7304     closesocket(fdWrite);
7305 
7306     /* Close the socket currently being polled in a thread */
7307     ok(!tcp_socketpair(&fdRead, &fdWrite), "creating socket pair failed\n");
7308     thread_handle = CreateThread(NULL, 0, SelectCloseThread, &fdWrite, 0, &id);
7309     ok(thread_handle != NULL, "CreateThread failed unexpectedly: %d\n", GetLastError());
7310     POLL_CLEAR();
7311     POLL_SET(fdWrite, POLLIN | POLLOUT);
7312     ret = pWSAPoll(fds, ix, poll_timeout);
7313     ok(ret == 1, "expected 1, got %d\n", ret);
7314     ok(POLL_ISSET(fdWrite, POLLWRNORM), "fdWrite socket events incorrect\n");
7315     WaitForSingleObject (thread_handle, 1000);
7316     closesocket(fdRead);
7317     /* test again with less flags - behavior changes */
7318     ok(!tcp_socketpair(&fdRead, &fdWrite), "creating socket pair failed\n");
7319     thread_handle = CreateThread(NULL, 0, SelectCloseThread, &fdWrite, 0, &id);
7320     ok(thread_handle != NULL, "CreateThread failed unexpectedly: %d\n", GetLastError());
7321     POLL_CLEAR();
7322     POLL_SET(fdWrite, POLLIN);
7323     ret = pWSAPoll(fds, ix, poll_timeout);
7324     ok(ret == 1, "expected 1, got %d\n", ret);
7325     ok(POLL_ISSET(fdWrite, POLLNVAL), "fdWrite socket events incorrect\n");
7326     WaitForSingleObject (thread_handle, 1000);
7327     closesocket(fdRead);
7328 }
7329 #undef POLL_SET
7330 #undef POLL_ISSET
7331 #undef POLL_CLEAR
7332 
7333 static void test_GetAddrInfoW(void)
7334 {
7335     static const WCHAR port[] = {'8','0',0};
7336     static const WCHAR empty[] = {0};
7337     static const WCHAR localhost[] = {'l','o','c','a','l','h','o','s','t',0};
7338     static const WCHAR nxdomain[] =
7339         {'n','x','d','o','m','a','i','n','.','c','o','d','e','w','e','a','v','e','r','s','.','c','o','m',0};
7340     static const WCHAR zero[] = {'0',0};
7341     int i, ret;
7342     ADDRINFOW *result, *result2, *p, hint;
7343     WCHAR name[256];
7344     DWORD size = sizeof(name)/sizeof(WCHAR);
7345     /* te su to.winehq.org written in katakana */
7346     static const WCHAR idn_domain[] =
7347         {0x30C6,0x30B9,0x30C8,'.','w','i','n','e','h','q','.','o','r','g',0};
7348     static const WCHAR idn_punycode[] =
7349         {'x','n','-','-','z','c','k','z','a','h','.','w','i','n','e','h','q','.','o','r','g',0};
7350 
7351     if (!pGetAddrInfoW || !pFreeAddrInfoW)
7352     {
7353         win_skip("GetAddrInfoW and/or FreeAddrInfoW not present\n");
7354         return;
7355     }
7356     memset(&hint, 0, sizeof(ADDRINFOW));
7357     name[0] = 0;
7358     GetComputerNameExW( ComputerNamePhysicalDnsHostname, name, &size );
7359 
7360     result = (ADDRINFOW *)0xdeadbeef;
7361     WSASetLastError(0xdeadbeef);
7362     ret = pGetAddrInfoW(NULL, NULL, NULL, &result);
7363     ok(ret == WSAHOST_NOT_FOUND, "got %d expected WSAHOST_NOT_FOUND\n", ret);
7364     ok(WSAGetLastError() == WSAHOST_NOT_FOUND, "expected 11001, got %d\n", WSAGetLastError());
7365     ok(result == NULL, "got %p\n", result);
7366 
7367     result = NULL;
7368     WSASetLastError(0xdeadbeef);
7369     ret = pGetAddrInfoW(empty, NULL, NULL, &result);
7370     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7371     ok(result != NULL, "GetAddrInfoW failed\n");
7372     ok(WSAGetLastError() == 0, "expected 0, got %d\n", WSAGetLastError());
7373     pFreeAddrInfoW(result);
7374 
7375     result = NULL;
7376     ret = pGetAddrInfoW(NULL, zero, NULL, &result);
7377     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7378     ok(result != NULL, "GetAddrInfoW failed\n");
7379 
7380     result2 = NULL;
7381     ret = pGetAddrInfoW(NULL, empty, NULL, &result2);
7382     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7383     ok(result2 != NULL, "GetAddrInfoW failed\n");
7384     compare_addrinfow(result, result2);
7385     pFreeAddrInfoW(result);
7386     pFreeAddrInfoW(result2);
7387 
7388     result = NULL;
7389     ret = pGetAddrInfoW(empty, zero, NULL, &result);
7390     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7391     ok(WSAGetLastError() == 0, "expected 0, got %d\n", WSAGetLastError());
7392     ok(result != NULL, "GetAddrInfoW failed\n");
7393 
7394     result2 = NULL;
7395     ret = pGetAddrInfoW(empty, empty, NULL, &result2);
7396     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7397     ok(result2 != NULL, "GetAddrInfoW failed\n");
7398     compare_addrinfow(result, result2);
7399     pFreeAddrInfoW(result);
7400     pFreeAddrInfoW(result2);
7401 
7402     result = NULL;
7403     ret = pGetAddrInfoW(localhost, NULL, NULL, &result);
7404     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7405     pFreeAddrInfoW(result);
7406 
7407     result = NULL;
7408     ret = pGetAddrInfoW(localhost, empty, NULL, &result);
7409     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7410     pFreeAddrInfoW(result);
7411 
7412     result = NULL;
7413     ret = pGetAddrInfoW(localhost, zero, NULL, &result);
7414     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7415     pFreeAddrInfoW(result);
7416 
7417     result = NULL;
7418     ret = pGetAddrInfoW(localhost, port, NULL, &result);
7419     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7420     pFreeAddrInfoW(result);
7421 
7422     result = NULL;
7423     ret = pGetAddrInfoW(localhost, NULL, &hint, &result);
7424     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7425     pFreeAddrInfoW(result);
7426 
7427     result = NULL;
7428     SetLastError(0xdeadbeef);
7429     ret = pGetAddrInfoW(localhost, port, &hint, &result);
7430     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7431     ok(WSAGetLastError() == 0, "expected 0, got %d\n", WSAGetLastError());
7432     pFreeAddrInfoW(result);
7433 
7434     /* try to get information from the computer name, result is the same
7435      * as if requesting with an empty host name. */
7436     ret = pGetAddrInfoW(name, NULL, NULL, &result);
7437     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7438     ok(result != NULL, "GetAddrInfoW failed\n");
7439 
7440     ret = pGetAddrInfoW(empty, NULL, NULL, &result2);
7441     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7442 #ifdef __REACTOS__
7443     ok(result2 != NULL, "GetAddrInfoW failed\n");
7444 #else
7445     ok(result != NULL, "GetAddrInfoW failed\n");
7446 #endif
7447     compare_addrinfow(result, result2);
7448     pFreeAddrInfoW(result);
7449     pFreeAddrInfoW(result2);
7450 
7451     ret = pGetAddrInfoW(name, empty, NULL, &result);
7452     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7453     ok(result != NULL, "GetAddrInfoW failed\n");
7454 
7455     ret = pGetAddrInfoW(empty, empty, NULL, &result2);
7456     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7457 #ifdef __REACTOS__
7458     ok(result2 != NULL, "GetAddrInfoW failed\n");
7459 #else
7460     ok(result != NULL, "GetAddrInfoW failed\n");
7461 #endif
7462     compare_addrinfow(result, result2);
7463     pFreeAddrInfoW(result);
7464     pFreeAddrInfoW(result2);
7465 
7466     result = (ADDRINFOW *)0xdeadbeef;
7467     WSASetLastError(0xdeadbeef);
7468     ret = pGetAddrInfoW(NULL, NULL, NULL, &result);
7469     if(ret == 0)
7470     {
7471         skip("nxdomain returned success. Broken ISP redirects?\n");
7472         return;
7473     }
7474     ok(ret == WSAHOST_NOT_FOUND, "got %d expected WSAHOST_NOT_FOUND\n", ret);
7475     ok(WSAGetLastError() == WSAHOST_NOT_FOUND, "expected 11001, got %d\n", WSAGetLastError());
7476     ok(result == NULL, "got %p\n", result);
7477 
7478     result = (ADDRINFOW *)0xdeadbeef;
7479     WSASetLastError(0xdeadbeef);
7480     ret = pGetAddrInfoW(nxdomain, NULL, NULL, &result);
7481     if(ret == 0)
7482     {
7483         skip("nxdomain returned success. Broken ISP redirects?\n");
7484         return;
7485     }
7486     ok(ret == WSAHOST_NOT_FOUND, "got %d expected WSAHOST_NOT_FOUND\n", ret);
7487     ok(WSAGetLastError() == WSAHOST_NOT_FOUND, "expected 11001, got %d\n", WSAGetLastError());
7488     ok(result == NULL, "got %p\n", result);
7489 
7490     for (i = 0;i < (sizeof(hinttests) / sizeof(hinttests[0]));i++)
7491     {
7492         hint.ai_family = hinttests[i].family;
7493         hint.ai_socktype = hinttests[i].socktype;
7494         hint.ai_protocol = hinttests[i].protocol;
7495 
7496         result = NULL;
7497         SetLastError(0xdeadbeef);
7498         ret = pGetAddrInfoW(localhost, NULL, &hint, &result);
7499         if (!ret)
7500         {
7501             if (hinttests[i].error)
7502                 ok(0, "test %d: GetAddrInfoW succeeded unexpectedly\n", i);
7503             else
7504             {
7505                 p = result;
7506                 do
7507                 {
7508                     /* when AF_UNSPEC is used the return will be either AF_INET or AF_INET6 */
7509                     if (hinttests[i].family == AF_UNSPEC)
7510                         ok(p->ai_family == AF_INET || p->ai_family == AF_INET6,
7511                            "test %d: expected AF_INET or AF_INET6, got %d\n",
7512                            i, p->ai_family);
7513                     else
7514                         ok(p->ai_family == hinttests[i].family,
7515                            "test %d: expected family %d, got %d\n",
7516                            i, hinttests[i].family, p->ai_family);
7517 
7518                     ok(p->ai_socktype == hinttests[i].socktype,
7519                        "test %d: expected type %d, got %d\n",
7520                        i, hinttests[i].socktype, p->ai_socktype);
7521                     ok(p->ai_protocol == hinttests[i].protocol,
7522                        "test %d: expected protocol %d, got %d\n",
7523                        i, hinttests[i].protocol, p->ai_protocol);
7524                     p = p->ai_next;
7525                 }
7526                 while (p);
7527             }
7528             pFreeAddrInfoW(result);
7529         }
7530         else
7531         {
7532             DWORD err = WSAGetLastError();
7533             if (hinttests[i].error)
7534                 ok(hinttests[i].error == err, "test %d: GetAddrInfoW failed with error %d, expected %d\n",
7535                    i, err, hinttests[i].error);
7536             else
7537                 ok(0, "test %d: GetAddrInfoW failed with %d (err %d)\n", i, ret, err);
7538         }
7539     }
7540 
7541     /* Test IDN resolution (Internationalized Domain Names) present since Windows 8 */
7542     trace("Testing punycode IDN %s\n", wine_dbgstr_w(idn_punycode));
7543     result = NULL;
7544     ret = pGetAddrInfoW(idn_punycode, NULL, NULL, &result);
7545     ok(!ret, "got %d expected success\n", ret);
7546     ok(result != NULL, "got %p\n", result);
7547     pFreeAddrInfoW(result);
7548 
7549     hint.ai_family = AF_INET;
7550     hint.ai_socktype = 0;
7551     hint.ai_protocol = 0;
7552     hint.ai_flags = 0;
7553 
7554     result = NULL;
7555     ret = pGetAddrInfoW(idn_punycode, NULL, &hint, &result);
7556     ok(!ret, "got %d expected success\n", ret);
7557     ok(result != NULL, "got %p\n", result);
7558 
7559     trace("Testing unicode IDN %s\n", wine_dbgstr_w(idn_domain));
7560     result2 = NULL;
7561     ret = pGetAddrInfoW(idn_domain, NULL, NULL, &result2);
7562     if (ret == WSAHOST_NOT_FOUND && broken(1))
7563     {
7564         pFreeAddrInfoW(result);
7565         win_skip("IDN resolution not supported in Win <= 7\n");
7566         return;
7567     }
7568 
7569     ok(!ret, "got %d expected success\n", ret);
7570     ok(result2 != NULL, "got %p\n", result2);
7571     pFreeAddrInfoW(result2);
7572 
7573     hint.ai_family = AF_INET;
7574     hint.ai_socktype = 0;
7575     hint.ai_protocol = 0;
7576     hint.ai_flags = 0;
7577 
7578     result2 = NULL;
7579     ret = pGetAddrInfoW(idn_domain, NULL, &hint, &result2);
7580     ok(!ret, "got %d expected success\n", ret);
7581     ok(result2 != NULL, "got %p\n", result2);
7582 
7583     /* ensure manually resolved punycode and unicode hosts result in same data */
7584     compare_addrinfow(result, result2);
7585 
7586     pFreeAddrInfoW(result);
7587     pFreeAddrInfoW(result2);
7588 
7589     hint.ai_family = AF_INET;
7590     hint.ai_socktype = 0;
7591     hint.ai_protocol = 0;
7592     hint.ai_flags = 0;
7593 
7594     result2 = NULL;
7595     ret = pGetAddrInfoW(idn_domain, NULL, &hint, &result2);
7596     ok(!ret, "got %d expected success\n", ret);
7597     ok(result2 != NULL, "got %p\n", result2);
7598     pFreeAddrInfoW(result2);
7599 
7600     /* Disable IDN resolution and test again*/
7601     hint.ai_family = AF_INET;
7602     hint.ai_socktype = 0;
7603     hint.ai_protocol = 0;
7604     hint.ai_flags = AI_DISABLE_IDN_ENCODING;
7605 
7606     SetLastError(0xdeadbeef);
7607     result2 = NULL;
7608     ret = pGetAddrInfoW(idn_domain, NULL, &hint, &result2);
7609     ok(ret == WSAHOST_NOT_FOUND, "got %d expected WSAHOST_NOT_FOUND\n", ret);
7610     ok(WSAGetLastError() == WSAHOST_NOT_FOUND, "expected 11001, got %d\n", WSAGetLastError());
7611     ok(result2 == NULL, "got %p\n", result2);
7612 }
7613 
7614 static void test_GetAddrInfoExW(void)
7615 {
7616     static const WCHAR empty[] = {0};
7617     static const WCHAR localhost[] = {'l','o','c','a','l','h','o','s','t',0};
7618     static const WCHAR winehq[] = {'t','e','s','t','.','w','i','n','e','h','q','.','o','r','g',0};
7619     ADDRINFOEXW *result;
7620     OVERLAPPED overlapped;
7621     HANDLE event;
7622     int ret;
7623 
7624     if (!pGetAddrInfoExW || !pGetAddrInfoExOverlappedResult)
7625     {
7626         win_skip("GetAddrInfoExW and/or GetAddrInfoExOverlappedResult not present\n");
7627         return;
7628     }
7629 
7630     event = WSACreateEvent();
7631 
7632     result = (ADDRINFOEXW *)0xdeadbeef;
7633     WSASetLastError(0xdeadbeef);
7634     ret = pGetAddrInfoExW(NULL, NULL, NS_DNS, NULL, NULL, &result, NULL, NULL, NULL, NULL);
7635     ok(ret == WSAHOST_NOT_FOUND, "got %d expected WSAHOST_NOT_FOUND\n", ret);
7636     ok(WSAGetLastError() == WSAHOST_NOT_FOUND, "expected 11001, got %d\n", WSAGetLastError());
7637     ok(result == NULL, "got %p\n", result);
7638 
7639     result = NULL;
7640     WSASetLastError(0xdeadbeef);
7641     ret = pGetAddrInfoExW(empty, NULL, NS_DNS, NULL, NULL, &result, NULL, NULL, NULL, NULL);
7642     ok(!ret, "GetAddrInfoExW failed with %d\n", WSAGetLastError());
7643     ok(result != NULL, "GetAddrInfoW failed\n");
7644     ok(WSAGetLastError() == 0, "expected 0, got %d\n", WSAGetLastError());
7645     pFreeAddrInfoExW(result);
7646 
7647     result = NULL;
7648     ret = pGetAddrInfoExW(localhost, NULL, NS_DNS, NULL, NULL, &result, NULL, NULL, NULL, NULL);
7649     ok(!ret, "GetAddrInfoExW failed with %d\n", WSAGetLastError());
7650     pFreeAddrInfoExW(result);
7651 
7652     result = (void*)0xdeadbeef;
7653     memset(&overlapped, 0xcc, sizeof(overlapped));
7654     overlapped.hEvent = event;
7655     ResetEvent(event);
7656     ret = pGetAddrInfoExW(localhost, NULL, NS_DNS, NULL, NULL, &result, NULL, &overlapped, NULL, NULL);
7657     ok(ret == ERROR_IO_PENDING, "GetAddrInfoExW failed with %d\n", WSAGetLastError());
7658     ok(!result, "result != NULL\n");
7659     ok(WaitForSingleObject(event, 1000) == WAIT_OBJECT_0, "wait failed\n");
7660     ret = pGetAddrInfoExOverlappedResult(&overlapped);
7661     ok(!ret, "overlapped result is %d\n", ret);
7662     pFreeAddrInfoExW(result);
7663 
7664     result = (void*)0xdeadbeef;
7665     memset(&overlapped, 0xcc, sizeof(overlapped));
7666     ResetEvent(event);
7667     overlapped.hEvent = event;
7668     WSASetLastError(0xdeadbeef);
7669     ret = pGetAddrInfoExW(winehq, NULL, NS_DNS, NULL, NULL, &result, NULL, &overlapped, NULL, NULL);
7670     ok(ret == ERROR_IO_PENDING, "GetAddrInfoExW failed with %d\n", WSAGetLastError());
7671     ok(WSAGetLastError() == ERROR_IO_PENDING, "expected 11001, got %d\n", WSAGetLastError());
7672     ret = overlapped.Internal;
7673     ok(ret == WSAEINPROGRESS || ret == ERROR_SUCCESS, "overlapped.Internal = %u\n", ret);
7674     ok(WaitForSingleObject(event, 1000) == WAIT_OBJECT_0, "wait failed\n");
7675     ret = pGetAddrInfoExOverlappedResult(&overlapped);
7676     ok(!ret, "overlapped result is %d\n", ret);
7677     ok(overlapped.hEvent == event, "hEvent changed %p\n", overlapped.hEvent);
7678     ok(overlapped.Internal == ERROR_SUCCESS, "overlapped.Internal = %lx\n", overlapped.Internal);
7679     ok(overlapped.Pointer == &result, "overlapped.Pointer != &result\n");
7680     ok(result != NULL, "result == NULL\n");
7681     if (result != NULL)
7682     {
7683         ok(!result->ai_blob, "ai_blob != NULL\n");
7684         ok(!result->ai_bloblen, "ai_bloblen != 0\n");
7685         ok(!result->ai_provider, "ai_provider = %s\n", wine_dbgstr_guid(result->ai_provider));
7686         pFreeAddrInfoExW(result);
7687     }
7688 
7689     result = (void*)0xdeadbeef;
7690     memset(&overlapped, 0xcc, sizeof(overlapped));
7691     ResetEvent(event);
7692     overlapped.hEvent = event;
7693     ret = pGetAddrInfoExW(NULL, NULL, NS_DNS, NULL, NULL, &result, NULL, &overlapped, NULL, NULL);
7694     todo_wine
7695     ok(ret == WSAHOST_NOT_FOUND, "got %d expected WSAHOST_NOT_FOUND\n", ret);
7696     todo_wine
7697     ok(WSAGetLastError() == WSAHOST_NOT_FOUND, "expected 11001, got %d\n", WSAGetLastError());
7698     ok(result == NULL, "got %p\n", result);
7699     ret = WaitForSingleObject(event, 0);
7700     todo_wine_if(ret != WAIT_TIMEOUT) /* Remove when abowe todo_wines are fixed */
7701     ok(ret == WAIT_TIMEOUT, "wait failed\n");
7702 
7703     WSACloseEvent(event);
7704 }
7705 
7706 static void verify_ipv6_addrinfo(ADDRINFOA *result, const char *expectedIp)
7707 {
7708     SOCKADDR_IN6 *sockaddr6;
7709     char ipBuffer[256];
7710     const char *ret;
7711 
7712     ok(result->ai_family == AF_INET6, "ai_family == %d\n", result->ai_family);
7713     ok(result->ai_addrlen >= sizeof(struct sockaddr_in6), "ai_addrlen == %d\n", (int)result->ai_addrlen);
7714     ok(result->ai_addr != NULL, "ai_addr == NULL\n");
7715 
7716     if (result->ai_addr != NULL)
7717     {
7718         sockaddr6 = (SOCKADDR_IN6 *)result->ai_addr;
7719         ok(sockaddr6->sin6_family == AF_INET6, "ai_addr->sin6_family == %d\n", sockaddr6->sin6_family);
7720         ok(sockaddr6->sin6_port == 0, "ai_addr->sin6_port == %d\n", sockaddr6->sin6_port);
7721 
7722         ZeroMemory(ipBuffer, sizeof(ipBuffer));
7723         ret = pInetNtop(AF_INET6, &sockaddr6->sin6_addr, ipBuffer, sizeof(ipBuffer));
7724         ok(ret != NULL, "inet_ntop failed (%d)\n", WSAGetLastError());
7725         ok(strcmp(ipBuffer, expectedIp) == 0, "ai_addr->sin6_addr == '%s' (expected '%s')\n", ipBuffer, expectedIp);
7726     }
7727 }
7728 
7729 static void test_getaddrinfo(void)
7730 {
7731     int i, ret;
7732     ADDRINFOA *result, *result2, *p, hint;
7733     SOCKADDR_IN *sockaddr;
7734     CHAR name[256], *ip;
7735     DWORD size = sizeof(name);
7736 
7737     if (!pgetaddrinfo || !pfreeaddrinfo)
7738     {
7739         win_skip("getaddrinfo and/or freeaddrinfo not present\n");
7740         return;
7741     }
7742     memset(&hint, 0, sizeof(ADDRINFOA));
7743     GetComputerNameExA( ComputerNamePhysicalDnsHostname, name, &size );
7744 
7745     result = (ADDRINFOA *)0xdeadbeef;
7746     WSASetLastError(0xdeadbeef);
7747     ret = pgetaddrinfo(NULL, NULL, NULL, &result);
7748     ok(ret == WSAHOST_NOT_FOUND, "got %d expected WSAHOST_NOT_FOUND\n", ret);
7749     ok(WSAGetLastError() == WSAHOST_NOT_FOUND, "expected 11001, got %d\n", WSAGetLastError());
7750     ok(result == NULL, "got %p\n", result);
7751 
7752     result = NULL;
7753     WSASetLastError(0xdeadbeef);
7754     ret = pgetaddrinfo("", NULL, NULL, &result);
7755     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7756     ok(result != NULL, "getaddrinfo failed\n");
7757     ok(WSAGetLastError() == 0, "expected 0, got %d\n", WSAGetLastError());
7758     pfreeaddrinfo(result);
7759 
7760     result = NULL;
7761     ret = pgetaddrinfo(NULL, "0", NULL, &result);
7762     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7763     ok(result != NULL, "getaddrinfo failed\n");
7764 
7765     result2 = NULL;
7766     ret = pgetaddrinfo(NULL, "", NULL, &result2);
7767     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7768     ok(result2 != NULL, "getaddrinfo failed\n");
7769     compare_addrinfo(result, result2);
7770     pfreeaddrinfo(result);
7771     pfreeaddrinfo(result2);
7772 
7773     result = NULL;
7774     WSASetLastError(0xdeadbeef);
7775     ret = pgetaddrinfo("", "0", NULL, &result);
7776     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7777     ok(WSAGetLastError() == 0, "expected 0, got %d\n", WSAGetLastError());
7778     ok(result != NULL, "getaddrinfo failed\n");
7779 
7780     result2 = NULL;
7781     ret = pgetaddrinfo("", "", NULL, &result2);
7782     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7783     ok(result2 != NULL, "getaddrinfo failed\n");
7784     compare_addrinfo(result, result2);
7785     pfreeaddrinfo(result);
7786     pfreeaddrinfo(result2);
7787 
7788     result = NULL;
7789     ret = pgetaddrinfo("localhost", NULL, NULL, &result);
7790     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7791     pfreeaddrinfo(result);
7792 
7793     result = NULL;
7794     ret = pgetaddrinfo("localhost", "", NULL, &result);
7795     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7796     pfreeaddrinfo(result);
7797 
7798     result = NULL;
7799     ret = pgetaddrinfo("localhost", "0", NULL, &result);
7800     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7801     pfreeaddrinfo(result);
7802 
7803     result = NULL;
7804     ret = pgetaddrinfo("localhost", "80", NULL, &result);
7805     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7806     pfreeaddrinfo(result);
7807 
7808     result = NULL;
7809     ret = pgetaddrinfo("localhost", NULL, &hint, &result);
7810     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7811     pfreeaddrinfo(result);
7812 
7813     result = NULL;
7814     WSASetLastError(0xdeadbeef);
7815     ret = pgetaddrinfo("localhost", "80", &hint, &result);
7816     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7817     ok(WSAGetLastError() == 0, "expected 0, got %d\n", WSAGetLastError());
7818     pfreeaddrinfo(result);
7819 
7820     hint.ai_flags = AI_NUMERICHOST;
7821     result = (void*)0xdeadbeef;
7822     ret = pgetaddrinfo("localhost", "80", &hint, &result);
7823     ok(ret == WSAHOST_NOT_FOUND, "getaddrinfo failed with %d\n", WSAGetLastError());
7824     ok(WSAGetLastError() == WSAHOST_NOT_FOUND, "expected WSAHOST_NOT_FOUND, got %d\n", WSAGetLastError());
7825     ok(!result, "result = %p\n", result);
7826     hint.ai_flags = 0;
7827 
7828     /* try to get information from the computer name, result is the same
7829      * as if requesting with an empty host name. */
7830     ret = pgetaddrinfo(name, NULL, NULL, &result);
7831     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7832 #ifdef __REACTOS__
7833     ok(result != NULL, "getaddrinfo failed\n");
7834 #else
7835     ok(result != NULL, "GetAddrInfoW failed\n");
7836 #endif
7837 
7838     ret = pgetaddrinfo("", NULL, NULL, &result2);
7839     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7840 #ifdef __REACTOS__
7841     ok(result2 != NULL, "getaddrinfo failed\n");
7842 #else
7843     ok(result != NULL, "GetAddrInfoW failed\n");
7844 #endif
7845     compare_addrinfo(result, result2);
7846     pfreeaddrinfo(result);
7847     pfreeaddrinfo(result2);
7848 
7849     ret = pgetaddrinfo(name, "", NULL, &result);
7850     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7851 #ifdef __REACTOS__
7852     ok(result != NULL, "getaddrinfo failed\n");
7853 #else
7854     ok(result != NULL, "GetAddrInfoW failed\n");
7855 #endif
7856 
7857     ret = pgetaddrinfo("", "", NULL, &result2);
7858     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7859 #ifdef __REACTOS__
7860     ok(result2 != NULL, "getaddrinfo failed\n");
7861 #else
7862     ok(result != NULL, "GetAddrInfoW failed\n");
7863 #endif
7864     compare_addrinfo(result, result2);
7865     pfreeaddrinfo(result);
7866     pfreeaddrinfo(result2);
7867 
7868     result = (ADDRINFOA *)0xdeadbeef;
7869     WSASetLastError(0xdeadbeef);
7870     ret = pgetaddrinfo("nxdomain.codeweavers.com", NULL, NULL, &result);
7871     if(ret == 0)
7872     {
7873         skip("nxdomain returned success. Broken ISP redirects?\n");
7874         return;
7875     }
7876     ok(ret == WSAHOST_NOT_FOUND, "got %d expected WSAHOST_NOT_FOUND\n", ret);
7877     ok(WSAGetLastError() == WSAHOST_NOT_FOUND, "expected 11001, got %d\n", WSAGetLastError());
7878     ok(result == NULL, "got %p\n", result);
7879 
7880     /* Test IPv4 address conversion */
7881     result = NULL;
7882     ret = pgetaddrinfo("192.168.1.253", NULL, NULL, &result);
7883     ok(!ret, "getaddrinfo failed with %d\n", ret);
7884     ok(result->ai_family == AF_INET, "ai_family == %d\n", result->ai_family);
7885     ok(result->ai_addrlen >= sizeof(struct sockaddr_in), "ai_addrlen == %d\n", (int)result->ai_addrlen);
7886     ok(result->ai_addr != NULL, "ai_addr == NULL\n");
7887     sockaddr = (SOCKADDR_IN *)result->ai_addr;
7888     ok(sockaddr->sin_family == AF_INET, "ai_addr->sin_family == %d\n", sockaddr->sin_family);
7889     ok(sockaddr->sin_port == 0, "ai_addr->sin_port == %d\n", sockaddr->sin_port);
7890 
7891     ip = inet_ntoa(sockaddr->sin_addr);
7892     ok(strcmp(ip, "192.168.1.253") == 0, "sockaddr->ai_addr == '%s'\n", ip);
7893     pfreeaddrinfo(result);
7894 
7895     /* Test IPv4 address conversion with port */
7896     result = NULL;
7897     hint.ai_flags = AI_NUMERICHOST;
7898     ret = pgetaddrinfo("192.168.1.253:1024", NULL, &hint, &result);
7899     hint.ai_flags = 0;
7900     ok(ret == WSAHOST_NOT_FOUND, "getaddrinfo returned unexpected result: %d\n", ret);
7901     ok(result == NULL, "expected NULL, got %p\n", result);
7902 
7903     /* Test IPv6 address conversion */
7904     result = NULL;
7905     SetLastError(0xdeadbeef);
7906     ret = pgetaddrinfo("2a00:2039:dead:beef:cafe::6666", NULL, NULL, &result);
7907 
7908     if (result != NULL)
7909     {
7910         ok(!ret, "getaddrinfo failed with %d\n", ret);
7911         verify_ipv6_addrinfo(result, "2a00:2039:dead:beef:cafe::6666");
7912         pfreeaddrinfo(result);
7913 
7914         /* Test IPv6 address conversion with brackets */
7915         result = NULL;
7916         ret = pgetaddrinfo("[beef::cafe]", NULL, NULL, &result);
7917         ok(!ret, "getaddrinfo failed with %d\n", ret);
7918         verify_ipv6_addrinfo(result, "beef::cafe");
7919         pfreeaddrinfo(result);
7920 
7921         /* Test IPv6 address conversion with brackets and hints */
7922         memset(&hint, 0, sizeof(ADDRINFOA));
7923         hint.ai_flags = AI_NUMERICHOST;
7924         hint.ai_family = AF_INET6;
7925         result = NULL;
7926         ret = pgetaddrinfo("[beef::cafe]", NULL, &hint, &result);
7927         ok(!ret, "getaddrinfo failed with %d\n", ret);
7928         verify_ipv6_addrinfo(result, "beef::cafe");
7929         pfreeaddrinfo(result);
7930 
7931         memset(&hint, 0, sizeof(ADDRINFOA));
7932         hint.ai_flags = AI_NUMERICHOST;
7933         hint.ai_family = AF_INET;
7934         result = NULL;
7935         ret = pgetaddrinfo("[beef::cafe]", NULL, &hint, &result);
7936         ok(ret == WSAHOST_NOT_FOUND, "getaddrinfo failed with %d\n", ret);
7937 
7938         /* Test IPv6 address conversion with brackets and port */
7939         result = NULL;
7940         ret = pgetaddrinfo("[beef::cafe]:10239", NULL, NULL, &result);
7941         ok(!ret, "getaddrinfo failed with %d\n", ret);
7942         verify_ipv6_addrinfo(result, "beef::cafe");
7943         pfreeaddrinfo(result);
7944 
7945         /* Test IPv6 address conversion with unmatched brackets */
7946         result = NULL;
7947         hint.ai_flags = AI_NUMERICHOST;
7948         ret = pgetaddrinfo("[beef::cafe", NULL, &hint, &result);
7949         ok(ret == WSAHOST_NOT_FOUND, "getaddrinfo failed with %d\n", ret);
7950 
7951         ret = pgetaddrinfo("beef::cafe]", NULL, &hint, &result);
7952         ok(ret == WSAHOST_NOT_FOUND, "getaddrinfo failed with %d\n", ret);
7953     }
7954     else
7955     {
7956         ok(ret == WSAHOST_NOT_FOUND, "getaddrinfo failed with %d\n", ret);
7957         win_skip("getaddrinfo does not support IPV6\n");
7958     }
7959 
7960     hint.ai_flags = 0;
7961 
7962     for (i = 0;i < (sizeof(hinttests) / sizeof(hinttests[0]));i++)
7963     {
7964         hint.ai_family = hinttests[i].family;
7965         hint.ai_socktype = hinttests[i].socktype;
7966         hint.ai_protocol = hinttests[i].protocol;
7967 
7968         result = NULL;
7969         SetLastError(0xdeadbeef);
7970         ret = pgetaddrinfo("localhost", NULL, &hint, &result);
7971         if(!ret)
7972         {
7973             if (hinttests[i].error)
7974                 ok(0, "test %d: getaddrinfo succeeded unexpectedly\n", i);
7975             else
7976             {
7977                 p = result;
7978                 do
7979                 {
7980                     /* when AF_UNSPEC is used the return will be either AF_INET or AF_INET6 */
7981                     if (hinttests[i].family == AF_UNSPEC)
7982                         ok(p->ai_family == AF_INET || p->ai_family == AF_INET6,
7983                            "test %d: expected AF_INET or AF_INET6, got %d\n",
7984                            i, p->ai_family);
7985                     else
7986                         ok(p->ai_family == hinttests[i].family,
7987                            "test %d: expected family %d, got %d\n",
7988                            i, hinttests[i].family, p->ai_family);
7989 
7990                     ok(p->ai_socktype == hinttests[i].socktype,
7991                        "test %d: expected type %d, got %d\n",
7992                        i, hinttests[i].socktype, p->ai_socktype);
7993                     ok(p->ai_protocol == hinttests[i].protocol,
7994                        "test %d: expected protocol %d, got %d\n",
7995                        i, hinttests[i].protocol, p->ai_protocol);
7996                     p = p->ai_next;
7997                 }
7998                 while (p);
7999             }
8000             pfreeaddrinfo(result);
8001         }
8002         else
8003         {
8004             DWORD err = WSAGetLastError();
8005             if (hinttests[i].error)
8006                 ok(hinttests[i].error == err, "test %d: getaddrinfo failed with error %d, expected %d\n",
8007                    i, err, hinttests[i].error);
8008             else
8009                 ok(0, "test %d: getaddrinfo failed with %d (err %d)\n", i, ret, err);
8010         }
8011     }
8012 }
8013 
8014 static void test_ConnectEx(void)
8015 {
8016     SOCKET listener = INVALID_SOCKET;
8017     SOCKET acceptor = INVALID_SOCKET;
8018     SOCKET connector = INVALID_SOCKET;
8019     struct sockaddr_in address, conaddress;
8020     int addrlen;
8021     OVERLAPPED overlapped;
8022     LPFN_CONNECTEX pConnectEx;
8023     GUID connectExGuid = WSAID_CONNECTEX;
8024     DWORD bytesReturned;
8025     char buffer[1024];
8026     BOOL bret;
8027     DWORD dwret;
8028     int iret;
8029 
8030     memset(&overlapped, 0, sizeof(overlapped));
8031 
8032     listener = socket(AF_INET, SOCK_STREAM, 0);
8033     if (listener == INVALID_SOCKET) {
8034         skip("could not create listener socket, error %d\n", WSAGetLastError());
8035         goto end;
8036     }
8037 
8038     connector = socket(AF_INET, SOCK_STREAM, 0);
8039     if (connector == INVALID_SOCKET) {
8040         skip("could not create connector socket, error %d\n", WSAGetLastError());
8041         goto end;
8042     }
8043 
8044     memset(&address, 0, sizeof(address));
8045     address.sin_family = AF_INET;
8046     address.sin_addr.s_addr = inet_addr("127.0.0.1");
8047     iret = bind(listener, (struct sockaddr*)&address, sizeof(address));
8048     if (iret != 0) {
8049         skip("failed to bind, error %d\n", WSAGetLastError());
8050         goto end;
8051     }
8052 
8053     addrlen = sizeof(address);
8054     iret = getsockname(listener, (struct sockaddr*)&address, &addrlen);
8055     if (iret != 0) {
8056         skip("failed to lookup bind address, error %d\n", WSAGetLastError());
8057         goto end;
8058     }
8059 
8060     if (set_blocking(listener, TRUE)) {
8061         skip("couldn't make socket non-blocking, error %d\n", WSAGetLastError());
8062         goto end;
8063     }
8064 
8065     bytesReturned = 0xdeadbeef;
8066     iret = WSAIoctl(connector, SIO_GET_EXTENSION_FUNCTION_POINTER, &connectExGuid, sizeof(connectExGuid),
8067         &pConnectEx, sizeof(pConnectEx), &bytesReturned, NULL, NULL);
8068     if (iret) {
8069         win_skip("WSAIoctl failed to get ConnectEx with ret %d + errno %d\n", iret, WSAGetLastError());
8070         goto end;
8071     }
8072 
8073     ok(bytesReturned == sizeof(pConnectEx), "expected sizeof(pConnectEx), got %u\n", bytesReturned);
8074 
8075     bret = pConnectEx(INVALID_SOCKET, (struct sockaddr*)&address, addrlen, NULL, 0, &bytesReturned, &overlapped);
8076     ok(bret == FALSE && WSAGetLastError() == WSAENOTSOCK, "ConnectEx on invalid socket "
8077         "returned %d + errno %d\n", bret, WSAGetLastError());
8078 
8079     bret = pConnectEx(connector, (struct sockaddr*)&address, addrlen, NULL, 0, &bytesReturned, &overlapped);
8080     ok(bret == FALSE && WSAGetLastError() == WSAEINVAL, "ConnectEx on a unbound socket "
8081         "returned %d + errno %d\n", bret, WSAGetLastError());
8082     if (bret == TRUE || WSAGetLastError() != WSAEINVAL)
8083     {
8084         acceptor = accept(listener, NULL, NULL);
8085         if (acceptor != INVALID_SOCKET) {
8086             closesocket(acceptor);
8087             acceptor = INVALID_SOCKET;
8088         }
8089 
8090         closesocket(connector);
8091         connector = socket(AF_INET, SOCK_STREAM, 0);
8092         if (connector == INVALID_SOCKET) {
8093             skip("could not create connector socket, error %d\n", WSAGetLastError());
8094             goto end;
8095         }
8096     }
8097 
8098     /* ConnectEx needs a bound socket */
8099     memset(&conaddress, 0, sizeof(conaddress));
8100     conaddress.sin_family = AF_INET;
8101     conaddress.sin_addr.s_addr = inet_addr("127.0.0.1");
8102     iret = bind(connector, (struct sockaddr*)&conaddress, sizeof(conaddress));
8103     if (iret != 0) {
8104         skip("failed to bind, error %d\n", WSAGetLastError());
8105         goto end;
8106     }
8107 
8108     bret = pConnectEx(connector, (struct sockaddr*)&address, addrlen, NULL, 0, &bytesReturned, NULL);
8109     ok(bret == FALSE && WSAGetLastError() == ERROR_INVALID_PARAMETER, "ConnectEx on a NULL overlapped "
8110         "returned %d + errno %d\n", bret, WSAGetLastError());
8111 
8112     overlapped.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
8113     if (overlapped.hEvent == NULL) {
8114         skip("could not create event object, errno = %d\n", GetLastError());
8115         goto end;
8116     }
8117 
8118     iret = listen(listener, 1);
8119     if (iret != 0) {
8120         skip("listening failed, errno = %d\n", WSAGetLastError());
8121         goto end;
8122     }
8123 
8124     bret = pConnectEx(connector, (struct sockaddr*)&address, addrlen, NULL, 0, &bytesReturned, &overlapped);
8125     ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "ConnectEx failed: "
8126         "returned %d + errno %d\n", bret, WSAGetLastError());
8127     dwret = WaitForSingleObject(overlapped.hEvent, 15000);
8128     ok(dwret == WAIT_OBJECT_0, "Waiting for connect event failed with %d + errno %d\n", dwret, GetLastError());
8129 
8130     bret = GetOverlappedResult((HANDLE)connector, &overlapped, &bytesReturned, FALSE);
8131     ok(bret, "Connecting failed, error %d\n", GetLastError());
8132     ok(bytesReturned == 0, "Bytes sent is %d\n", bytesReturned);
8133 
8134     closesocket(connector);
8135     connector = socket(AF_INET, SOCK_STREAM, 0);
8136     if (connector == INVALID_SOCKET) {
8137         skip("could not create connector socket, error %d\n", WSAGetLastError());
8138         goto end;
8139     }
8140     /* ConnectEx needs a bound socket */
8141     memset(&conaddress, 0, sizeof(conaddress));
8142     conaddress.sin_family = AF_INET;
8143     conaddress.sin_addr.s_addr = inet_addr("127.0.0.1");
8144     iret = bind(connector, (struct sockaddr*)&conaddress, sizeof(conaddress));
8145     if (iret != 0) {
8146         skip("failed to bind, error %d\n", WSAGetLastError());
8147         goto end;
8148     }
8149 
8150     acceptor = accept(listener, NULL, NULL);
8151     if (acceptor != INVALID_SOCKET) {
8152         closesocket(acceptor);
8153     }
8154 
8155     buffer[0] = '1';
8156     buffer[1] = '2';
8157     buffer[2] = '3';
8158     bret = pConnectEx(connector, (struct sockaddr*)&address, addrlen, buffer, 3, &bytesReturned, &overlapped);
8159     ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "ConnectEx failed: "
8160         "returned %d + errno %d\n", bret, WSAGetLastError());
8161     dwret = WaitForSingleObject(overlapped.hEvent, 15000);
8162     ok(dwret == WAIT_OBJECT_0, "Waiting for connect event failed with %d + errno %d\n", dwret, GetLastError());
8163 
8164     bret = GetOverlappedResult((HANDLE)connector, &overlapped, &bytesReturned, FALSE);
8165     ok(bret, "Connecting failed, error %d\n", GetLastError());
8166     ok(bytesReturned == 3, "Bytes sent is %d\n", bytesReturned);
8167 
8168     acceptor = accept(listener, NULL, NULL);
8169     ok(acceptor != INVALID_SOCKET, "could not accept socket error %d\n", WSAGetLastError());
8170 
8171     bytesReturned = recv(acceptor, buffer, 3, 0);
8172     buffer[4] = 0;
8173     ok(bytesReturned == 3, "Didn't get all sent data, got only %d\n", bytesReturned);
8174     ok(buffer[0] == '1' && buffer[1] == '2' && buffer[2] == '3',
8175        "Failed to get the right data, expected '123', got '%s'\n", buffer);
8176 
8177     closesocket(connector);
8178     connector = socket(AF_INET, SOCK_STREAM, 0);
8179     if (connector == INVALID_SOCKET) {
8180         skip("could not create connector socket, error %d\n", WSAGetLastError());
8181         goto end;
8182     }
8183     /* ConnectEx needs a bound socket */
8184     memset(&conaddress, 0, sizeof(conaddress));
8185     conaddress.sin_family = AF_INET;
8186     conaddress.sin_addr.s_addr = inet_addr("127.0.0.1");
8187     iret = bind(connector, (struct sockaddr*)&conaddress, sizeof(conaddress));
8188     if (iret != 0) {
8189         skip("failed to bind, error %d\n", WSAGetLastError());
8190         goto end;
8191     }
8192 
8193     if (acceptor != INVALID_SOCKET) {
8194         closesocket(acceptor);
8195         acceptor = INVALID_SOCKET;
8196     }
8197 
8198     /* Connect with error */
8199     closesocket(listener);
8200     listener = INVALID_SOCKET;
8201 
8202     address.sin_port = htons(1);
8203 
8204     bret = pConnectEx(connector, (struct sockaddr*)&address, addrlen, NULL, 0, &bytesReturned, &overlapped);
8205     ok(bret == FALSE && GetLastError() == ERROR_IO_PENDING, "ConnectEx to bad destination failed: "
8206         "returned %d + errno %d\n", bret, GetLastError());
8207     dwret = WaitForSingleObject(overlapped.hEvent, 15000);
8208     ok(dwret == WAIT_OBJECT_0, "Waiting for connect event failed with %d + errno %d\n", dwret, GetLastError());
8209 
8210     bret = GetOverlappedResult((HANDLE)connector, &overlapped, &bytesReturned, FALSE);
8211     ok(bret == FALSE && GetLastError() == ERROR_CONNECTION_REFUSED,
8212        "Connecting to a disconnected host returned error %d - %d\n", bret, WSAGetLastError());
8213 
8214 end:
8215     if (overlapped.hEvent)
8216         WSACloseEvent(overlapped.hEvent);
8217     if (listener != INVALID_SOCKET)
8218         closesocket(listener);
8219     if (acceptor != INVALID_SOCKET)
8220         closesocket(acceptor);
8221     if (connector != INVALID_SOCKET)
8222         closesocket(connector);
8223 }
8224 
8225 static void test_AcceptEx(void)
8226 {
8227     SOCKET listener = INVALID_SOCKET;
8228     SOCKET acceptor = INVALID_SOCKET;
8229     SOCKET connector = INVALID_SOCKET;
8230     SOCKET connector2 = INVALID_SOCKET;
8231     struct sockaddr_in bindAddress, peerAddress, *readBindAddress, *readRemoteAddress;
8232     int socklen, optlen;
8233     GUID acceptExGuid = WSAID_ACCEPTEX, getAcceptExGuid = WSAID_GETACCEPTEXSOCKADDRS;
8234     LPFN_ACCEPTEX pAcceptEx = NULL;
8235     LPFN_GETACCEPTEXSOCKADDRS pGetAcceptExSockaddrs = NULL;
8236     fd_set fds_accept, fds_send;
8237     struct timeval timeout = {0,10}; /* wait for 10 milliseconds */
8238     int got, conn1, i;
8239     DWORD bytesReturned, connect_time;
8240     char buffer[1024], ipbuffer[32];
8241     OVERLAPPED overlapped;
8242     int iret, localSize = sizeof(struct sockaddr_in), remoteSize = localSize;
8243     BOOL bret;
8244     DWORD dwret;
8245 
8246     memset(&overlapped, 0, sizeof(overlapped));
8247 
8248     listener = socket(AF_INET, SOCK_STREAM, 0);
8249     if (listener == INVALID_SOCKET) {
8250         skip("could not create listener socket, error %d\n", WSAGetLastError());
8251         goto end;
8252     }
8253 
8254     acceptor = socket(AF_INET, SOCK_STREAM, 0);
8255     if (acceptor == INVALID_SOCKET) {
8256         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
8257         goto end;
8258     }
8259 
8260     connector = socket(AF_INET, SOCK_STREAM, 0);
8261     if (connector == INVALID_SOCKET) {
8262         skip("could not create connector socket, error %d\n", WSAGetLastError());
8263         goto end;
8264     }
8265 
8266     memset(&bindAddress, 0, sizeof(bindAddress));
8267     bindAddress.sin_family = AF_INET;
8268     bindAddress.sin_addr.s_addr = inet_addr("127.0.0.1");
8269     iret = bind(listener, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
8270     if (iret != 0) {
8271         skip("failed to bind, error %d\n", WSAGetLastError());
8272         goto end;
8273     }
8274 
8275     socklen = sizeof(bindAddress);
8276     iret = getsockname(listener, (struct sockaddr*)&bindAddress, &socklen);
8277     if (iret != 0) {
8278         skip("failed to lookup bind address, error %d\n", WSAGetLastError());
8279         goto end;
8280     }
8281 
8282     if (set_blocking(listener, FALSE)) {
8283         skip("couldn't make socket non-blocking, error %d\n", WSAGetLastError());
8284         goto end;
8285     }
8286 
8287     iret = WSAIoctl(listener, SIO_GET_EXTENSION_FUNCTION_POINTER, &acceptExGuid, sizeof(acceptExGuid),
8288         &pAcceptEx, sizeof(pAcceptEx), &bytesReturned, NULL, NULL);
8289     if (iret) {
8290         skip("WSAIoctl failed to get AcceptEx with ret %d + errno %d\n", iret, WSAGetLastError());
8291         goto end;
8292     }
8293 
8294     iret = WSAIoctl(listener, SIO_GET_EXTENSION_FUNCTION_POINTER, &getAcceptExGuid, sizeof(getAcceptExGuid),
8295         &pGetAcceptExSockaddrs, sizeof(pGetAcceptExSockaddrs), &bytesReturned, NULL, NULL);
8296     if (iret) {
8297         skip("WSAIoctl failed to get GetAcceptExSockaddrs with ret %d + errno %d\n", iret, WSAGetLastError());
8298         goto end;
8299     }
8300 
8301     bret = pAcceptEx(INVALID_SOCKET, acceptor, buffer, sizeof(buffer) - 2*(sizeof(struct sockaddr_in) + 16),
8302         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8303         &bytesReturned, &overlapped);
8304     ok(bret == FALSE && WSAGetLastError() == WSAENOTSOCK, "AcceptEx on invalid listening socket "
8305         "returned %d + errno %d\n", bret, WSAGetLastError());
8306 
8307     bret = pAcceptEx(listener, acceptor, buffer, sizeof(buffer) - 2*(sizeof(struct sockaddr_in) + 16),
8308         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8309         &bytesReturned, &overlapped);
8310 todo_wine
8311     ok(bret == FALSE && WSAGetLastError() == WSAEINVAL, "AcceptEx on a non-listening socket "
8312         "returned %d + errno %d\n", bret, WSAGetLastError());
8313 
8314     iret = listen(listener, 5);
8315     if (iret != 0) {
8316         skip("listening failed, errno = %d\n", WSAGetLastError());
8317         goto end;
8318     }
8319 
8320     bret = pAcceptEx(listener, INVALID_SOCKET, buffer, sizeof(buffer) - 2*(sizeof(struct sockaddr_in) + 16),
8321         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8322         &bytesReturned, &overlapped);
8323     ok(bret == FALSE && WSAGetLastError() == WSAENOTSOCK, "AcceptEx on invalid accepting socket "
8324         "returned %d + errno %d\n", bret, WSAGetLastError());
8325 
8326     bret = pAcceptEx(listener, acceptor, NULL, sizeof(buffer) - 2*(sizeof(struct sockaddr_in) + 16),
8327         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8328         &bytesReturned, &overlapped);
8329     todo_wine ok(bret == FALSE && WSAGetLastError() == WSAEFAULT,
8330         "AcceptEx on NULL buffer returned %d + errno %d\n", bret, WSAGetLastError());
8331 
8332     bret = pAcceptEx(listener, acceptor, buffer, 0, 0, sizeof(struct sockaddr_in) + 16,
8333         &bytesReturned, &overlapped);
8334     ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING,
8335         "AcceptEx on too small local address size returned %d + errno %d\n",
8336         bret, WSAGetLastError());
8337     bret = CancelIo((HANDLE) listener);
8338     ok(bret, "Failed to cancel pending accept socket\n");
8339 
8340     bret = pAcceptEx(listener, acceptor, buffer, 0, sizeof(struct sockaddr_in) + 15,
8341         sizeof(struct sockaddr_in) + 16, &bytesReturned, &overlapped);
8342     ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "AcceptEx on too small local address "
8343         "size returned %d + errno %d\n",
8344         bret, WSAGetLastError());
8345     bret = CancelIo((HANDLE) listener);
8346     ok(bret, "Failed to cancel pending accept socket\n");
8347 
8348     bret = pAcceptEx(listener, acceptor, buffer, 0, sizeof(struct sockaddr_in) + 16, 0,
8349         &bytesReturned, &overlapped);
8350     ok(bret == FALSE && WSAGetLastError() == WSAEFAULT,
8351         "AcceptEx on too small remote address size returned %d + errno %d\n", bret, WSAGetLastError());
8352 
8353     bret = pAcceptEx(listener, acceptor, buffer, 0, sizeof(struct sockaddr_in) + 16,
8354         sizeof(struct sockaddr_in) + 15, &bytesReturned, &overlapped);
8355     ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING,
8356         "AcceptEx on too small remote address size returned %d + errno %d\n", bret, WSAGetLastError());
8357     bret = CancelIo((HANDLE) listener);
8358     ok(bret, "Failed to cancel pending accept socket\n");
8359 
8360     bret = pAcceptEx(listener, acceptor, buffer, 0,
8361         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8362         &bytesReturned, NULL);
8363     ok(bret == FALSE && WSAGetLastError() == ERROR_INVALID_PARAMETER, "AcceptEx on a NULL overlapped "
8364         "returned %d + errno %d\n", bret, WSAGetLastError());
8365 
8366     bret = pAcceptEx(listener, acceptor, buffer, 0, 0, 0, &bytesReturned, NULL);
8367     ok(bret == FALSE && WSAGetLastError() == ERROR_INVALID_PARAMETER, "AcceptEx on a NULL overlapped "
8368         "returned %d + errno %d\n", bret, WSAGetLastError());
8369 
8370     overlapped.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
8371     if (overlapped.hEvent == NULL) {
8372         skip("could not create event object, errno = %d\n", GetLastError());
8373         goto end;
8374     }
8375 
8376     bret = pAcceptEx(listener, acceptor, buffer, 0,
8377         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8378         &bytesReturned, &overlapped);
8379     ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "AcceptEx returned %d + errno %d\n", bret, WSAGetLastError());
8380 
8381     bret = pAcceptEx(listener, acceptor, buffer, 0,
8382         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8383         &bytesReturned, &overlapped);
8384     todo_wine ok(bret == FALSE && WSAGetLastError() == WSAEINVAL,
8385        "AcceptEx on already pending socket returned %d + errno %d\n", bret, WSAGetLastError());
8386     if (bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING) {
8387         /* We need to cancel this call, otherwise things fail */
8388         bret = CancelIo((HANDLE) listener);
8389         ok(bret, "Failed to cancel failed test. Bailing...\n");
8390         if (!bret) return;
8391         WaitForSingleObject(overlapped.hEvent, 0);
8392 
8393         bret = pAcceptEx(listener, acceptor, buffer, 0,
8394             sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8395             &bytesReturned, &overlapped);
8396         ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "AcceptEx returned %d + errno %d\n", bret, WSAGetLastError());
8397     }
8398 
8399     iret = connect(acceptor,  (struct sockaddr*)&bindAddress, sizeof(bindAddress));
8400     todo_wine ok(iret == SOCKET_ERROR && WSAGetLastError() == WSAEINVAL,
8401        "connecting to acceptex acceptor succeeded? return %d + errno %d\n", iret, WSAGetLastError());
8402     if (!iret || (iret == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)) {
8403         /* We need to cancel this call, otherwise things fail */
8404         closesocket(acceptor);
8405         acceptor = socket(AF_INET, SOCK_STREAM, 0);
8406         if (acceptor == INVALID_SOCKET) {
8407             skip("could not create acceptor socket, error %d\n", WSAGetLastError());
8408             goto end;
8409         }
8410 
8411         bret = CancelIo((HANDLE) listener);
8412         ok(bret, "Failed to cancel failed test. Bailing...\n");
8413         if (!bret) return;
8414 
8415         bret = pAcceptEx(listener, acceptor, buffer, 0,
8416             sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8417             &bytesReturned, &overlapped);
8418         ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "AcceptEx returned %d + errno %d\n", bret, WSAGetLastError());
8419     }
8420 
8421     iret = connect(connector, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
8422     ok(iret == 0, "connecting to accepting socket failed, error %d\n", WSAGetLastError());
8423 
8424     dwret = WaitForSingleObject(overlapped.hEvent, INFINITE);
8425     ok(dwret == WAIT_OBJECT_0, "Waiting for accept event failed with %d + errno %d\n", dwret, GetLastError());
8426 
8427     bret = GetOverlappedResult((HANDLE)listener, &overlapped, &bytesReturned, FALSE);
8428     ok(bret, "GetOverlappedResult failed, error %d\n", GetLastError());
8429     ok(bytesReturned == 0, "bytesReturned isn't supposed to be %d\n", bytesReturned);
8430 
8431     closesocket(connector);
8432     connector = INVALID_SOCKET;
8433     closesocket(acceptor);
8434 
8435     /* Test short reads */
8436 
8437     acceptor = socket(AF_INET, SOCK_STREAM, 0);
8438     if (acceptor == INVALID_SOCKET) {
8439         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
8440         goto end;
8441     }
8442     connector = socket(AF_INET, SOCK_STREAM, 0);
8443     if (connector == INVALID_SOCKET) {
8444         skip("could not create connector socket, error %d\n", WSAGetLastError());
8445         goto end;
8446     }
8447     bret = pAcceptEx(listener, acceptor, buffer, 2,
8448         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8449         &bytesReturned, &overlapped);
8450     ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "AcceptEx returned %d + errno %d\n", bret, WSAGetLastError());
8451 
8452     connect_time = 0xdeadbeef;
8453     optlen = sizeof(connect_time);
8454     iret = getsockopt(connector, SOL_SOCKET, SO_CONNECT_TIME, (char *)&connect_time, &optlen);
8455     ok(!iret, "getsockopt failed %d\n", WSAGetLastError());
8456     ok(connect_time == ~0u, "unexpected connect time %u\n", connect_time);
8457 
8458     /* AcceptEx() still won't complete until we send data */
8459     iret = connect(connector, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
8460     ok(iret == 0, "connecting to accepting socket failed, error %d\n", WSAGetLastError());
8461 
8462     connect_time = 0xdeadbeef;
8463     optlen = sizeof(connect_time);
8464     iret = getsockopt(connector, SOL_SOCKET, SO_CONNECT_TIME, (char *)&connect_time, &optlen);
8465     ok(!iret, "getsockopt failed %d\n", WSAGetLastError());
8466     ok(connect_time < 0xdeadbeef, "unexpected connect time %u\n", connect_time);
8467 
8468     dwret = WaitForSingleObject(overlapped.hEvent, 0);
8469     ok(dwret == WAIT_TIMEOUT, "Waiting for accept event timeout failed with %d + errno %d\n", dwret, GetLastError());
8470 
8471     iret = getsockname( connector, (struct sockaddr *)&peerAddress, &remoteSize);
8472     ok( !iret, "getsockname failed.\n");
8473 
8474     /* AcceptEx() could complete any time now */
8475     iret = send(connector, buffer, 1, 0);
8476     ok(iret == 1, "could not send 1 byte: send %d errno %d\n", iret, WSAGetLastError());
8477 
8478     dwret = WaitForSingleObject(overlapped.hEvent, 1000);
8479     ok(dwret == WAIT_OBJECT_0, "Waiting for accept event failed with %d + errno %d\n", dwret, GetLastError());
8480 
8481     /* Check if the buffer from AcceptEx is decoded correctly */
8482     pGetAcceptExSockaddrs(buffer, 2, sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8483                           (struct sockaddr **)&readBindAddress, &localSize,
8484                           (struct sockaddr **)&readRemoteAddress, &remoteSize);
8485     strcpy( ipbuffer, inet_ntoa(readBindAddress->sin_addr));
8486     ok( readBindAddress->sin_addr.s_addr == bindAddress.sin_addr.s_addr,
8487             "Local socket address is different %s != %s\n",
8488             ipbuffer, inet_ntoa(bindAddress.sin_addr));
8489     ok( readBindAddress->sin_port == bindAddress.sin_port,
8490             "Local socket port is different: %d != %d\n",
8491             readBindAddress->sin_port, bindAddress.sin_port);
8492     strcpy( ipbuffer, inet_ntoa(readRemoteAddress->sin_addr));
8493     ok( readRemoteAddress->sin_addr.s_addr == peerAddress.sin_addr.s_addr,
8494             "Remote socket address is different %s != %s\n",
8495             ipbuffer, inet_ntoa(peerAddress.sin_addr));
8496     ok( readRemoteAddress->sin_port == peerAddress.sin_port,
8497             "Remote socket port is different: %d != %d\n",
8498             readRemoteAddress->sin_port, peerAddress.sin_port);
8499 
8500     bret = GetOverlappedResult((HANDLE)listener, &overlapped, &bytesReturned, FALSE);
8501     ok(bret, "GetOverlappedResult failed, error %d\n", GetLastError());
8502     ok(bytesReturned == 1, "bytesReturned isn't supposed to be %d\n", bytesReturned);
8503 
8504     closesocket(connector);
8505     connector = INVALID_SOCKET;
8506     closesocket(acceptor);
8507 
8508     /* Test CF_DEFER & AcceptEx interaction */
8509 
8510     acceptor = socket(AF_INET, SOCK_STREAM, 0);
8511     if (acceptor == INVALID_SOCKET) {
8512         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
8513         goto end;
8514     }
8515     connector = socket(AF_INET, SOCK_STREAM, 0);
8516     if (connector == INVALID_SOCKET) {
8517         skip("could not create connector socket, error %d\n", WSAGetLastError());
8518         goto end;
8519     }
8520     connector2 = socket(AF_INET, SOCK_STREAM, 0);
8521     if (connector == INVALID_SOCKET) {
8522         skip("could not create connector socket, error %d\n", WSAGetLastError());
8523         goto end;
8524     }
8525 
8526     if (set_blocking(connector, FALSE)) {
8527         skip("couldn't make socket non-blocking, error %d\n", WSAGetLastError());
8528         goto end;
8529     }
8530 
8531     if (set_blocking(connector2, FALSE)) {
8532         skip("couldn't make socket non-blocking, error %d\n", WSAGetLastError());
8533         goto end;
8534     }
8535 
8536     /* Connect socket #1 */
8537     iret = connect(connector, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
8538     ok(iret == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK, "connecting to accepting socket failed, error %d\n", WSAGetLastError());
8539 
8540     FD_ZERO ( &fds_accept );
8541     FD_ZERO ( &fds_send );
8542 
8543     FD_SET ( listener, &fds_accept );
8544     FD_SET ( connector, &fds_send );
8545 
8546     buffer[0] = '0';
8547     got = 0;
8548     conn1 = 0;
8549 
8550     for (i = 0; i < 4000; ++i)
8551     {
8552         fd_set fds_openaccept = fds_accept, fds_opensend = fds_send;
8553 
8554         wsa_ok ( ( select ( 0, &fds_openaccept, &fds_opensend, NULL, &timeout ) ), SOCKET_ERROR !=,
8555             "acceptex test(%d): could not select on socket, errno %d\n" );
8556 
8557         /* check for incoming requests */
8558         if ( FD_ISSET ( listener, &fds_openaccept ) ) {
8559             got++;
8560             if (got == 1) {
8561                 SOCKET tmp = WSAAccept(listener, NULL, NULL, (LPCONDITIONPROC) AlwaysDeferConditionFunc, 0);
8562                 ok(tmp == INVALID_SOCKET && WSAGetLastError() == WSATRY_AGAIN, "Failed to defer connection, %d\n", WSAGetLastError());
8563                 bret = pAcceptEx(listener, acceptor, buffer, 0,
8564                                     sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8565                                     &bytesReturned, &overlapped);
8566                 ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "AcceptEx returned %d + errno %d\n", bret, WSAGetLastError());
8567             }
8568             else if (got == 2) {
8569                 /* this should be socket #2 */
8570                 SOCKET tmp = accept(listener, NULL, NULL);
8571                 ok(tmp != INVALID_SOCKET, "accept failed %d\n", WSAGetLastError());
8572                 closesocket(tmp);
8573             }
8574             else {
8575                 ok(FALSE, "Got more than 2 connections?\n");
8576             }
8577         }
8578         if ( conn1 && FD_ISSET ( connector2, &fds_opensend ) ) {
8579             /* Send data on second socket, and stop */
8580             send(connector2, "2", 1, 0);
8581             FD_CLR ( connector2, &fds_send );
8582 
8583             break;
8584         }
8585         if ( FD_ISSET ( connector, &fds_opensend ) ) {
8586             /* Once #1 is connected, allow #2 to connect */
8587             conn1 = 1;
8588 
8589             send(connector, "1", 1, 0);
8590             FD_CLR ( connector, &fds_send );
8591 
8592             iret = connect(connector2, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
8593             ok(iret == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK, "connecting to accepting socket failed, error %d\n", WSAGetLastError());
8594             FD_SET ( connector2, &fds_send );
8595         }
8596     }
8597 
8598     ok (got == 2 || broken(got == 1) /* NT4 */,
8599             "Did not get both connections, got %d\n", got);
8600 
8601     dwret = WaitForSingleObject(overlapped.hEvent, 0);
8602     ok(dwret == WAIT_OBJECT_0, "Waiting for accept event failed with %d + errno %d\n", dwret, GetLastError());
8603 
8604     bret = GetOverlappedResult((HANDLE)listener, &overlapped, &bytesReturned, FALSE);
8605     ok(bret, "GetOverlappedResult failed, error %d\n", GetLastError());
8606     ok(bytesReturned == 0, "bytesReturned isn't supposed to be %d\n", bytesReturned);
8607 
8608     set_blocking(acceptor, TRUE);
8609     iret = recv( acceptor, buffer, 2, 0);
8610     ok(iret == 1, "Failed to get data, %d, errno: %d\n", iret, WSAGetLastError());
8611 
8612     ok(buffer[0] == '1', "The wrong first client was accepted by acceptex: %c != 1\n", buffer[0]);
8613 
8614     closesocket(connector);
8615     connector = INVALID_SOCKET;
8616     closesocket(acceptor);
8617 
8618     /* clean up in case of failures */
8619     while ((acceptor = accept(listener, NULL, NULL)) != INVALID_SOCKET)
8620         closesocket(acceptor);
8621 
8622     /* Disconnect during receive? */
8623 
8624     acceptor = socket(AF_INET, SOCK_STREAM, 0);
8625     if (acceptor == INVALID_SOCKET) {
8626         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
8627         goto end;
8628     }
8629     connector = socket(AF_INET, SOCK_STREAM, 0);
8630     if (connector == INVALID_SOCKET) {
8631         skip("could not create connector socket, error %d\n", WSAGetLastError());
8632         goto end;
8633     }
8634     bret = pAcceptEx(listener, acceptor, buffer, sizeof(buffer) - 2*(sizeof(struct sockaddr_in) + 16),
8635         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8636         &bytesReturned, &overlapped);
8637     ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "AcceptEx returned %d + errno %d\n", bret, WSAGetLastError());
8638 
8639     iret = connect(connector, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
8640     ok(iret == 0, "connecting to accepting socket failed, error %d\n", WSAGetLastError());
8641 
8642     closesocket(connector);
8643     connector = INVALID_SOCKET;
8644 
8645     dwret = WaitForSingleObject(overlapped.hEvent, 1000);
8646     ok(dwret == WAIT_OBJECT_0, "Waiting for accept event failed with %d + errno %d\n", dwret, GetLastError());
8647 
8648     bytesReturned = 123456;
8649     bret = GetOverlappedResult((HANDLE)listener, &overlapped, &bytesReturned, FALSE);
8650     ok(bret, "GetOverlappedResult failed, error %d\n", GetLastError());
8651     ok(bytesReturned == 0, "bytesReturned isn't supposed to be %d\n", bytesReturned);
8652 
8653     closesocket(acceptor);
8654 
8655     /* Test closing with pending requests */
8656 
8657     acceptor = socket(AF_INET, SOCK_STREAM, 0);
8658     if (acceptor == INVALID_SOCKET) {
8659         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
8660         goto end;
8661     }
8662     bret = pAcceptEx(listener, acceptor, buffer, sizeof(buffer) - 2*(sizeof(struct sockaddr_in) + 16),
8663         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8664         &bytesReturned, &overlapped);
8665     ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "AcceptEx returned %d + errno %d\n", bret, WSAGetLastError());
8666 
8667     closesocket(acceptor);
8668 
8669     dwret = WaitForSingleObject(overlapped.hEvent, 1000);
8670     todo_wine ok(dwret == WAIT_OBJECT_0,
8671        "Waiting for accept event failed with %d + errno %d\n", dwret, GetLastError());
8672 
8673     if (dwret != WAIT_TIMEOUT) {
8674         bret = GetOverlappedResult((HANDLE)listener, &overlapped, &bytesReturned, FALSE);
8675         ok(!bret && GetLastError() == ERROR_OPERATION_ABORTED, "GetOverlappedResult failed, error %d\n", GetLastError());
8676     }
8677     else {
8678         bret = CancelIo((HANDLE) listener);
8679         ok(bret, "Failed to cancel failed test. Bailing...\n");
8680         if (!bret) return;
8681         WaitForSingleObject(overlapped.hEvent, 0);
8682     }
8683 
8684     acceptor = socket(AF_INET, SOCK_STREAM, 0);
8685     if (acceptor == INVALID_SOCKET) {
8686         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
8687         goto end;
8688     }
8689     bret = pAcceptEx(listener, acceptor, buffer, sizeof(buffer) - 2*(sizeof(struct sockaddr_in) + 16),
8690         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8691         &bytesReturned, &overlapped);
8692     ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "AcceptEx returned %d + errno %d\n", bret, WSAGetLastError());
8693 
8694     CancelIo((HANDLE) acceptor);
8695 
8696     dwret = WaitForSingleObject(overlapped.hEvent, 1000);
8697     ok(dwret == WAIT_TIMEOUT, "Waiting for timeout failed with %d + errno %d\n", dwret, GetLastError());
8698 
8699     closesocket(acceptor);
8700 
8701     acceptor = socket(AF_INET, SOCK_STREAM, 0);
8702     if (acceptor == INVALID_SOCKET) {
8703         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
8704         goto end;
8705     }
8706     bret = pAcceptEx(listener, acceptor, buffer, sizeof(buffer) - 2*(sizeof(struct sockaddr_in) + 16),
8707         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8708         &bytesReturned, &overlapped);
8709     ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "AcceptEx returned %d + errno %d\n", bret, WSAGetLastError());
8710 
8711     closesocket(listener);
8712     listener = INVALID_SOCKET;
8713 
8714     dwret = WaitForSingleObject(overlapped.hEvent, 1000);
8715     ok(dwret == WAIT_OBJECT_0, "Waiting for accept event failed with %d + errno %d\n", dwret, GetLastError());
8716 
8717     bret = GetOverlappedResult((HANDLE)listener, &overlapped, &bytesReturned, FALSE);
8718     ok(!bret && GetLastError() == ERROR_OPERATION_ABORTED, "GetOverlappedResult failed, error %d\n", GetLastError());
8719 
8720 end:
8721     if (overlapped.hEvent)
8722         WSACloseEvent(overlapped.hEvent);
8723     if (listener != INVALID_SOCKET)
8724         closesocket(listener);
8725     if (acceptor != INVALID_SOCKET)
8726         closesocket(acceptor);
8727     if (connector != INVALID_SOCKET)
8728         closesocket(connector);
8729     if (connector2 != INVALID_SOCKET)
8730         closesocket(connector2);
8731 }
8732 
8733 static void test_DisconnectEx(void)
8734 {
8735     SOCKET listener, acceptor, connector;
8736     LPFN_DISCONNECTEX pDisconnectEx;
8737     GUID disconnectExGuid = WSAID_DISCONNECTEX;
8738     struct sockaddr_in address;
8739     DWORD num_bytes, flags;
8740     OVERLAPPED overlapped;
8741     int addrlen, iret;
8742     BOOL bret;
8743 
8744     connector = socket(AF_INET, SOCK_STREAM, 0);
8745     ok(connector != INVALID_SOCKET, "failed to create connector socket, error %d\n", WSAGetLastError());
8746 
8747     iret = WSAIoctl(connector, SIO_GET_EXTENSION_FUNCTION_POINTER, &disconnectExGuid, sizeof(disconnectExGuid),
8748                     &pDisconnectEx, sizeof(pDisconnectEx), &num_bytes, NULL, NULL);
8749     if (iret)
8750     {
8751         win_skip("WSAIoctl failed to get DisconnectEx, error %d\n", WSAGetLastError());
8752         closesocket(connector);
8753         return;
8754     }
8755 
8756     listener = socket(AF_INET, SOCK_STREAM, 0);
8757     ok(listener != INVALID_SOCKET, "failed to create listener socket, error %d\n", WSAGetLastError());
8758 
8759     memset(&address, 0, sizeof(address));
8760     address.sin_family = AF_INET;
8761     address.sin_addr.s_addr = inet_addr("127.0.0.1");
8762     iret = bind(listener, (struct sockaddr *)&address, sizeof(address));
8763     ok(iret == 0, "failed to bind, error %d\n", WSAGetLastError());
8764 
8765     addrlen = sizeof(address);
8766     iret = getsockname(listener, (struct sockaddr *)&address, &addrlen);
8767     ok(iret == 0, "failed to lookup bind address, error %d\n", WSAGetLastError());
8768 
8769     iret = listen(listener, 1);
8770     ok(iret == 0, "failed to listen, error %d\n", WSAGetLastError());
8771 
8772     set_blocking(listener, TRUE);
8773 
8774     memset(&overlapped, 0, sizeof(overlapped));
8775     bret = pDisconnectEx(INVALID_SOCKET, &overlapped, 0, 0);
8776     ok(bret == FALSE, "DisconnectEx unexpectedly succeeded\n");
8777     ok(WSAGetLastError() == WSAENOTSOCK, "expected WSAENOTSOCK, got %d\n", WSAGetLastError());
8778 
8779     memset(&overlapped, 0, sizeof(overlapped));
8780     bret = pDisconnectEx(connector, &overlapped, 0, 0);
8781     ok(bret == FALSE, "DisconnectEx unexpectedly succeeded\n");
8782     todo_wine ok(WSAGetLastError() == WSAENOTCONN, "expected WSAENOTCONN, got %d\n", WSAGetLastError());
8783 
8784     iret = connect(connector, (struct sockaddr *)&address, addrlen);
8785     ok(iret == 0, "failed to connect, error %d\n", WSAGetLastError());
8786 
8787     acceptor = accept(listener, NULL, NULL);
8788     ok(acceptor != INVALID_SOCKET, "could not accept socket, error %d\n", WSAGetLastError());
8789 
8790     memset(&overlapped, 0, sizeof(overlapped));
8791     overlapped.hEvent = WSACreateEvent();
8792     ok(overlapped.hEvent != WSA_INVALID_EVENT, "WSACreateEvent failed, error %d\n", WSAGetLastError());
8793     bret = pDisconnectEx(connector, &overlapped, 0, 0);
8794     if (bret)
8795         ok(overlapped.Internal == STATUS_PENDING, "expected STATUS_PENDING, got %08lx\n", overlapped.Internal);
8796     else if (WSAGetLastError() == ERROR_IO_PENDING)
8797         bret = WSAGetOverlappedResult(connector, &overlapped, &num_bytes, TRUE, &flags);
8798     ok(bret, "DisconnectEx failed, error %d\n", WSAGetLastError());
8799     WSACloseEvent(overlapped.hEvent);
8800 
8801     iret = connect(connector, (struct sockaddr *)&address, sizeof(address));
8802     ok(iret != 0, "connect unexpectedly succeeded\n");
8803     ok(WSAGetLastError() == WSAEISCONN, "expected WSAEISCONN, got %d\n", WSAGetLastError());
8804 
8805     closesocket(acceptor);
8806     closesocket(connector);
8807 
8808     connector = socket(AF_INET, SOCK_STREAM, 0);
8809     ok(connector != INVALID_SOCKET, "failed to create connector socket, error %d\n", WSAGetLastError());
8810 
8811     iret = connect(connector, (struct sockaddr *)&address, addrlen);
8812     ok(iret == 0, "failed to connect, error %d\n", WSAGetLastError());
8813 
8814     acceptor = accept(listener, NULL, NULL);
8815     ok(acceptor != INVALID_SOCKET, "could not accept socket, error %d\n", WSAGetLastError());
8816 
8817     bret = pDisconnectEx(connector, NULL, 0, 0);
8818     ok(bret, "DisconnectEx failed, error %d\n", WSAGetLastError());
8819 
8820     iret = connect(connector, (struct sockaddr *)&address, sizeof(address));
8821     ok(iret != 0, "connect unexpectedly succeeded\n");
8822     ok(WSAGetLastError() == WSAEISCONN, "expected WSAEISCONN, got %d\n", WSAGetLastError());
8823 
8824     closesocket(acceptor);
8825     closesocket(connector);
8826     closesocket(listener);
8827 }
8828 
8829 #define compare_file(h,s,o) compare_file2(h,s,o,__FILE__,__LINE__)
8830 
8831 static void compare_file2(HANDLE handle, SOCKET sock, int offset, const char *file, int line)
8832 {
8833     char buf1[256], buf2[256];
8834     BOOL success;
8835     int i = 0;
8836 
8837     SetFilePointer(handle, offset, NULL, FILE_BEGIN);
8838     while (1)
8839     {
8840         DWORD n1 = 0, n2 = 0;
8841 
8842         success = ReadFile(handle, buf1, sizeof(buf1), &n1, NULL);
8843         ok_(file,line)(success, "Failed to read from file.\n");
8844         if (success && n1 == 0)
8845             break;
8846         else if(!success)
8847             return;
8848         n2 = recv(sock, buf2, n1, 0);
8849         ok_(file,line)(n1 == n2, "Block %d size mismatch (%d != %d)\n", i, n1, n2);
8850         ok_(file,line)(memcmp(buf1, buf2, n2) == 0, "Block %d failed\n", i);
8851         i++;
8852     }
8853 }
8854 
8855 static void test_TransmitFile(void)
8856 {
8857     DWORD num_bytes, err, file_size, total_sent;
8858     GUID transmitFileGuid = WSAID_TRANSMITFILE;
8859     LPFN_TRANSMITFILE pTransmitFile = NULL;
8860     HANDLE file = INVALID_HANDLE_VALUE;
8861     char header_msg[] = "hello world";
8862     char footer_msg[] = "goodbye!!!";
8863     char system_ini_path[MAX_PATH];
8864     struct sockaddr_in bindAddress;
8865     TRANSMIT_FILE_BUFFERS buffers;
8866     SOCKET client, server, dest;
8867     WSAOVERLAPPED ov;
8868     char buf[256];
8869     int iret, len;
8870     BOOL bret;
8871 
8872     memset( &ov, 0, sizeof(ov) );
8873 
8874     /* Setup sockets for testing TransmitFile */
8875     client = socket(AF_INET, SOCK_STREAM, 0);
8876     server = socket(AF_INET, SOCK_STREAM, 0);
8877     if (client == INVALID_SOCKET || server == INVALID_SOCKET)
8878     {
8879         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
8880         goto cleanup;
8881     }
8882     iret = WSAIoctl(client, SIO_GET_EXTENSION_FUNCTION_POINTER, &transmitFileGuid, sizeof(transmitFileGuid),
8883                     &pTransmitFile, sizeof(pTransmitFile), &num_bytes, NULL, NULL);
8884     if (iret)
8885     {
8886         skip("WSAIoctl failed to get TransmitFile with ret %d + errno %d\n", iret, WSAGetLastError());
8887         goto cleanup;
8888     }
8889     GetSystemWindowsDirectoryA(system_ini_path, MAX_PATH );
8890     strcat(system_ini_path, "\\system.ini");
8891     file = CreateFileA(system_ini_path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, 0x0, NULL);
8892     if (file == INVALID_HANDLE_VALUE)
8893     {
8894         skip("Unable to open a file to transmit.\n");
8895         goto cleanup;
8896     }
8897     file_size = GetFileSize(file, NULL);
8898 
8899     /* Test TransmitFile with an invalid socket */
8900     bret = pTransmitFile(INVALID_SOCKET, file, 0, 0, NULL, NULL, 0);
8901     err = WSAGetLastError();
8902     ok(!bret, "TransmitFile succeeded unexpectedly.\n");
8903     ok(err == WSAENOTSOCK, "TransmitFile triggered unexpected errno (%d != %d)\n", err, WSAENOTSOCK);
8904 
8905     /* Test a bogus TransmitFile without a connected socket */
8906     bret = pTransmitFile(client, NULL, 0, 0, NULL, NULL, TF_REUSE_SOCKET);
8907     err = WSAGetLastError();
8908     ok(!bret, "TransmitFile succeeded unexpectedly.\n");
8909     ok(err == WSAENOTCONN, "TransmitFile triggered unexpected errno (%d != %d)\n", err, WSAENOTCONN);
8910 
8911     /* Setup a properly connected socket for transfers */
8912     memset(&bindAddress, 0, sizeof(bindAddress));
8913     bindAddress.sin_family = AF_INET;
8914     bindAddress.sin_port = htons(SERVERPORT+1);
8915     bindAddress.sin_addr.s_addr = inet_addr("127.0.0.1");
8916     iret = bind(server, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
8917     if (iret != 0)
8918     {
8919         skip("failed to bind(), error %d\n", WSAGetLastError());
8920         goto cleanup;
8921     }
8922     iret = listen(server, 1);
8923     if (iret != 0)
8924     {
8925         skip("failed to listen(), error %d\n", WSAGetLastError());
8926         goto cleanup;
8927     }
8928     iret = connect(client, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
8929     if (iret != 0)
8930     {
8931         skip("failed to connect(), error %d\n", WSAGetLastError());
8932         goto cleanup;
8933     }
8934     len = sizeof(bindAddress);
8935     dest = accept(server, (struct sockaddr*)&bindAddress, &len);
8936     if (dest == INVALID_SOCKET)
8937     {
8938         skip("failed to accept(), error %d\n", WSAGetLastError());
8939         goto cleanup;
8940     }
8941     if (set_blocking(dest, FALSE))
8942     {
8943         skip("couldn't make socket non-blocking, error %d\n", WSAGetLastError());
8944         goto cleanup;
8945     }
8946 
8947     /* Test TransmitFile with no possible buffer */
8948     bret = pTransmitFile(client, NULL, 0, 0, NULL, NULL, 0);
8949     ok(bret, "TransmitFile failed unexpectedly.\n");
8950     iret = recv(dest, buf, sizeof(buf), 0);
8951     ok(iret == -1, "Returned an unexpected buffer from TransmitFile (%d != -1).\n", iret);
8952 
8953     /* Test TransmitFile with only buffer data */
8954     buffers.Head = &header_msg[0];
8955     buffers.HeadLength = sizeof(header_msg);
8956     buffers.Tail = &footer_msg[0];
8957     buffers.TailLength = sizeof(footer_msg);
8958     bret = pTransmitFile(client, NULL, 0, 0, NULL, &buffers, 0);
8959     ok(bret, "TransmitFile failed unexpectedly.\n");
8960     iret = recv(dest, buf, sizeof(buf), 0);
8961     ok(iret == sizeof(header_msg)+sizeof(footer_msg),
8962        "Returned an unexpected buffer from TransmitFile: %d\n", iret );
8963     ok(memcmp(&buf[0], &header_msg[0], sizeof(header_msg)) == 0,
8964        "TransmitFile header buffer did not match!\n");
8965     ok(memcmp(&buf[sizeof(header_msg)], &footer_msg[0], sizeof(footer_msg)) == 0,
8966        "TransmitFile footer buffer did not match!\n");
8967 
8968     /* Test TransmitFile with only file data */
8969     bret = pTransmitFile(client, file, 0, 0, NULL, NULL, 0);
8970     ok(bret, "TransmitFile failed unexpectedly.\n");
8971     compare_file(file, dest, 0);
8972 
8973     /* Test TransmitFile with both file and buffer data */
8974     buffers.Head = &header_msg[0];
8975     buffers.HeadLength = sizeof(header_msg);
8976     buffers.Tail = &footer_msg[0];
8977     buffers.TailLength = sizeof(footer_msg);
8978     SetFilePointer(file, 0, NULL, FILE_BEGIN);
8979     bret = pTransmitFile(client, file, 0, 0, NULL, &buffers, 0);
8980     ok(bret, "TransmitFile failed unexpectedly.\n");
8981     iret = recv(dest, buf, sizeof(header_msg), 0);
8982     ok(memcmp(buf, &header_msg[0], sizeof(header_msg)) == 0,
8983        "TransmitFile header buffer did not match!\n");
8984     compare_file(file, dest, 0);
8985     iret = recv(dest, buf, sizeof(footer_msg), 0);
8986     ok(memcmp(buf, &footer_msg[0], sizeof(footer_msg)) == 0,
8987        "TransmitFile footer buffer did not match!\n");
8988 
8989     /* Test overlapped TransmitFile */
8990     ov.hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
8991     if (ov.hEvent == INVALID_HANDLE_VALUE)
8992     {
8993         skip("Could not create event object, some tests will be skipped. errno = %d\n",
8994              GetLastError());
8995         goto cleanup;
8996     }
8997     SetFilePointer(file, 0, NULL, FILE_BEGIN);
8998     bret = pTransmitFile(client, file, 0, 0, &ov, NULL, 0);
8999     err = WSAGetLastError();
9000     ok(!bret, "TransmitFile succeeded unexpectedly.\n");
9001     ok(err == ERROR_IO_PENDING, "TransmitFile triggered unexpected errno (%d != %d)\n",
9002        err, ERROR_IO_PENDING);
9003     iret = WaitForSingleObject(ov.hEvent, 2000);
9004     ok(iret == WAIT_OBJECT_0, "Overlapped TransmitFile failed.\n");
9005     WSAGetOverlappedResult(client, &ov, &total_sent, FALSE, NULL);
9006     ok(total_sent == file_size,
9007        "Overlapped TransmitFile sent an unexpected number of bytes (%d != %d).\n",
9008        total_sent, file_size);
9009     compare_file(file, dest, 0);
9010 
9011     /* Test overlapped TransmitFile w/ start offset */
9012     ov.hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
9013     if (ov.hEvent == INVALID_HANDLE_VALUE)
9014     {
9015         skip("Could not create event object, some tests will be skipped. errno = %d\n", GetLastError());
9016         goto cleanup;
9017     }
9018     SetFilePointer(file, 0, NULL, FILE_BEGIN);
9019     ov.Offset = 10;
9020     bret = pTransmitFile(client, file, 0, 0, &ov, NULL, 0);
9021     err = WSAGetLastError();
9022     ok(!bret, "TransmitFile succeeded unexpectedly.\n");
9023     ok(err == ERROR_IO_PENDING, "TransmitFile triggered unexpected errno (%d != %d)\n", err, ERROR_IO_PENDING);
9024     iret = WaitForSingleObject(ov.hEvent, 2000);
9025     ok(iret == WAIT_OBJECT_0, "Overlapped TransmitFile failed.\n");
9026     WSAGetOverlappedResult(client, &ov, &total_sent, FALSE, NULL);
9027     ok(total_sent == (file_size - ov.Offset),
9028        "Overlapped TransmitFile sent an unexpected number of bytes (%d != %d).\n",
9029        total_sent, file_size - ov.Offset);
9030     compare_file(file, dest, ov.Offset);
9031 
9032     /* Test overlapped TransmitFile w/ file and buffer data */
9033     ov.hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
9034     if (ov.hEvent == INVALID_HANDLE_VALUE)
9035     {
9036         skip("Could not create event object, some tests will be skipped. errno = %d\n", GetLastError());
9037         goto cleanup;
9038     }
9039     buffers.Head = &header_msg[0];
9040     buffers.HeadLength = sizeof(header_msg);
9041     buffers.Tail = &footer_msg[0];
9042     buffers.TailLength = sizeof(footer_msg);
9043     SetFilePointer(file, 0, NULL, FILE_BEGIN);
9044     ov.Offset = 0;
9045     bret = pTransmitFile(client, file, 0, 0, &ov, &buffers, 0);
9046     err = WSAGetLastError();
9047     ok(!bret, "TransmitFile succeeded unexpectedly.\n");
9048     ok(err == ERROR_IO_PENDING, "TransmitFile triggered unexpected errno (%d != %d)\n", err, ERROR_IO_PENDING);
9049     iret = WaitForSingleObject(ov.hEvent, 2000);
9050     ok(iret == WAIT_OBJECT_0, "Overlapped TransmitFile failed.\n");
9051     WSAGetOverlappedResult(client, &ov, &total_sent, FALSE, NULL);
9052     ok(total_sent == (file_size + buffers.HeadLength + buffers.TailLength),
9053        "Overlapped TransmitFile sent an unexpected number of bytes (%d != %d).\n",
9054        total_sent, file_size  + buffers.HeadLength + buffers.TailLength);
9055     iret = recv(dest, buf, sizeof(header_msg), 0);
9056     ok(memcmp(buf, &header_msg[0], sizeof(header_msg)) == 0,
9057        "TransmitFile header buffer did not match!\n");
9058     compare_file(file, dest, 0);
9059     iret = recv(dest, buf, sizeof(footer_msg), 0);
9060     ok(memcmp(buf, &footer_msg[0], sizeof(footer_msg)) == 0,
9061        "TransmitFile footer buffer did not match!\n");
9062 
9063     /* Test TransmitFile w/ TF_DISCONNECT */
9064     SetFilePointer(file, 0, NULL, FILE_BEGIN);
9065     bret = pTransmitFile(client, file, 0, 0, NULL, NULL, TF_DISCONNECT);
9066     ok(bret, "TransmitFile failed unexpectedly.\n");
9067     compare_file(file, dest, 0);
9068     closesocket(client);
9069     ok(send(client, "test", 4, 0) == -1, "send() after TF_DISCONNECT succeeded unexpectedly.\n");
9070     err = WSAGetLastError();
9071     todo_wine ok(err == WSAENOTSOCK, "send() after TF_DISCONNECT triggered unexpected errno (%d != %d)\n",
9072                  err, WSAENOTSOCK);
9073 
9074     /* Test TransmitFile with a UDP datagram socket */
9075     client = socket(AF_INET, SOCK_DGRAM, 0);
9076     bret = pTransmitFile(client, NULL, 0, 0, NULL, NULL, 0);
9077     err = WSAGetLastError();
9078     ok(!bret, "TransmitFile succeeded unexpectedly.\n");
9079     ok(err == WSAENOTCONN, "TransmitFile triggered unexpected errno (%d != %d)\n", err, WSAENOTCONN);
9080 
9081 cleanup:
9082     CloseHandle(file);
9083     CloseHandle(ov.hEvent);
9084     closesocket(client);
9085     closesocket(server);
9086 }
9087 
9088 static void test_getpeername(void)
9089 {
9090     SOCKET sock;
9091     struct sockaddr_in sa, sa_out;
9092     SOCKADDR_STORAGE ss;
9093     int sa_len;
9094     const char buf[] = "hello world";
9095     int ret;
9096 
9097     /* Test the parameter validation order. */
9098     ret = getpeername(INVALID_SOCKET, NULL, NULL);
9099     ok(ret == SOCKET_ERROR, "Expected getpeername to return SOCKET_ERROR, got %d\n", ret);
9100     ok(WSAGetLastError() == WSAENOTSOCK,
9101        "Expected WSAGetLastError() to return WSAENOTSOCK, got %d\n", WSAGetLastError());
9102 
9103     sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
9104     ok(sock != INVALID_SOCKET, "Expected socket to return a valid socket\n");
9105     if (sock == INVALID_SOCKET)
9106     {
9107         skip("Socket creation failed with %d\n", WSAGetLastError());
9108         return;
9109     }
9110 
9111     ret = getpeername(sock, NULL, NULL);
9112     ok(ret == SOCKET_ERROR, "Expected getpeername to return SOCKET_ERROR, got %d\n", ret);
9113     ok(WSAGetLastError() == WSAENOTCONN,
9114        "Expected WSAGetLastError() to return WSAENOTCONN, got %d\n", WSAGetLastError());
9115 
9116     memset(&sa, 0, sizeof(sa));
9117     sa.sin_family = AF_INET;
9118     sa.sin_port = htons(139);
9119     sa.sin_addr.s_addr = inet_addr("127.0.0.1");
9120 
9121     /* sendto does not change a socket's connection state. */
9122     ret = sendto(sock, buf, sizeof(buf), 0, (struct sockaddr*)&sa, sizeof(sa));
9123     ok(ret != SOCKET_ERROR,
9124        "Expected sendto to succeed, WSAGetLastError() = %d\n", WSAGetLastError());
9125 
9126     ret = getpeername(sock, NULL, NULL);
9127     ok(ret == SOCKET_ERROR, "Expected getpeername to return SOCKET_ERROR, got %d\n", ret);
9128     ok(WSAGetLastError() == WSAENOTCONN,
9129        "Expected WSAGetLastError() to return WSAENOTCONN, got %d\n", WSAGetLastError());
9130 
9131     ret = connect(sock, (struct sockaddr*)&sa, sizeof(sa));
9132     ok(ret == 0,
9133        "Expected connect to succeed, WSAGetLastError() = %d\n", WSAGetLastError());
9134 
9135     ret = getpeername(sock, NULL, NULL);
9136     ok(ret == SOCKET_ERROR, "Expected getpeername to return SOCKET_ERROR, got %d\n", ret);
9137     ok(WSAGetLastError() == WSAEFAULT,
9138        "Expected WSAGetLastError() to return WSAEFAULT, got %d\n", WSAGetLastError());
9139 
9140     /* Test crashes on Wine. */
9141     if (0)
9142     {
9143         ret = getpeername(sock, (void*)0xdeadbeef, (void*)0xcafebabe);
9144         ok(ret == SOCKET_ERROR, "Expected getpeername to return SOCKET_ERROR, got %d\n", ret);
9145         ok(WSAGetLastError() == WSAEFAULT,
9146            "Expected WSAGetLastError() to return WSAEFAULT, got %d\n", WSAGetLastError());
9147     }
9148 
9149     ret = getpeername(sock, (struct sockaddr*)&sa_out, NULL);
9150     ok(ret == SOCKET_ERROR, "Expected getpeername to return 0, got %d\n", ret);
9151     ok(WSAGetLastError() == WSAEFAULT,
9152        "Expected WSAGetLastError() to return WSAEFAULT, got %d\n", WSAGetLastError());
9153 
9154     sa_len = 0;
9155     ret = getpeername(sock, NULL, &sa_len);
9156     ok(ret == SOCKET_ERROR, "Expected getpeername to return 0, got %d\n", ret);
9157     ok(WSAGetLastError() == WSAEFAULT,
9158        "Expected WSAGetLastError() to return WSAEFAULT, got %d\n", WSAGetLastError());
9159     ok(!sa_len, "got %d\n", sa_len);
9160 
9161     sa_len = 0;
9162     ret = getpeername(sock, (struct sockaddr *)&ss, &sa_len);
9163     ok(ret == SOCKET_ERROR, "Expected getpeername to return 0, got %d\n", ret);
9164     ok(WSAGetLastError() == WSAEFAULT,
9165        "Expected WSAGetLastError() to return WSAEFAULT, got %d\n", WSAGetLastError());
9166     ok(!sa_len, "got %d\n", sa_len);
9167 
9168     sa_len = sizeof(ss);
9169     ret = getpeername(sock, (struct sockaddr *)&ss, &sa_len);
9170     ok(ret == 0, "Expected getpeername to return 0, got %d\n", ret);
9171     ok(!memcmp(&sa, &ss, sizeof(sa)),
9172        "Expected the returned structure to be identical to the connect structure\n");
9173     ok(sa_len == sizeof(sa), "got %d\n", sa_len);
9174 
9175     closesocket(sock);
9176 }
9177 
9178 static void test_sioRoutingInterfaceQuery(void)
9179 {
9180     int ret;
9181     SOCKET sock;
9182     SOCKADDR_IN sin = { 0 }, sout = { 0 };
9183     DWORD bytesReturned;
9184 
9185     sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
9186     ok(sock != INVALID_SOCKET, "Expected socket to return a valid socket\n");
9187     if (sock == INVALID_SOCKET)
9188     {
9189         skip("Socket creation failed with %d\n", WSAGetLastError());
9190         return;
9191     }
9192     ret = WSAIoctl(sock, SIO_ROUTING_INTERFACE_QUERY, NULL, 0, NULL, 0, NULL,
9193                    NULL, NULL);
9194     ok(ret == SOCKET_ERROR && WSAGetLastError() == WSAEFAULT,
9195        "expected WSAEFAULT, got %d\n", WSAGetLastError());
9196     ret = WSAIoctl(sock, SIO_ROUTING_INTERFACE_QUERY, &sin, sizeof(sin),
9197                    NULL, 0, NULL, NULL, NULL);
9198     ok(ret == SOCKET_ERROR && WSAGetLastError() == WSAEFAULT,
9199        "expected WSAEFAULT, got %d\n", WSAGetLastError());
9200     ret = WSAIoctl(sock, SIO_ROUTING_INTERFACE_QUERY, &sin, sizeof(sin),
9201                    NULL, 0, &bytesReturned, NULL, NULL);
9202     todo_wine ok(ret == SOCKET_ERROR && WSAGetLastError() == WSAEAFNOSUPPORT,
9203        "expected WSAEAFNOSUPPORT, got %d\n", WSAGetLastError());
9204     sin.sin_family = AF_INET;
9205     ret = WSAIoctl(sock, SIO_ROUTING_INTERFACE_QUERY, &sin, sizeof(sin),
9206                    NULL, 0, &bytesReturned, NULL, NULL);
9207     todo_wine ok(ret == SOCKET_ERROR && WSAGetLastError() == WSAEINVAL,
9208        "expected WSAEINVAL, got %d\n", WSAGetLastError());
9209     sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
9210     ret = WSAIoctl(sock, SIO_ROUTING_INTERFACE_QUERY, &sin, sizeof(sin),
9211                    NULL, 0, &bytesReturned, NULL, NULL);
9212     ok(ret == SOCKET_ERROR && WSAGetLastError() == WSAEFAULT,
9213        "expected WSAEFAULT, got %d\n", WSAGetLastError());
9214     ret = WSAIoctl(sock, SIO_ROUTING_INTERFACE_QUERY, &sin, sizeof(sin),
9215                    &sout, sizeof(sout), &bytesReturned, NULL, NULL);
9216     ok(!ret, "WSAIoctl failed: %d\n", WSAGetLastError());
9217     ok(sout.sin_family == AF_INET, "expected AF_INET, got %d\n", sout.sin_family);
9218     /* We expect the source address to be INADDR_LOOPBACK as well, but
9219      * there's no guarantee that a route to the loopback address exists,
9220      * so rather than introduce spurious test failures we do not test the
9221      * source address.
9222      */
9223     closesocket(sock);
9224 }
9225 
9226 static void test_sioAddressListChange(void)
9227 {
9228     struct sockaddr_in bindAddress;
9229     struct in_addr net_address;
9230     WSAOVERLAPPED overlapped, *olp;
9231     struct hostent *h;
9232     DWORD num_bytes, error, tick;
9233     SOCKET sock, sock2, sock3;
9234     WSAEVENT event2, event3;
9235     HANDLE io_port;
9236     ULONG_PTR key;
9237     int acount;
9238     BOOL bret;
9239     int ret;
9240 
9241     /* Use gethostbyname to find the list of local network interfaces */
9242     h = gethostbyname("");
9243     if (!h)
9244     {
9245         skip("Cannot test SIO_ADDRESS_LIST_CHANGE, gethostbyname failed with %u\n",
9246              WSAGetLastError());
9247         return;
9248     }
9249     for (acount = 0; h->h_addr_list[acount]; acount++);
9250     if (acount == 0)
9251     {
9252         skip("Cannot test SIO_ADDRESS_LIST_CHANGE, test requires a network card.\n");
9253         return;
9254     }
9255 
9256     net_address.s_addr = *(ULONG *) h->h_addr_list[0];
9257 
9258     sock = socket(AF_INET, 0, IPPROTO_TCP);
9259     ok(sock != INVALID_SOCKET, "socket() failed\n");
9260 
9261     memset(&bindAddress, 0, sizeof(bindAddress));
9262     bindAddress.sin_family = AF_INET;
9263     bindAddress.sin_addr.s_addr = net_address.s_addr;
9264     SetLastError(0xdeadbeef);
9265     ret = bind(sock, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
9266     ok (!ret, "bind() failed with error %d\n", GetLastError());
9267     set_blocking(sock, FALSE);
9268 
9269     memset(&overlapped, 0, sizeof(overlapped));
9270     overlapped.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
9271     SetLastError(0xdeadbeef);
9272     ret = WSAIoctl(sock, SIO_ADDRESS_LIST_CHANGE, NULL, 0, NULL, 0, &num_bytes, &overlapped, NULL);
9273     error = GetLastError();
9274     ok (ret == SOCKET_ERROR, "WSAIoctl(SIO_ADDRESS_LIST_CHANGE) failed with error %d\n", error);
9275     ok (error == ERROR_IO_PENDING, "expected 0x3e5, got 0x%x\n", error);
9276 
9277     CloseHandle(overlapped.hEvent);
9278     closesocket(sock);
9279 
9280     sock = socket(AF_INET, 0, IPPROTO_TCP);
9281     ok(sock != INVALID_SOCKET, "socket() failed\n");
9282 
9283     SetLastError(0xdeadbeef);
9284     ret = bind(sock, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
9285     ok (!ret, "bind() failed with error %d\n", GetLastError());
9286     set_blocking(sock, TRUE);
9287 
9288     memset(&overlapped, 0, sizeof(overlapped));
9289     overlapped.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
9290     SetLastError(0xdeadbeef);
9291     ret = WSAIoctl(sock, SIO_ADDRESS_LIST_CHANGE, NULL, 0, NULL, 0, &num_bytes, &overlapped, NULL);
9292     error = GetLastError();
9293     ok (ret == SOCKET_ERROR, "WSAIoctl(SIO_ADDRESS_LIST_CHANGE) failed with error %d\n", error);
9294     ok (error == ERROR_IO_PENDING, "expected 0x3e5, got 0x%x\n", error);
9295 
9296     CloseHandle(overlapped.hEvent);
9297     closesocket(sock);
9298 
9299     sock = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
9300     ok(sock != INVALID_SOCKET, "socket() failed\n");
9301 
9302     SetLastError(0xdeadbeef);
9303     ret = bind(sock, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
9304     ok (!ret, "bind() failed with error %d\n", GetLastError());
9305     set_blocking(sock, FALSE);
9306 
9307     memset(&overlapped, 0, sizeof(overlapped));
9308     overlapped.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
9309     SetLastError(0xdeadbeef);
9310     ret = WSAIoctl(sock, SIO_ADDRESS_LIST_CHANGE, NULL, 0, NULL, 0, &num_bytes, &overlapped, NULL);
9311     error = GetLastError();
9312     ok (ret == SOCKET_ERROR, "WSAIoctl(SIO_ADDRESS_LIST_CHANGE) failed with error %d\n", error);
9313     ok (error == ERROR_IO_PENDING, "expected 0x3e5, got 0x%x\n", error);
9314 
9315     CloseHandle(overlapped.hEvent);
9316     closesocket(sock);
9317 
9318     sock = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
9319     ok(sock != INVALID_SOCKET, "socket() failed\n");
9320 
9321     SetLastError(0xdeadbeef);
9322     ret = bind(sock, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
9323     ok (!ret, "bind() failed with error %d\n", GetLastError());
9324     set_blocking(sock, TRUE);
9325 
9326     memset(&overlapped, 0, sizeof(overlapped));
9327     overlapped.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
9328     SetLastError(0xdeadbeef);
9329     ret = WSAIoctl(sock, SIO_ADDRESS_LIST_CHANGE, NULL, 0, NULL, 0, &num_bytes, &overlapped, NULL);
9330     error = GetLastError();
9331     ok (ret == SOCKET_ERROR, "WSAIoctl(SIO_ADDRESS_LIST_CHANGE) failed with error %d\n", error);
9332     ok (error == ERROR_IO_PENDING, "expected 0x3e5, got 0x%x\n", error);
9333 
9334     CloseHandle(overlapped.hEvent);
9335     closesocket(sock);
9336 
9337     /* When the socket is overlapped non-blocking and the list change is requested without
9338      * an overlapped structure the error will be different. */
9339     sock = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
9340     ok(sock != INVALID_SOCKET, "socket() failed\n");
9341 
9342     SetLastError(0xdeadbeef);
9343     ret = bind(sock, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
9344     ok (!ret, "bind() failed with error %d\n", GetLastError());
9345     set_blocking(sock, FALSE);
9346 
9347     SetLastError(0xdeadbeef);
9348     ret = WSAIoctl(sock, SIO_ADDRESS_LIST_CHANGE, NULL, 0, NULL, 0, &num_bytes, NULL, NULL);
9349     error = GetLastError();
9350     ok (ret == SOCKET_ERROR, "WSAIoctl(SIO_ADDRESS_LIST_CHANGE) failed with error %d\n", error);
9351     ok (error == WSAEWOULDBLOCK, "expected 10035, got %d\n", error);
9352 
9353     io_port = CreateIoCompletionPort( (HANDLE)sock, NULL, 0, 0 );
9354     ok (io_port != NULL, "failed to create completion port %u\n", GetLastError());
9355 
9356     set_blocking(sock, FALSE);
9357     memset(&overlapped, 0, sizeof(overlapped));
9358     SetLastError(0xdeadbeef);
9359     ret = WSAIoctl(sock, SIO_ADDRESS_LIST_CHANGE, NULL, 0, NULL, 0, &num_bytes, &overlapped, NULL);
9360     error = GetLastError();
9361     ok (ret == SOCKET_ERROR, "WSAIoctl(SIO_ADDRESS_LIST_CHANGE) failed with error %u\n", error);
9362     ok (error == ERROR_IO_PENDING, "expected ERROR_IO_PENDING got %u\n", error);
9363 
9364     olp = (WSAOVERLAPPED *)0xdeadbeef;
9365     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 0 );
9366     ok(!bret, "failed to get completion status %u\n", bret);
9367     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
9368     ok(!olp, "Overlapped structure is at %p\n", olp);
9369 
9370     closesocket(sock);
9371 
9372     olp = (WSAOVERLAPPED *)0xdeadbeef;
9373     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 0 );
9374     ok(!bret, "failed to get completion status %u\n", bret);
9375     ok(GetLastError() == ERROR_OPERATION_ABORTED, "Last error was %u\n", GetLastError());
9376     ok(olp == &overlapped, "Overlapped structure is at %p\n", olp);
9377 
9378     CloseHandle(io_port);
9379 
9380     /* Misuse of the API by using a blocking socket and not using an overlapped structure,
9381      * this leads to a hang forever. */
9382     if (0)
9383     {
9384         sock = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
9385 
9386         SetLastError(0xdeadbeef);
9387         bind(sock, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
9388 
9389         set_blocking(sock, TRUE);
9390         WSAIoctl(sock, SIO_ADDRESS_LIST_CHANGE, NULL, 0, NULL, 0, &num_bytes, NULL, NULL);
9391         /* hang */
9392 
9393         closesocket(sock);
9394     }
9395 
9396     if (!winetest_interactive)
9397     {
9398         skip("Cannot test SIO_ADDRESS_LIST_CHANGE, interactive tests must be enabled\n");
9399         return;
9400     }
9401 
9402     /* Bind an overlapped socket to the first found network interface */
9403     sock = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
9404     ok(sock != INVALID_SOCKET, "Expected socket to return a valid socket\n");
9405     sock2 = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
9406     ok(sock2 != INVALID_SOCKET, "Expected socket to return a valid socket\n");
9407     sock3 = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
9408     ok(sock3 != INVALID_SOCKET, "Expected socket to return a valid socket\n");
9409 
9410     ret = bind(sock, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
9411     ok(!ret, "bind failed unexpectedly\n");
9412     ret = bind(sock2, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
9413     ok(!ret, "bind failed unexpectedly\n");
9414     ret = bind(sock3, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
9415     ok(!ret, "bind failed unexpectedly\n");
9416 
9417     set_blocking(sock2, FALSE);
9418     set_blocking(sock3, FALSE);
9419 
9420     /* Wait for address changes, request that the user connects/disconnects an interface */
9421     memset(&overlapped, 0, sizeof(overlapped));
9422     overlapped.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
9423     ret = WSAIoctl(sock, SIO_ADDRESS_LIST_CHANGE, NULL, 0, NULL, 0, &num_bytes, &overlapped, NULL);
9424     ok(ret == SOCKET_ERROR, "WSAIoctl succeeded unexpectedly\n");
9425     ok(WSAGetLastError() == WSA_IO_PENDING, "Expected pending last error, got %d\n", WSAGetLastError());
9426 
9427     ret = WSAIoctl(sock2, SIO_ADDRESS_LIST_CHANGE, NULL, 0, NULL, 0, &num_bytes, NULL, NULL);
9428     ok(ret == SOCKET_ERROR, "WSAIoctl succeeded unexpectedly\n");
9429     ok(WSAGetLastError() == WSAEWOULDBLOCK, "Expected would block last error, got %d\n", WSAGetLastError());
9430 
9431     event2 = WSACreateEvent();
9432     event3 = WSACreateEvent();
9433     ret = WSAEventSelect (sock2, event2, FD_ADDRESS_LIST_CHANGE);
9434     ok(!ret, "WSAEventSelect failed with %d\n", WSAGetLastError());
9435     /* sock3 did not request SIO_ADDRESS_LIST_CHANGE but it is trying to wait anyway */
9436     ret = WSAEventSelect (sock3, event3, FD_ADDRESS_LIST_CHANGE);
9437     ok(!ret, "WSAEventSelect failed with %d\n", WSAGetLastError());
9438 
9439     trace("Testing socket-based ipv4 address list change notification. Please connect/disconnect or"
9440           " change the ipv4 address of any of the local network interfaces (15 second timeout).\n");
9441     tick = GetTickCount();
9442     ret = WaitForSingleObject(overlapped.hEvent, 15000);
9443     ok(ret == WAIT_OBJECT_0, "failed to get overlapped event %u\n", ret);
9444 
9445     ret = WaitForSingleObject(event2, 500);
9446 todo_wine
9447     ok(ret == WAIT_OBJECT_0, "failed to get change event %u\n", ret);
9448 
9449     ret = WaitForSingleObject(event3, 500);
9450     ok(ret == WAIT_TIMEOUT, "unexpected change event\n");
9451 
9452     trace("Spent %d ms waiting.\n", GetTickCount() - tick);
9453 
9454     WSACloseEvent(event2);
9455     WSACloseEvent(event3);
9456 
9457     closesocket(sock);
9458     closesocket(sock2);
9459     closesocket(sock3);
9460 }
9461 
9462 static void test_synchronous_WSAIoctl(void)
9463 {
9464     HANDLE previous_port, io_port;
9465     WSAOVERLAPPED overlapped, *olp;
9466     SOCKET socket;
9467     ULONG on;
9468     ULONG_PTR key;
9469     DWORD num_bytes;
9470     BOOL ret;
9471     int res;
9472 
9473     previous_port = CreateIoCompletionPort( INVALID_HANDLE_VALUE, NULL, 0, 0 );
9474     ok( previous_port != NULL, "failed to create completion port %u\n", GetLastError() );
9475 
9476     socket = WSASocketW( AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED );
9477     ok( socket != INVALID_SOCKET, "failed to create socket %d\n", WSAGetLastError() );
9478 
9479     io_port = CreateIoCompletionPort( (HANDLE)socket, previous_port, 0, 0 );
9480     ok( io_port != NULL, "failed to create completion port %u\n", GetLastError() );
9481 
9482     on = 1;
9483     memset( &overlapped, 0, sizeof(overlapped) );
9484     res = WSAIoctl( socket, FIONBIO, &on, sizeof(on), NULL, 0, &num_bytes, &overlapped, NULL );
9485     ok( !res, "WSAIoctl failed %d\n", WSAGetLastError() );
9486 
9487     ret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 10000 );
9488     ok( ret, "failed to get completion status %u\n", GetLastError() );
9489 
9490     CloseHandle( io_port );
9491     closesocket( socket );
9492     CloseHandle( previous_port );
9493 }
9494 
9495 #define WM_ASYNCCOMPLETE (WM_USER + 100)
9496 static HWND create_async_message_window(void)
9497 {
9498     static const char class_name[] = "ws2_32 async message window class";
9499 
9500     WNDCLASSEXA wndclass;
9501     HWND hWnd;
9502 
9503     wndclass.cbSize         = sizeof(wndclass);
9504     wndclass.style          = CS_HREDRAW | CS_VREDRAW;
9505     wndclass.lpfnWndProc    = DefWindowProcA;
9506     wndclass.cbClsExtra     = 0;
9507     wndclass.cbWndExtra     = 0;
9508     wndclass.hInstance      = GetModuleHandleA(NULL);
9509     wndclass.hIcon          = LoadIconA(NULL, (LPCSTR)IDI_APPLICATION);
9510     wndclass.hIconSm        = LoadIconA(NULL, (LPCSTR)IDI_APPLICATION);
9511     wndclass.hCursor        = LoadCursorA(NULL, (LPCSTR)IDC_ARROW);
9512     wndclass.hbrBackground  = (HBRUSH)(COLOR_WINDOW + 1);
9513     wndclass.lpszClassName  = class_name;
9514     wndclass.lpszMenuName   = NULL;
9515 
9516     RegisterClassExA(&wndclass);
9517 
9518     hWnd = CreateWindowA(class_name, "ws2_32 async message window", WS_OVERLAPPEDWINDOW,
9519                         0, 0, 500, 500, NULL, NULL, GetModuleHandleA(NULL), NULL);
9520     if (!hWnd)
9521     {
9522         ok(0, "failed to create window: %u\n", GetLastError());
9523         return NULL;
9524     }
9525 
9526     return hWnd;
9527 }
9528 
9529 static void wait_for_async_message(HWND hwnd, HANDLE handle)
9530 {
9531     BOOL ret;
9532     MSG msg;
9533 
9534     while ((ret = GetMessageA(&msg, 0, 0, 0)) &&
9535            !(msg.hwnd == hwnd && msg.message == WM_ASYNCCOMPLETE))
9536     {
9537         TranslateMessage(&msg);
9538         DispatchMessageA(&msg);
9539     }
9540 
9541     ok(ret, "did not expect WM_QUIT message\n");
9542     ok(msg.wParam == (WPARAM)handle, "expected wParam = %p, got %lx\n", handle, msg.wParam);
9543 }
9544 
9545 static void test_WSAAsyncGetServByPort(void)
9546 {
9547     HWND hwnd = create_async_message_window();
9548     HANDLE ret;
9549     char buffer[MAXGETHOSTSTRUCT];
9550 
9551     if (!hwnd)
9552         return;
9553 
9554     /* FIXME: The asynchronous window messages should be tested. */
9555 
9556     /* Parameters are not checked when initiating the asynchronous operation.  */
9557     ret = WSAAsyncGetServByPort(NULL, 0, 0, NULL, NULL, 0);
9558     ok(ret != NULL, "WSAAsyncGetServByPort returned NULL\n");
9559 
9560     ret = WSAAsyncGetServByPort(hwnd, WM_ASYNCCOMPLETE, 0, NULL, NULL, 0);
9561     ok(ret != NULL, "WSAAsyncGetServByPort returned NULL\n");
9562     wait_for_async_message(hwnd, ret);
9563 
9564     ret = WSAAsyncGetServByPort(hwnd, WM_ASYNCCOMPLETE, htons(80), NULL, NULL, 0);
9565     ok(ret != NULL, "WSAAsyncGetServByPort returned NULL\n");
9566     wait_for_async_message(hwnd, ret);
9567 
9568     ret = WSAAsyncGetServByPort(hwnd, WM_ASYNCCOMPLETE, htons(80), NULL, buffer, MAXGETHOSTSTRUCT);
9569     ok(ret != NULL, "WSAAsyncGetServByPort returned NULL\n");
9570     wait_for_async_message(hwnd, ret);
9571 
9572     DestroyWindow(hwnd);
9573 }
9574 
9575 static void test_WSAAsyncGetServByName(void)
9576 {
9577     HWND hwnd = create_async_message_window();
9578     HANDLE ret;
9579     char buffer[MAXGETHOSTSTRUCT];
9580 
9581     if (!hwnd)
9582         return;
9583 
9584     /* FIXME: The asynchronous window messages should be tested. */
9585 
9586     /* Parameters are not checked when initiating the asynchronous operation.  */
9587     ret = WSAAsyncGetServByName(hwnd, WM_ASYNCCOMPLETE, "", NULL, NULL, 0);
9588     ok(ret != NULL, "WSAAsyncGetServByName returned NULL\n");
9589     wait_for_async_message(hwnd, ret);
9590 
9591     ret = WSAAsyncGetServByName(hwnd, WM_ASYNCCOMPLETE, "", "", buffer, MAXGETHOSTSTRUCT);
9592     ok(ret != NULL, "WSAAsyncGetServByName returned NULL\n");
9593     wait_for_async_message(hwnd, ret);
9594 
9595     ret = WSAAsyncGetServByName(hwnd, WM_ASYNCCOMPLETE, "http", NULL, NULL, 0);
9596     ok(ret != NULL, "WSAAsyncGetServByName returned NULL\n");
9597     wait_for_async_message(hwnd, ret);
9598 
9599     ret = WSAAsyncGetServByName(hwnd, WM_ASYNCCOMPLETE, "http", "tcp", buffer, MAXGETHOSTSTRUCT);
9600     ok(ret != NULL, "WSAAsyncGetServByName returned NULL\n");
9601     wait_for_async_message(hwnd, ret);
9602 
9603     DestroyWindow(hwnd);
9604 }
9605 
9606 /*
9607  * Provide consistent initialization for the AcceptEx IOCP tests.
9608  */
9609 static SOCKET setup_iocp_src(struct sockaddr_in *bindAddress)
9610 {
9611     SOCKET src, ret = INVALID_SOCKET;
9612     int iret, socklen;
9613 
9614     src = socket(AF_INET, SOCK_STREAM, 0);
9615     if (src == INVALID_SOCKET)
9616     {
9617         skip("could not create listener socket, error %d\n", WSAGetLastError());
9618         goto end;
9619     }
9620 
9621     memset(bindAddress, 0, sizeof(*bindAddress));
9622     bindAddress->sin_family = AF_INET;
9623     bindAddress->sin_addr.s_addr = inet_addr("127.0.0.1");
9624     iret = bind(src, (struct sockaddr*)bindAddress, sizeof(*bindAddress));
9625     if (iret != 0)
9626     {
9627         skip("failed to bind, error %d\n", WSAGetLastError());
9628         goto end;
9629     }
9630 
9631     socklen = sizeof(*bindAddress);
9632     iret = getsockname(src, (struct sockaddr*)bindAddress, &socklen);
9633     if (iret != 0) {
9634         skip("failed to lookup bind address, error %d\n", WSAGetLastError());
9635         goto end;
9636     }
9637 
9638     if (set_blocking(src, FALSE))
9639     {
9640         skip("couldn't make socket non-blocking, error %d\n", WSAGetLastError());
9641         goto end;
9642     }
9643 
9644     iret = listen(src, 5);
9645     if (iret != 0)
9646     {
9647         skip("listening failed, errno = %d\n", WSAGetLastError());
9648         goto end;
9649     }
9650 
9651     ret = src;
9652 end:
9653     if (src != ret && ret == INVALID_SOCKET)
9654         closesocket(src);
9655     return ret;
9656 }
9657 
9658 static void test_completion_port(void)
9659 {
9660     FILE_IO_COMPLETION_NOTIFICATION_INFORMATION io_info;
9661     HANDLE previous_port, io_port;
9662     WSAOVERLAPPED ov, *olp;
9663     SOCKET src, dest, dup, connector = INVALID_SOCKET;
9664     WSAPROTOCOL_INFOA info;
9665     IO_STATUS_BLOCK io;
9666     NTSTATUS status;
9667     char buf[1024];
9668     WSABUF bufs;
9669     DWORD num_bytes, flags;
9670     struct linger ling;
9671     int iret;
9672     BOOL bret;
9673     ULONG_PTR key;
9674     struct sockaddr_in bindAddress;
9675     GUID acceptExGuid = WSAID_ACCEPTEX;
9676     LPFN_ACCEPTEX pAcceptEx = NULL;
9677     fd_set fds_recv;
9678 
9679     memset(buf, 0, sizeof(buf));
9680     previous_port = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
9681     ok( previous_port != NULL, "Failed to create completion port %u\n", GetLastError());
9682 
9683     memset(&ov, 0, sizeof(ov));
9684 
9685     tcp_socketpair(&src, &dest);
9686     if (src == INVALID_SOCKET || dest == INVALID_SOCKET)
9687     {
9688         skip("failed to create sockets\n");
9689         goto end;
9690     }
9691 
9692     bufs.len = sizeof(buf);
9693     bufs.buf = buf;
9694     flags = 0;
9695 
9696     ling.l_onoff = 1;
9697     ling.l_linger = 0;
9698     iret = setsockopt (src, SOL_SOCKET, SO_LINGER, (char *) &ling, sizeof(ling));
9699     ok(!iret, "Failed to set linger %d\n", GetLastError());
9700 
9701     io_port = CreateIoCompletionPort( (HANDLE)dest, previous_port, 125, 0 );
9702     ok(io_port != NULL, "Failed to create completion port %u\n", GetLastError());
9703 
9704     SetLastError(0xdeadbeef);
9705 
9706     iret = WSARecv(dest, &bufs, 1, &num_bytes, &flags, &ov, NULL);
9707     ok(iret == SOCKET_ERROR, "WSARecv returned %d\n", iret);
9708     ok(GetLastError() == ERROR_IO_PENDING, "Last error was %d\n", GetLastError());
9709 
9710     Sleep(100);
9711 
9712     closesocket(src);
9713     src = INVALID_SOCKET;
9714 
9715     SetLastError(0xdeadbeef);
9716     key = 0xdeadbeef;
9717     num_bytes = 0xdeadbeef;
9718     olp = (WSAOVERLAPPED *)0xdeadbeef;
9719 
9720     bret = GetQueuedCompletionStatus(io_port, &num_bytes, &key, &olp, 100);
9721     todo_wine ok(bret == FALSE, "GetQueuedCompletionStatus returned %d\n", bret);
9722     todo_wine ok(GetLastError() == ERROR_NETNAME_DELETED, "Last error was %d\n", GetLastError());
9723     ok(key == 125, "Key is %lu\n", key);
9724     ok(num_bytes == 0, "Number of bytes received is %u\n", num_bytes);
9725     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
9726 
9727     SetLastError(0xdeadbeef);
9728     key = 0xdeadbeef;
9729     num_bytes = 0xdeadbeef;
9730     olp = (WSAOVERLAPPED *)0xdeadbeef;
9731 
9732     bret = GetQueuedCompletionStatus(io_port, &num_bytes, &key, &olp, 100);
9733     ok(bret == FALSE, "GetQueuedCompletionStatus returned %d\n", bret );
9734     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
9735     ok(key == 0xdeadbeef, "Key is %lu\n", key);
9736     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
9737     ok(!olp, "Overlapped structure is at %p\n", olp);
9738 
9739     if (dest != INVALID_SOCKET)
9740         closesocket(dest);
9741 
9742     memset(&ov, 0, sizeof(ov));
9743 
9744     tcp_socketpair(&src, &dest);
9745     if (src == INVALID_SOCKET || dest == INVALID_SOCKET)
9746     {
9747         skip("failed to create sockets\n");
9748         goto end;
9749     }
9750 
9751     bufs.len = sizeof(buf);
9752     bufs.buf = buf;
9753     flags = 0;
9754 
9755     ling.l_onoff = 1;
9756     ling.l_linger = 0;
9757     iret = setsockopt (src, SOL_SOCKET, SO_LINGER, (char *) &ling, sizeof(ling));
9758     ok(!iret, "Failed to set linger %d\n", GetLastError());
9759 
9760     io_port = CreateIoCompletionPort((HANDLE)dest, previous_port, 125, 0);
9761     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
9762 
9763     set_blocking(dest, FALSE);
9764 
9765     closesocket(src);
9766     src = INVALID_SOCKET;
9767 
9768     Sleep(100);
9769 
9770     num_bytes = 0xdeadbeef;
9771     SetLastError(0xdeadbeef);
9772 
9773     iret = WSASend(dest, &bufs, 1, &num_bytes, 0, &ov, NULL);
9774     ok(iret == SOCKET_ERROR, "WSASend failed - %d\n", iret);
9775     ok(GetLastError() == WSAECONNRESET, "Last error was %d\n", GetLastError());
9776     ok(num_bytes == 0xdeadbeef, "Managed to send %d\n", num_bytes);
9777 
9778     SetLastError(0xdeadbeef);
9779     key = 0xdeadbeef;
9780     num_bytes = 0xdeadbeef;
9781     olp = (WSAOVERLAPPED *)0xdeadbeef;
9782 
9783     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
9784     ok(bret == FALSE, "GetQueuedCompletionStatus returned %u\n", bret );
9785     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
9786     ok(key == 0xdeadbeef, "Key is %lu\n", key);
9787     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
9788     ok(!olp, "Overlapped structure is at %p\n", olp);
9789 
9790     if (dest != INVALID_SOCKET)
9791         closesocket(dest);
9792 
9793     /* Test IOCP response on successful immediate read. */
9794     tcp_socketpair(&src, &dest);
9795     if (src == INVALID_SOCKET || dest == INVALID_SOCKET)
9796     {
9797         skip("failed to create sockets\n");
9798         goto end;
9799     }
9800 
9801     bufs.len = sizeof(buf);
9802     bufs.buf = buf;
9803     flags = 0;
9804     SetLastError(0xdeadbeef);
9805 
9806     iret = WSASend(src, &bufs, 1, &num_bytes, 0, &ov, NULL);
9807     ok(!iret, "WSASend failed - %d, last error %u\n", iret, GetLastError());
9808     ok(num_bytes == sizeof(buf), "Managed to send %d\n", num_bytes);
9809 
9810     io_port = CreateIoCompletionPort((HANDLE)dest, previous_port, 125, 0);
9811     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
9812     set_blocking(dest, FALSE);
9813 
9814     FD_ZERO(&fds_recv);
9815     FD_SET(dest, &fds_recv);
9816     select(dest + 1, &fds_recv, NULL, NULL, NULL);
9817 
9818     num_bytes = 0xdeadbeef;
9819     flags = 0;
9820 
9821     iret = WSARecv(dest, &bufs, 1, &num_bytes, &flags, &ov, NULL);
9822     ok(!iret, "WSARecv failed - %d, last error %u\n", iret, GetLastError());
9823     ok(num_bytes == sizeof(buf), "Managed to read %d\n", num_bytes);
9824 
9825     SetLastError(0xdeadbeef);
9826     key = 0xdeadbeef;
9827     num_bytes = 0xdeadbeef;
9828     olp = (WSAOVERLAPPED *)0xdeadbeef;
9829 
9830     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
9831     ok(bret == TRUE, "failed to get completion status %u\n", bret);
9832     ok(GetLastError() == 0xdeadbeef, "Last error was %d\n", GetLastError());
9833     ok(key == 125, "Key is %lu\n", key);
9834     ok(num_bytes == sizeof(buf), "Number of bytes transferred is %u\n", num_bytes);
9835     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
9836 
9837     /* Test IOCP response on graceful shutdown. */
9838     closesocket(src);
9839 
9840     FD_ZERO(&fds_recv);
9841     FD_SET(dest, &fds_recv);
9842     select(dest + 1, &fds_recv, NULL, NULL, NULL);
9843 
9844     num_bytes = 0xdeadbeef;
9845     flags = 0;
9846     memset(&ov, 0, sizeof(ov));
9847 
9848     iret = WSARecv(dest, &bufs, 1, &num_bytes, &flags, &ov, NULL);
9849     ok(!iret, "WSARecv failed - %d, last error %u\n", iret, GetLastError());
9850     ok(!num_bytes, "Managed to read %d\n", num_bytes);
9851 
9852     SetLastError(0xdeadbeef);
9853     key = 0xdeadbeef;
9854     num_bytes = 0xdeadbeef;
9855     olp = (WSAOVERLAPPED *)0xdeadbeef;
9856 
9857     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
9858     ok(bret == TRUE, "failed to get completion status %u\n", bret);
9859     ok(GetLastError() == 0xdeadbeef, "Last error was %d\n", GetLastError());
9860     ok(key == 125, "Key is %lu\n", key);
9861     ok(!num_bytes, "Number of bytes transferred is %u\n", num_bytes);
9862     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
9863 
9864     closesocket(src);
9865     src = INVALID_SOCKET;
9866     closesocket(dest);
9867     dest = INVALID_SOCKET;
9868 
9869     /* Test IOCP response on hard shutdown. This was the condition that triggered
9870      * a crash in an actual app (bug 38980). */
9871     tcp_socketpair(&src, &dest);
9872     if (src == INVALID_SOCKET || dest == INVALID_SOCKET)
9873     {
9874         skip("failed to create sockets\n");
9875         goto end;
9876     }
9877 
9878     bufs.len = sizeof(buf);
9879     bufs.buf = buf;
9880     flags = 0;
9881     memset(&ov, 0, sizeof(ov));
9882 
9883     ling.l_onoff = 1;
9884     ling.l_linger = 0;
9885     iret = setsockopt (src, SOL_SOCKET, SO_LINGER, (char *) &ling, sizeof(ling));
9886     ok(!iret, "Failed to set linger %d\n", GetLastError());
9887 
9888     io_port = CreateIoCompletionPort((HANDLE)dest, previous_port, 125, 0);
9889     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
9890     set_blocking(dest, FALSE);
9891 
9892     closesocket(src);
9893     src = INVALID_SOCKET;
9894 
9895     FD_ZERO(&fds_recv);
9896     FD_SET(dest, &fds_recv);
9897     select(dest + 1, &fds_recv, NULL, NULL, NULL);
9898 
9899     num_bytes = 0xdeadbeef;
9900     SetLastError(0xdeadbeef);
9901 
9902     /* Somehow a hard shutdown doesn't work on my Linux box. It seems SO_LINGER is ignored. */
9903     iret = WSARecv(dest, &bufs, 1, &num_bytes, &flags, &ov, NULL);
9904     todo_wine ok(iret == SOCKET_ERROR, "WSARecv failed - %d\n", iret);
9905     todo_wine ok(GetLastError() == WSAECONNRESET, "Last error was %d\n", GetLastError());
9906     todo_wine ok(num_bytes == 0xdeadbeef, "Managed to read %d\n", num_bytes);
9907 
9908     SetLastError(0xdeadbeef);
9909     key = 0xdeadbeef;
9910     num_bytes = 0xdeadbeef;
9911     olp = (WSAOVERLAPPED *)0xdeadbeef;
9912 
9913     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
9914     todo_wine ok(bret == FALSE, "GetQueuedCompletionStatus returned %u\n", bret );
9915     todo_wine ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
9916     todo_wine ok(key == 0xdeadbeef, "Key is %lu\n", key);
9917     todo_wine ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
9918     todo_wine ok(!olp, "Overlapped structure is at %p\n", olp);
9919 
9920     closesocket(dest);
9921 
9922     /* Test reading from a non-connected socket, mostly because the above test is marked todo. */
9923     dest = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
9924     ok(dest != INVALID_SOCKET, "socket() failed\n");
9925 
9926     io_port = CreateIoCompletionPort((HANDLE)dest, previous_port, 125, 0);
9927     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
9928     set_blocking(dest, FALSE);
9929 
9930     num_bytes = 0xdeadbeef;
9931     SetLastError(0xdeadbeef);
9932     memset(&ov, 0, sizeof(ov));
9933 
9934     iret = WSARecv(dest, &bufs, 1, &num_bytes, &flags, &ov, NULL);
9935     ok(iret == SOCKET_ERROR, "WSARecv failed - %d\n", iret);
9936     ok(GetLastError() == WSAENOTCONN, "Last error was %d\n", GetLastError());
9937     ok(num_bytes == 0xdeadbeef, "Managed to read %d\n", num_bytes);
9938 
9939     SetLastError(0xdeadbeef);
9940     key = 0xdeadbeef;
9941     num_bytes = 0xdeadbeef;
9942     olp = (WSAOVERLAPPED *)0xdeadbeef;
9943 
9944     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
9945     ok(bret == FALSE, "GetQueuedCompletionStatus returned %u\n", bret );
9946     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
9947     ok(key == 0xdeadbeef, "Key is %lu\n", key);
9948     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
9949     ok(!olp, "Overlapped structure is at %p\n", olp);
9950 
9951     num_bytes = 0xdeadbeef;
9952     closesocket(dest);
9953 
9954     dest = socket(AF_INET, SOCK_STREAM, 0);
9955     if (dest == INVALID_SOCKET)
9956     {
9957         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
9958         goto end;
9959     }
9960 
9961     iret = WSAIoctl(dest, SIO_GET_EXTENSION_FUNCTION_POINTER, &acceptExGuid, sizeof(acceptExGuid),
9962             &pAcceptEx, sizeof(pAcceptEx), &num_bytes, NULL, NULL);
9963     if (iret)
9964     {
9965         skip("WSAIoctl failed to get AcceptEx with ret %d + errno %d\n", iret, WSAGetLastError());
9966         goto end;
9967     }
9968 
9969     /* Test IOCP response on socket close (IOCP created after AcceptEx) */
9970 
9971     if ((src = setup_iocp_src(&bindAddress)) == INVALID_SOCKET)
9972         goto end;
9973 
9974     SetLastError(0xdeadbeef);
9975 
9976     bret = pAcceptEx(src, dest, buf, sizeof(buf) - 2*(sizeof(struct sockaddr_in) + 16),
9977             sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
9978             &num_bytes, &ov);
9979     ok(bret == FALSE, "AcceptEx returned %d\n", bret);
9980     ok(GetLastError() == ERROR_IO_PENDING, "Last error was %d\n", GetLastError());
9981 
9982     io_port = CreateIoCompletionPort((HANDLE)src, previous_port, 125, 0);
9983     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
9984 
9985     closesocket(src);
9986     src = INVALID_SOCKET;
9987 
9988     SetLastError(0xdeadbeef);
9989     key = 0xdeadbeef;
9990     num_bytes = 0xdeadbeef;
9991     olp = (WSAOVERLAPPED *)0xdeadbeef;
9992 
9993     bret = GetQueuedCompletionStatus(io_port, &num_bytes, &key, &olp, 100);
9994     ok(bret == FALSE, "failed to get completion status %u\n", bret);
9995     ok(GetLastError() == ERROR_OPERATION_ABORTED, "Last error was %d\n", GetLastError());
9996     ok(key == 125, "Key is %lu\n", key);
9997     ok(num_bytes == 0, "Number of bytes transferred is %u\n", num_bytes);
9998     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
9999     ok(olp && (olp->Internal == (ULONG)STATUS_CANCELLED), "Internal status is %lx\n", olp ? olp->Internal : 0);
10000 
10001     SetLastError(0xdeadbeef);
10002     key = 0xdeadbeef;
10003     num_bytes = 0xdeadbeef;
10004     olp = (WSAOVERLAPPED *)0xdeadbeef;
10005     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
10006     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10007     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
10008     ok(key == 0xdeadbeef, "Key is %lu\n", key);
10009     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
10010     ok(!olp, "Overlapped structure is at %p\n", olp);
10011 
10012     /* Test IOCP response on socket close (IOCP created before AcceptEx) */
10013 
10014     if ((src = setup_iocp_src(&bindAddress)) == INVALID_SOCKET)
10015         goto end;
10016 
10017     SetLastError(0xdeadbeef);
10018 
10019     io_port = CreateIoCompletionPort((HANDLE)src, previous_port, 125, 0);
10020     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
10021 
10022     bret = pAcceptEx(src, dest, buf, sizeof(buf) - 2*(sizeof(struct sockaddr_in) + 16),
10023             sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
10024             &num_bytes, &ov);
10025     ok(bret == FALSE, "AcceptEx returned %d\n", bret);
10026     ok(GetLastError() == ERROR_IO_PENDING, "Last error was %d\n", GetLastError());
10027 
10028     closesocket(src);
10029     src = INVALID_SOCKET;
10030 
10031     SetLastError(0xdeadbeef);
10032     key = 0xdeadbeef;
10033     num_bytes = 0xdeadbeef;
10034     olp = (WSAOVERLAPPED *)0xdeadbeef;
10035 
10036     bret = GetQueuedCompletionStatus(io_port, &num_bytes, &key, &olp, 100);
10037     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10038     ok(GetLastError() == ERROR_OPERATION_ABORTED, "Last error was %d\n", GetLastError());
10039     ok(key == 125, "Key is %lu\n", key);
10040     ok(num_bytes == 0, "Number of bytes transferred is %u\n", num_bytes);
10041     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
10042     ok(olp && (olp->Internal == (ULONG)STATUS_CANCELLED), "Internal status is %lx\n", olp ? olp->Internal : 0);
10043 
10044     SetLastError(0xdeadbeef);
10045     key = 0xdeadbeef;
10046     num_bytes = 0xdeadbeef;
10047     olp = (WSAOVERLAPPED *)0xdeadbeef;
10048     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
10049     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10050     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
10051     ok(key == 0xdeadbeef, "Key is %lu\n", key);
10052     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
10053     ok(!olp, "Overlapped structure is at %p\n", olp);
10054 
10055     /* Test IOCP with duplicated handle */
10056 
10057     if ((src = setup_iocp_src(&bindAddress)) == INVALID_SOCKET)
10058         goto end;
10059 
10060     SetLastError(0xdeadbeef);
10061 
10062     io_port = CreateIoCompletionPort((HANDLE)src, previous_port, 125, 0);
10063     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
10064 
10065     WSADuplicateSocketA( src, GetCurrentProcessId(), &info );
10066     dup = WSASocketA(AF_INET, SOCK_STREAM, 0, &info, 0, WSA_FLAG_OVERLAPPED);
10067     ok(dup != INVALID_SOCKET, "failed to duplicate socket!\n");
10068 
10069     bret = pAcceptEx(dup, dest, buf, sizeof(buf) - 2*(sizeof(struct sockaddr_in) + 16),
10070             sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
10071             &num_bytes, &ov);
10072     ok(bret == FALSE, "AcceptEx returned %d\n", bret);
10073     ok(GetLastError() == ERROR_IO_PENDING, "Last error was %d\n", GetLastError());
10074 
10075     SetLastError(0xdeadbeef);
10076     key = 0xdeadbeef;
10077     num_bytes = 0xdeadbeef;
10078     olp = (WSAOVERLAPPED *)0xdeadbeef;
10079     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
10080     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10081     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
10082     ok(key == 0xdeadbeef, "Key is %lu\n", key);
10083     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
10084     ok(!olp, "Overlapped structure is at %p\n", olp);
10085 
10086     closesocket(src);
10087     src = INVALID_SOCKET;
10088     closesocket(dup);
10089     dup = INVALID_SOCKET;
10090 
10091     SetLastError(0xdeadbeef);
10092     key = 0xdeadbeef;
10093     num_bytes = 0xdeadbeef;
10094     olp = (WSAOVERLAPPED *)0xdeadbeef;
10095     bret = GetQueuedCompletionStatus(io_port, &num_bytes, &key, &olp, 100);
10096     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10097     ok(GetLastError() == ERROR_OPERATION_ABORTED, "Last error was %d\n", GetLastError());
10098     ok(key == 125, "Key is %lu\n", key);
10099     ok(num_bytes == 0, "Number of bytes transferred is %u\n", num_bytes);
10100     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
10101     ok(olp && olp->Internal == (ULONG)STATUS_CANCELLED, "Internal status is %lx\n", olp ? olp->Internal : 0);
10102 
10103     SetLastError(0xdeadbeef);
10104     key = 0xdeadbeef;
10105     num_bytes = 0xdeadbeef;
10106     olp = (WSAOVERLAPPED *)0xdeadbeef;
10107     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
10108     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10109     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
10110     ok(key == 0xdeadbeef, "Key is %lu\n", key);
10111     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
10112     ok(!olp, "Overlapped structure is at %p\n", olp);
10113 
10114     /* Test IOCP with duplicated handle (closing duplicated handle) */
10115 
10116     if ((src = setup_iocp_src(&bindAddress)) == INVALID_SOCKET)
10117         goto end;
10118 
10119     SetLastError(0xdeadbeef);
10120 
10121     io_port = CreateIoCompletionPort((HANDLE)src, previous_port, 125, 0);
10122     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
10123 
10124     WSADuplicateSocketA( src, GetCurrentProcessId(), &info );
10125     dup = WSASocketA(AF_INET, SOCK_STREAM, 0, &info, 0, WSA_FLAG_OVERLAPPED);
10126     ok(dup != INVALID_SOCKET, "failed to duplicate socket!\n");
10127 
10128     bret = pAcceptEx(dup, dest, buf, sizeof(buf) - 2*(sizeof(struct sockaddr_in) + 16),
10129             sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
10130             &num_bytes, &ov);
10131     ok(bret == FALSE, "AcceptEx returned %d\n", bret);
10132     ok(GetLastError() == ERROR_IO_PENDING, "Last error was %d\n", GetLastError());
10133 
10134     closesocket(dup);
10135     dup = INVALID_SOCKET;
10136 
10137     SetLastError(0xdeadbeef);
10138     key = 0xdeadbeef;
10139     num_bytes = 0xdeadbeef;
10140     olp = (WSAOVERLAPPED *)0xdeadbeef;
10141     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
10142     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10143     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
10144     ok(key == 0xdeadbeef, "Key is %lu\n", key);
10145     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
10146     ok(!olp, "Overlapped structure is at %p\n", olp);
10147 
10148     SetLastError(0xdeadbeef);
10149     key = 0xdeadbeef;
10150     num_bytes = 0xdeadbeef;
10151     olp = (WSAOVERLAPPED *)0xdeadbeef;
10152     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
10153     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10154     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
10155     ok(key == 0xdeadbeef, "Key is %lu\n", key);
10156     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
10157     ok(!olp, "Overlapped structure is at %p\n", olp);
10158 
10159     closesocket(src);
10160     src = INVALID_SOCKET;
10161 
10162     bret = GetQueuedCompletionStatus(io_port, &num_bytes, &key, &olp, 100);
10163     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10164     ok(GetLastError() == ERROR_OPERATION_ABORTED, "Last error was %d\n", GetLastError());
10165     ok(key == 125, "Key is %lu\n", key);
10166     ok(num_bytes == 0, "Number of bytes transferred is %u\n", num_bytes);
10167     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
10168     ok(olp && (olp->Internal == (ULONG)STATUS_CANCELLED), "Internal status is %lx\n", olp ? olp->Internal : 0);
10169 
10170     SetLastError(0xdeadbeef);
10171     key = 0xdeadbeef;
10172     num_bytes = 0xdeadbeef;
10173     olp = (WSAOVERLAPPED *)0xdeadbeef;
10174     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
10175     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10176     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
10177     ok(key == 0xdeadbeef, "Key is %lu\n", key);
10178     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
10179     ok(!olp, "Overlapped structure is at %p\n", olp);
10180 
10181     /* Test IOCP with duplicated handle (closing original handle) */
10182 
10183     if ((src = setup_iocp_src(&bindAddress)) == INVALID_SOCKET)
10184         goto end;
10185 
10186     SetLastError(0xdeadbeef);
10187 
10188     io_port = CreateIoCompletionPort((HANDLE)src, previous_port, 125, 0);
10189     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
10190 
10191     WSADuplicateSocketA( src, GetCurrentProcessId(), &info );
10192     dup = WSASocketA(AF_INET, SOCK_STREAM, 0, &info, 0, WSA_FLAG_OVERLAPPED);
10193     ok(dup != INVALID_SOCKET, "failed to duplicate socket!\n");
10194 
10195     bret = pAcceptEx(dup, dest, buf, sizeof(buf) - 2*(sizeof(struct sockaddr_in) + 16),
10196             sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
10197             &num_bytes, &ov);
10198     ok(bret == FALSE, "AcceptEx returned %d\n", bret);
10199     ok(GetLastError() == ERROR_IO_PENDING, "Last error was %d\n", GetLastError());
10200 
10201     closesocket(src);
10202     src = INVALID_SOCKET;
10203 
10204     SetLastError(0xdeadbeef);
10205     key = 0xdeadbeef;
10206     num_bytes = 0xdeadbeef;
10207     olp = (WSAOVERLAPPED *)0xdeadbeef;
10208     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
10209     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10210     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
10211     ok(key == 0xdeadbeef, "Key is %lu\n", key);
10212     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
10213     ok(!olp, "Overlapped structure is at %p\n", olp);
10214 
10215     closesocket(dup);
10216     dup = INVALID_SOCKET;
10217 
10218     bret = GetQueuedCompletionStatus(io_port, &num_bytes, &key, &olp, 100);
10219     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10220     ok(GetLastError() == ERROR_OPERATION_ABORTED, "Last error was %d\n", GetLastError());
10221     ok(key == 125, "Key is %lu\n", key);
10222     ok(num_bytes == 0, "Number of bytes transferred is %u\n", num_bytes);
10223     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
10224     ok(olp && (olp->Internal == (ULONG)STATUS_CANCELLED), "Internal status is %lx\n", olp ? olp->Internal : 0);
10225 
10226     SetLastError(0xdeadbeef);
10227     key = 0xdeadbeef;
10228     num_bytes = 0xdeadbeef;
10229     olp = (WSAOVERLAPPED *)0xdeadbeef;
10230     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
10231     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10232     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
10233     ok(key == 0xdeadbeef, "Key is %lu\n", key);
10234     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
10235     ok(!olp, "Overlapped structure is at %p\n", olp);
10236 
10237     /* Test IOCP without AcceptEx */
10238 
10239     if ((src = setup_iocp_src(&bindAddress)) == INVALID_SOCKET)
10240         goto end;
10241 
10242     SetLastError(0xdeadbeef);
10243 
10244     io_port = CreateIoCompletionPort((HANDLE)src, previous_port, 125, 0);
10245     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
10246 
10247     closesocket(src);
10248     src = INVALID_SOCKET;
10249 
10250     SetLastError(0xdeadbeef);
10251     key = 0xdeadbeef;
10252     num_bytes = 0xdeadbeef;
10253     olp = (WSAOVERLAPPED *)0xdeadbeef;
10254     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
10255     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10256     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
10257     ok(key == 0xdeadbeef, "Key is %lu\n", key);
10258     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
10259     ok(!olp, "Overlapped structure is at %p\n", olp);
10260 
10261     /* */
10262 
10263     if ((src = setup_iocp_src(&bindAddress)) == INVALID_SOCKET)
10264         goto end;
10265 
10266     connector = socket(AF_INET, SOCK_STREAM, 0);
10267     if (connector == INVALID_SOCKET) {
10268         skip("could not create connector socket, error %d\n", WSAGetLastError());
10269         goto end;
10270     }
10271 
10272     io_port = CreateIoCompletionPort((HANDLE)src, previous_port, 125, 0);
10273     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
10274 
10275     io_port = CreateIoCompletionPort((HANDLE)dest, previous_port, 236, 0);
10276     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
10277 
10278     bret = pAcceptEx(src, dest, buf, sizeof(buf) - 2*(sizeof(struct sockaddr_in) + 16),
10279             sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
10280             &num_bytes, &ov);
10281     ok(bret == FALSE, "AcceptEx returned %d\n", bret);
10282     ok(GetLastError() == ERROR_IO_PENDING, "Last error was %d\n", GetLastError());
10283 
10284     iret = connect(connector, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
10285     ok(iret == 0, "connecting to accepting socket failed, error %d\n", GetLastError());
10286 
10287     closesocket(connector);
10288     connector = INVALID_SOCKET;
10289 
10290     SetLastError(0xdeadbeef);
10291     key = 0xdeadbeef;
10292     num_bytes = 0xdeadbeef;
10293     olp = (WSAOVERLAPPED *)0xdeadbeef;
10294 
10295     bret = GetQueuedCompletionStatus(io_port, &num_bytes, &key, &olp, 100);
10296     ok(bret == TRUE, "failed to get completion status %u\n", bret);
10297     ok(GetLastError() == 0xdeadbeef, "Last error was %d\n", GetLastError());
10298     ok(key == 125, "Key is %lu\n", key);
10299     ok(num_bytes == 0, "Number of bytes transferred is %u\n", num_bytes);
10300     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
10301     ok(olp && (olp->Internal == (ULONG)STATUS_SUCCESS), "Internal status is %lx\n", olp ? olp->Internal : 0);
10302 
10303     SetLastError(0xdeadbeef);
10304     key = 0xdeadbeef;
10305     num_bytes = 0xdeadbeef;
10306     olp = (WSAOVERLAPPED *)0xdeadbeef;
10307     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
10308     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10309     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
10310     ok(key == 0xdeadbeef, "Key is %lu\n", key);
10311     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
10312     ok(!olp, "Overlapped structure is at %p\n", olp);
10313 
10314     if (dest != INVALID_SOCKET)
10315         closesocket(dest);
10316     if (src != INVALID_SOCKET)
10317         closesocket(dest);
10318 
10319     /* */
10320 
10321     if ((src = setup_iocp_src(&bindAddress)) == INVALID_SOCKET)
10322         goto end;
10323 
10324     dest = socket(AF_INET, SOCK_STREAM, 0);
10325     if (dest == INVALID_SOCKET)
10326     {
10327         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
10328         goto end;
10329     }
10330 
10331     connector = socket(AF_INET, SOCK_STREAM, 0);
10332     if (connector == INVALID_SOCKET) {
10333         skip("could not create connector socket, error %d\n", WSAGetLastError());
10334         goto end;
10335     }
10336 
10337     io_port = CreateIoCompletionPort((HANDLE)src, previous_port, 125, 0);
10338     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
10339 
10340     io_port = CreateIoCompletionPort((HANDLE)dest, previous_port, 236, 0);
10341     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
10342 
10343     io_info.Flags = FILE_SKIP_COMPLETION_PORT_ON_SUCCESS;
10344     status = pNtSetInformationFile((HANDLE)src, &io, &io_info, sizeof(io_info), FileIoCompletionNotificationInformation);
10345     ok(status == STATUS_SUCCESS || broken(status == STATUS_INVALID_INFO_CLASS) /* XP */,
10346        "expected STATUS_SUCCESS, got %08x\n", status);
10347 
10348     io_info.Flags = FILE_SKIP_COMPLETION_PORT_ON_SUCCESS;
10349     status = pNtSetInformationFile((HANDLE)dest, &io, &io_info, sizeof(io_info), FileIoCompletionNotificationInformation);
10350     ok(status == STATUS_SUCCESS || broken(status == STATUS_INVALID_INFO_CLASS) /* XP */,
10351        "expected STATUS_SUCCESS, got %08x\n", status);
10352 
10353     bret = pAcceptEx(src, dest, buf, sizeof(buf) - 2*(sizeof(struct sockaddr_in) + 16),
10354             sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
10355             &num_bytes, &ov);
10356     ok(bret == FALSE, "AcceptEx returned %d\n", bret);
10357     ok(GetLastError() == ERROR_IO_PENDING, "Last error was %d\n", GetLastError());
10358 
10359     iret = connect(connector, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
10360     ok(iret == 0, "connecting to accepting socket failed, error %d\n", GetLastError());
10361 
10362     iret = send(connector, buf, 1, 0);
10363     ok(iret == 1, "could not send 1 byte: send %d errno %d\n", iret, WSAGetLastError());
10364 
10365     Sleep(100);
10366 
10367     closesocket(dest);
10368     dest = INVALID_SOCKET;
10369 
10370     SetLastError(0xdeadbeef);
10371     key = 0xdeadbeef;
10372     num_bytes = 0xdeadbeef;
10373     olp = (WSAOVERLAPPED *)0xdeadbeef;
10374 
10375     bret = GetQueuedCompletionStatus(io_port, &num_bytes, &key, &olp, 100);
10376     ok(bret == TRUE, "failed to get completion status %u\n", bret);
10377     ok(GetLastError() == 0xdeadbeef, "Last error was %d\n", GetLastError());
10378     ok(key == 125, "Key is %lu\n", key);
10379     ok(num_bytes == 1, "Number of bytes transferred is %u\n", num_bytes);
10380     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
10381     ok(olp && (olp->Internal == (ULONG)STATUS_SUCCESS), "Internal status is %lx\n", olp ? olp->Internal : 0);
10382 
10383     io_info.Flags = 0;
10384     status = pNtQueryInformationFile((HANDLE)dest, &io, &io_info, sizeof(io_info), FileIoCompletionNotificationInformation);
10385     ok(status == STATUS_SUCCESS || broken(status == STATUS_INVALID_INFO_CLASS) /* XP */,
10386        "expected STATUS_SUCCESS, got %08x\n", status);
10387     if (status == STATUS_SUCCESS)
10388         ok((io_info.Flags & FILE_SKIP_COMPLETION_PORT_ON_SUCCESS) != 0, "got %08x\n", io_info.Flags);
10389 
10390     SetLastError(0xdeadbeef);
10391     key = 0xdeadbeef;
10392     num_bytes = 0xdeadbeef;
10393     olp = (WSAOVERLAPPED *)0xdeadbeef;
10394     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
10395     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10396     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
10397     ok(key == 0xdeadbeef, "Key is %lu\n", key);
10398     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
10399     ok(!olp, "Overlapped structure is at %p\n", olp);
10400 
10401     if (src != INVALID_SOCKET)
10402         closesocket(src);
10403     if (connector != INVALID_SOCKET)
10404         closesocket(connector);
10405 
10406     /* */
10407 
10408     if ((src = setup_iocp_src(&bindAddress)) == INVALID_SOCKET)
10409         goto end;
10410 
10411     dest = socket(AF_INET, SOCK_STREAM, 0);
10412     if (dest == INVALID_SOCKET)
10413     {
10414         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
10415         goto end;
10416     }
10417 
10418     connector = socket(AF_INET, SOCK_STREAM, 0);
10419     if (connector == INVALID_SOCKET) {
10420         skip("could not create connector socket, error %d\n", WSAGetLastError());
10421         goto end;
10422     }
10423 
10424     io_port = CreateIoCompletionPort((HANDLE)src, previous_port, 125, 0);
10425     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
10426 
10427     io_port = CreateIoCompletionPort((HANDLE)dest, previous_port, 236, 0);
10428     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
10429 
10430     bret = pAcceptEx(src, dest, buf, sizeof(buf) - 2*(sizeof(struct sockaddr_in) + 16),
10431             sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
10432             &num_bytes, &ov);
10433     ok(bret == FALSE, "AcceptEx returned %d\n", bret);
10434     ok(GetLastError() == ERROR_IO_PENDING, "Last error was %d\n", GetLastError());
10435 
10436     iret = connect(connector, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
10437     ok(iret == 0, "connecting to accepting socket failed, error %d\n", GetLastError());
10438 
10439     closesocket(dest);
10440     dest = INVALID_SOCKET;
10441 
10442     SetLastError(0xdeadbeef);
10443     key = 0xdeadbeef;
10444     num_bytes = 0xdeadbeef;
10445     olp = (WSAOVERLAPPED *)0xdeadbeef;
10446 
10447     bret = GetQueuedCompletionStatus(io_port, &num_bytes, &key, &olp, 100);
10448     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10449     todo_wine ok(GetLastError() == ERROR_NETNAME_DELETED ||
10450                  GetLastError() == ERROR_OPERATION_ABORTED ||
10451                  GetLastError() == ERROR_CONNECTION_ABORTED ||
10452                  GetLastError() == ERROR_PIPE_NOT_CONNECTED /* win 2000 */,
10453                  "Last error was %d\n", GetLastError());
10454     ok(key == 125, "Key is %lu\n", key);
10455     ok(num_bytes == 0, "Number of bytes transferred is %u\n", num_bytes);
10456     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
10457     todo_wine ok(olp && (olp->Internal == (ULONG)STATUS_LOCAL_DISCONNECT ||
10458                          olp->Internal == (ULONG)STATUS_CANCELLED ||
10459                          olp->Internal == (ULONG)STATUS_CONNECTION_ABORTED ||
10460                          olp->Internal == (ULONG)STATUS_PIPE_DISCONNECTED /* win 2000 */),
10461                          "Internal status is %lx\n", olp ? olp->Internal : 0);
10462 
10463     SetLastError(0xdeadbeef);
10464     key = 0xdeadbeef;
10465     num_bytes = 0xdeadbeef;
10466     olp = (WSAOVERLAPPED *)0xdeadbeef;
10467     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
10468     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10469     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
10470     ok(key == 0xdeadbeef, "Key is %lu\n", key);
10471     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
10472     ok(!olp, "Overlapped structure is at %p\n", olp);
10473 
10474 
10475     end:
10476     if (dest != INVALID_SOCKET)
10477         closesocket(dest);
10478     if (src != INVALID_SOCKET)
10479         closesocket(src);
10480     if (connector != INVALID_SOCKET)
10481         closesocket(connector);
10482     CloseHandle(previous_port);
10483 }
10484 
10485 static void test_address_list_query(void)
10486 {
10487     SOCKET_ADDRESS_LIST *address_list;
10488     DWORD bytes_returned, size;
10489     unsigned int i;
10490     SOCKET s;
10491     int ret;
10492 
10493     s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
10494     ok(s != INVALID_SOCKET, "Failed to create socket, error %d.\n", WSAGetLastError());
10495 
10496     bytes_returned = 0;
10497     ret = WSAIoctl(s, SIO_ADDRESS_LIST_QUERY, NULL, 0, NULL, 0, &bytes_returned, NULL, NULL);
10498     ok(ret == SOCKET_ERROR, "Got unexpected ret %d.\n", ret);
10499     ok(WSAGetLastError() == WSAEFAULT, "Got unexpected error %d.\n", WSAGetLastError());
10500     ok(bytes_returned >= FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]),
10501             "Got unexpected bytes_returned %u.\n", bytes_returned);
10502 
10503     size = bytes_returned;
10504     bytes_returned = 0;
10505     address_list = HeapAlloc(GetProcessHeap(), 0, size * 2);
10506     ret = WSAIoctl(s, SIO_ADDRESS_LIST_QUERY, NULL, 0, address_list, size * 2, &bytes_returned, NULL, NULL);
10507     ok(!ret, "Got unexpected ret %d, error %d.\n", ret, WSAGetLastError());
10508     ok(bytes_returned == size, "Got unexpected bytes_returned %u, expected %u.\n", bytes_returned, size);
10509 
10510     bytes_returned = FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[address_list->iAddressCount]);
10511     for (i = 0; i < address_list->iAddressCount; ++i)
10512     {
10513         bytes_returned += address_list->Address[i].iSockaddrLength;
10514     }
10515     ok(size == bytes_returned, "Got unexpected size %u, expected %u.\n", size, bytes_returned);
10516 
10517     ret = WSAIoctl(s, SIO_ADDRESS_LIST_QUERY, NULL, 0, address_list, size, NULL, NULL, NULL);
10518     ok(ret == SOCKET_ERROR, "Got unexpected ret %d.\n", ret);
10519     ok(WSAGetLastError() == WSAEFAULT, "Got unexpected error %d.\n", WSAGetLastError());
10520 
10521     bytes_returned = 0xdeadbeef;
10522     ret = WSAIoctl(s, SIO_ADDRESS_LIST_QUERY, NULL, 0, NULL, size, &bytes_returned, NULL, NULL);
10523     ok(ret == SOCKET_ERROR, "Got unexpected ret %d.\n", ret);
10524     ok(WSAGetLastError() == WSAEFAULT, "Got unexpected error %d.\n", WSAGetLastError());
10525     ok(bytes_returned == size, "Got unexpected bytes_returned %u, expected %u.\n", bytes_returned, size);
10526 
10527     ret = WSAIoctl(s, SIO_ADDRESS_LIST_QUERY, NULL, 0, address_list, 1, &bytes_returned, NULL, NULL);
10528     ok(ret == SOCKET_ERROR, "Got unexpected ret %d.\n", ret);
10529     ok(WSAGetLastError() == WSAEINVAL, "Got unexpected error %d.\n", WSAGetLastError());
10530     ok(bytes_returned == 0, "Got unexpected bytes_returned %u.\n", bytes_returned);
10531 
10532     ret = WSAIoctl(s, SIO_ADDRESS_LIST_QUERY, NULL, 0, address_list,
10533             FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]), &bytes_returned, NULL, NULL);
10534     ok(ret == SOCKET_ERROR, "Got unexpected ret %d.\n", ret);
10535     ok(WSAGetLastError() == WSAEFAULT, "Got unexpected error %d.\n", WSAGetLastError());
10536     ok(bytes_returned == size, "Got unexpected bytes_returned %u, expected %u.\n", bytes_returned, size);
10537 
10538     HeapFree(GetProcessHeap(), 0, address_list);
10539     closesocket(s);
10540 }
10541 
10542 static DWORD WINAPI inet_ntoa_thread_proc(void *param)
10543 {
10544     ULONG addr;
10545     const char *str;
10546     HANDLE *event = param;
10547 
10548     addr = inet_addr("4.3.2.1");
10549     ok(addr == htonl(0x04030201), "expected 0x04030201, got %08x\n", addr);
10550     str = inet_ntoa(*(struct in_addr *)&addr);
10551     ok(!strcmp(str, "4.3.2.1"), "expected 4.3.2.1, got %s\n", str);
10552 
10553     SetEvent(event[0]);
10554     WaitForSingleObject(event[1], 3000);
10555 
10556     return 0;
10557 }
10558 
10559 static void test_inet_ntoa(void)
10560 {
10561     ULONG addr;
10562     const char *str;
10563     HANDLE thread, event[2];
10564     DWORD tid;
10565 
10566     addr = inet_addr("1.2.3.4");
10567     ok(addr == htonl(0x01020304), "expected 0x01020304, got %08x\n", addr);
10568     str = inet_ntoa(*(struct in_addr *)&addr);
10569     ok(!strcmp(str, "1.2.3.4"), "expected 1.2.3.4, got %s\n", str);
10570 
10571     event[0] = CreateEventW(NULL, TRUE, FALSE, NULL);
10572     event[1] = CreateEventW(NULL, TRUE, FALSE, NULL);
10573 
10574     thread = CreateThread(NULL, 0, inet_ntoa_thread_proc, event, 0, &tid);
10575     WaitForSingleObject(event[0], 3000);
10576 
10577     ok(!strcmp(str, "1.2.3.4"), "expected 1.2.3.4, got %s\n", str);
10578 
10579     SetEvent(event[1]);
10580     WaitForSingleObject(thread, 3000);
10581 
10582     CloseHandle(event[0]);
10583     CloseHandle(event[1]);
10584     CloseHandle(thread);
10585 }
10586 
10587 static void test_WSALookupService(void)
10588 {
10589     char buffer[4096], strbuff[128];
10590     WSAQUERYSETW *qs = NULL;
10591     HANDLE hnd;
10592     PNLA_BLOB netdata;
10593     int ret;
10594     DWORD error, offset, bsize;
10595 
10596     if (!pWSALookupServiceBeginW || !pWSALookupServiceEnd || !pWSALookupServiceNextW)
10597     {
10598         win_skip("WSALookupServiceBeginW or WSALookupServiceEnd or WSALookupServiceNextW not found\n");
10599         return;
10600     }
10601 
10602     qs = (WSAQUERYSETW *)buffer;
10603     memset(qs, 0, sizeof(*qs));
10604 
10605     /* invalid parameter tests */
10606     ret = pWSALookupServiceBeginW(NULL, 0, &hnd);
10607     error = WSAGetLastError();
10608     ok(ret == SOCKET_ERROR, "WSALookupServiceBeginW should have failed\n");
10609 todo_wine
10610     ok(error == WSAEFAULT, "expected 10014, got %d\n", error);
10611 
10612     ret = pWSALookupServiceBeginW(qs, 0, NULL);
10613     error = WSAGetLastError();
10614     ok(ret == SOCKET_ERROR, "WSALookupServiceBeginW should have failed\n");
10615 todo_wine
10616     ok(error == WSAEFAULT, "expected 10014, got %d\n", error);
10617 
10618     ret = pWSALookupServiceBeginW(qs, 0, &hnd);
10619     error = WSAGetLastError();
10620     ok(ret == SOCKET_ERROR, "WSALookupServiceBeginW should have failed\n");
10621 todo_wine
10622     ok(error == WSAEINVAL
10623        || broken(error == ERROR_INVALID_PARAMETER) /* == XP */
10624        || broken(error == WSAEFAULT) /* == NT */
10625        || broken(error == WSASERVICE_NOT_FOUND) /* == 2000 */,
10626        "expected 10022, got %d\n", error);
10627 
10628     ret = pWSALookupServiceEnd(NULL);
10629     error = WSAGetLastError();
10630 todo_wine
10631     ok(ret == SOCKET_ERROR, "WSALookupServiceEnd should have failed\n");
10632 todo_wine
10633     ok(error == ERROR_INVALID_HANDLE, "expected 6, got %d\n", error);
10634 
10635     /* standard network list query */
10636     qs->dwSize = sizeof(*qs);
10637     hnd = (HANDLE)0xdeadbeef;
10638     ret = pWSALookupServiceBeginW(qs, LUP_RETURN_ALL | LUP_DEEP, &hnd);
10639     error = WSAGetLastError();
10640     if(ret && error == ERROR_INVALID_PARAMETER)
10641     {
10642         win_skip("the current WSALookupServiceBeginW test is not supported in win <= 2000\n");
10643         return;
10644     }
10645 
10646 todo_wine
10647     ok(!ret, "WSALookupServiceBeginW failed unexpectedly with error %d\n", error);
10648 todo_wine
10649     ok(hnd != (HANDLE)0xdeadbeef, "Handle was not filled\n");
10650 
10651     offset = 0;
10652     do
10653     {
10654         memset(qs, 0, sizeof(*qs));
10655         bsize = sizeof(buffer);
10656 
10657         if (pWSALookupServiceNextW(hnd, 0, &bsize, qs) == SOCKET_ERROR)
10658         {
10659             error = WSAGetLastError();
10660             if (error == WSA_E_NO_MORE) break;
10661             ok(0, "Error %d happened while listing services\n", error);
10662             break;
10663         }
10664 
10665         WideCharToMultiByte(CP_ACP, 0, qs->lpszServiceInstanceName, -1,
10666                             strbuff, sizeof(strbuff), NULL, NULL);
10667         trace("Network Name: %s\n", strbuff);
10668 
10669         /* network data is written in the blob field */
10670         if (qs->lpBlob)
10671         {
10672             /* each network may have multiple NLA_BLOB information structures */
10673             do
10674             {
10675                 netdata = (PNLA_BLOB) &qs->lpBlob->pBlobData[offset];
10676                 switch (netdata->header.type)
10677                 {
10678                     case NLA_RAW_DATA:
10679                         trace("\tNLA Data Type: NLA_RAW_DATA\n");
10680                         break;
10681                     case NLA_INTERFACE:
10682                         trace("\tNLA Data Type: NLA_INTERFACE\n");
10683                         trace("\t\tType: %d\n", netdata->data.interfaceData.dwType);
10684                         trace("\t\tSpeed: %d\n", netdata->data.interfaceData.dwSpeed);
10685                         trace("\t\tAdapter Name: %s\n", netdata->data.interfaceData.adapterName);
10686                         break;
10687                     case NLA_802_1X_LOCATION:
10688                         trace("\tNLA Data Type: NLA_802_1X_LOCATION\n");
10689                         trace("\t\tInformation: %s\n", netdata->data.locationData.information);
10690                         break;
10691                     case NLA_CONNECTIVITY:
10692                         switch (netdata->data.connectivity.type)
10693                         {
10694                             case NLA_NETWORK_AD_HOC:
10695                                 trace("\t\tNetwork Type: AD HOC\n");
10696                                 break;
10697                             case NLA_NETWORK_MANAGED:
10698                                 trace("\t\tNetwork Type: Managed\n");
10699                                 break;
10700                             case NLA_NETWORK_UNMANAGED:
10701                                 trace("\t\tNetwork Type: Unmanaged\n");
10702                                 break;
10703                             case NLA_NETWORK_UNKNOWN:
10704                                 trace("\t\tNetwork Type: Unknown\n");
10705                         }
10706                         switch (netdata->data.connectivity.internet)
10707                         {
10708                             case NLA_INTERNET_NO:
10709                                 trace("\t\tInternet connectivity: No\n");
10710                                 break;
10711                             case NLA_INTERNET_YES:
10712                                 trace("\t\tInternet connectivity: Yes\n");
10713                                 break;
10714                             case NLA_INTERNET_UNKNOWN:
10715                                 trace("\t\tInternet connectivity: Unknown\n");
10716                                 break;
10717                         }
10718                         break;
10719                     case NLA_ICS:
10720                         trace("\tNLA Data Type: NLA_ICS\n");
10721                         trace("\t\tSpeed: %d\n",
10722                                netdata->data.ICS.remote.speed);
10723                         trace("\t\tType: %d\n",
10724                                netdata->data.ICS.remote.type);
10725                         trace("\t\tState: %d\n",
10726                                netdata->data.ICS.remote.state);
10727                         WideCharToMultiByte(CP_ACP, 0, netdata->data.ICS.remote.machineName, -1,
10728                             strbuff, sizeof(strbuff), NULL, NULL);
10729                         trace("\t\tMachine Name: %s\n", strbuff);
10730                         WideCharToMultiByte(CP_ACP, 0, netdata->data.ICS.remote.sharedAdapterName, -1,
10731                             strbuff, sizeof(strbuff), NULL, NULL);
10732                         trace("\t\tShared Adapter Name: %s\n", strbuff);
10733                         break;
10734                     default:
10735                         trace("\tNLA Data Type: Unknown\n");
10736                         break;
10737                 }
10738             }
10739             while (offset);
10740         }
10741     }
10742     while (1);
10743 
10744     ret = pWSALookupServiceEnd(hnd);
10745     ok(!ret, "WSALookupServiceEnd failed unexpectedly\n");
10746 }
10747 
10748 static void test_WSAEnumNameSpaceProvidersA(void)
10749 {
10750     LPWSANAMESPACE_INFOA name = NULL;
10751     DWORD ret, error, blen = 0, i;
10752     if (!pWSAEnumNameSpaceProvidersA)
10753     {
10754         win_skip("WSAEnumNameSpaceProvidersA not found\n");
10755         return;
10756     }
10757 
10758     SetLastError(0xdeadbeef);
10759     ret = pWSAEnumNameSpaceProvidersA(&blen, name);
10760     error = WSAGetLastError();
10761 todo_wine
10762     ok(ret == SOCKET_ERROR, "Expected failure, got %u\n", ret);
10763 todo_wine
10764     ok(error == WSAEFAULT, "Expected 10014, got %u\n", error);
10765 
10766     /* Invalid parameter tests */
10767     SetLastError(0xdeadbeef);
10768     ret = pWSAEnumNameSpaceProvidersA(NULL, name);
10769     error = WSAGetLastError();
10770 todo_wine
10771     ok(ret == SOCKET_ERROR, "Expected failure, got %u\n", ret);
10772 todo_wine
10773     ok(error == WSAEFAULT, "Expected 10014, got %u\n", error);
10774 
10775     SetLastError(0xdeadbeef);
10776     ret = pWSAEnumNameSpaceProvidersA(NULL, NULL);
10777     error = WSAGetLastError();
10778 todo_wine
10779     ok(ret == SOCKET_ERROR, "Expected failure, got %u\n", ret);
10780 todo_wine
10781     ok(error == WSAEFAULT, "Expected 10014, got %u\n", error);
10782 
10783     SetLastError(0xdeadbeef);
10784     ret = pWSAEnumNameSpaceProvidersA(&blen, NULL);
10785     error = WSAGetLastError();
10786 todo_wine
10787     ok(ret == SOCKET_ERROR, "Expected failure, got %u\n", ret);
10788 todo_wine
10789     ok(error == WSAEFAULT, "Expected 10014, got %u\n", error);
10790 
10791 #ifdef __REACTOS__ /* ROSTESTS-233 */
10792     if (!blen)
10793     {
10794         skip("Failed to get length needed for name space providers.\n");
10795         return;
10796     }
10797 #endif
10798 
10799     name = HeapAlloc(GetProcessHeap(), 0, blen);
10800     if (!name)
10801     {
10802         skip("Failed to alloc memory\n");
10803         return;
10804     }
10805 
10806     ret = pWSAEnumNameSpaceProvidersA(&blen, name);
10807 todo_wine
10808     ok(ret > 0, "Expected more than zero name space providers\n");
10809 
10810     for (i = 0;i < ret; i++)
10811     {
10812         trace("Name space Identifier (%p): %s\n", name[i].lpszIdentifier,
10813               name[i].lpszIdentifier);
10814         switch (name[i].dwNameSpace)
10815         {
10816             case NS_DNS:
10817                 trace("\tName space ID: NS_DNS (%u)\n", name[i].dwNameSpace);
10818                 break;
10819             case NS_NLA:
10820                 trace("\tName space ID: NS_NLA (%u)\n", name[i].dwNameSpace);
10821                 break;
10822             default:
10823                 trace("\tName space ID: Unknown (%u)\n", name[i].dwNameSpace);
10824                 break;
10825         }
10826         trace("\tActive:  %d\n", name[i].fActive);
10827         trace("\tVersion: %d\n", name[i].dwVersion);
10828     }
10829 
10830     HeapFree(GetProcessHeap(), 0, name);
10831 }
10832 
10833 static void test_WSAEnumNameSpaceProvidersW(void)
10834 {
10835     LPWSANAMESPACE_INFOW name = NULL;
10836     DWORD ret, error, blen = 0, i;
10837     if (!pWSAEnumNameSpaceProvidersW)
10838     {
10839         win_skip("WSAEnumNameSpaceProvidersW not found\n");
10840         return;
10841     }
10842 
10843     SetLastError(0xdeadbeef);
10844     ret = pWSAEnumNameSpaceProvidersW(&blen, name);
10845     error = WSAGetLastError();
10846 todo_wine
10847     ok(ret == SOCKET_ERROR, "Expected failure, got %u\n", ret);
10848 todo_wine
10849     ok(error == WSAEFAULT, "Expected 10014, got %u\n", error);
10850 
10851     /* Invalid parameter tests */
10852     SetLastError(0xdeadbeef);
10853     ret = pWSAEnumNameSpaceProvidersW(NULL, name);
10854     error = WSAGetLastError();
10855 todo_wine
10856     ok(ret == SOCKET_ERROR, "Expected failure, got %u\n", ret);
10857 todo_wine
10858     ok(error == WSAEFAULT, "Expected 10014, got %u\n", error);
10859 
10860     SetLastError(0xdeadbeef);
10861     ret = pWSAEnumNameSpaceProvidersW(NULL, NULL);
10862     error = WSAGetLastError();
10863 todo_wine
10864     ok(ret == SOCKET_ERROR, "Expected failure, got %u\n", ret);
10865 todo_wine
10866     ok(error == WSAEFAULT, "Expected 10014, got %u\n", error);
10867 
10868     SetLastError(0xdeadbeef);
10869     ret = pWSAEnumNameSpaceProvidersW(&blen, NULL);
10870     error = WSAGetLastError();
10871 todo_wine
10872     ok(ret == SOCKET_ERROR, "Expected failure, got %u\n", ret);
10873 todo_wine
10874     ok(error == WSAEFAULT, "Expected 10014, got %u\n", error);
10875 
10876 #ifdef __REACTOS__ /* ROSTESTS-233 */
10877     if (!blen)
10878     {
10879         skip("Failed to get length needed for name space providers.\n");
10880         return;
10881     }
10882 #endif
10883 
10884     name = HeapAlloc(GetProcessHeap(), 0, blen);
10885     if (!name)
10886     {
10887         skip("Failed to alloc memory\n");
10888         return;
10889     }
10890 
10891     ret = pWSAEnumNameSpaceProvidersW(&blen, name);
10892 todo_wine
10893     ok(ret > 0, "Expected more than zero name space providers\n");
10894 
10895     for (i = 0;i < ret; i++)
10896     {
10897         trace("Name space Identifier (%p): %s\n", name[i].lpszIdentifier,
10898                wine_dbgstr_w(name[i].lpszIdentifier));
10899         switch (name[i].dwNameSpace)
10900         {
10901             case NS_DNS:
10902                 trace("\tName space ID: NS_DNS (%u)\n", name[i].dwNameSpace);
10903                 break;
10904             case NS_NLA:
10905                 trace("\tName space ID: NS_NLA (%u)\n", name[i].dwNameSpace);
10906                 break;
10907             default:
10908                 trace("\tName space ID: Unknown (%u)\n", name[i].dwNameSpace);
10909                 break;
10910         }
10911         trace("\tActive:  %d\n", name[i].fActive);
10912         trace("\tVersion: %d\n", name[i].dwVersion);
10913     }
10914 
10915     HeapFree(GetProcessHeap(), 0, name);
10916 }
10917 
10918 static void sync_read(SOCKET src, SOCKET dst)
10919 {
10920     int ret;
10921     char data[512];
10922 
10923     ret = send(dst, "Hello World!", 12, 0);
10924     ok(ret == 12, "send returned %d\n", ret);
10925 
10926     memset(data, 0, sizeof(data));
10927     ret = recv(src, data, sizeof(data), 0);
10928     ok(ret == 12, "expected 12, got %d\n", ret);
10929     ok(!memcmp(data, "Hello World!", 12), "got %u bytes (%*s)\n", ret, ret, data);
10930 }
10931 
10932 static void iocp_async_read(SOCKET src, SOCKET dst)
10933 {
10934     HANDLE port;
10935     WSAOVERLAPPED ovl, *ovl_iocp;
10936     WSABUF buf;
10937     int ret;
10938     char data[512];
10939     DWORD flags, bytes;
10940     ULONG_PTR key;
10941 
10942     memset(data, 0, sizeof(data));
10943     memset(&ovl, 0, sizeof(ovl));
10944 
10945     port = CreateIoCompletionPort((HANDLE)src, 0, 0x12345678, 0);
10946     ok(port != 0, "CreateIoCompletionPort error %u\n", GetLastError());
10947 
10948     buf.len = sizeof(data);
10949     buf.buf = data;
10950     bytes = 0xdeadbeef;
10951     flags = 0;
10952     SetLastError(0xdeadbeef);
10953     ret = WSARecv(src, &buf, 1, &bytes, &flags, &ovl, NULL);
10954     ok(ret == SOCKET_ERROR, "got %d\n", ret);
10955     ok(GetLastError() == ERROR_IO_PENDING, "got %u\n", GetLastError());
10956     ok(bytes == 0xdeadbeef, "got bytes %u\n", bytes);
10957 
10958     bytes = 0xdeadbeef;
10959     key = 0xdeadbeef;
10960     ovl_iocp = (void *)0xdeadbeef;
10961     SetLastError(0xdeadbeef);
10962     ret = GetQueuedCompletionStatus(port, &bytes, &key, &ovl_iocp, 100);
10963     ok(!ret, "got %d\n", ret);
10964     ok(GetLastError() == WAIT_TIMEOUT, "got %u\n", GetLastError());
10965     ok(bytes == 0xdeadbeef, "got bytes %u\n", bytes);
10966     ok(key == 0xdeadbeef, "got key %#lx\n", key);
10967     ok(!ovl_iocp, "got ovl %p\n", ovl_iocp);
10968 
10969     ret = send(dst, "Hello World!", 12, 0);
10970     ok(ret == 12, "send returned %d\n", ret);
10971 
10972     bytes = 0xdeadbeef;
10973     key = 0xdeadbeef;
10974     ovl_iocp = NULL;
10975     SetLastError(0xdeadbeef);
10976     ret = GetQueuedCompletionStatus(port, &bytes, &key, &ovl_iocp, 100);
10977     ok(ret, "got %d\n", ret);
10978     ok(bytes == 12, "got bytes %u\n", bytes);
10979     ok(key == 0x12345678, "got key %#lx\n", key);
10980     ok(ovl_iocp == &ovl, "got ovl %p\n", ovl_iocp);
10981     if (ovl_iocp)
10982     {
10983         ok(ovl_iocp->InternalHigh == 12, "got %#lx\n", ovl_iocp->InternalHigh);
10984         ok(!ovl_iocp->Internal , "got %#lx\n", ovl_iocp->Internal);
10985         ok(!memcmp(data, "Hello World!", 12), "got %u bytes (%*s)\n", bytes, bytes, data);
10986     }
10987 
10988     bytes = 0xdeadbeef;
10989     key = 0xdeadbeef;
10990     ovl_iocp = (void *)0xdeadbeef;
10991     SetLastError(0xdeadbeef);
10992     ret = GetQueuedCompletionStatus(port, &bytes, &key, &ovl_iocp, 100);
10993     ok(!ret, "got %d\n", ret);
10994     ok(GetLastError() == WAIT_TIMEOUT, "got %u\n", GetLastError());
10995     ok(bytes == 0xdeadbeef, "got bytes %u\n", bytes);
10996     ok(key == 0xdeadbeef, "got key %#lx\n", key);
10997     ok(!ovl_iocp, "got ovl %p\n", ovl_iocp);
10998 
10999     CloseHandle(port);
11000 }
11001 
11002 static void iocp_async_read_closesocket(SOCKET src, int how_to_close)
11003 {
11004     HANDLE port;
11005     WSAOVERLAPPED ovl, *ovl_iocp;
11006     WSABUF buf;
11007     int ret;
11008     char data[512];
11009     DWORD flags, bytes;
11010     ULONG_PTR key;
11011     HWND hwnd;
11012     MSG msg;
11013 
11014     hwnd = CreateWindowExA(0, "static", NULL, WS_POPUP,
11015                            0, 0, 0, 0, NULL, NULL, 0, NULL);
11016     ok(hwnd != 0, "CreateWindowEx failed\n");
11017 
11018     ret = WSAAsyncSelect(src, hwnd, WM_SOCKET, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE);
11019     ok(!ret, "got %d\n", ret);
11020 
11021     Sleep(100);
11022     memset(&msg, 0, sizeof(msg));
11023     ret = PeekMessageA(&msg, hwnd, WM_SOCKET, WM_SOCKET, PM_REMOVE);
11024     ok(ret, "got %d\n", ret);
11025     ok(msg.hwnd == hwnd, "got %p\n", msg.hwnd);
11026     ok(msg.message == WM_SOCKET, "got %04x\n", msg.message);
11027     ok(msg.wParam == src, "got %08lx\n", msg.wParam);
11028     ok(msg.lParam == 2, "got %08lx\n", msg.lParam);
11029 
11030     memset(data, 0, sizeof(data));
11031     memset(&ovl, 0, sizeof(ovl));
11032 
11033     port = CreateIoCompletionPort((HANDLE)src, 0, 0x12345678, 0);
11034     ok(port != 0, "CreateIoCompletionPort error %u\n", GetLastError());
11035 
11036     Sleep(100);
11037     ret = PeekMessageA(&msg, hwnd, WM_SOCKET, WM_SOCKET, PM_REMOVE);
11038     ok(!ret, "got %04x,%08lx,%08lx\n", msg.message, msg.wParam, msg.lParam);
11039 
11040     buf.len = sizeof(data);
11041     buf.buf = data;
11042     bytes = 0xdeadbeef;
11043     flags = 0;
11044     SetLastError(0xdeadbeef);
11045     ret = WSARecv(src, &buf, 1, &bytes, &flags, &ovl, NULL);
11046     ok(ret == SOCKET_ERROR, "got %d\n", ret);
11047     ok(GetLastError() == ERROR_IO_PENDING, "got %u\n", GetLastError());
11048     ok(bytes == 0xdeadbeef, "got bytes %u\n", bytes);
11049 
11050     Sleep(100);
11051     ret = PeekMessageA(&msg, hwnd, WM_SOCKET, WM_SOCKET, PM_REMOVE);
11052     ok(!ret, "got %04x,%08lx,%08lx\n", msg.message, msg.wParam, msg.lParam);
11053 
11054     bytes = 0xdeadbeef;
11055     key = 0xdeadbeef;
11056     ovl_iocp = (void *)0xdeadbeef;
11057     SetLastError(0xdeadbeef);
11058     ret = GetQueuedCompletionStatus(port, &bytes, &key, &ovl_iocp, 100);
11059     ok(!ret, "got %d\n", ret);
11060     ok(GetLastError() == WAIT_TIMEOUT, "got %u\n", GetLastError());
11061     ok(bytes == 0xdeadbeef, "got bytes %u\n", bytes);
11062     ok(key == 0xdeadbeef, "got key %#lx\n", key);
11063     ok(!ovl_iocp, "got ovl %p\n", ovl_iocp);
11064 
11065     Sleep(100);
11066     ret = PeekMessageA(&msg, hwnd, WM_SOCKET, WM_SOCKET, PM_REMOVE);
11067     ok(!ret, "got %04x,%08lx,%08lx\n", msg.message, msg.wParam, msg.lParam);
11068 
11069     switch (how_to_close)
11070     {
11071     case 0:
11072         closesocket(src);
11073         break;
11074     case 1:
11075         CloseHandle((HANDLE)src);
11076         break;
11077     case 2:
11078         pNtClose((HANDLE)src);
11079         break;
11080     default:
11081         ok(0, "wrong value %d\n", how_to_close);
11082         break;
11083     }
11084 
11085     Sleep(200);
11086     memset(&msg, 0, sizeof(msg));
11087     ret = PeekMessageA(&msg, hwnd, WM_SOCKET, WM_SOCKET, PM_REMOVE);
11088     switch (how_to_close)
11089     {
11090     case 0:
11091         ok(!ret, "got %04x,%08lx,%08lx\n", msg.message, msg.wParam, msg.lParam);
11092         break;
11093     case 1:
11094     case 2:
11095 todo_wine
11096 {
11097         ok(ret, "got %d\n", ret);
11098         ok(msg.hwnd == hwnd, "got %p\n", msg.hwnd);
11099         ok(msg.message == WM_SOCKET, "got %04x\n", msg.message);
11100         ok(msg.wParam == src, "got %08lx\n", msg.wParam);
11101         ok(msg.lParam == 0x20, "got %08lx\n", msg.lParam);
11102 }
11103         break;
11104     default:
11105         ok(0, "wrong value %d\n", how_to_close);
11106         break;
11107     }
11108 
11109     bytes = 0xdeadbeef;
11110     key = 0xdeadbeef;
11111     ovl_iocp = NULL;
11112     SetLastError(0xdeadbeef);
11113     ret = GetQueuedCompletionStatus(port, &bytes, &key, &ovl_iocp, 100);
11114     ok(!ret, "got %d\n", ret);
11115 todo_wine
11116     ok(GetLastError() == ERROR_CONNECTION_ABORTED || GetLastError() == ERROR_NETNAME_DELETED /* XP */, "got %u\n", GetLastError());
11117     ok(!bytes, "got bytes %u\n", bytes);
11118     ok(key == 0x12345678, "got key %#lx\n", key);
11119     ok(ovl_iocp == &ovl, "got ovl %p\n", ovl_iocp);
11120     if (ovl_iocp)
11121     {
11122         ok(!ovl_iocp->InternalHigh, "got %#lx\n", ovl_iocp->InternalHigh);
11123 todo_wine
11124         ok(ovl_iocp->Internal == (ULONG)STATUS_CONNECTION_ABORTED || ovl_iocp->Internal == (ULONG)STATUS_LOCAL_DISCONNECT /* XP */, "got %#lx\n", ovl_iocp->Internal);
11125     }
11126 
11127     bytes = 0xdeadbeef;
11128     key = 0xdeadbeef;
11129     ovl_iocp = (void *)0xdeadbeef;
11130     SetLastError(0xdeadbeef);
11131     ret = GetQueuedCompletionStatus(port, &bytes, &key, &ovl_iocp, 100);
11132     ok(!ret, "got %d\n", ret);
11133     ok(GetLastError() == WAIT_TIMEOUT, "got %u\n", GetLastError());
11134     ok(bytes == 0xdeadbeef, "got bytes %u\n", bytes);
11135     ok(key == 0xdeadbeef, "got key %#lx\n", key);
11136     ok(!ovl_iocp, "got ovl %p\n", ovl_iocp);
11137 
11138     CloseHandle(port);
11139 
11140     DestroyWindow(hwnd);
11141 }
11142 
11143 static void iocp_async_closesocket(SOCKET src)
11144 {
11145     HANDLE port;
11146     WSAOVERLAPPED *ovl_iocp;
11147     int ret;
11148     DWORD bytes;
11149     ULONG_PTR key;
11150     HWND hwnd;
11151     MSG msg;
11152 
11153     hwnd = CreateWindowExA(0, "static", NULL, WS_POPUP,
11154                            0, 0, 0, 0, NULL, NULL, 0, NULL);
11155     ok(hwnd != 0, "CreateWindowEx failed\n");
11156 
11157     ret = WSAAsyncSelect(src, hwnd, WM_SOCKET, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE);
11158     ok(!ret, "got %d\n", ret);
11159 
11160     Sleep(100);
11161     memset(&msg, 0, sizeof(msg));
11162     ret = PeekMessageA(&msg, hwnd, WM_SOCKET, WM_SOCKET, PM_REMOVE);
11163     ok(ret, "got %d\n", ret);
11164     ok(msg.hwnd == hwnd, "got %p\n", msg.hwnd);
11165     ok(msg.message == WM_SOCKET, "got %04x\n", msg.message);
11166     ok(msg.wParam == src, "got %08lx\n", msg.wParam);
11167     ok(msg.lParam == 2, "got %08lx\n", msg.lParam);
11168 
11169     port = CreateIoCompletionPort((HANDLE)src, 0, 0x12345678, 0);
11170     ok(port != 0, "CreateIoCompletionPort error %u\n", GetLastError());
11171 
11172     Sleep(100);
11173     ret = PeekMessageA(&msg, hwnd, WM_SOCKET, WM_SOCKET, PM_REMOVE);
11174     ok(!ret, "got %04x,%08lx,%08lx\n", msg.message, msg.wParam, msg.lParam);
11175 
11176     bytes = 0xdeadbeef;
11177     key = 0xdeadbeef;
11178     ovl_iocp = (void *)0xdeadbeef;
11179     SetLastError(0xdeadbeef);
11180     ret = GetQueuedCompletionStatus(port, &bytes, &key, &ovl_iocp, 100);
11181     ok(!ret, "got %d\n", ret);
11182     ok(GetLastError() == WAIT_TIMEOUT, "got %u\n", GetLastError());
11183     ok(bytes == 0xdeadbeef, "got bytes %u\n", bytes);
11184     ok(key == 0xdeadbeef, "got key %lu\n", key);
11185     ok(!ovl_iocp, "got ovl %p\n", ovl_iocp);
11186 
11187     Sleep(100);
11188     ret = PeekMessageA(&msg, hwnd, WM_SOCKET, WM_SOCKET, PM_REMOVE);
11189     ok(!ret, "got %04x,%08lx,%08lx\n", msg.message, msg.wParam, msg.lParam);
11190 
11191     closesocket(src);
11192 
11193     Sleep(100);
11194     memset(&msg, 0, sizeof(msg));
11195     ret = PeekMessageA(&msg, hwnd, WM_SOCKET, WM_SOCKET, PM_REMOVE);
11196     ok(!ret, "got %04x,%08lx,%08lx\n", msg.message, msg.wParam, msg.lParam);
11197 
11198     bytes = 0xdeadbeef;
11199     key = 0xdeadbeef;
11200     ovl_iocp = (void *)0xdeadbeef;
11201     SetLastError(0xdeadbeef);
11202     ret = GetQueuedCompletionStatus(port, &bytes, &key, &ovl_iocp, 100);
11203     ok(!ret, "got %d\n", ret);
11204     ok(GetLastError() == WAIT_TIMEOUT, "got %u\n", GetLastError());
11205     ok(bytes == 0xdeadbeef, "got bytes %u\n", bytes);
11206     ok(key == 0xdeadbeef, "got key %lu\n", key);
11207     ok(!ovl_iocp, "got ovl %p\n", ovl_iocp);
11208 
11209     CloseHandle(port);
11210 
11211     DestroyWindow(hwnd);
11212 }
11213 
11214 struct wsa_async_select_info
11215 {
11216     SOCKET sock;
11217     HWND hwnd;
11218 };
11219 
11220 static DWORD WINAPI wsa_async_select_thread(void *param)
11221 {
11222     struct wsa_async_select_info *info = param;
11223     int ret;
11224 
11225     ret = WSAAsyncSelect(info->sock, info->hwnd, WM_SOCKET, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE);
11226     ok(!ret, "got %d\n", ret);
11227 
11228     return 0;
11229 }
11230 
11231 struct wsa_recv_info
11232 {
11233     SOCKET sock;
11234     WSABUF wsa_buf;
11235     WSAOVERLAPPED ovl;
11236 };
11237 
11238 static DWORD WINAPI wsa_recv_thread(void *param)
11239 {
11240     struct wsa_recv_info *info = param;
11241     int ret;
11242     DWORD flags, bytes;
11243 
11244     bytes = 0xdeadbeef;
11245     flags = 0;
11246     SetLastError(0xdeadbeef);
11247     ret = WSARecv(info->sock, &info->wsa_buf, 1, &bytes, &flags, &info->ovl, NULL);
11248     ok(ret == SOCKET_ERROR, "got %d\n", ret);
11249     ok(GetLastError() == ERROR_IO_PENDING, "got %u\n", GetLastError());
11250     ok(bytes == 0xdeadbeef, "got bytes %u\n", bytes);
11251 
11252     return 0;
11253 }
11254 
11255 static void iocp_async_read_thread_closesocket(SOCKET src)
11256 {
11257     struct wsa_async_select_info select_info;
11258     struct wsa_recv_info recv_info;
11259     HANDLE port, thread;
11260     WSAOVERLAPPED *ovl_iocp;
11261     int ret;
11262     char data[512];
11263     DWORD bytes, tid;
11264     ULONG_PTR key;
11265     HWND hwnd;
11266     MSG msg;
11267 
11268     hwnd = CreateWindowExA(0, "static", NULL, WS_POPUP,
11269                            0, 0, 0, 0, NULL, NULL, 0, NULL);
11270     ok(hwnd != 0, "CreateWindowEx failed\n");
11271 
11272     select_info.sock = src;
11273     select_info.hwnd = hwnd;
11274     thread = CreateThread(NULL, 0, wsa_async_select_thread, &select_info, 0, &tid);
11275     ok(thread != 0, "CreateThread error %u\n", GetLastError());
11276     ret = WaitForSingleObject(thread, 10000);
11277     ok(ret == WAIT_OBJECT_0, "thread failed to terminate\n");
11278 
11279     Sleep(100);
11280     memset(&msg, 0, sizeof(msg));
11281     ret = PeekMessageA(&msg, hwnd, WM_SOCKET, WM_SOCKET, PM_REMOVE);
11282     ok(ret, "got %d\n", ret);
11283     ok(msg.hwnd == hwnd, "got %p\n", msg.hwnd);
11284     ok(msg.message == WM_SOCKET, "got %04x\n", msg.message);
11285     ok(msg.wParam == src, "got %08lx\n", msg.wParam);
11286     ok(msg.lParam == 2, "got %08lx\n", msg.lParam);
11287 
11288     port = CreateIoCompletionPort((HANDLE)src, 0, 0x12345678, 0);
11289     ok(port != 0, "CreateIoCompletionPort error %u\n", GetLastError());
11290 
11291     Sleep(100);
11292     ret = PeekMessageA(&msg, hwnd, WM_SOCKET, WM_SOCKET, PM_REMOVE);
11293     ok(!ret, "got %04x,%08lx,%08lx\n", msg.message, msg.wParam, msg.lParam);
11294 
11295     memset(data, 0, sizeof(data));
11296     memset(&recv_info.ovl, 0, sizeof(recv_info.ovl));
11297     recv_info.sock = src;
11298     recv_info.wsa_buf.len = sizeof(data);
11299     recv_info.wsa_buf.buf = data;
11300     thread = CreateThread(NULL, 0, wsa_recv_thread, &recv_info, 0, &tid);
11301     ok(thread != 0, "CreateThread error %u\n", GetLastError());
11302     ret = WaitForSingleObject(thread, 10000);
11303     ok(ret == WAIT_OBJECT_0, "thread failed to terminate\n");
11304 
11305     Sleep(100);
11306     ret = PeekMessageA(&msg, hwnd, WM_SOCKET, WM_SOCKET, PM_REMOVE);
11307     ok(!ret, "got %04x,%08lx,%08lx\n", msg.message, msg.wParam, msg.lParam);
11308 
11309     bytes = 0xdeadbeef;
11310     key = 0xdeadbeef;
11311     ovl_iocp = (void *)0xdeadbeef;
11312     SetLastError(0xdeadbeef);
11313     ret = GetQueuedCompletionStatus(port, &bytes, &key, &ovl_iocp, 100);
11314     ok(!ret, "got %d\n", ret);
11315     ok(GetLastError() == WAIT_TIMEOUT || broken(GetLastError() == ERROR_OPERATION_ABORTED) /* XP */,
11316        "got %u\n", GetLastError());
11317     if (GetLastError() == WAIT_TIMEOUT)
11318     {
11319         ok(bytes == 0xdeadbeef, "got bytes %u\n", bytes);
11320         ok(key == 0xdeadbeef, "got key %lx\n", key);
11321         ok(!ovl_iocp, "got ovl %p\n", ovl_iocp);
11322     }
11323     else /* document XP behaviour */
11324     {
11325         ok(!bytes, "got bytes %u\n", bytes);
11326         ok(key == 0x12345678, "got key %#lx\n", key);
11327         ok(ovl_iocp == &recv_info.ovl, "got ovl %p\n", ovl_iocp);
11328         if (ovl_iocp)
11329         {
11330             ok(!ovl_iocp->InternalHigh, "got %#lx\n", ovl_iocp->InternalHigh);
11331             ok(ovl_iocp->Internal == STATUS_CANCELLED, "got %#lx\n", ovl_iocp->Internal);
11332         }
11333 
11334         closesocket(src);
11335         goto xp_is_broken;
11336     }
11337 
11338     Sleep(100);
11339     ret = PeekMessageA(&msg, hwnd, WM_SOCKET, WM_SOCKET, PM_REMOVE);
11340     ok(!ret, "got %04x,%08lx,%08lx\n", msg.message, msg.wParam, msg.lParam);
11341 
11342     closesocket(src);
11343 
11344     Sleep(100);
11345     ret = PeekMessageA(&msg, hwnd, WM_SOCKET, WM_SOCKET, PM_REMOVE);
11346     ok(!ret, "got %04x,%08lx,%08lx\n", msg.message, msg.wParam, msg.lParam);
11347 
11348     bytes = 0xdeadbeef;
11349     key = 0xdeadbeef;
11350     ovl_iocp = NULL;
11351     SetLastError(0xdeadbeef);
11352     ret = GetQueuedCompletionStatus(port, &bytes, &key, &ovl_iocp, 100);
11353     ok(!ret, "got %d\n", ret);
11354 todo_wine
11355     ok(GetLastError() == ERROR_CONNECTION_ABORTED || GetLastError() == ERROR_NETNAME_DELETED /* XP */, "got %u\n", GetLastError());
11356     ok(!bytes, "got bytes %u\n", bytes);
11357     ok(key == 0x12345678, "got key %#lx\n", key);
11358     ok(ovl_iocp == &recv_info.ovl, "got ovl %p\n", ovl_iocp);
11359     if (ovl_iocp)
11360     {
11361         ok(!ovl_iocp->InternalHigh, "got %#lx\n", ovl_iocp->InternalHigh);
11362 todo_wine
11363         ok(ovl_iocp->Internal == (ULONG)STATUS_CONNECTION_ABORTED || ovl_iocp->Internal == (ULONG)STATUS_LOCAL_DISCONNECT /* XP */, "got %#lx\n", ovl_iocp->Internal);
11364     }
11365 
11366 xp_is_broken:
11367     bytes = 0xdeadbeef;
11368     key = 0xdeadbeef;
11369     ovl_iocp = (void *)0xdeadbeef;
11370     SetLastError(0xdeadbeef);
11371     ret = GetQueuedCompletionStatus(port, &bytes, &key, &ovl_iocp, 100);
11372     ok(!ret, "got %d\n", ret);
11373     ok(GetLastError() == WAIT_TIMEOUT, "got %u\n", GetLastError());
11374     ok(bytes == 0xdeadbeef, "got bytes %u\n", bytes);
11375     ok(key == 0xdeadbeef, "got key %lu\n", key);
11376     ok(!ovl_iocp, "got ovl %p\n", ovl_iocp);
11377 
11378     CloseHandle(port);
11379 
11380     DestroyWindow(hwnd);
11381 }
11382 
11383 static void iocp_async_read_thread(SOCKET src, SOCKET dst)
11384 {
11385     struct wsa_async_select_info select_info;
11386     struct wsa_recv_info recv_info;
11387     HANDLE port, thread;
11388     WSAOVERLAPPED *ovl_iocp;
11389     int ret;
11390     char data[512];
11391     DWORD bytes, tid;
11392     ULONG_PTR key;
11393     HWND hwnd;
11394     MSG msg;
11395 
11396     hwnd = CreateWindowExA(0, "static", NULL, WS_POPUP,
11397                            0, 0, 0, 0, NULL, NULL, 0, NULL);
11398     ok(hwnd != 0, "CreateWindowEx failed\n");
11399 
11400     select_info.sock = src;
11401     select_info.hwnd = hwnd;
11402     thread = CreateThread(NULL, 0, wsa_async_select_thread, &select_info, 0, &tid);
11403     ok(thread != 0, "CreateThread error %u\n", GetLastError());
11404     ret = WaitForSingleObject(thread, 10000);
11405     ok(ret == WAIT_OBJECT_0, "thread failed to terminate\n");
11406 
11407     Sleep(100);
11408     memset(&msg, 0, sizeof(msg));
11409     ret = PeekMessageA(&msg, hwnd, WM_SOCKET, WM_SOCKET, PM_REMOVE);
11410     ok(ret, "got %d\n", ret);
11411     ok(msg.hwnd == hwnd, "got %p\n", msg.hwnd);
11412     ok(msg.message == WM_SOCKET, "got %04x\n", msg.message);
11413     ok(msg.wParam == src, "got %08lx\n", msg.wParam);
11414     ok(msg.lParam == 2, "got %08lx\n", msg.lParam);
11415 
11416     port = CreateIoCompletionPort((HANDLE)src, 0, 0x12345678, 0);
11417     ok(port != 0, "CreateIoCompletionPort error %u\n", GetLastError());
11418 
11419     Sleep(100);
11420     ret = PeekMessageA(&msg, hwnd, WM_SOCKET, WM_SOCKET, PM_REMOVE);
11421     ok(!ret, "got %04x,%08lx,%08lx\n", msg.message, msg.wParam, msg.lParam);
11422 
11423     memset(data, 0, sizeof(data));
11424     memset(&recv_info.ovl, 0, sizeof(recv_info.ovl));
11425     recv_info.sock = src;
11426     recv_info.wsa_buf.len = sizeof(data);
11427     recv_info.wsa_buf.buf = data;
11428     thread = CreateThread(NULL, 0, wsa_recv_thread, &recv_info, 0, &tid);
11429     ok(thread != 0, "CreateThread error %u\n", GetLastError());
11430     ret = WaitForSingleObject(thread, 10000);
11431     ok(ret == WAIT_OBJECT_0, "thread failed to terminate\n");
11432 
11433     Sleep(100);
11434     ret = PeekMessageA(&msg, hwnd, WM_SOCKET, WM_SOCKET, PM_REMOVE);
11435     ok(!ret, "got %04x,%08lx,%08lx\n", msg.message, msg.wParam, msg.lParam);
11436 
11437     bytes = 0xdeadbeef;
11438     key = 0xdeadbeef;
11439     ovl_iocp = (void *)0xdeadbeef;
11440     SetLastError(0xdeadbeef);
11441     ret = GetQueuedCompletionStatus(port, &bytes, &key, &ovl_iocp, 100);
11442     ok(!ret, "got %d\n", ret);
11443     ok(GetLastError() == WAIT_TIMEOUT || broken(GetLastError() == ERROR_OPERATION_ABORTED) /* XP */, "got %u\n", GetLastError());
11444     if (GetLastError() == WAIT_TIMEOUT)
11445     {
11446         ok(bytes == 0xdeadbeef, "got bytes %u\n", bytes);
11447         ok(key == 0xdeadbeef, "got key %lu\n", key);
11448         ok(!ovl_iocp, "got ovl %p\n", ovl_iocp);
11449     }
11450     else /* document XP behaviour */
11451     {
11452         ok(bytes == 0, "got bytes %u\n", bytes);
11453         ok(key == 0x12345678, "got key %#lx\n", key);
11454         ok(ovl_iocp == &recv_info.ovl, "got ovl %p\n", ovl_iocp);
11455         if (ovl_iocp)
11456         {
11457             ok(!ovl_iocp->InternalHigh, "got %#lx\n", ovl_iocp->InternalHigh);
11458             ok(ovl_iocp->Internal == STATUS_CANCELLED, "got %#lx\n", ovl_iocp->Internal);
11459         }
11460     }
11461 
11462     Sleep(100);
11463     memset(&msg, 0, sizeof(msg));
11464     ret = PeekMessageA(&msg, hwnd, WM_SOCKET, WM_SOCKET, PM_REMOVE);
11465     ok(!ret || broken(msg.hwnd == hwnd) /* XP */, "got %04x,%08lx,%08lx\n", msg.message, msg.wParam, msg.lParam);
11466     if (ret) /* document XP behaviour */
11467     {
11468         ok(msg.message == WM_SOCKET, "got %04x\n", msg.message);
11469         ok(msg.wParam == src, "got %08lx\n", msg.wParam);
11470         ok(msg.lParam == 1, "got %08lx\n", msg.lParam);
11471     }
11472 
11473     ret = send(dst, "Hello World!", 12, 0);
11474     ok(ret == 12, "send returned %d\n", ret);
11475 
11476     Sleep(100);
11477     memset(&msg, 0, sizeof(msg));
11478     ret = PeekMessageA(&msg, hwnd, WM_SOCKET, WM_SOCKET, PM_REMOVE);
11479     ok(!ret || broken(msg.hwnd == hwnd) /* XP */, "got %04x,%08lx,%08lx\n", msg.message, msg.wParam, msg.lParam);
11480     if (ret) /* document XP behaviour */
11481     {
11482         ok(msg.hwnd == hwnd, "got %p\n", msg.hwnd);
11483         ok(msg.message == WM_SOCKET, "got %04x\n", msg.message);
11484         ok(msg.wParam == src, "got %08lx\n", msg.wParam);
11485         ok(msg.lParam == 1, "got %08lx\n", msg.lParam);
11486     }
11487 
11488     bytes = 0xdeadbeef;
11489     key = 0xdeadbeef;
11490     ovl_iocp = (void *)0xdeadbeef;
11491     SetLastError(0xdeadbeef);
11492     ret = GetQueuedCompletionStatus(port, &bytes, &key, &ovl_iocp, 100);
11493     ok(ret || broken(GetLastError() == WAIT_TIMEOUT) /* XP */, "got %u\n", GetLastError());
11494     if (ret)
11495     {
11496         ok(bytes == 12, "got bytes %u\n", bytes);
11497         ok(key == 0x12345678, "got key %#lx\n", key);
11498         ok(ovl_iocp == &recv_info.ovl, "got ovl %p\n", ovl_iocp);
11499         if (ovl_iocp)
11500         {
11501             ok(ovl_iocp->InternalHigh == 12, "got %#lx\n", ovl_iocp->InternalHigh);
11502             ok(!ovl_iocp->Internal , "got %#lx\n", ovl_iocp->Internal);
11503             ok(!memcmp(data, "Hello World!", 12), "got %u bytes (%*s)\n", bytes, bytes, data);
11504         }
11505     }
11506     else /* document XP behaviour */
11507     {
11508         ok(bytes == 0xdeadbeef, "got bytes %u\n", bytes);
11509         ok(key == 0xdeadbeef, "got key %lu\n", key);
11510         ok(!ovl_iocp, "got ovl %p\n", ovl_iocp);
11511     }
11512 
11513     CloseHandle(port);
11514 
11515     DestroyWindow(hwnd);
11516 }
11517 
11518 static void test_iocp(void)
11519 {
11520     SOCKET src, dst;
11521     int i, ret;
11522 
11523     ret = tcp_socketpair_ovl(&src, &dst);
11524     ok(!ret, "creating socket pair failed\n");
11525     sync_read(src, dst);
11526     iocp_async_read(src, dst);
11527     closesocket(src);
11528     closesocket(dst);
11529 
11530     ret = tcp_socketpair_ovl(&src, &dst);
11531     ok(!ret, "creating socket pair failed\n");
11532     iocp_async_read_thread(src, dst);
11533     closesocket(src);
11534     closesocket(dst);
11535 
11536     for (i = 0; i <= 2; i++)
11537     {
11538         ret = tcp_socketpair_ovl(&src, &dst);
11539         ok(!ret, "creating socket pair failed\n");
11540         iocp_async_read_closesocket(src, i);
11541         closesocket(dst);
11542     }
11543 
11544     ret = tcp_socketpair_ovl(&src, &dst);
11545     ok(!ret, "creating socket pair failed\n");
11546     iocp_async_closesocket(src);
11547     closesocket(dst);
11548 
11549     ret = tcp_socketpair_ovl(&src, &dst);
11550     ok(!ret, "creating socket pair failed\n");
11551     iocp_async_read_thread_closesocket(src);
11552     closesocket(dst);
11553 }
11554 
11555 START_TEST( sock )
11556 {
11557     int i;
11558 
11559 /* Leave these tests at the beginning. They depend on WSAStartup not having been
11560  * called, which is done by Init() below. */
11561     test_WithoutWSAStartup();
11562     test_WithWSAStartup();
11563 
11564     Init();
11565 
11566     test_inet_ntoa();
11567     test_inet_pton();
11568     test_set_getsockopt();
11569     test_so_reuseaddr();
11570     test_ip_pktinfo();
11571     test_extendedSocketOptions();
11572 
11573     for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++)
11574     {
11575         trace ( " **** STARTING TEST %d ****\n", i );
11576         do_test (  &tests[i] );
11577         trace ( " **** TEST %d COMPLETE ****\n", i );
11578     }
11579 
11580     test_UDP();
11581 
11582     test_getservbyname();
11583     test_WSASocket();
11584     test_WSADuplicateSocket();
11585     test_WSAEnumNetworkEvents();
11586 
11587     test_WSAAddressToStringA();
11588     test_WSAAddressToStringW();
11589 
11590     test_WSAStringToAddressA();
11591     test_WSAStringToAddressW();
11592 
11593     test_errors();
11594     test_listen();
11595     test_select();
11596     test_accept();
11597     test_getpeername();
11598     test_getsockname();
11599     test_inet_addr();
11600     test_addr_to_print();
11601     test_ioctlsocket();
11602     test_dns();
11603     test_gethostbyname();
11604     test_gethostbyname_hack();
11605     test_gethostname();
11606 
11607     test_WSASendMsg();
11608     test_WSASendTo();
11609     test_WSARecv();
11610     test_WSAPoll();
11611     test_write_watch();
11612     test_iocp();
11613 
11614     test_events(0);
11615     test_events(1);
11616 
11617     test_ipv6only();
11618     test_TransmitFile();
11619     test_GetAddrInfoW();
11620     test_GetAddrInfoExW();
11621     test_getaddrinfo();
11622     test_AcceptEx();
11623     test_ConnectEx();
11624     test_DisconnectEx();
11625 
11626     test_sioRoutingInterfaceQuery();
11627     test_sioAddressListChange();
11628 
11629     test_WSALookupService();
11630     test_WSAEnumNameSpaceProvidersA();
11631     test_WSAEnumNameSpaceProvidersW();
11632 
11633     test_WSAAsyncGetServByPort();
11634     test_WSAAsyncGetServByName();
11635 
11636     test_completion_port();
11637     test_address_list_query();
11638 
11639     /* this is an io heavy test, do it at the end so the kernel doesn't start dropping packets */
11640     test_send();
11641     test_synchronous_WSAIoctl();
11642 
11643     Exit();
11644 }
11645