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