comctl32/treeview: Use a code set by dispinfo holder to convert data encoding after...
[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 static 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         if (i == 0) {
551             trace("Server calling non-overlapped ConnectNamedPipe on overlapped pipe...\n");
552             success = ConnectNamedPipe(hnp, NULL);
553             err = GetLastError();
554             ok(success || (err == ERROR_PIPE_CONNECTED), "ConnectNamedPipe failed: %d\n", err);
555             trace("ConnectNamedPipe operation complete.\n");
556         } else {
557             trace("Server calling overlapped ConnectNamedPipe...\n");
558             success = ConnectNamedPipe(hnp, &oOverlap);
559             err = GetLastError();
560             ok(!success && (err == ERROR_IO_PENDING || err == ERROR_PIPE_CONNECTED), "overlapped ConnectNamedPipe\n");
561             trace("overlapped ConnectNamedPipe returned.\n");
562             if (!success && (err == ERROR_IO_PENDING)) {
563                 if (letWFSOEwait)
564                 {
565                     DWORD ret;
566                     do {
567                         ret = WaitForSingleObjectEx(hEvent, INFINITE, TRUE);
568                     } while (ret == WAIT_IO_COMPLETION);
569                     ok(ret == 0, "wait ConnectNamedPipe returned %x\n", ret);
570                 }
571                 success = GetOverlappedResult(hnp, &oOverlap, &dummy, letGORwait);
572                 if (!letGORwait && !letWFSOEwait && !success) {
573                     ok(GetLastError() == ERROR_IO_INCOMPLETE, "GetOverlappedResult\n");
574                     success = GetOverlappedResult(hnp, &oOverlap, &dummy, TRUE);
575                 }
576             }
577             ok(success || (err == ERROR_PIPE_CONNECTED), "GetOverlappedResult ConnectNamedPipe\n");
578             trace("overlapped ConnectNamedPipe operation complete.\n");
579         }
580
581         /* Echo bytes once */
582         memset(buf, 0, sizeof(buf));
583
584         trace("Server reading...\n");
585         success = ReadFile(hnp, buf, sizeof(buf), &readden, &oOverlap);
586         trace("Server ReadFile returned...\n");
587         err = GetLastError();
588         ok(success || err == ERROR_IO_PENDING, "overlapped ReadFile\n");
589         trace("overlapped ReadFile returned.\n");
590         if (!success && (err == ERROR_IO_PENDING)) {
591             if (letWFSOEwait)
592             {
593                 DWORD ret;
594                 do {
595                     ret = WaitForSingleObjectEx(hEvent, INFINITE, TRUE);
596                 } while (ret == WAIT_IO_COMPLETION);
597                 ok(ret == 0, "wait ReadFile returned %x\n", ret);
598             }
599             success = GetOverlappedResult(hnp, &oOverlap, &readden, letGORwait);
600             if (!letGORwait && !letWFSOEwait && !success) {
601                 ok(GetLastError() == ERROR_IO_INCOMPLETE, "GetOverlappedResult\n");
602                 success = GetOverlappedResult(hnp, &oOverlap, &readden, TRUE);
603             }
604         }
605         trace("Server done reading.\n");
606         ok(success, "overlapped ReadFile\n");
607
608         trace("Server writing...\n");
609         success = WriteFile(hnp, buf, readden, &written, &oOverlap);
610         trace("Server WriteFile returned...\n");
611         err = GetLastError();
612         ok(success || err == ERROR_IO_PENDING, "overlapped WriteFile\n");
613         trace("overlapped WriteFile returned.\n");
614         if (!success && (err == ERROR_IO_PENDING)) {
615             if (letWFSOEwait)
616             {
617                 DWORD ret;
618                 do {
619                     ret = WaitForSingleObjectEx(hEvent, INFINITE, TRUE);
620                 } while (ret == WAIT_IO_COMPLETION);
621                 ok(ret == 0, "wait WriteFile returned %x\n", ret);
622             }
623             success = GetOverlappedResult(hnp, &oOverlap, &written, letGORwait);
624             if (!letGORwait && !letWFSOEwait && !success) {
625                 ok(GetLastError() == ERROR_IO_INCOMPLETE, "GetOverlappedResult\n");
626                 success = GetOverlappedResult(hnp, &oOverlap, &written, TRUE);
627             }
628         }
629         trace("Server done writing.\n");
630         ok(success, "overlapped WriteFile\n");
631         ok(written == readden, "write file len\n");
632
633         /* finish this connection, wait for next one */
634         ok(FlushFileBuffers(hnp), "FlushFileBuffers\n");
635         ok(DisconnectNamedPipe(hnp), "DisconnectNamedPipe\n");
636     }
637     return 0;
638 }
639
640 /** Trivial byte echo server - uses i/o completion ports */
641 static DWORD CALLBACK serverThreadMain4(LPVOID arg)
642 {
643     int i;
644     HANDLE hcompletion;
645
646     trace("serverThreadMain4\n");
647     /* Set up a simple echo server */
648     hnp = CreateNamedPipe(PIPENAME "serverThreadMain4", PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
649         PIPE_TYPE_BYTE | PIPE_WAIT,
650         /* nMaxInstances */ 1,
651         /* nOutBufSize */ 1024,
652         /* nInBufSize */ 1024,
653         /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
654         /* lpSecurityAttrib */ NULL);
655     ok(hnp != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
656
657     hcompletion = CreateIoCompletionPort(hnp, NULL, 12345, 1);
658     ok(hcompletion != NULL, "CreateIoCompletionPort failed, error=%i\n", GetLastError());
659
660     for (i = 0; i < NB_SERVER_LOOPS; i++) {
661         char buf[512];
662         DWORD written;
663         DWORD readden;
664         DWORD dummy;
665         DWORD success;
666         OVERLAPPED oConnect;
667         OVERLAPPED oRead;
668         OVERLAPPED oWrite;
669         OVERLAPPED *oResult;
670         DWORD err;
671         ULONG_PTR compkey;
672
673         memset(&oConnect, 0, sizeof(oConnect));
674         memset(&oRead, 0, sizeof(oRead));
675         memset(&oWrite, 0, sizeof(oWrite));
676
677         /* Wait for client to connect */
678         trace("Server calling overlapped ConnectNamedPipe...\n");
679         success = ConnectNamedPipe(hnp, &oConnect);
680         err = GetLastError();
681         ok(!success && (err == ERROR_IO_PENDING || err == ERROR_PIPE_CONNECTED),
682            "overlapped ConnectNamedPipe got %u err %u\n", success, err );
683         if (!success && err == ERROR_IO_PENDING) {
684             trace("ConnectNamedPipe GetQueuedCompletionStatus\n");
685             success = GetQueuedCompletionStatus(hcompletion, &dummy, &compkey, &oResult, 0);
686             if (!success)
687             {
688                 ok( GetLastError() == WAIT_TIMEOUT,
689                     "ConnectNamedPipe GetQueuedCompletionStatus wrong error %u\n", GetLastError());
690                 success = GetQueuedCompletionStatus(hcompletion, &dummy, &compkey, &oResult, 10000);
691             }
692             ok(success, "ConnectNamedPipe GetQueuedCompletionStatus failed, errno=%i\n", GetLastError());
693             if (success)
694             {
695                 ok(compkey == 12345, "got completion key %i instead of 12345\n", (int)compkey);
696                 ok(oResult == &oConnect, "got overlapped pointer %p instead of %p\n", oResult, &oConnect);
697             }
698         }
699         trace("overlapped ConnectNamedPipe operation complete.\n");
700
701         /* Echo bytes once */
702         memset(buf, 0, sizeof(buf));
703
704         trace("Server reading...\n");
705         success = ReadFile(hnp, buf, sizeof(buf), &readden, &oRead);
706         trace("Server ReadFile returned...\n");
707         err = GetLastError();
708         ok(success || err == ERROR_IO_PENDING, "overlapped ReadFile, err=%i\n", err);
709         success = GetQueuedCompletionStatus(hcompletion, &readden, &compkey,
710             &oResult, 10000);
711         ok(success, "ReadFile GetQueuedCompletionStatus failed, errno=%i\n", GetLastError());
712         if (success)
713         {
714             ok(compkey == 12345, "got completion key %i instead of 12345\n", (int)compkey);
715             ok(oResult == &oRead, "got overlapped pointer %p instead of %p\n", oResult, &oRead);
716         }
717         trace("Server done reading.\n");
718
719         trace("Server writing...\n");
720         success = WriteFile(hnp, buf, readden, &written, &oWrite);
721         trace("Server WriteFile returned...\n");
722         err = GetLastError();
723         ok(success || err == ERROR_IO_PENDING, "overlapped WriteFile failed, err=%u\n", err);
724         success = GetQueuedCompletionStatus(hcompletion, &written, &compkey,
725             &oResult, 10000);
726         ok(success, "WriteFile GetQueuedCompletionStatus failed, errno=%i\n", GetLastError());
727         if (success)
728         {
729             ok(compkey == 12345, "got completion key %i instead of 12345\n", (int)compkey);
730             ok(oResult == &oWrite, "got overlapped pointer %p instead of %p\n", oResult, &oWrite);
731             ok(written == readden, "write file len\n");
732         }
733         trace("Server done writing.\n");
734
735         /* finish this connection, wait for next one */
736         ok(FlushFileBuffers(hnp), "FlushFileBuffers\n");
737         success = DisconnectNamedPipe(hnp);
738         ok(success, "DisconnectNamedPipe failed, err %u\n", GetLastError());
739     }
740
741     ok(CloseHandle(hnp), "CloseHandle named pipe failed, err=%i\n", GetLastError());
742     ok(CloseHandle(hcompletion), "CloseHandle completion failed, err=%i\n", GetLastError());
743
744     return 0;
745 }
746
747 static void exercizeServer(const char *pipename, HANDLE serverThread)
748 {
749     int i;
750
751     trace("exercizeServer starting\n");
752     for (i = 0; i < NB_SERVER_LOOPS; i++) {
753         HANDLE hFile=INVALID_HANDLE_VALUE;
754         static const char obuf[] = "Bit Bucket";
755         char ibuf[32];
756         DWORD written;
757         DWORD readden;
758         int loop;
759
760         for (loop = 0; loop < 3; loop++) {
761             DWORD err;
762             trace("Client connecting...\n");
763             /* Connect to the server */
764             hFile = CreateFileA(pipename, GENERIC_READ | GENERIC_WRITE, 0,
765                 NULL, OPEN_EXISTING, 0, 0);
766             if (hFile != INVALID_HANDLE_VALUE)
767                 break;
768             err = GetLastError();
769             if (loop == 0)
770                 ok(err == ERROR_PIPE_BUSY || err == ERROR_FILE_NOT_FOUND, "connecting to pipe\n");
771             else
772                 ok(err == ERROR_PIPE_BUSY, "connecting to pipe\n");
773             trace("connect failed, retrying\n");
774             Sleep(200);
775         }
776         ok(hFile != INVALID_HANDLE_VALUE, "client opening named pipe\n");
777
778         /* Make sure it can echo */
779         memset(ibuf, 0, sizeof(ibuf));
780         trace("Client writing...\n");
781         ok(WriteFile(hFile, obuf, sizeof(obuf), &written, NULL), "WriteFile to client end of pipe\n");
782         ok(written == sizeof(obuf), "write file len\n");
783         trace("Client reading...\n");
784         ok(ReadFile(hFile, ibuf, sizeof(obuf), &readden, NULL), "ReadFile from client end of pipe\n");
785         ok(readden == sizeof(obuf), "read file len\n");
786         ok(memcmp(obuf, ibuf, written) == 0, "content check\n");
787
788         trace("Client closing...\n");
789         ok(CloseHandle(hFile), "CloseHandle\n");
790     }
791
792     ok(WaitForSingleObject(serverThread,INFINITE) == WAIT_OBJECT_0, "WaitForSingleObject\n");
793     CloseHandle(hnp);
794     trace("exercizeServer returning\n");
795 }
796
797 static void test_NamedPipe_2(void)
798 {
799     HANDLE serverThread;
800     DWORD serverThreadId;
801     HANDLE alarmThread;
802     DWORD alarmThreadId;
803
804     trace("test_NamedPipe_2 starting\n");
805     /* Set up a twenty second timeout */
806     alarm_event = CreateEvent( NULL, TRUE, FALSE, NULL );
807     SetLastError(0xdeadbeef);
808     alarmThread = CreateThread(NULL, 0, alarmThreadMain, (void *) 20000, 0, &alarmThreadId);
809     ok(alarmThread != NULL, "CreateThread failed: %d\n", GetLastError());
810
811     /* The servers we're about to exercise do try to clean up carefully,
812      * but to reduce the chance of a test failure due to a pipe handle
813      * leak in the test code, we'll use a different pipe name for each server.
814      */
815
816     /* Try server #1 */
817     SetLastError(0xdeadbeef);
818     serverThread = CreateThread(NULL, 0, serverThreadMain1, (void *)8, 0, &serverThreadId);
819     ok(serverThread != NULL, "CreateThread failed: %d\n", GetLastError());
820     exercizeServer(PIPENAME "serverThreadMain1", serverThread);
821
822     /* Try server #2 */
823     SetLastError(0xdeadbeef);
824     serverThread = CreateThread(NULL, 0, serverThreadMain2, 0, 0, &serverThreadId);
825     ok(serverThread != NULL, "CreateThread failed: %d\n", GetLastError());
826     exercizeServer(PIPENAME "serverThreadMain2", serverThread);
827
828     /* Try server #3 */
829     SetLastError(0xdeadbeef);
830     serverThread = CreateThread(NULL, 0, serverThreadMain3, 0, 0, &serverThreadId);
831     ok(serverThread != NULL, "CreateThread failed: %d\n", GetLastError());
832     exercizeServer(PIPENAME "serverThreadMain3", serverThread);
833
834     /* Try server #4 */
835     SetLastError(0xdeadbeef);
836     serverThread = CreateThread(NULL, 0, serverThreadMain4, 0, 0, &serverThreadId);
837     ok(serverThread != NULL, "CreateThread failed: %d\n", GetLastError());
838     exercizeServer(PIPENAME "serverThreadMain4", serverThread);
839
840     ok(SetEvent( alarm_event ), "SetEvent\n");
841     CloseHandle( alarm_event );
842     trace("test_NamedPipe_2 returning\n");
843 }
844
845 static int test_DisconnectNamedPipe(void)
846 {
847     HANDLE hnp;
848     HANDLE hFile;
849     static const char obuf[] = "Bit Bucket";
850     char ibuf[32];
851     DWORD written;
852     DWORD readden;
853     DWORD ret;
854
855     SetLastError(0xdeadbeef);
856     hnp = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_WAIT,
857         /* nMaxInstances */ 1,
858         /* nOutBufSize */ 1024,
859         /* nInBufSize */ 1024,
860         /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
861         /* lpSecurityAttrib */ NULL);
862     if ((hnp == INVALID_HANDLE_VALUE /* Win98 */ || !hnp /* Win95 */)
863         && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED) {
864
865         win_skip("Named pipes are not implemented\n");
866         return 1;
867     }
868
869     ok(WriteFile(hnp, obuf, sizeof(obuf), &written, NULL) == 0
870         && GetLastError() == ERROR_PIPE_LISTENING, "WriteFile to not-yet-connected pipe\n");
871     ok(ReadFile(hnp, ibuf, sizeof(ibuf), &readden, NULL) == 0
872         && GetLastError() == ERROR_PIPE_LISTENING, "ReadFile from not-yet-connected pipe\n");
873
874     hFile = CreateFileA(PIPENAME, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
875     ok(hFile != INVALID_HANDLE_VALUE, "CreateFile failed\n");
876
877     /* don't try to do i/o if one side couldn't be opened, as it hangs */
878     if (hFile != INVALID_HANDLE_VALUE) {
879
880         /* see what happens if server calls DisconnectNamedPipe
881          * when there are bytes in the pipe
882          */
883
884         ok(WriteFile(hFile, obuf, sizeof(obuf), &written, NULL), "WriteFile\n");
885         ok(written == sizeof(obuf), "write file len\n");
886         ok(DisconnectNamedPipe(hnp), "DisconnectNamedPipe while messages waiting\n");
887         ok(WriteFile(hFile, obuf, sizeof(obuf), &written, NULL) == 0
888             && GetLastError() == ERROR_PIPE_NOT_CONNECTED, "WriteFile to disconnected pipe\n");
889         ok(ReadFile(hnp, ibuf, sizeof(ibuf), &readden, NULL) == 0
890             && GetLastError() == ERROR_PIPE_NOT_CONNECTED,
891             "ReadFile from disconnected pipe with bytes waiting\n");
892         ok(!DisconnectNamedPipe(hnp) && GetLastError() == ERROR_PIPE_NOT_CONNECTED,
893            "DisconnectNamedPipe worked twice\n");
894         ret = WaitForSingleObject(hFile, 0);
895         ok(ret == WAIT_TIMEOUT, "WaitForSingleObject returned %X\n", ret);
896         ok(CloseHandle(hFile), "CloseHandle\n");
897     }
898
899     ok(CloseHandle(hnp), "CloseHandle\n");
900
901     return 0;
902 }
903 static void test_CreatePipe(void)
904 {
905     SECURITY_ATTRIBUTES pipe_attr;
906     HANDLE piperead, pipewrite;
907     DWORD written;
908     DWORD read;
909     DWORD i, size;
910     BYTE *buffer;
911     char readbuf[32];
912
913     pipe_attr.nLength = sizeof(SECURITY_ATTRIBUTES); 
914     pipe_attr.bInheritHandle = TRUE; 
915     pipe_attr.lpSecurityDescriptor = NULL; 
916     ok(CreatePipe(&piperead, &pipewrite, &pipe_attr, 0) != 0, "CreatePipe failed\n");
917     ok(WriteFile(pipewrite,PIPENAME,sizeof(PIPENAME), &written, NULL), "Write to anonymous pipe failed\n");
918     ok(written == sizeof(PIPENAME), "Write to anonymous pipe wrote %d bytes\n", written);
919     ok(ReadFile(piperead,readbuf,sizeof(readbuf),&read, NULL), "Read from non empty pipe failed\n");
920     ok(read == sizeof(PIPENAME), "Read from  anonymous pipe got %d bytes\n", read);
921     ok(CloseHandle(pipewrite), "CloseHandle for the write pipe failed\n");
922     ok(CloseHandle(piperead), "CloseHandle for the read pipe failed\n");
923
924     /* Now write another chunk*/
925     ok(CreatePipe(&piperead, &pipewrite, &pipe_attr, 0) != 0, "CreatePipe failed\n");
926     ok(WriteFile(pipewrite,PIPENAME,sizeof(PIPENAME), &written, NULL), "Write to anonymous pipe failed\n");
927     ok(written == sizeof(PIPENAME), "Write to anonymous pipe wrote %d bytes\n", written);
928     /* and close the write end, read should still succeed*/
929     ok(CloseHandle(pipewrite), "CloseHandle for the Write Pipe failed\n");
930     ok(ReadFile(piperead,readbuf,sizeof(readbuf),&read, NULL), "Read from broken pipe withe with pending data failed\n");
931     ok(read == sizeof(PIPENAME), "Read from  anonymous pipe got %d bytes\n", read);
932     /* But now we need to get informed that the pipe is closed */
933     ok(ReadFile(piperead,readbuf,sizeof(readbuf),&read, NULL) == 0, "Broken pipe not detected\n");
934     ok(CloseHandle(piperead), "CloseHandle for the read pipe failed\n");
935
936     /* Try bigger chunks */
937     size = 32768;
938     buffer = HeapAlloc( GetProcessHeap(), 0, size );
939     for (i = 0; i < size; i++) buffer[i] = i;
940     ok(CreatePipe(&piperead, &pipewrite, &pipe_attr, (size + 24)) != 0, "CreatePipe failed\n");
941     ok(WriteFile(pipewrite, buffer, size, &written, NULL), "Write to anonymous pipe failed\n");
942     ok(written == size, "Write to anonymous pipe wrote %d bytes\n", written);
943     /* and close the write end, read should still succeed*/
944     ok(CloseHandle(pipewrite), "CloseHandle for the Write Pipe failed\n");
945     memset( buffer, 0, size );
946     ok(ReadFile(piperead, buffer, size, &read, NULL), "Read from broken pipe withe with pending data failed\n");
947     ok(read == size, "Read from  anonymous pipe got %d bytes\n", read);
948     for (i = 0; i < size; i++) ok( buffer[i] == (BYTE)i, "invalid data %x at %x\n", buffer[i], i );
949     /* But now we need to get informed that the pipe is closed */
950     ok(ReadFile(piperead,readbuf,sizeof(readbuf),&read, NULL) == 0, "Broken pipe not detected\n");
951     ok(CloseHandle(piperead), "CloseHandle for the read pipe failed\n");
952     HeapFree(GetProcessHeap(), 0, buffer);
953 }
954
955 struct named_pipe_client_params
956 {
957     DWORD security_flags;
958     HANDLE token;
959     BOOL revert;
960 };
961
962 #define PIPE_NAME "\\\\.\\pipe\\named_pipe_test"
963
964 static DWORD CALLBACK named_pipe_client_func(LPVOID p)
965 {
966     struct named_pipe_client_params *params = p;
967     HANDLE pipe;
968     BOOL ret;
969     const char message[] = "Test";
970     DWORD bytes_read, bytes_written;
971     char dummy;
972     TOKEN_PRIVILEGES *Privileges = NULL;
973
974     if (params->token)
975     {
976         if (params->revert)
977         {
978             /* modify the token so we can tell if the pipe impersonation
979              * token reverts to the process token */
980             ret = AdjustTokenPrivileges(params->token, TRUE, NULL, 0, NULL, NULL);
981             ok(ret, "AdjustTokenPrivileges failed with error %d\n", GetLastError());
982         }
983         ret = SetThreadToken(NULL, params->token);
984         ok(ret, "SetThreadToken failed with error %d\n", GetLastError());
985     }
986     else
987     {
988         DWORD Size = 0;
989         HANDLE process_token;
990
991         ret = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES, &process_token);
992         ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
993
994         ret = GetTokenInformation(process_token, TokenPrivileges, NULL, 0, &Size);
995         ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "GetTokenInformation(TokenPrivileges) failed with %d\n", GetLastError());
996         Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
997         ret = GetTokenInformation(process_token, TokenPrivileges, Privileges, Size, &Size);
998         ok(ret, "GetTokenInformation(TokenPrivileges) failed with %d\n", GetLastError());
999
1000         ret = AdjustTokenPrivileges(process_token, TRUE, NULL, 0, NULL, NULL);
1001         ok(ret, "AdjustTokenPrivileges failed with error %d\n", GetLastError());
1002
1003         CloseHandle(process_token);
1004     }
1005
1006     pipe = CreateFile(PIPE_NAME, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, params->security_flags, NULL);
1007     ok(pipe != INVALID_HANDLE_VALUE, "CreateFile for pipe failed with error %d\n", GetLastError());
1008
1009     ret = WriteFile(pipe, message, sizeof(message), &bytes_written, NULL);
1010     ok(ret, "WriteFile failed with error %d\n", GetLastError());
1011
1012     ret = ReadFile(pipe, &dummy, sizeof(dummy), &bytes_read, NULL);
1013     ok(ret, "ReadFile failed with error %d\n", GetLastError());
1014
1015     if (params->token)
1016     {
1017         if (params->revert)
1018         {
1019             ret = RevertToSelf();
1020             ok(ret, "RevertToSelf failed with error %d\n", GetLastError());
1021         }
1022         else
1023         {
1024             ret = AdjustTokenPrivileges(params->token, TRUE, NULL, 0, NULL, NULL);
1025             ok(ret, "AdjustTokenPrivileges failed with error %d\n", GetLastError());
1026         }
1027     }
1028     else
1029     {
1030         HANDLE process_token;
1031
1032         ret = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &process_token);
1033         ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1034
1035         ret = AdjustTokenPrivileges(process_token, FALSE, Privileges, 0, NULL, NULL);
1036         ok(ret, "AdjustTokenPrivileges failed with error %d\n", GetLastError());
1037
1038         HeapFree(GetProcessHeap(), 0, Privileges);
1039
1040         CloseHandle(process_token);
1041     }
1042
1043     ret = WriteFile(pipe, message, sizeof(message), &bytes_written, NULL);
1044     ok(ret, "WriteFile failed with error %d\n", GetLastError());
1045
1046     ret = ReadFile(pipe, &dummy, sizeof(dummy), &bytes_read, NULL);
1047     ok(ret, "ReadFile failed with error %d\n", GetLastError());
1048
1049     CloseHandle(pipe);
1050
1051     return 0;
1052 }
1053
1054 static HANDLE make_impersonation_token(DWORD Access, SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
1055 {
1056     HANDLE ProcessToken;
1057     HANDLE Token = NULL;
1058     BOOL ret;
1059
1060     ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &ProcessToken);
1061     ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
1062
1063     ret = pDuplicateTokenEx(ProcessToken, Access, NULL, ImpersonationLevel, TokenImpersonation, &Token);
1064     ok(ret, "DuplicateToken failed with error %d\n", GetLastError());
1065
1066     CloseHandle(ProcessToken);
1067
1068     return Token;
1069 }
1070
1071 static void test_ImpersonateNamedPipeClient(HANDLE hClientToken, DWORD security_flags, BOOL revert, void (*test_func)(int, HANDLE))
1072 {
1073     HANDLE hPipeServer;
1074     BOOL ret;
1075     DWORD dwTid;
1076     HANDLE hThread;
1077     char buffer[256];
1078     DWORD dwBytesRead;
1079     DWORD error;
1080     struct named_pipe_client_params params;
1081     char dummy = 0;
1082     DWORD dwBytesWritten;
1083     HANDLE hToken = NULL;
1084     SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
1085     DWORD size;
1086
1087     hPipeServer = CreateNamedPipe(PIPE_NAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, 1, 100, 100, NMPWAIT_USE_DEFAULT_WAIT, NULL);
1088     ok(hPipeServer != INVALID_HANDLE_VALUE, "CreateNamedPipe failed with error %d\n", GetLastError());
1089
1090     params.security_flags = security_flags;
1091     params.token = hClientToken;
1092     params.revert = revert;
1093     hThread = CreateThread(NULL, 0, named_pipe_client_func, &params, 0, &dwTid);
1094     ok(hThread != NULL, "CreateThread failed with error %d\n", GetLastError());
1095
1096     SetLastError(0xdeadbeef);
1097     ret = ImpersonateNamedPipeClient(hPipeServer);
1098     error = GetLastError();
1099     ok(ret /* win2k3 */ || (error == ERROR_CANNOT_IMPERSONATE),
1100        "ImpersonateNamedPipeClient should have failed with ERROR_CANNOT_IMPERSONATE instead of %d\n", GetLastError());
1101
1102     ret = ConnectNamedPipe(hPipeServer, NULL);
1103     ok(ret || (GetLastError() == ERROR_PIPE_CONNECTED), "ConnectNamedPipe failed with error %d\n", GetLastError());
1104
1105     ret = ReadFile(hPipeServer, buffer, sizeof(buffer), &dwBytesRead, NULL);
1106     ok(ret, "ReadFile failed with error %d\n", GetLastError());
1107
1108     ret = ImpersonateNamedPipeClient(hPipeServer);
1109     ok(ret, "ImpersonateNamedPipeClient failed with error %d\n", GetLastError());
1110
1111     ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, FALSE, &hToken);
1112     ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
1113
1114     (*test_func)(0, hToken);
1115
1116     ImpersonationLevel = 0xdeadbeef; /* to avoid false positives */
1117     ret = GetTokenInformation(hToken, TokenImpersonationLevel, &ImpersonationLevel, sizeof(ImpersonationLevel), &size);
1118     ok(ret, "GetTokenInformation(TokenImpersonationLevel) failed with error %d\n", GetLastError());
1119     ok(ImpersonationLevel == SecurityImpersonation, "ImpersonationLevel should have been SecurityImpersonation(%d) instead of %d\n", SecurityImpersonation, ImpersonationLevel);
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     ret = ReadFile(hPipeServer, buffer, sizeof(buffer), &dwBytesRead, NULL);
1129     ok(ret, "ReadFile failed with error %d\n", GetLastError());
1130
1131     ret = ImpersonateNamedPipeClient(hPipeServer);
1132     ok(ret, "ImpersonateNamedPipeClient failed with error %d\n", GetLastError());
1133
1134     ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, FALSE, &hToken);
1135     ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
1136
1137     (*test_func)(1, hToken);
1138
1139     CloseHandle(hToken);
1140
1141     RevertToSelf();
1142
1143     ret = WriteFile(hPipeServer, &dummy, sizeof(dummy), &dwBytesWritten, NULL);
1144     ok(ret, "WriteFile failed with error %d\n", GetLastError());
1145
1146     WaitForSingleObject(hThread, INFINITE);
1147
1148     ret = ImpersonateNamedPipeClient(hPipeServer);
1149     ok(ret, "ImpersonateNamedPipeClient failed with error %d\n", GetLastError());
1150
1151     RevertToSelf();
1152
1153     CloseHandle(hThread);
1154     CloseHandle(hPipeServer);
1155 }
1156
1157 static BOOL are_all_privileges_disabled(HANDLE hToken)
1158 {
1159     BOOL ret;
1160     TOKEN_PRIVILEGES *Privileges = NULL;
1161     DWORD Size = 0;
1162     BOOL all_privs_disabled = TRUE;
1163     DWORD i;
1164
1165     ret = GetTokenInformation(hToken, TokenPrivileges, NULL, 0, &Size);
1166     if (!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
1167     {
1168         Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
1169         ret = GetTokenInformation(hToken, TokenPrivileges, Privileges, Size, &Size);
1170         if (!ret)
1171         {
1172             HeapFree(GetProcessHeap(), 0, Privileges);
1173             return FALSE;
1174         }
1175     }
1176     else
1177         return FALSE;
1178
1179     for (i = 0; i < Privileges->PrivilegeCount; i++)
1180     {
1181         if (Privileges->Privileges[i].Attributes & SE_PRIVILEGE_ENABLED)
1182         {
1183             all_privs_disabled = FALSE;
1184             break;
1185         }
1186     }
1187
1188     HeapFree(GetProcessHeap(), 0, Privileges);
1189
1190     return all_privs_disabled;
1191 }
1192
1193 static DWORD get_privilege_count(HANDLE hToken)
1194 {
1195     TOKEN_STATISTICS Statistics;
1196     DWORD Size = sizeof(Statistics);
1197     BOOL ret;
1198
1199     ret = GetTokenInformation(hToken, TokenStatistics, &Statistics, Size, &Size);
1200     ok(ret, "GetTokenInformation(TokenStatistics)\n");
1201     if (!ret) return -1;
1202
1203     return Statistics.PrivilegeCount;
1204 }
1205
1206 static void test_no_sqos_no_token(int call_index, HANDLE hToken)
1207 {
1208     DWORD priv_count;
1209
1210     switch (call_index)
1211     {
1212     case 0:
1213         priv_count = get_privilege_count(hToken);
1214         todo_wine
1215         ok(priv_count == 0, "privilege count should have been 0 instead of %d\n", priv_count);
1216         break;
1217     case 1:
1218         priv_count = get_privilege_count(hToken);
1219         ok(priv_count > 0, "privilege count should now be > 0 instead of 0\n");
1220         ok(!are_all_privileges_disabled(hToken), "impersonated token should not have been modified\n");
1221         break;
1222     default:
1223         ok(0, "shouldn't happen\n");
1224     }
1225 }
1226
1227 static void test_no_sqos(int call_index, HANDLE hToken)
1228 {
1229     switch (call_index)
1230     {
1231     case 0:
1232         ok(!are_all_privileges_disabled(hToken), "token should be a copy of the process one\n");
1233         break;
1234     case 1:
1235         todo_wine
1236         ok(are_all_privileges_disabled(hToken), "impersonated token should have been modified\n");
1237         break;
1238     default:
1239         ok(0, "shouldn't happen\n");
1240     }
1241 }
1242
1243 static void test_static_context(int call_index, HANDLE hToken)
1244 {
1245     switch (call_index)
1246     {
1247     case 0:
1248         ok(!are_all_privileges_disabled(hToken), "token should be a copy of the process one\n");
1249         break;
1250     case 1:
1251         ok(!are_all_privileges_disabled(hToken), "impersonated token should not have been modified\n");
1252         break;
1253     default:
1254         ok(0, "shouldn't happen\n");
1255     }
1256 }
1257
1258 static void test_dynamic_context(int call_index, HANDLE hToken)
1259 {
1260     switch (call_index)
1261     {
1262     case 0:
1263         ok(!are_all_privileges_disabled(hToken), "token should be a copy of the process one\n");
1264         break;
1265     case 1:
1266         todo_wine
1267         ok(are_all_privileges_disabled(hToken), "impersonated token should have been modified\n");
1268         break;
1269     default:
1270         ok(0, "shouldn't happen\n");
1271     }
1272 }
1273
1274 static void test_dynamic_context_no_token(int call_index, HANDLE hToken)
1275 {
1276     switch (call_index)
1277     {
1278     case 0:
1279         ok(are_all_privileges_disabled(hToken), "token should be a copy of the process one\n");
1280         break;
1281     case 1:
1282         ok(!are_all_privileges_disabled(hToken), "process token modification should have been detected and impersonation token updated\n");
1283         break;
1284     default:
1285         ok(0, "shouldn't happen\n");
1286     }
1287 }
1288
1289 static void test_no_sqos_revert(int call_index, HANDLE hToken)
1290 {
1291     DWORD priv_count;
1292     switch (call_index)
1293     {
1294     case 0:
1295         priv_count = get_privilege_count(hToken);
1296         todo_wine
1297         ok(priv_count == 0, "privilege count should have been 0 instead of %d\n", priv_count);
1298         break;
1299     case 1:
1300         priv_count = get_privilege_count(hToken);
1301         ok(priv_count > 0, "privilege count should now be > 0 instead of 0\n");
1302         ok(!are_all_privileges_disabled(hToken), "impersonated token should not have been modified\n");
1303         break;
1304     default:
1305         ok(0, "shouldn't happen\n");
1306     }
1307 }
1308
1309 static void test_static_context_revert(int call_index, HANDLE hToken)
1310 {
1311     switch (call_index)
1312     {
1313     case 0:
1314         todo_wine
1315         ok(are_all_privileges_disabled(hToken), "privileges should have been disabled\n");
1316         break;
1317     case 1:
1318         todo_wine
1319         ok(are_all_privileges_disabled(hToken), "impersonated token should not have been modified\n");
1320         break;
1321     default:
1322         ok(0, "shouldn't happen\n");
1323     }
1324 }
1325
1326 static void test_dynamic_context_revert(int call_index, HANDLE hToken)
1327 {
1328     switch (call_index)
1329     {
1330     case 0:
1331         todo_wine
1332         ok(are_all_privileges_disabled(hToken), "privileges should have been disabled\n");
1333         break;
1334     case 1:
1335         ok(!are_all_privileges_disabled(hToken), "impersonated token should now be process token\n");
1336         break;
1337     default:
1338         ok(0, "shouldn't happen\n");
1339     }
1340 }
1341
1342 static void test_impersonation(void)
1343 {
1344     HANDLE hClientToken;
1345     HANDLE hProcessToken;
1346     BOOL ret;
1347
1348     if( !pDuplicateTokenEx ) {
1349         skip("DuplicateTokenEx not found\n");
1350         return;
1351     }
1352
1353     ret = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hProcessToken);
1354     if (!ret)
1355     {
1356         skip("couldn't open process token, skipping impersonation tests\n");
1357         return;
1358     }
1359
1360     if (!get_privilege_count(hProcessToken) || are_all_privileges_disabled(hProcessToken))
1361     {
1362         skip("token didn't have any privileges or they were all disabled. token not suitable for impersonation tests\n");
1363         CloseHandle(hProcessToken);
1364         return;
1365     }
1366     CloseHandle(hProcessToken);
1367
1368     test_ImpersonateNamedPipeClient(NULL, 0, FALSE, test_no_sqos_no_token);
1369     hClientToken = make_impersonation_token(TOKEN_IMPERSONATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, SecurityImpersonation);
1370     test_ImpersonateNamedPipeClient(hClientToken, 0, FALSE, test_no_sqos);
1371     CloseHandle(hClientToken);
1372     hClientToken = make_impersonation_token(TOKEN_IMPERSONATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, SecurityImpersonation);
1373     test_ImpersonateNamedPipeClient(hClientToken,
1374         SECURITY_SQOS_PRESENT | SECURITY_IMPERSONATION, FALSE,
1375         test_static_context);
1376     CloseHandle(hClientToken);
1377     hClientToken = make_impersonation_token(TOKEN_IMPERSONATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, SecurityImpersonation);
1378     test_ImpersonateNamedPipeClient(hClientToken,
1379         SECURITY_SQOS_PRESENT | SECURITY_CONTEXT_TRACKING | SECURITY_IMPERSONATION,
1380         FALSE, test_dynamic_context);
1381     CloseHandle(hClientToken);
1382     test_ImpersonateNamedPipeClient(NULL,
1383         SECURITY_SQOS_PRESENT | SECURITY_CONTEXT_TRACKING | SECURITY_IMPERSONATION,
1384         FALSE, test_dynamic_context_no_token);
1385
1386     hClientToken = make_impersonation_token(TOKEN_IMPERSONATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, SecurityImpersonation);
1387     test_ImpersonateNamedPipeClient(hClientToken, 0, TRUE, test_no_sqos_revert);
1388     CloseHandle(hClientToken);
1389     hClientToken = make_impersonation_token(TOKEN_IMPERSONATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, SecurityImpersonation);
1390     test_ImpersonateNamedPipeClient(hClientToken,
1391         SECURITY_SQOS_PRESENT | SECURITY_IMPERSONATION, TRUE,
1392         test_static_context_revert);
1393     CloseHandle(hClientToken);
1394     hClientToken = make_impersonation_token(TOKEN_IMPERSONATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, SecurityImpersonation);
1395     test_ImpersonateNamedPipeClient(hClientToken,
1396         SECURITY_SQOS_PRESENT | SECURITY_CONTEXT_TRACKING | SECURITY_IMPERSONATION,
1397         TRUE, test_dynamic_context_revert);
1398     CloseHandle(hClientToken);
1399 }
1400
1401 struct overlapped_server_args
1402 {
1403     HANDLE pipe_created;
1404 };
1405
1406 static DWORD CALLBACK overlapped_server(LPVOID arg)
1407 {
1408     OVERLAPPED ol;
1409     HANDLE pipe;
1410     int ret, err;
1411     struct overlapped_server_args *a = arg;
1412     DWORD num;
1413     char buf[100];
1414
1415     pipe = CreateNamedPipeA("\\\\.\\pipe\\my pipe", FILE_FLAG_OVERLAPPED | PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE, 1, 0, 0, 100000, NULL);
1416     ok(pipe != NULL, "pipe NULL\n");
1417
1418     ol.hEvent = CreateEventA(0, 1, 0, 0);
1419     ok(ol.hEvent != NULL, "event NULL\n");
1420     ret = ConnectNamedPipe(pipe, &ol);
1421     err = GetLastError();
1422     ok(ret == 0, "ret %d\n", ret);
1423     ok(err == ERROR_IO_PENDING, "gle %d\n", err);
1424     SetEvent(a->pipe_created);
1425
1426     ret = WaitForSingleObjectEx(ol.hEvent, INFINITE, 1);
1427     ok(ret == WAIT_OBJECT_0, "ret %x\n", ret);
1428
1429     ret = GetOverlappedResult(pipe, &ol, &num, 1);
1430     ok(ret == 1, "ret %d\n", ret);
1431
1432     /* This should block */
1433     ret = ReadFile(pipe, buf, sizeof(buf), &num, NULL);
1434     ok(ret == 1, "ret %d\n", ret);
1435
1436     DisconnectNamedPipe(pipe);
1437     CloseHandle(ol.hEvent);
1438     CloseHandle(pipe);
1439     return 1;
1440 }
1441
1442 static void test_overlapped(void)
1443 {
1444     DWORD tid, num;
1445     HANDLE thread, pipe;
1446     int ret;
1447     struct overlapped_server_args args;
1448
1449     args.pipe_created = CreateEventA(0, 1, 0, 0);
1450     thread = CreateThread(NULL, 0, overlapped_server, &args, 0, &tid);
1451
1452     WaitForSingleObject(args.pipe_created, INFINITE);
1453     pipe = CreateFileA("\\\\.\\pipe\\my pipe", GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
1454     ok(pipe != INVALID_HANDLE_VALUE, "cf failed\n");
1455
1456     /* Sleep to try to get the ReadFile in the server to occur before the following WriteFile */
1457     Sleep(1);
1458
1459     ret = WriteFile(pipe, "x", 1, &num, NULL);
1460     ok(ret == 1, "ret %d\n", ret);
1461
1462     WaitForSingleObject(thread, INFINITE);
1463     CloseHandle(pipe);
1464     CloseHandle(args.pipe_created);
1465     CloseHandle(thread);
1466 }
1467
1468 static void test_NamedPipeHandleState(void)
1469 {
1470     HANDLE server, client;
1471     BOOL ret;
1472     DWORD state, instances, maxCollectionCount, collectDataTimeout;
1473     char userName[MAX_PATH];
1474
1475     server = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX,
1476         /* dwOpenMode */ PIPE_TYPE_BYTE | PIPE_WAIT,
1477         /* nMaxInstances */ 1,
1478         /* nOutBufSize */ 1024,
1479         /* nInBufSize */ 1024,
1480         /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
1481         /* lpSecurityAttrib */ NULL);
1482     ok(server != INVALID_HANDLE_VALUE, "cf failed\n");
1483     ret = GetNamedPipeHandleState(server, NULL, NULL, NULL, NULL, NULL, 0);
1484     todo_wine
1485     ok(ret, "GetNamedPipeHandleState failed: %d\n", GetLastError());
1486     ret = GetNamedPipeHandleState(server, &state, &instances, NULL, NULL, NULL,
1487         0);
1488     todo_wine
1489     ok(ret, "GetNamedPipeHandleState failed: %d\n", GetLastError());
1490     if (ret)
1491     {
1492         ok(state == 0, "unexpected state %08x\n", state);
1493         ok(instances == 1, "expected 1 instances, got %d\n", instances);
1494     }
1495     /* Some parameters have no meaning, and therefore can't be retrieved,
1496      * on a local pipe.
1497      */
1498     SetLastError(0xdeadbeef);
1499     ret = GetNamedPipeHandleState(server, &state, &instances,
1500         &maxCollectionCount, &collectDataTimeout, userName,
1501         sizeof(userName) / sizeof(userName[0]));
1502     todo_wine
1503     ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
1504        "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
1505     /* A byte-mode pipe server can't be changed to message mode. */
1506     state = PIPE_READMODE_MESSAGE;
1507     SetLastError(0xdeadbeef);
1508     ret = SetNamedPipeHandleState(server, &state, NULL, NULL);
1509     todo_wine
1510     ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
1511        "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
1512
1513     client = CreateFileA(PIPENAME, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1514         OPEN_EXISTING, 0, NULL);
1515     ok(client != INVALID_HANDLE_VALUE, "cf failed\n");
1516
1517     state = PIPE_READMODE_BYTE;
1518     ret = SetNamedPipeHandleState(client, &state, NULL, NULL);
1519     todo_wine
1520     ok(ret, "SetNamedPipeHandleState failed: %d\n", GetLastError());
1521     /* A byte-mode pipe client can't be changed to message mode, either. */
1522     state = PIPE_READMODE_MESSAGE;
1523     SetLastError(0xdeadbeef);
1524     ret = SetNamedPipeHandleState(server, &state, NULL, NULL);
1525     todo_wine
1526     ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
1527        "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
1528
1529     CloseHandle(client);
1530     CloseHandle(server);
1531
1532     server = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX,
1533         /* dwOpenMode */ PIPE_TYPE_MESSAGE | PIPE_WAIT,
1534         /* nMaxInstances */ 1,
1535         /* nOutBufSize */ 1024,
1536         /* nInBufSize */ 1024,
1537         /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
1538         /* lpSecurityAttrib */ NULL);
1539     ok(server != INVALID_HANDLE_VALUE, "cf failed\n");
1540     ret = GetNamedPipeHandleState(server, NULL, NULL, NULL, NULL, NULL, 0);
1541     todo_wine
1542     ok(ret, "GetNamedPipeHandleState failed: %d\n", GetLastError());
1543     ret = GetNamedPipeHandleState(server, &state, &instances, NULL, NULL, NULL,
1544         0);
1545     todo_wine
1546     ok(ret, "GetNamedPipeHandleState failed: %d\n", GetLastError());
1547     if (ret)
1548     {
1549         ok(state == 0, "unexpected state %08x\n", state);
1550         ok(instances == 1, "expected 1 instances, got %d\n", instances);
1551     }
1552     /* In contrast to byte-mode pipes, a message-mode pipe server can be
1553      * changed to byte mode.
1554      */
1555     state = PIPE_READMODE_BYTE;
1556     ret = SetNamedPipeHandleState(server, &state, NULL, NULL);
1557     todo_wine
1558     ok(ret, "SetNamedPipeHandleState failed: %d\n", GetLastError());
1559
1560     client = CreateFileA(PIPENAME, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1561         OPEN_EXISTING, 0, NULL);
1562     ok(client != INVALID_HANDLE_VALUE, "cf failed\n");
1563
1564     state = PIPE_READMODE_MESSAGE;
1565     ret = SetNamedPipeHandleState(client, &state, NULL, NULL);
1566     todo_wine
1567     ok(ret, "SetNamedPipeHandleState failed: %d\n", GetLastError());
1568     /* A message-mode pipe client can also be changed to byte mode.
1569      */
1570     state = PIPE_READMODE_BYTE;
1571     ret = SetNamedPipeHandleState(client, &state, NULL, NULL);
1572     todo_wine
1573     ok(ret, "SetNamedPipeHandleState failed: %d\n", GetLastError());
1574
1575     CloseHandle(client);
1576     CloseHandle(server);
1577 }
1578
1579 START_TEST(pipe)
1580 {
1581     HMODULE hmod;
1582
1583     hmod = GetModuleHandle("advapi32.dll");
1584     pDuplicateTokenEx = (void *) GetProcAddress(hmod, "DuplicateTokenEx");
1585
1586     if (test_DisconnectNamedPipe())
1587         return;
1588     test_CreateNamedPipe_instances_must_match();
1589     test_NamedPipe_2();
1590     test_CreateNamedPipe(PIPE_TYPE_BYTE);
1591     test_CreateNamedPipe(PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE);
1592     test_CreatePipe();
1593     test_impersonation();
1594     test_overlapped();
1595     test_NamedPipeHandleState();
1596 }