mshtml: Implement IHTMLDOMNode replaceChild.
[wine] / dlls / kernel32 / tests / pipe.c
1 /*
2  * Unit tests for named pipe functions in Wine
3  *
4  * Copyright (c) 2002 Dan Kegel
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include <stdarg.h>
22 #include <stdio.h>
23
24 #include <windef.h>
25 #include <winbase.h>
26 #include <winsock.h>
27 #include <wtypes.h>
28 #include <winerror.h>
29
30 #include "wine/test.h"
31
32 #define PIPENAME "\\\\.\\PiPe\\tests_pipe.c"
33
34 #define NB_SERVER_LOOPS 8
35
36 static HANDLE alarm_event;
37 static BOOL (WINAPI *pDuplicateTokenEx)(HANDLE,DWORD,LPSECURITY_ATTRIBUTES,
38                                         SECURITY_IMPERSONATION_LEVEL,TOKEN_TYPE,PHANDLE);
39 static DWORD (WINAPI *pQueueUserAPC)(PAPCFUNC pfnAPC, HANDLE hThread, ULONG_PTR dwData);
40
41 static BOOL user_apc_ran;
42 static void CALLBACK user_apc(ULONG_PTR param)
43 {
44     user_apc_ran = TRUE;
45 }
46
47 static void test_CreateNamedPipe(int pipemode)
48 {
49     HANDLE hnp;
50     HANDLE hFile;
51     static const char obuf[] = "Bit Bucket";
52     static const char obuf2[] = "More bits";
53     char ibuf[32], *pbuf;
54     DWORD written;
55     DWORD readden;
56     DWORD avail;
57     DWORD lpmode;
58     BOOL ret;
59
60     if (pipemode == PIPE_TYPE_BYTE)
61         trace("test_CreateNamedPipe starting in byte mode\n");
62     else
63         trace("test_CreateNamedPipe starting in message mode\n");
64     /* Bad parameter checks */
65     hnp = CreateNamedPipe("not a named pipe", PIPE_ACCESS_DUPLEX, pipemode | PIPE_WAIT,
66         /* nMaxInstances */ 1,
67         /* nOutBufSize */ 1024,
68         /* nInBufSize */ 1024,
69         /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
70         /* lpSecurityAttrib */ NULL);
71     ok(hnp == INVALID_HANDLE_VALUE && GetLastError() == ERROR_INVALID_NAME,
72         "CreateNamedPipe should fail if name doesn't start with \\\\.\\pipe\n");
73
74     hnp = CreateNamedPipe(NULL,
75         PIPE_ACCESS_DUPLEX, pipemode | PIPE_WAIT,
76         1, 1024, 1024, NMPWAIT_USE_DEFAULT_WAIT, NULL);
77     ok(hnp == INVALID_HANDLE_VALUE && GetLastError() == ERROR_PATH_NOT_FOUND,
78         "CreateNamedPipe should fail if name is NULL\n");
79
80     hFile = CreateFileA(PIPENAME, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
81     ok(hFile == INVALID_HANDLE_VALUE
82         && GetLastError() == ERROR_FILE_NOT_FOUND,
83         "connecting to nonexistent named pipe should fail with ERROR_FILE_NOT_FOUND\n");
84
85     /* Functional checks */
86
87     hnp = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX, pipemode | PIPE_WAIT,
88         /* nMaxInstances */ 1,
89         /* nOutBufSize */ 1024,
90         /* nInBufSize */ 1024,
91         /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
92         /* lpSecurityAttrib */ NULL);
93     ok(hnp != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
94
95     ret = WaitNamedPipeA(PIPENAME, 2000);
96     ok(ret, "WaitNamedPipe failed (%d)\n", GetLastError());
97
98     hFile = CreateFileA(PIPENAME, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
99     ok(hFile != INVALID_HANDLE_VALUE, "CreateFile failed (%d)\n", GetLastError());
100
101     ok(!WaitNamedPipeA(PIPENAME, 1000), "WaitNamedPipe succeeded\n");
102
103     ok(GetLastError() == ERROR_SEM_TIMEOUT, "wrong error %u\n", GetLastError());
104
105     /* don't try to do i/o if one side couldn't be opened, as it hangs */
106     if (hFile != INVALID_HANDLE_VALUE) {
107         HANDLE hFile2;
108
109         /* Make sure we can read and write a few bytes in both directions */
110         memset(ibuf, 0, sizeof(ibuf));
111         ok(WriteFile(hnp, obuf, sizeof(obuf), &written, NULL), "WriteFile\n");
112         ok(written == sizeof(obuf), "write file len 1\n");
113         ok(PeekNamedPipe(hFile, NULL, 0, NULL, &readden, NULL), "Peek\n");
114         ok(readden == sizeof(obuf), "peek 1 got %d bytes\n", readden);
115         ok(ReadFile(hFile, ibuf, sizeof(ibuf), &readden, NULL), "ReadFile\n");
116         ok(readden == sizeof(obuf), "read 1 got %d bytes\n", readden);
117         ok(memcmp(obuf, ibuf, written) == 0, "content 1 check\n");
118
119         memset(ibuf, 0, sizeof(ibuf));
120         ok(WriteFile(hFile, obuf2, sizeof(obuf2), &written, NULL), "WriteFile\n");
121         ok(written == sizeof(obuf2), "write file len 2\n");
122         ok(PeekNamedPipe(hnp, NULL, 0, NULL, &readden, NULL), "Peek\n");
123         ok(readden == sizeof(obuf2), "peek 2 got %d bytes\n", readden);
124         ok(PeekNamedPipe(hnp, (LPVOID)1, 0, NULL, &readden, NULL), "Peek\n");
125         ok(readden == sizeof(obuf2), "peek 2 got %d bytes\n", readden);
126         ok(ReadFile(hnp, ibuf, sizeof(ibuf), &readden, NULL), "ReadFile\n");
127         ok(readden == sizeof(obuf2), "read 2 got %d bytes\n", readden);
128         ok(memcmp(obuf2, ibuf, written) == 0, "content 2 check\n");
129
130         /* Test reading of multiple writes */
131         memset(ibuf, 0, sizeof(ibuf));
132         ok(WriteFile(hnp, obuf, sizeof(obuf), &written, NULL), "WriteFile3a\n");
133         ok(written == sizeof(obuf), "write file len 3a\n");
134         ok(WriteFile(hnp, obuf2, sizeof(obuf2), &written, NULL), " WriteFile3b\n");
135         ok(written == sizeof(obuf2), "write file len 3b\n");
136         ok(PeekNamedPipe(hFile, ibuf, sizeof(ibuf), &readden, &avail, NULL), "Peek3\n");
137         if (pipemode == PIPE_TYPE_BYTE) {
138             if (readden != sizeof(obuf))  /* Linux only returns the first message */
139                 ok(readden == sizeof(obuf) + sizeof(obuf2), "peek3 got %d bytes\n", readden);
140             else
141                 todo_wine ok(readden == sizeof(obuf) + sizeof(obuf2), "peek3 got %d bytes\n", readden);
142         }
143         else
144         {
145             if (readden != sizeof(obuf) + sizeof(obuf2))  /* MacOS returns both messages */
146                 ok(readden == sizeof(obuf), "peek3 got %d bytes\n", readden);
147             else
148                 todo_wine ok(readden == sizeof(obuf), "peek3 got %d bytes\n", readden);
149         }
150         if (avail != sizeof(obuf)) /* older Linux kernels only return the first write here */
151             ok(avail == sizeof(obuf) + sizeof(obuf2), "peek3 got %d bytes available\n", avail);
152         pbuf = ibuf;
153         ok(memcmp(obuf, pbuf, sizeof(obuf)) == 0, "pipe content 3a check\n");
154         if (pipemode == PIPE_TYPE_BYTE && readden >= sizeof(obuf)+sizeof(obuf2)) {
155             pbuf += sizeof(obuf);
156             ok(memcmp(obuf2, pbuf, sizeof(obuf2)) == 0, "pipe content 3b check\n");
157         }
158         ok(ReadFile(hFile, ibuf, sizeof(ibuf), &readden, NULL), "ReadFile\n");
159         ok(readden == sizeof(obuf) + sizeof(obuf2), "read 3 got %d bytes\n", readden);
160         pbuf = ibuf;
161         ok(memcmp(obuf, pbuf, sizeof(obuf)) == 0, "content 3a check\n");
162         pbuf += sizeof(obuf);
163         ok(memcmp(obuf2, pbuf, sizeof(obuf2)) == 0, "content 3b check\n");
164
165         /* Multiple writes in the reverse direction */
166         memset(ibuf, 0, sizeof(ibuf));
167         ok(WriteFile(hFile, obuf, sizeof(obuf), &written, NULL), "WriteFile4a\n");
168         ok(written == sizeof(obuf), "write file len 4a\n");
169         ok(WriteFile(hFile, obuf2, sizeof(obuf2), &written, NULL), " WriteFile4b\n");
170         ok(written == sizeof(obuf2), "write file len 4b\n");
171         ok(PeekNamedPipe(hnp, ibuf, sizeof(ibuf), &readden, &avail, NULL), "Peek4\n");
172         if (pipemode == PIPE_TYPE_BYTE) {
173             if (readden != sizeof(obuf))  /* Linux only returns the first message */
174                 /* should return all 23 bytes */
175                 ok(readden == sizeof(obuf) + sizeof(obuf2), "peek4 got %d bytes\n", readden);
176             else
177                 todo_wine ok(readden == sizeof(obuf) + sizeof(obuf2), "peek4 got %d bytes\n", readden);
178         }
179         else
180         {
181             if (readden != sizeof(obuf) + sizeof(obuf2))  /* MacOS returns both messages */
182                 ok(readden == sizeof(obuf), "peek4 got %d bytes\n", readden);
183             else
184                 todo_wine ok(readden == sizeof(obuf), "peek4 got %d bytes\n", readden);
185         }
186         if (avail != sizeof(obuf)) /* older Linux kernels only return the first write here */
187             ok(avail == sizeof(obuf) + sizeof(obuf2), "peek4 got %d bytes available\n", avail);
188         pbuf = ibuf;
189         ok(memcmp(obuf, pbuf, sizeof(obuf)) == 0, "pipe content 4a check\n");
190         if (pipemode == PIPE_TYPE_BYTE && readden >= sizeof(obuf)+sizeof(obuf2)) {
191             pbuf += sizeof(obuf);
192             ok(memcmp(obuf2, pbuf, sizeof(obuf2)) == 0, "pipe content 4b check\n");
193         }
194         ok(ReadFile(hnp, ibuf, sizeof(ibuf), &readden, NULL), "ReadFile\n");
195         if (pipemode == PIPE_TYPE_BYTE) {
196             ok(readden == sizeof(obuf) + sizeof(obuf2), "read 4 got %d bytes\n", readden);
197         }
198         else {
199             todo_wine {
200                 ok(readden == sizeof(obuf), "read 4 got %d bytes\n", readden);
201             }
202         }
203         pbuf = ibuf;
204         ok(memcmp(obuf, pbuf, sizeof(obuf)) == 0, "content 4a check\n");
205         if (pipemode == PIPE_TYPE_BYTE) {
206             pbuf += sizeof(obuf);
207             ok(memcmp(obuf2, pbuf, sizeof(obuf2)) == 0, "content 4b check\n");
208         }
209
210         /* Test reading of multiple writes after a mode change
211           (CreateFile always creates a byte mode pipe) */
212         lpmode = PIPE_READMODE_MESSAGE;
213         if (pipemode == PIPE_TYPE_BYTE) {
214             /* trying to change the client end of a byte pipe to message mode should fail */
215             ok(!SetNamedPipeHandleState(hFile, &lpmode, NULL, NULL), "Change mode\n");
216         }
217         else {
218             todo_wine {
219                 ok(SetNamedPipeHandleState(hFile, &lpmode, NULL, NULL), "Change mode\n");
220             }
221         
222             memset(ibuf, 0, sizeof(ibuf));
223             ok(WriteFile(hnp, obuf, sizeof(obuf), &written, NULL), "WriteFile5a\n");
224             ok(written == sizeof(obuf), "write file len 3a\n");
225             ok(WriteFile(hnp, obuf2, sizeof(obuf2), &written, NULL), " WriteFile5b\n");
226             ok(written == sizeof(obuf2), "write file len 3b\n");
227             ok(PeekNamedPipe(hFile, ibuf, sizeof(ibuf), &readden, &avail, NULL), "Peek5\n");
228             if (readden != sizeof(obuf) + sizeof(obuf2))  /* MacOS returns both writes */
229                 ok(readden == sizeof(obuf), "peek5 got %d bytes\n", readden);
230             else
231                 todo_wine ok(readden == sizeof(obuf), "peek5 got %d bytes\n", readden);
232             if (avail != sizeof(obuf)) /* older Linux kernels only return the first write here */
233                 ok(avail == sizeof(obuf) + sizeof(obuf2), "peek5 got %d bytes available\n", avail);
234             else
235                 todo_wine ok(avail == sizeof(obuf) + sizeof(obuf2), "peek5 got %d bytes available\n", avail);
236             pbuf = ibuf;
237             ok(memcmp(obuf, pbuf, sizeof(obuf)) == 0, "content 5a check\n");
238             ok(ReadFile(hFile, ibuf, sizeof(ibuf), &readden, NULL), "ReadFile\n");
239             todo_wine {
240                 ok(readden == sizeof(obuf), "read 5 got %d bytes\n", readden);
241             }
242             pbuf = ibuf;
243             ok(memcmp(obuf, pbuf, sizeof(obuf)) == 0, "content 5a check\n");
244     
245             /* Multiple writes in the reverse direction */
246             /* the write of obuf2 from write4 should still be in the buffer */
247             ok(PeekNamedPipe(hnp, ibuf, sizeof(ibuf), &readden, &avail, NULL), "Peek6a\n");
248             todo_wine {
249                 ok(readden == sizeof(obuf2), "peek6a got %d bytes\n", readden);
250                 ok(avail == sizeof(obuf2), "peek6a got %d bytes available\n", avail);
251             }
252             if (avail > 0) {
253                 ok(ReadFile(hnp, ibuf, sizeof(ibuf), &readden, NULL), "ReadFile\n");
254                 ok(readden == sizeof(obuf2), "read 6a got %d bytes\n", readden);
255                 pbuf = ibuf;
256                 ok(memcmp(obuf2, pbuf, sizeof(obuf2)) == 0, "content 6a check\n");
257             }
258             memset(ibuf, 0, sizeof(ibuf));
259             ok(WriteFile(hFile, obuf, sizeof(obuf), &written, NULL), "WriteFile6a\n");
260             ok(written == sizeof(obuf), "write file len 6a\n");
261             ok(WriteFile(hFile, obuf2, sizeof(obuf2), &written, NULL), " WriteFile6b\n");
262             ok(written == sizeof(obuf2), "write file len 6b\n");
263             ok(PeekNamedPipe(hnp, ibuf, sizeof(ibuf), &readden, &avail, NULL), "Peek6\n");
264             if (readden != sizeof(obuf) + sizeof(obuf2))  /* MacOS returns both writes */
265                 ok(readden == sizeof(obuf), "peek6 got %d bytes\n", readden);
266             else
267                 todo_wine ok(readden == sizeof(obuf), "peek6 got %d bytes\n", readden);
268             if (avail != sizeof(obuf)) /* older Linux kernels only return the first write here */
269                 ok(avail == sizeof(obuf) + sizeof(obuf2), "peek6b got %d bytes available\n", avail);
270             pbuf = ibuf;
271             ok(memcmp(obuf, pbuf, sizeof(obuf)) == 0, "content 6a check\n");
272             ok(ReadFile(hnp, ibuf, sizeof(ibuf), &readden, NULL), "ReadFile\n");
273             todo_wine {
274                 ok(readden == sizeof(obuf), "read 6b got %d bytes\n", readden);
275             }
276             pbuf = ibuf;
277             ok(memcmp(obuf, pbuf, sizeof(obuf)) == 0, "content 6a check\n");
278         }
279
280         /* Picky conformance tests */
281
282         /* Verify that you can't connect to pipe again
283          * until server calls DisconnectNamedPipe+ConnectNamedPipe
284          * or creates a new pipe
285          * case 1: other client not yet closed
286          */
287         hFile2 = CreateFileA(PIPENAME, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
288         ok(hFile2 == INVALID_HANDLE_VALUE,
289             "connecting to named pipe after other client closes but before DisconnectNamedPipe should fail\n");
290         ok(GetLastError() == ERROR_PIPE_BUSY,
291             "connecting to named pipe before other client closes should fail with ERROR_PIPE_BUSY\n");
292
293         ok(CloseHandle(hFile), "CloseHandle\n");
294
295         /* case 2: other client already closed */
296         hFile = CreateFileA(PIPENAME, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
297         ok(hFile == INVALID_HANDLE_VALUE,
298             "connecting to named pipe after other client closes but before DisconnectNamedPipe should fail\n");
299         ok(GetLastError() == ERROR_PIPE_BUSY,
300             "connecting to named pipe after other client closes but before DisconnectNamedPipe should fail with ERROR_PIPE_BUSY\n");
301
302         ok(DisconnectNamedPipe(hnp), "DisconnectNamedPipe\n");
303
304         /* case 3: server has called DisconnectNamedPipe but not ConnectNamed Pipe */
305         hFile = CreateFileA(PIPENAME, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
306         ok(hFile == INVALID_HANDLE_VALUE,
307             "connecting to named pipe after other client closes but before DisconnectNamedPipe should fail\n");
308         ok(GetLastError() == ERROR_PIPE_BUSY,
309             "connecting to named pipe after other client closes but before ConnectNamedPipe should fail with ERROR_PIPE_BUSY\n");
310
311         /* to be complete, we'd call ConnectNamedPipe here and loop,
312          * but by default that's blocking, so we'd either have
313          * to turn on the uncommon nonblocking mode, or
314          * use another thread.
315          */
316     }
317
318     ok(CloseHandle(hnp), "CloseHandle\n");
319
320     trace("test_CreateNamedPipe returning\n");
321 }
322
323 static void test_CreateNamedPipe_instances_must_match(void)
324 {
325     HANDLE hnp, hnp2;
326
327     /* Check no mismatch */
328     hnp = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_WAIT,
329         /* nMaxInstances */ 2,
330         /* nOutBufSize */ 1024,
331         /* nInBufSize */ 1024,
332         /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
333         /* lpSecurityAttrib */ NULL);
334     ok(hnp != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
335
336     hnp2 = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_WAIT,
337         /* nMaxInstances */ 2,
338         /* nOutBufSize */ 1024,
339         /* nInBufSize */ 1024,
340         /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
341         /* lpSecurityAttrib */ NULL);
342     ok(hnp2 != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
343
344     ok(CloseHandle(hnp), "CloseHandle\n");
345     ok(CloseHandle(hnp2), "CloseHandle\n");
346
347     /* Check nMaxInstances */
348     hnp = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_WAIT,
349         /* nMaxInstances */ 1,
350         /* nOutBufSize */ 1024,
351         /* nInBufSize */ 1024,
352         /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
353         /* lpSecurityAttrib */ NULL);
354     ok(hnp != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
355
356     hnp2 = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_WAIT,
357         /* nMaxInstances */ 1,
358         /* nOutBufSize */ 1024,
359         /* nInBufSize */ 1024,
360         /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
361         /* lpSecurityAttrib */ NULL);
362     ok(hnp2 == INVALID_HANDLE_VALUE
363         && GetLastError() == ERROR_PIPE_BUSY, "nMaxInstances not obeyed\n");
364
365     ok(CloseHandle(hnp), "CloseHandle\n");
366
367     /* Check PIPE_ACCESS_* */
368     hnp = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_WAIT,
369         /* nMaxInstances */ 2,
370         /* nOutBufSize */ 1024,
371         /* nInBufSize */ 1024,
372         /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
373         /* lpSecurityAttrib */ NULL);
374     ok(hnp != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
375
376     hnp2 = CreateNamedPipe(PIPENAME, PIPE_ACCESS_INBOUND, PIPE_TYPE_BYTE | PIPE_WAIT,
377         /* nMaxInstances */ 2,
378         /* nOutBufSize */ 1024,
379         /* nInBufSize */ 1024,
380         /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
381         /* lpSecurityAttrib */ NULL);
382     ok(hnp2 == INVALID_HANDLE_VALUE
383         && GetLastError() == ERROR_ACCESS_DENIED, "PIPE_ACCESS_* mismatch allowed\n");
384
385     ok(CloseHandle(hnp), "CloseHandle\n");
386
387     /* check everything else */
388     hnp = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_WAIT,
389         /* nMaxInstances */ 4,
390         /* nOutBufSize */ 1024,
391         /* nInBufSize */ 1024,
392         /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
393         /* lpSecurityAttrib */ NULL);
394     ok(hnp != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
395
396     hnp2 = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE,
397         /* nMaxInstances */ 3,
398         /* nOutBufSize */ 102,
399         /* nInBufSize */ 24,
400         /* nDefaultWait */ 1234,
401         /* lpSecurityAttrib */ NULL);
402     ok(hnp2 != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
403
404     ok(CloseHandle(hnp), "CloseHandle\n");
405     ok(CloseHandle(hnp2), "CloseHandle\n");
406 }
407
408 /** implementation of alarm() */
409 static DWORD CALLBACK alarmThreadMain(LPVOID arg)
410 {
411     DWORD_PTR timeout = (DWORD_PTR) arg;
412     trace("alarmThreadMain\n");
413     if (WaitForSingleObject( alarm_event, timeout ) == WAIT_TIMEOUT)
414     {
415         ok(FALSE, "alarm\n");
416         ExitProcess(1);
417     }
418     return 1;
419 }
420
421 static HANDLE hnp = INVALID_HANDLE_VALUE;
422
423 /** Trivial byte echo server - disconnects after each session */
424 static DWORD CALLBACK serverThreadMain1(LPVOID arg)
425 {
426     int i;
427
428     trace("serverThreadMain1 start\n");
429     /* Set up a simple echo server */
430     hnp = CreateNamedPipe(PIPENAME "serverThreadMain1", PIPE_ACCESS_DUPLEX,
431         PIPE_TYPE_BYTE | PIPE_WAIT,
432         /* nMaxInstances */ 1,
433         /* nOutBufSize */ 1024,
434         /* nInBufSize */ 1024,
435         /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
436         /* lpSecurityAttrib */ NULL);
437
438     ok(hnp != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
439     for (i = 0; i < NB_SERVER_LOOPS; i++) {
440         char buf[512];
441         DWORD written;
442         DWORD readden;
443         DWORD success;
444
445         /* Wait for client to connect */
446         trace("Server calling ConnectNamedPipe...\n");
447         ok(ConnectNamedPipe(hnp, NULL)
448             || GetLastError() == ERROR_PIPE_CONNECTED, "ConnectNamedPipe\n");
449         trace("ConnectNamedPipe returned.\n");
450
451         /* Echo bytes once */
452         memset(buf, 0, sizeof(buf));
453
454         trace("Server reading...\n");
455         success = ReadFile(hnp, buf, sizeof(buf), &readden, NULL);
456         trace("Server done reading.\n");
457         ok(success, "ReadFile\n");
458         ok(readden, "short read\n");
459
460         trace("Server writing...\n");
461         ok(WriteFile(hnp, buf, readden, &written, NULL), "WriteFile\n");
462         trace("Server done writing.\n");
463         ok(written == readden, "write file len\n");
464
465         /* finish this connection, wait for next one */
466         ok(FlushFileBuffers(hnp), "FlushFileBuffers\n");
467         trace("Server done flushing.\n");
468         ok(DisconnectNamedPipe(hnp), "DisconnectNamedPipe\n");
469         trace("Server done disconnecting.\n");
470     }
471     return 0;
472 }
473
474 /** Trivial byte echo server - closes after each connection */
475 static DWORD CALLBACK serverThreadMain2(LPVOID arg)
476 {
477     int i;
478     HANDLE hnpNext = 0;
479
480     trace("serverThreadMain2\n");
481     /* Set up a simple echo server */
482     hnp = CreateNamedPipe(PIPENAME "serverThreadMain2", PIPE_ACCESS_DUPLEX,
483         PIPE_TYPE_BYTE | PIPE_WAIT,
484         /* nMaxInstances */ 2,
485         /* nOutBufSize */ 1024,
486         /* nInBufSize */ 1024,
487         /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
488         /* lpSecurityAttrib */ NULL);
489     ok(hnp != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
490
491     for (i = 0; i < NB_SERVER_LOOPS; i++) {
492         char buf[512];
493         DWORD written;
494         DWORD readden;
495         DWORD success;
496
497         user_apc_ran = FALSE;
498         if (i == 0 && pQueueUserAPC) {
499             trace("Queueing an user APC\n"); /* verify the pipe is non alerable */
500             success = pQueueUserAPC(&user_apc, GetCurrentThread(), 0);
501             ok(success, "QueueUserAPC failed: %d\n", GetLastError());
502         }
503
504         /* Wait for client to connect */
505         trace("Server calling ConnectNamedPipe...\n");
506         ok(ConnectNamedPipe(hnp, NULL)
507             || GetLastError() == ERROR_PIPE_CONNECTED, "ConnectNamedPipe\n");
508         trace("ConnectNamedPipe returned.\n");
509
510         /* Echo bytes once */
511         memset(buf, 0, sizeof(buf));
512
513         trace("Server reading...\n");
514         success = ReadFile(hnp, buf, sizeof(buf), &readden, NULL);
515         trace("Server done reading.\n");
516         ok(success, "ReadFile\n");
517
518         trace("Server writing...\n");
519         ok(WriteFile(hnp, buf, readden, &written, NULL), "WriteFile\n");
520         trace("Server done writing.\n");
521         ok(written == readden, "write file len\n");
522
523         /* finish this connection, wait for next one */
524         ok(FlushFileBuffers(hnp), "FlushFileBuffers\n");
525         ok(DisconnectNamedPipe(hnp), "DisconnectNamedPipe\n");
526
527         ok(user_apc_ran == FALSE, "UserAPC ran, pipe using alertable io mode\n");
528
529         if (i == 0 && pQueueUserAPC)
530             SleepEx(0, TRUE); /* get rid of apc */
531
532         /* Set up next echo server */
533         hnpNext =
534             CreateNamedPipe(PIPENAME "serverThreadMain2", PIPE_ACCESS_DUPLEX,
535             PIPE_TYPE_BYTE | PIPE_WAIT,
536             /* nMaxInstances */ 2,
537             /* nOutBufSize */ 1024,
538             /* nInBufSize */ 1024,
539             /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
540             /* lpSecurityAttrib */ NULL);
541
542         ok(hnpNext != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
543
544         ok(CloseHandle(hnp), "CloseHandle\n");
545         hnp = hnpNext;
546     }
547     return 0;
548 }
549
550 /** Trivial byte echo server - uses overlapped named pipe calls */
551 static DWORD CALLBACK serverThreadMain3(LPVOID arg)
552 {
553     int i;
554     HANDLE hEvent;
555
556     trace("serverThreadMain3\n");
557     /* Set up a simple echo server */
558     hnp = CreateNamedPipe(PIPENAME "serverThreadMain3", PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
559         PIPE_TYPE_BYTE | PIPE_WAIT,
560         /* nMaxInstances */ 1,
561         /* nOutBufSize */ 1024,
562         /* nInBufSize */ 1024,
563         /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
564         /* lpSecurityAttrib */ NULL);
565     ok(hnp != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
566
567     hEvent = CreateEvent(NULL,  /* security attribute */
568         TRUE,                   /* manual reset event */
569         FALSE,                  /* initial state */
570         NULL);                  /* name */
571     ok(hEvent != NULL, "CreateEvent\n");
572
573     for (i = 0; i < NB_SERVER_LOOPS; i++) {
574         char buf[512];
575         DWORD written;
576         DWORD readden;
577         DWORD dummy;
578         DWORD success;
579         OVERLAPPED oOverlap;
580         int letWFSOEwait = (i & 2);
581         int letGORwait = (i & 1);
582         DWORD err;
583
584         memset(&oOverlap, 0, sizeof(oOverlap));
585         oOverlap.hEvent = hEvent;
586
587         /* Wait for client to connect */
588         if (i == 0) {
589             trace("Server calling non-overlapped ConnectNamedPipe on overlapped pipe...\n");
590             success = ConnectNamedPipe(hnp, NULL);
591             err = GetLastError();
592             ok(success || (err == ERROR_PIPE_CONNECTED), "ConnectNamedPipe failed: %d\n", err);
593             trace("ConnectNamedPipe operation complete.\n");
594         } else {
595             trace("Server calling overlapped ConnectNamedPipe...\n");
596             success = ConnectNamedPipe(hnp, &oOverlap);
597             err = GetLastError();
598             ok(!success && (err == ERROR_IO_PENDING || err == ERROR_PIPE_CONNECTED), "overlapped ConnectNamedPipe\n");
599             trace("overlapped ConnectNamedPipe returned.\n");
600             if (!success && (err == ERROR_IO_PENDING)) {
601                 if (letWFSOEwait)
602                 {
603                     DWORD ret;
604                     do {
605                         ret = WaitForSingleObjectEx(hEvent, INFINITE, TRUE);
606                     } while (ret == WAIT_IO_COMPLETION);
607                     ok(ret == 0, "wait ConnectNamedPipe returned %x\n", ret);
608                 }
609                 success = GetOverlappedResult(hnp, &oOverlap, &dummy, letGORwait);
610                 if (!letGORwait && !letWFSOEwait && !success) {
611                     ok(GetLastError() == ERROR_IO_INCOMPLETE, "GetOverlappedResult\n");
612                     success = GetOverlappedResult(hnp, &oOverlap, &dummy, TRUE);
613                 }
614             }
615             ok(success || (err == ERROR_PIPE_CONNECTED), "GetOverlappedResult ConnectNamedPipe\n");
616             trace("overlapped ConnectNamedPipe operation complete.\n");
617         }
618
619         /* Echo bytes once */
620         memset(buf, 0, sizeof(buf));
621
622         trace("Server reading...\n");
623         success = ReadFile(hnp, buf, sizeof(buf), &readden, &oOverlap);
624         trace("Server ReadFile returned...\n");
625         err = GetLastError();
626         ok(success || err == ERROR_IO_PENDING, "overlapped ReadFile\n");
627         trace("overlapped ReadFile returned.\n");
628         if (!success && (err == ERROR_IO_PENDING)) {
629             if (letWFSOEwait)
630             {
631                 DWORD ret;
632                 do {
633                     ret = WaitForSingleObjectEx(hEvent, INFINITE, TRUE);
634                 } while (ret == WAIT_IO_COMPLETION);
635                 ok(ret == 0, "wait ReadFile returned %x\n", ret);
636             }
637             success = GetOverlappedResult(hnp, &oOverlap, &readden, letGORwait);
638             if (!letGORwait && !letWFSOEwait && !success) {
639                 ok(GetLastError() == ERROR_IO_INCOMPLETE, "GetOverlappedResult\n");
640                 success = GetOverlappedResult(hnp, &oOverlap, &readden, TRUE);
641             }
642         }
643         trace("Server done reading.\n");
644         ok(success, "overlapped ReadFile\n");
645
646         trace("Server writing...\n");
647         success = WriteFile(hnp, buf, readden, &written, &oOverlap);
648         trace("Server WriteFile returned...\n");
649         err = GetLastError();
650         ok(success || err == ERROR_IO_PENDING, "overlapped WriteFile\n");
651         trace("overlapped WriteFile returned.\n");
652         if (!success && (err == ERROR_IO_PENDING)) {
653             if (letWFSOEwait)
654             {
655                 DWORD ret;
656                 do {
657                     ret = WaitForSingleObjectEx(hEvent, INFINITE, TRUE);
658                 } while (ret == WAIT_IO_COMPLETION);
659                 ok(ret == 0, "wait WriteFile returned %x\n", ret);
660             }
661             success = GetOverlappedResult(hnp, &oOverlap, &written, letGORwait);
662             if (!letGORwait && !letWFSOEwait && !success) {
663                 ok(GetLastError() == ERROR_IO_INCOMPLETE, "GetOverlappedResult\n");
664                 success = GetOverlappedResult(hnp, &oOverlap, &written, TRUE);
665             }
666         }
667         trace("Server done writing.\n");
668         ok(success, "overlapped WriteFile\n");
669         ok(written == readden, "write file len\n");
670
671         /* finish this connection, wait for next one */
672         ok(FlushFileBuffers(hnp), "FlushFileBuffers\n");
673         ok(DisconnectNamedPipe(hnp), "DisconnectNamedPipe\n");
674     }
675     return 0;
676 }
677
678 /** Trivial byte echo server - uses i/o completion ports */
679 static DWORD CALLBACK serverThreadMain4(LPVOID arg)
680 {
681     int i;
682     HANDLE hcompletion;
683     BOOL ret;
684
685     trace("serverThreadMain4\n");
686     /* Set up a simple echo server */
687     hnp = CreateNamedPipe(PIPENAME "serverThreadMain4", PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
688         PIPE_TYPE_BYTE | PIPE_WAIT,
689         /* nMaxInstances */ 1,
690         /* nOutBufSize */ 1024,
691         /* nInBufSize */ 1024,
692         /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
693         /* lpSecurityAttrib */ NULL);
694     ok(hnp != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
695
696     hcompletion = CreateIoCompletionPort(hnp, NULL, 12345, 1);
697     ok(hcompletion != NULL, "CreateIoCompletionPort failed, error=%i\n", GetLastError());
698
699     for (i = 0; i < NB_SERVER_LOOPS; i++) {
700         char buf[512];
701         DWORD written;
702         DWORD readden;
703         DWORD dummy;
704         DWORD success;
705         OVERLAPPED oConnect;
706         OVERLAPPED oRead;
707         OVERLAPPED oWrite;
708         OVERLAPPED *oResult;
709         DWORD err;
710         ULONG_PTR compkey;
711
712         memset(&oConnect, 0, sizeof(oConnect));
713         memset(&oRead, 0, sizeof(oRead));
714         memset(&oWrite, 0, sizeof(oWrite));
715
716         /* Wait for client to connect */
717         trace("Server calling overlapped ConnectNamedPipe...\n");
718         success = ConnectNamedPipe(hnp, &oConnect);
719         err = GetLastError();
720         ok(!success && (err == ERROR_IO_PENDING || err == ERROR_PIPE_CONNECTED),
721            "overlapped ConnectNamedPipe got %u err %u\n", success, err );
722         if (!success && err == ERROR_IO_PENDING) {
723             trace("ConnectNamedPipe GetQueuedCompletionStatus\n");
724             success = GetQueuedCompletionStatus(hcompletion, &dummy, &compkey, &oResult, 0);
725             if (!success)
726             {
727                 ok( GetLastError() == WAIT_TIMEOUT,
728                     "ConnectNamedPipe GetQueuedCompletionStatus wrong error %u\n", GetLastError());
729                 success = GetQueuedCompletionStatus(hcompletion, &dummy, &compkey, &oResult, 10000);
730             }
731             ok(success, "ConnectNamedPipe GetQueuedCompletionStatus failed, errno=%i\n", GetLastError());
732             if (success)
733             {
734                 ok(compkey == 12345, "got completion key %i instead of 12345\n", (int)compkey);
735                 ok(oResult == &oConnect, "got overlapped pointer %p instead of %p\n", oResult, &oConnect);
736             }
737         }
738         trace("overlapped ConnectNamedPipe operation complete.\n");
739
740         /* Echo bytes once */
741         memset(buf, 0, sizeof(buf));
742
743         trace("Server reading...\n");
744         success = ReadFile(hnp, buf, sizeof(buf), &readden, &oRead);
745         trace("Server ReadFile returned...\n");
746         err = GetLastError();
747         ok(success || err == ERROR_IO_PENDING, "overlapped ReadFile, err=%i\n", err);
748         success = GetQueuedCompletionStatus(hcompletion, &readden, &compkey,
749             &oResult, 10000);
750         ok(success, "ReadFile GetQueuedCompletionStatus failed, errno=%i\n", GetLastError());
751         if (success)
752         {
753             ok(compkey == 12345, "got completion key %i instead of 12345\n", (int)compkey);
754             ok(oResult == &oRead, "got overlapped pointer %p instead of %p\n", oResult, &oRead);
755         }
756         trace("Server done reading.\n");
757
758         trace("Server writing...\n");
759         success = WriteFile(hnp, buf, readden, &written, &oWrite);
760         trace("Server WriteFile returned...\n");
761         err = GetLastError();
762         ok(success || err == ERROR_IO_PENDING, "overlapped WriteFile failed, err=%u\n", err);
763         success = GetQueuedCompletionStatus(hcompletion, &written, &compkey,
764             &oResult, 10000);
765         ok(success, "WriteFile GetQueuedCompletionStatus failed, errno=%i\n", GetLastError());
766         if (success)
767         {
768             ok(compkey == 12345, "got completion key %i instead of 12345\n", (int)compkey);
769             ok(oResult == &oWrite, "got overlapped pointer %p instead of %p\n", oResult, &oWrite);
770             ok(written == readden, "write file len\n");
771         }
772         trace("Server done writing.\n");
773
774         /* finish this connection, wait for next one */
775         ok(FlushFileBuffers(hnp), "FlushFileBuffers\n");
776         success = DisconnectNamedPipe(hnp);
777         ok(success, "DisconnectNamedPipe failed, err %u\n", GetLastError());
778     }
779
780     ret = CloseHandle(hnp);
781     ok(ret, "CloseHandle named pipe failed, err=%i\n", GetLastError());
782     ret = CloseHandle(hcompletion);
783     ok(ret, "CloseHandle completion failed, err=%i\n", GetLastError());
784
785     return 0;
786 }
787
788 static void exercizeServer(const char *pipename, HANDLE serverThread)
789 {
790     int i;
791
792     trace("exercizeServer starting\n");
793     for (i = 0; i < NB_SERVER_LOOPS; i++) {
794         HANDLE hFile=INVALID_HANDLE_VALUE;
795         static const char obuf[] = "Bit Bucket";
796         char ibuf[32];
797         DWORD written;
798         DWORD readden;
799         int loop;
800
801         for (loop = 0; loop < 3; loop++) {
802             DWORD err;
803             trace("Client connecting...\n");
804             /* Connect to the server */
805             hFile = CreateFileA(pipename, GENERIC_READ | GENERIC_WRITE, 0,
806                 NULL, OPEN_EXISTING, 0, 0);
807             if (hFile != INVALID_HANDLE_VALUE)
808                 break;
809             err = GetLastError();
810             if (loop == 0)
811                 ok(err == ERROR_PIPE_BUSY || err == ERROR_FILE_NOT_FOUND, "connecting to pipe\n");
812             else
813                 ok(err == ERROR_PIPE_BUSY, "connecting to pipe\n");
814             trace("connect failed, retrying\n");
815             Sleep(200);
816         }
817         ok(hFile != INVALID_HANDLE_VALUE, "client opening named pipe\n");
818
819         /* Make sure it can echo */
820         memset(ibuf, 0, sizeof(ibuf));
821         trace("Client writing...\n");
822         ok(WriteFile(hFile, obuf, sizeof(obuf), &written, NULL), "WriteFile to client end of pipe\n");
823         ok(written == sizeof(obuf), "write file len\n");
824         trace("Client reading...\n");
825         ok(ReadFile(hFile, ibuf, sizeof(obuf), &readden, NULL), "ReadFile from client end of pipe\n");
826         ok(readden == sizeof(obuf), "read file len\n");
827         ok(memcmp(obuf, ibuf, written) == 0, "content check\n");
828
829         trace("Client closing...\n");
830         ok(CloseHandle(hFile), "CloseHandle\n");
831     }
832
833     ok(WaitForSingleObject(serverThread,INFINITE) == WAIT_OBJECT_0, "WaitForSingleObject\n");
834     CloseHandle(hnp);
835     trace("exercizeServer returning\n");
836 }
837
838 static void test_NamedPipe_2(void)
839 {
840     HANDLE serverThread;
841     DWORD serverThreadId;
842     HANDLE alarmThread;
843     DWORD alarmThreadId;
844
845     trace("test_NamedPipe_2 starting\n");
846     /* Set up a twenty second timeout */
847     alarm_event = CreateEvent( NULL, TRUE, FALSE, NULL );
848     SetLastError(0xdeadbeef);
849     alarmThread = CreateThread(NULL, 0, alarmThreadMain, (void *) 20000, 0, &alarmThreadId);
850     ok(alarmThread != NULL, "CreateThread failed: %d\n", GetLastError());
851
852     /* The servers we're about to exercise do try to clean up carefully,
853      * but to reduce the chance of a test failure due to a pipe handle
854      * leak in the test code, we'll use a different pipe name for each server.
855      */
856
857     /* Try server #1 */
858     SetLastError(0xdeadbeef);
859     serverThread = CreateThread(NULL, 0, serverThreadMain1, (void *)8, 0, &serverThreadId);
860     ok(serverThread != NULL, "CreateThread failed: %d\n", GetLastError());
861     exercizeServer(PIPENAME "serverThreadMain1", serverThread);
862
863     /* Try server #2 */
864     SetLastError(0xdeadbeef);
865     serverThread = CreateThread(NULL, 0, serverThreadMain2, 0, 0, &serverThreadId);
866     ok(serverThread != NULL, "CreateThread failed: %d\n", GetLastError());
867     exercizeServer(PIPENAME "serverThreadMain2", serverThread);
868
869     /* Try server #3 */
870     SetLastError(0xdeadbeef);
871     serverThread = CreateThread(NULL, 0, serverThreadMain3, 0, 0, &serverThreadId);
872     ok(serverThread != NULL, "CreateThread failed: %d\n", GetLastError());
873     exercizeServer(PIPENAME "serverThreadMain3", serverThread);
874
875     /* Try server #4 */
876     SetLastError(0xdeadbeef);
877     serverThread = CreateThread(NULL, 0, serverThreadMain4, 0, 0, &serverThreadId);
878     ok(serverThread != NULL, "CreateThread failed: %d\n", GetLastError());
879     exercizeServer(PIPENAME "serverThreadMain4", serverThread);
880
881     ok(SetEvent( alarm_event ), "SetEvent\n");
882     CloseHandle( alarm_event );
883     trace("test_NamedPipe_2 returning\n");
884 }
885
886 static int test_DisconnectNamedPipe(void)
887 {
888     HANDLE hnp;
889     HANDLE hFile;
890     static const char obuf[] = "Bit Bucket";
891     char ibuf[32];
892     DWORD written;
893     DWORD readden;
894     DWORD ret;
895
896     SetLastError(0xdeadbeef);
897     hnp = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_WAIT,
898         /* nMaxInstances */ 1,
899         /* nOutBufSize */ 1024,
900         /* nInBufSize */ 1024,
901         /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
902         /* lpSecurityAttrib */ NULL);
903     if ((hnp == INVALID_HANDLE_VALUE /* Win98 */ || !hnp /* Win95 */)
904         && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED) {
905
906         win_skip("Named pipes are not implemented\n");
907         return 1;
908     }
909
910     ok(WriteFile(hnp, obuf, sizeof(obuf), &written, NULL) == 0
911         && GetLastError() == ERROR_PIPE_LISTENING, "WriteFile to not-yet-connected pipe\n");
912     ok(ReadFile(hnp, ibuf, sizeof(ibuf), &readden, NULL) == 0
913         && GetLastError() == ERROR_PIPE_LISTENING, "ReadFile from not-yet-connected pipe\n");
914
915     hFile = CreateFileA(PIPENAME, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
916     ok(hFile != INVALID_HANDLE_VALUE, "CreateFile failed\n");
917
918     /* don't try to do i/o if one side couldn't be opened, as it hangs */
919     if (hFile != INVALID_HANDLE_VALUE) {
920
921         /* see what happens if server calls DisconnectNamedPipe
922          * when there are bytes in the pipe
923          */
924
925         ok(WriteFile(hFile, obuf, sizeof(obuf), &written, NULL), "WriteFile\n");
926         ok(written == sizeof(obuf), "write file len\n");
927         ok(DisconnectNamedPipe(hnp), "DisconnectNamedPipe while messages waiting\n");
928         ok(WriteFile(hFile, obuf, sizeof(obuf), &written, NULL) == 0
929             && GetLastError() == ERROR_PIPE_NOT_CONNECTED, "WriteFile to disconnected pipe\n");
930         ok(ReadFile(hnp, ibuf, sizeof(ibuf), &readden, NULL) == 0
931             && GetLastError() == ERROR_PIPE_NOT_CONNECTED,
932             "ReadFile from disconnected pipe with bytes waiting\n");
933         ok(!DisconnectNamedPipe(hnp) && GetLastError() == ERROR_PIPE_NOT_CONNECTED,
934            "DisconnectNamedPipe worked twice\n");
935         ret = WaitForSingleObject(hFile, 0);
936         ok(ret == WAIT_TIMEOUT, "WaitForSingleObject returned %X\n", ret);
937         ok(CloseHandle(hFile), "CloseHandle\n");
938     }
939
940     ok(CloseHandle(hnp), "CloseHandle\n");
941
942     return 0;
943 }
944 static void test_CreatePipe(void)
945 {
946     SECURITY_ATTRIBUTES pipe_attr;
947     HANDLE piperead, pipewrite;
948     DWORD written;
949     DWORD read;
950     DWORD i, size;
951     BYTE *buffer;
952     char readbuf[32];
953
954     user_apc_ran = FALSE;
955     if (pQueueUserAPC)
956         ok(pQueueUserAPC(user_apc, GetCurrentThread(), 0), "couldn't create user apc\n");
957
958     pipe_attr.nLength = sizeof(SECURITY_ATTRIBUTES); 
959     pipe_attr.bInheritHandle = TRUE; 
960     pipe_attr.lpSecurityDescriptor = NULL;
961     ok(CreatePipe(&piperead, &pipewrite, &pipe_attr, 0) != 0, "CreatePipe failed\n");
962     ok(WriteFile(pipewrite,PIPENAME,sizeof(PIPENAME), &written, NULL), "Write to anonymous pipe failed\n");
963     ok(written == sizeof(PIPENAME), "Write to anonymous pipe wrote %d bytes\n", written);
964     ok(ReadFile(piperead,readbuf,sizeof(readbuf),&read, NULL), "Read from non empty pipe failed\n");
965     ok(read == sizeof(PIPENAME), "Read from  anonymous pipe got %d bytes\n", read);
966     ok(CloseHandle(pipewrite), "CloseHandle for the write pipe failed\n");
967     ok(CloseHandle(piperead), "CloseHandle for the read pipe failed\n");
968
969     /* Now write another chunk*/
970     ok(CreatePipe(&piperead, &pipewrite, &pipe_attr, 0) != 0, "CreatePipe failed\n");
971     ok(WriteFile(pipewrite,PIPENAME,sizeof(PIPENAME), &written, NULL), "Write to anonymous pipe failed\n");
972     ok(written == sizeof(PIPENAME), "Write to anonymous pipe wrote %d bytes\n", written);
973     /* and close the write end, read should still succeed*/
974     ok(CloseHandle(pipewrite), "CloseHandle for the Write Pipe failed\n");
975     ok(ReadFile(piperead,readbuf,sizeof(readbuf),&read, NULL), "Read from broken pipe withe with pending data failed\n");
976     ok(read == sizeof(PIPENAME), "Read from  anonymous pipe got %d bytes\n", read);
977     /* But now we need to get informed that the pipe is closed */
978     ok(ReadFile(piperead,readbuf,sizeof(readbuf),&read, NULL) == 0, "Broken pipe not detected\n");
979     ok(CloseHandle(piperead), "CloseHandle for the read pipe failed\n");
980
981     /* Try bigger chunks */
982     size = 32768;
983     buffer = HeapAlloc( GetProcessHeap(), 0, size );
984     for (i = 0; i < size; i++) buffer[i] = i;
985     ok(CreatePipe(&piperead, &pipewrite, &pipe_attr, (size + 24)) != 0, "CreatePipe failed\n");
986     ok(WriteFile(pipewrite, buffer, size, &written, NULL), "Write to anonymous pipe failed\n");
987     ok(written == size, "Write to anonymous pipe wrote %d bytes\n", written);
988     /* and close the write end, read should still succeed*/
989     ok(CloseHandle(pipewrite), "CloseHandle for the Write Pipe failed\n");
990     memset( buffer, 0, size );
991     ok(ReadFile(piperead, buffer, size, &read, NULL), "Read from broken pipe withe with pending data failed\n");
992     ok(read == size, "Read from  anonymous pipe got %d bytes\n", read);
993     for (i = 0; i < size; i++) ok( buffer[i] == (BYTE)i, "invalid data %x at %x\n", buffer[i], i );
994     /* But now we need to get informed that the pipe is closed */
995     ok(ReadFile(piperead,readbuf,sizeof(readbuf),&read, NULL) == 0, "Broken pipe not detected\n");
996     ok(CloseHandle(piperead), "CloseHandle for the read pipe failed\n");
997     HeapFree(GetProcessHeap(), 0, buffer);
998
999     ok(user_apc_ran == FALSE, "user apc ran, pipe using alertable io mode\n");
1000     SleepEx(0, TRUE); /* get rid of apc */
1001 }
1002
1003 struct named_pipe_client_params
1004 {
1005     DWORD security_flags;
1006     HANDLE token;
1007     BOOL revert;
1008 };
1009
1010 #define PIPE_NAME "\\\\.\\pipe\\named_pipe_test"
1011
1012 static DWORD CALLBACK named_pipe_client_func(LPVOID p)
1013 {
1014     struct named_pipe_client_params *params = p;
1015     HANDLE pipe;
1016     BOOL ret;
1017     const char message[] = "Test";
1018     DWORD bytes_read, bytes_written;
1019     char dummy;
1020     TOKEN_PRIVILEGES *Privileges = NULL;
1021
1022     if (params->token)
1023     {
1024         if (params->revert)
1025         {
1026             /* modify the token so we can tell if the pipe impersonation
1027              * token reverts to the process token */
1028             ret = AdjustTokenPrivileges(params->token, TRUE, NULL, 0, NULL, NULL);
1029             ok(ret, "AdjustTokenPrivileges failed with error %d\n", GetLastError());
1030         }
1031         ret = SetThreadToken(NULL, params->token);
1032         ok(ret, "SetThreadToken failed with error %d\n", GetLastError());
1033     }
1034     else
1035     {
1036         DWORD Size = 0;
1037         HANDLE process_token;
1038
1039         ret = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES, &process_token);
1040         ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1041
1042         ret = GetTokenInformation(process_token, TokenPrivileges, NULL, 0, &Size);
1043         ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "GetTokenInformation(TokenPrivileges) failed with %d\n", GetLastError());
1044         Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
1045         ret = GetTokenInformation(process_token, TokenPrivileges, Privileges, Size, &Size);
1046         ok(ret, "GetTokenInformation(TokenPrivileges) failed with %d\n", GetLastError());
1047
1048         ret = AdjustTokenPrivileges(process_token, TRUE, NULL, 0, NULL, NULL);
1049         ok(ret, "AdjustTokenPrivileges failed with error %d\n", GetLastError());
1050
1051         CloseHandle(process_token);
1052     }
1053
1054     pipe = CreateFile(PIPE_NAME, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, params->security_flags, NULL);
1055     ok(pipe != INVALID_HANDLE_VALUE, "CreateFile for pipe failed with error %d\n", GetLastError());
1056
1057     ret = WriteFile(pipe, message, sizeof(message), &bytes_written, NULL);
1058     ok(ret, "WriteFile failed with error %d\n", GetLastError());
1059
1060     ret = ReadFile(pipe, &dummy, sizeof(dummy), &bytes_read, NULL);
1061     ok(ret, "ReadFile failed with error %d\n", GetLastError());
1062
1063     if (params->token)
1064     {
1065         if (params->revert)
1066         {
1067             ret = RevertToSelf();
1068             ok(ret, "RevertToSelf failed with error %d\n", GetLastError());
1069         }
1070         else
1071         {
1072             ret = AdjustTokenPrivileges(params->token, TRUE, NULL, 0, NULL, NULL);
1073             ok(ret, "AdjustTokenPrivileges failed with error %d\n", GetLastError());
1074         }
1075     }
1076     else
1077     {
1078         HANDLE process_token;
1079
1080         ret = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &process_token);
1081         ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1082
1083         ret = AdjustTokenPrivileges(process_token, FALSE, Privileges, 0, NULL, NULL);
1084         ok(ret, "AdjustTokenPrivileges failed with error %d\n", GetLastError());
1085
1086         HeapFree(GetProcessHeap(), 0, Privileges);
1087
1088         CloseHandle(process_token);
1089     }
1090
1091     ret = WriteFile(pipe, message, sizeof(message), &bytes_written, NULL);
1092     ok(ret, "WriteFile failed with error %d\n", GetLastError());
1093
1094     ret = ReadFile(pipe, &dummy, sizeof(dummy), &bytes_read, NULL);
1095     ok(ret, "ReadFile failed with error %d\n", GetLastError());
1096
1097     CloseHandle(pipe);
1098
1099     return 0;
1100 }
1101
1102 static HANDLE make_impersonation_token(DWORD Access, SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
1103 {
1104     HANDLE ProcessToken;
1105     HANDLE Token = NULL;
1106     BOOL ret;
1107
1108     ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &ProcessToken);
1109     ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1110
1111     ret = pDuplicateTokenEx(ProcessToken, Access, NULL, ImpersonationLevel, TokenImpersonation, &Token);
1112     ok(ret, "DuplicateToken failed with error %d\n", GetLastError());
1113
1114     CloseHandle(ProcessToken);
1115
1116     return Token;
1117 }
1118
1119 static void test_ImpersonateNamedPipeClient(HANDLE hClientToken, DWORD security_flags, BOOL revert, void (*test_func)(int, HANDLE))
1120 {
1121     HANDLE hPipeServer;
1122     BOOL ret;
1123     DWORD dwTid;
1124     HANDLE hThread;
1125     char buffer[256];
1126     DWORD dwBytesRead;
1127     DWORD error;
1128     struct named_pipe_client_params params;
1129     char dummy = 0;
1130     DWORD dwBytesWritten;
1131     HANDLE hToken = NULL;
1132     SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
1133     DWORD size;
1134
1135     hPipeServer = CreateNamedPipe(PIPE_NAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, 1, 100, 100, NMPWAIT_USE_DEFAULT_WAIT, NULL);
1136     ok(hPipeServer != INVALID_HANDLE_VALUE, "CreateNamedPipe failed with error %d\n", GetLastError());
1137
1138     params.security_flags = security_flags;
1139     params.token = hClientToken;
1140     params.revert = revert;
1141     hThread = CreateThread(NULL, 0, named_pipe_client_func, &params, 0, &dwTid);
1142     ok(hThread != NULL, "CreateThread failed with error %d\n", GetLastError());
1143
1144     SetLastError(0xdeadbeef);
1145     ret = ImpersonateNamedPipeClient(hPipeServer);
1146     error = GetLastError();
1147     ok(ret /* win2k3 */ || (error == ERROR_CANNOT_IMPERSONATE),
1148        "ImpersonateNamedPipeClient should have failed with ERROR_CANNOT_IMPERSONATE instead of %d\n", GetLastError());
1149
1150     ret = ConnectNamedPipe(hPipeServer, NULL);
1151     ok(ret || (GetLastError() == ERROR_PIPE_CONNECTED), "ConnectNamedPipe failed with error %d\n", GetLastError());
1152
1153     ret = ReadFile(hPipeServer, buffer, sizeof(buffer), &dwBytesRead, NULL);
1154     ok(ret, "ReadFile failed with error %d\n", GetLastError());
1155
1156     ret = ImpersonateNamedPipeClient(hPipeServer);
1157     ok(ret, "ImpersonateNamedPipeClient failed with error %d\n", GetLastError());
1158
1159     ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, FALSE, &hToken);
1160     ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
1161
1162     (*test_func)(0, hToken);
1163
1164     ImpersonationLevel = 0xdeadbeef; /* to avoid false positives */
1165     ret = GetTokenInformation(hToken, TokenImpersonationLevel, &ImpersonationLevel, sizeof(ImpersonationLevel), &size);
1166     ok(ret, "GetTokenInformation(TokenImpersonationLevel) failed with error %d\n", GetLastError());
1167     ok(ImpersonationLevel == SecurityImpersonation, "ImpersonationLevel should have been SecurityImpersonation(%d) instead of %d\n", SecurityImpersonation, ImpersonationLevel);
1168
1169     CloseHandle(hToken);
1170
1171     RevertToSelf();
1172
1173     ret = WriteFile(hPipeServer, &dummy, sizeof(dummy), &dwBytesWritten, NULL);
1174     ok(ret, "WriteFile failed with error %d\n", GetLastError());
1175
1176     ret = ReadFile(hPipeServer, buffer, sizeof(buffer), &dwBytesRead, NULL);
1177     ok(ret, "ReadFile failed with error %d\n", GetLastError());
1178
1179     ret = ImpersonateNamedPipeClient(hPipeServer);
1180     ok(ret, "ImpersonateNamedPipeClient failed with error %d\n", GetLastError());
1181
1182     ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, FALSE, &hToken);
1183     ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
1184
1185     (*test_func)(1, hToken);
1186
1187     CloseHandle(hToken);
1188
1189     RevertToSelf();
1190
1191     ret = WriteFile(hPipeServer, &dummy, sizeof(dummy), &dwBytesWritten, NULL);
1192     ok(ret, "WriteFile failed with error %d\n", GetLastError());
1193
1194     WaitForSingleObject(hThread, INFINITE);
1195
1196     ret = ImpersonateNamedPipeClient(hPipeServer);
1197     ok(ret, "ImpersonateNamedPipeClient failed with error %d\n", GetLastError());
1198
1199     RevertToSelf();
1200
1201     CloseHandle(hThread);
1202     CloseHandle(hPipeServer);
1203 }
1204
1205 static BOOL are_all_privileges_disabled(HANDLE hToken)
1206 {
1207     BOOL ret;
1208     TOKEN_PRIVILEGES *Privileges = NULL;
1209     DWORD Size = 0;
1210     BOOL all_privs_disabled = TRUE;
1211     DWORD i;
1212
1213     ret = GetTokenInformation(hToken, TokenPrivileges, NULL, 0, &Size);
1214     if (!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
1215     {
1216         Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
1217         ret = GetTokenInformation(hToken, TokenPrivileges, Privileges, Size, &Size);
1218         if (!ret)
1219         {
1220             HeapFree(GetProcessHeap(), 0, Privileges);
1221             return FALSE;
1222         }
1223     }
1224     else
1225         return FALSE;
1226
1227     for (i = 0; i < Privileges->PrivilegeCount; i++)
1228     {
1229         if (Privileges->Privileges[i].Attributes & SE_PRIVILEGE_ENABLED)
1230         {
1231             all_privs_disabled = FALSE;
1232             break;
1233         }
1234     }
1235
1236     HeapFree(GetProcessHeap(), 0, Privileges);
1237
1238     return all_privs_disabled;
1239 }
1240
1241 static DWORD get_privilege_count(HANDLE hToken)
1242 {
1243     TOKEN_STATISTICS Statistics;
1244     DWORD Size = sizeof(Statistics);
1245     BOOL ret;
1246
1247     ret = GetTokenInformation(hToken, TokenStatistics, &Statistics, Size, &Size);
1248     ok(ret, "GetTokenInformation(TokenStatistics)\n");
1249     if (!ret) return -1;
1250
1251     return Statistics.PrivilegeCount;
1252 }
1253
1254 static void test_no_sqos_no_token(int call_index, HANDLE hToken)
1255 {
1256     DWORD priv_count;
1257
1258     switch (call_index)
1259     {
1260     case 0:
1261         priv_count = get_privilege_count(hToken);
1262         todo_wine
1263         ok(priv_count == 0, "privilege count should have been 0 instead of %d\n", priv_count);
1264         break;
1265     case 1:
1266         priv_count = get_privilege_count(hToken);
1267         ok(priv_count > 0, "privilege count should now be > 0 instead of 0\n");
1268         ok(!are_all_privileges_disabled(hToken), "impersonated token should not have been modified\n");
1269         break;
1270     default:
1271         ok(0, "shouldn't happen\n");
1272     }
1273 }
1274
1275 static void test_no_sqos(int call_index, HANDLE hToken)
1276 {
1277     switch (call_index)
1278     {
1279     case 0:
1280         ok(!are_all_privileges_disabled(hToken), "token should be a copy of the process one\n");
1281         break;
1282     case 1:
1283         todo_wine
1284         ok(are_all_privileges_disabled(hToken), "impersonated token should have been modified\n");
1285         break;
1286     default:
1287         ok(0, "shouldn't happen\n");
1288     }
1289 }
1290
1291 static void test_static_context(int call_index, HANDLE hToken)
1292 {
1293     switch (call_index)
1294     {
1295     case 0:
1296         ok(!are_all_privileges_disabled(hToken), "token should be a copy of the process one\n");
1297         break;
1298     case 1:
1299         ok(!are_all_privileges_disabled(hToken), "impersonated token should not have been modified\n");
1300         break;
1301     default:
1302         ok(0, "shouldn't happen\n");
1303     }
1304 }
1305
1306 static void test_dynamic_context(int call_index, HANDLE hToken)
1307 {
1308     switch (call_index)
1309     {
1310     case 0:
1311         ok(!are_all_privileges_disabled(hToken), "token should be a copy of the process one\n");
1312         break;
1313     case 1:
1314         todo_wine
1315         ok(are_all_privileges_disabled(hToken), "impersonated token should have been modified\n");
1316         break;
1317     default:
1318         ok(0, "shouldn't happen\n");
1319     }
1320 }
1321
1322 static void test_dynamic_context_no_token(int call_index, HANDLE hToken)
1323 {
1324     switch (call_index)
1325     {
1326     case 0:
1327         ok(are_all_privileges_disabled(hToken), "token should be a copy of the process one\n");
1328         break;
1329     case 1:
1330         ok(!are_all_privileges_disabled(hToken), "process token modification should have been detected and impersonation token updated\n");
1331         break;
1332     default:
1333         ok(0, "shouldn't happen\n");
1334     }
1335 }
1336
1337 static void test_no_sqos_revert(int call_index, HANDLE hToken)
1338 {
1339     DWORD priv_count;
1340     switch (call_index)
1341     {
1342     case 0:
1343         priv_count = get_privilege_count(hToken);
1344         todo_wine
1345         ok(priv_count == 0, "privilege count should have been 0 instead of %d\n", priv_count);
1346         break;
1347     case 1:
1348         priv_count = get_privilege_count(hToken);
1349         ok(priv_count > 0, "privilege count should now be > 0 instead of 0\n");
1350         ok(!are_all_privileges_disabled(hToken), "impersonated token should not have been modified\n");
1351         break;
1352     default:
1353         ok(0, "shouldn't happen\n");
1354     }
1355 }
1356
1357 static void test_static_context_revert(int call_index, HANDLE hToken)
1358 {
1359     switch (call_index)
1360     {
1361     case 0:
1362         todo_wine
1363         ok(are_all_privileges_disabled(hToken), "privileges should have been disabled\n");
1364         break;
1365     case 1:
1366         todo_wine
1367         ok(are_all_privileges_disabled(hToken), "impersonated token should not have been modified\n");
1368         break;
1369     default:
1370         ok(0, "shouldn't happen\n");
1371     }
1372 }
1373
1374 static void test_dynamic_context_revert(int call_index, HANDLE hToken)
1375 {
1376     switch (call_index)
1377     {
1378     case 0:
1379         todo_wine
1380         ok(are_all_privileges_disabled(hToken), "privileges should have been disabled\n");
1381         break;
1382     case 1:
1383         ok(!are_all_privileges_disabled(hToken), "impersonated token should now be process token\n");
1384         break;
1385     default:
1386         ok(0, "shouldn't happen\n");
1387     }
1388 }
1389
1390 static void test_impersonation(void)
1391 {
1392     HANDLE hClientToken;
1393     HANDLE hProcessToken;
1394     BOOL ret;
1395
1396     if( !pDuplicateTokenEx ) {
1397         skip("DuplicateTokenEx not found\n");
1398         return;
1399     }
1400
1401     ret = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hProcessToken);
1402     if (!ret)
1403     {
1404         skip("couldn't open process token, skipping impersonation tests\n");
1405         return;
1406     }
1407
1408     if (!get_privilege_count(hProcessToken) || are_all_privileges_disabled(hProcessToken))
1409     {
1410         skip("token didn't have any privileges or they were all disabled. token not suitable for impersonation tests\n");
1411         CloseHandle(hProcessToken);
1412         return;
1413     }
1414     CloseHandle(hProcessToken);
1415
1416     test_ImpersonateNamedPipeClient(NULL, 0, FALSE, test_no_sqos_no_token);
1417     hClientToken = make_impersonation_token(TOKEN_IMPERSONATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, SecurityImpersonation);
1418     test_ImpersonateNamedPipeClient(hClientToken, 0, FALSE, test_no_sqos);
1419     CloseHandle(hClientToken);
1420     hClientToken = make_impersonation_token(TOKEN_IMPERSONATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, SecurityImpersonation);
1421     test_ImpersonateNamedPipeClient(hClientToken,
1422         SECURITY_SQOS_PRESENT | SECURITY_IMPERSONATION, FALSE,
1423         test_static_context);
1424     CloseHandle(hClientToken);
1425     hClientToken = make_impersonation_token(TOKEN_IMPERSONATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, SecurityImpersonation);
1426     test_ImpersonateNamedPipeClient(hClientToken,
1427         SECURITY_SQOS_PRESENT | SECURITY_CONTEXT_TRACKING | SECURITY_IMPERSONATION,
1428         FALSE, test_dynamic_context);
1429     CloseHandle(hClientToken);
1430     test_ImpersonateNamedPipeClient(NULL,
1431         SECURITY_SQOS_PRESENT | SECURITY_CONTEXT_TRACKING | SECURITY_IMPERSONATION,
1432         FALSE, test_dynamic_context_no_token);
1433
1434     hClientToken = make_impersonation_token(TOKEN_IMPERSONATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, SecurityImpersonation);
1435     test_ImpersonateNamedPipeClient(hClientToken, 0, TRUE, test_no_sqos_revert);
1436     CloseHandle(hClientToken);
1437     hClientToken = make_impersonation_token(TOKEN_IMPERSONATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, SecurityImpersonation);
1438     test_ImpersonateNamedPipeClient(hClientToken,
1439         SECURITY_SQOS_PRESENT | SECURITY_IMPERSONATION, TRUE,
1440         test_static_context_revert);
1441     CloseHandle(hClientToken);
1442     hClientToken = make_impersonation_token(TOKEN_IMPERSONATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, SecurityImpersonation);
1443     test_ImpersonateNamedPipeClient(hClientToken,
1444         SECURITY_SQOS_PRESENT | SECURITY_CONTEXT_TRACKING | SECURITY_IMPERSONATION,
1445         TRUE, test_dynamic_context_revert);
1446     CloseHandle(hClientToken);
1447 }
1448
1449 struct overlapped_server_args
1450 {
1451     HANDLE pipe_created;
1452 };
1453
1454 static DWORD CALLBACK overlapped_server(LPVOID arg)
1455 {
1456     OVERLAPPED ol;
1457     HANDLE pipe;
1458     int ret, err;
1459     struct overlapped_server_args *a = arg;
1460     DWORD num;
1461     char buf[100];
1462
1463     pipe = CreateNamedPipeA("\\\\.\\pipe\\my pipe", FILE_FLAG_OVERLAPPED | PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE, 1, 0, 0, 100000, NULL);
1464     ok(pipe != NULL, "pipe NULL\n");
1465
1466     ol.hEvent = CreateEventA(0, 1, 0, 0);
1467     ok(ol.hEvent != NULL, "event NULL\n");
1468     ret = ConnectNamedPipe(pipe, &ol);
1469     err = GetLastError();
1470     ok(ret == 0, "ret %d\n", ret);
1471     ok(err == ERROR_IO_PENDING, "gle %d\n", err);
1472     SetEvent(a->pipe_created);
1473
1474     ret = WaitForSingleObjectEx(ol.hEvent, INFINITE, 1);
1475     ok(ret == WAIT_OBJECT_0, "ret %x\n", ret);
1476
1477     ret = GetOverlappedResult(pipe, &ol, &num, 1);
1478     ok(ret == 1, "ret %d\n", ret);
1479
1480     /* This should block */
1481     ret = ReadFile(pipe, buf, sizeof(buf), &num, NULL);
1482     ok(ret == 1, "ret %d\n", ret);
1483
1484     DisconnectNamedPipe(pipe);
1485     CloseHandle(ol.hEvent);
1486     CloseHandle(pipe);
1487     return 1;
1488 }
1489
1490 static void test_overlapped(void)
1491 {
1492     DWORD tid, num;
1493     HANDLE thread, pipe;
1494     BOOL ret;
1495     struct overlapped_server_args args;
1496
1497     args.pipe_created = CreateEventA(0, 1, 0, 0);
1498     thread = CreateThread(NULL, 0, overlapped_server, &args, 0, &tid);
1499
1500     WaitForSingleObject(args.pipe_created, INFINITE);
1501     pipe = CreateFileA("\\\\.\\pipe\\my pipe", GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
1502     ok(pipe != INVALID_HANDLE_VALUE, "cf failed\n");
1503
1504     /* Sleep to try to get the ReadFile in the server to occur before the following WriteFile */
1505     Sleep(1);
1506
1507     ret = WriteFile(pipe, "x", 1, &num, NULL);
1508     ok(ret, "WriteFile failed with error %d\n", GetLastError());
1509
1510     WaitForSingleObject(thread, INFINITE);
1511     CloseHandle(pipe);
1512     CloseHandle(args.pipe_created);
1513     CloseHandle(thread);
1514 }
1515
1516 static void test_NamedPipeHandleState(void)
1517 {
1518     HANDLE server, client;
1519     BOOL ret;
1520     DWORD state, instances, maxCollectionCount, collectDataTimeout;
1521     char userName[MAX_PATH];
1522
1523     server = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX,
1524         /* dwOpenMode */ PIPE_TYPE_BYTE | PIPE_WAIT,
1525         /* nMaxInstances */ 1,
1526         /* nOutBufSize */ 1024,
1527         /* nInBufSize */ 1024,
1528         /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
1529         /* lpSecurityAttrib */ NULL);
1530     ok(server != INVALID_HANDLE_VALUE, "cf failed\n");
1531     ret = GetNamedPipeHandleState(server, NULL, NULL, NULL, NULL, NULL, 0);
1532     todo_wine
1533     ok(ret, "GetNamedPipeHandleState failed: %d\n", GetLastError());
1534     ret = GetNamedPipeHandleState(server, &state, &instances, NULL, NULL, NULL,
1535         0);
1536     todo_wine
1537     ok(ret, "GetNamedPipeHandleState failed: %d\n", GetLastError());
1538     if (ret)
1539     {
1540         ok(state == 0, "unexpected state %08x\n", state);
1541         ok(instances == 1, "expected 1 instances, got %d\n", instances);
1542     }
1543     /* Some parameters have no meaning, and therefore can't be retrieved,
1544      * on a local pipe.
1545      */
1546     SetLastError(0xdeadbeef);
1547     ret = GetNamedPipeHandleState(server, &state, &instances,
1548         &maxCollectionCount, &collectDataTimeout, userName,
1549         sizeof(userName) / sizeof(userName[0]));
1550     todo_wine
1551     ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
1552        "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
1553     /* A byte-mode pipe server can't be changed to message mode. */
1554     state = PIPE_READMODE_MESSAGE;
1555     SetLastError(0xdeadbeef);
1556     ret = SetNamedPipeHandleState(server, &state, NULL, NULL);
1557     todo_wine
1558     ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
1559        "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
1560
1561     client = CreateFileA(PIPENAME, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1562         OPEN_EXISTING, 0, NULL);
1563     ok(client != INVALID_HANDLE_VALUE, "cf failed\n");
1564
1565     state = PIPE_READMODE_BYTE;
1566     ret = SetNamedPipeHandleState(client, &state, NULL, NULL);
1567     todo_wine
1568     ok(ret, "SetNamedPipeHandleState failed: %d\n", GetLastError());
1569     /* A byte-mode pipe client can't be changed to message mode, either. */
1570     state = PIPE_READMODE_MESSAGE;
1571     SetLastError(0xdeadbeef);
1572     ret = SetNamedPipeHandleState(server, &state, NULL, NULL);
1573     todo_wine
1574     ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
1575        "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
1576
1577     CloseHandle(client);
1578     CloseHandle(server);
1579
1580     server = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX,
1581         /* dwOpenMode */ PIPE_TYPE_MESSAGE | PIPE_WAIT,
1582         /* nMaxInstances */ 1,
1583         /* nOutBufSize */ 1024,
1584         /* nInBufSize */ 1024,
1585         /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
1586         /* lpSecurityAttrib */ NULL);
1587     ok(server != INVALID_HANDLE_VALUE, "cf failed\n");
1588     ret = GetNamedPipeHandleState(server, NULL, NULL, NULL, NULL, NULL, 0);
1589     todo_wine
1590     ok(ret, "GetNamedPipeHandleState failed: %d\n", GetLastError());
1591     ret = GetNamedPipeHandleState(server, &state, &instances, NULL, NULL, NULL,
1592         0);
1593     todo_wine
1594     ok(ret, "GetNamedPipeHandleState failed: %d\n", GetLastError());
1595     if (ret)
1596     {
1597         ok(state == 0, "unexpected state %08x\n", state);
1598         ok(instances == 1, "expected 1 instances, got %d\n", instances);
1599     }
1600     /* In contrast to byte-mode pipes, a message-mode pipe server can be
1601      * changed to byte mode.
1602      */
1603     state = PIPE_READMODE_BYTE;
1604     ret = SetNamedPipeHandleState(server, &state, NULL, NULL);
1605     todo_wine
1606     ok(ret, "SetNamedPipeHandleState failed: %d\n", GetLastError());
1607
1608     client = CreateFileA(PIPENAME, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1609         OPEN_EXISTING, 0, NULL);
1610     ok(client != INVALID_HANDLE_VALUE, "cf failed\n");
1611
1612     state = PIPE_READMODE_MESSAGE;
1613     ret = SetNamedPipeHandleState(client, &state, NULL, NULL);
1614     todo_wine
1615     ok(ret, "SetNamedPipeHandleState failed: %d\n", GetLastError());
1616     /* A message-mode pipe client can also be changed to byte mode.
1617      */
1618     state = PIPE_READMODE_BYTE;
1619     ret = SetNamedPipeHandleState(client, &state, NULL, NULL);
1620     todo_wine
1621     ok(ret, "SetNamedPipeHandleState failed: %d\n", GetLastError());
1622
1623     CloseHandle(client);
1624     CloseHandle(server);
1625 }
1626
1627 START_TEST(pipe)
1628 {
1629     HMODULE hmod;
1630
1631     hmod = GetModuleHandle("advapi32.dll");
1632     pDuplicateTokenEx = (void *) GetProcAddress(hmod, "DuplicateTokenEx");
1633     hmod = GetModuleHandle("kernel32.dll");
1634     pQueueUserAPC = (void *) GetProcAddress(hmod, "QueueUserAPC");
1635
1636     if (test_DisconnectNamedPipe())
1637         return;
1638     test_CreateNamedPipe_instances_must_match();
1639     test_NamedPipe_2();
1640     test_CreateNamedPipe(PIPE_TYPE_BYTE);
1641     test_CreateNamedPipe(PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE);
1642     test_CreatePipe();
1643     test_impersonation();
1644     test_overlapped();
1645     test_NamedPipeHandleState();
1646 }