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