pipe.c 73.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Unit tests for named pipe functions in Wine
 *
 * Copyright (c) 2002 Dan Kegel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 20
 */

21
#include <stdarg.h>
22
#include <stdio.h>
23 24 25 26

#include <windef.h>
#include <winbase.h>
#include <winsock.h>
27
#include <wtypes.h>
28 29
#include <winerror.h>

30 31
#include "wine/test.h"

32
#define PIPENAME "\\\\.\\PiPe\\tests_pipe.c"
33

34 35 36
#define NB_SERVER_LOOPS 8

static HANDLE alarm_event;
37 38
static BOOL (WINAPI *pDuplicateTokenEx)(HANDLE,DWORD,LPSECURITY_ATTRIBUTES,
                                        SECURITY_IMPERSONATION_LEVEL,TOKEN_TYPE,PHANDLE);
39
static DWORD (WINAPI *pQueueUserAPC)(PAPCFUNC pfnAPC, HANDLE hThread, ULONG_PTR dwData);
40

41 42 43 44 45
static BOOL user_apc_ran;
static void CALLBACK user_apc(ULONG_PTR param)
{
    user_apc_ran = TRUE;
}
46

47
static void test_CreateNamedPipe(int pipemode)
48 49 50
{
    HANDLE hnp;
    HANDLE hFile;
51 52
    static const char obuf[] = "Bit Bucket";
    static const char obuf2[] = "More bits";
53
    char ibuf[32], *pbuf;
54
    DWORD written;
Dan Kegel's avatar
Dan Kegel committed
55
    DWORD readden;
56 57
    DWORD avail;
    DWORD lpmode;
58
    BOOL ret;
59

60 61 62 63
    if (pipemode == PIPE_TYPE_BYTE)
        trace("test_CreateNamedPipe starting in byte mode\n");
    else
        trace("test_CreateNamedPipe starting in message mode\n");
64
    /* Bad parameter checks */
65
    hnp = CreateNamedPipe("not a named pipe", PIPE_ACCESS_DUPLEX, pipemode | PIPE_WAIT,
66 67 68 69 70 71
        /* nMaxInstances */ 1,
        /* nOutBufSize */ 1024,
        /* nInBufSize */ 1024,
        /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
        /* lpSecurityAttrib */ NULL);
    ok(hnp == INVALID_HANDLE_VALUE && GetLastError() == ERROR_INVALID_NAME,
72
        "CreateNamedPipe should fail if name doesn't start with \\\\.\\pipe\n");
73

74 75 76 77 78 79 80 81 82 83 84 85 86
    if (pipemode == PIPE_TYPE_BYTE)
    {
        /* Bad parameter checks */
        hnp = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_MESSAGE,
            /* nMaxInstances */ 1,
            /* nOutBufSize */ 1024,
            /* nInBufSize */ 1024,
            /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
            /* lpSecurityAttrib */ NULL);
        ok(hnp == INVALID_HANDLE_VALUE && GetLastError() == ERROR_INVALID_PARAMETER,
            "CreateNamedPipe should fail with PIPE_TYPE_BYTE | PIPE_READMODE_MESSAGE\n");
    }

Dan Kegel's avatar
Dan Kegel committed
87
    hnp = CreateNamedPipe(NULL,
88
        PIPE_ACCESS_DUPLEX, pipemode | PIPE_WAIT,
89 90
        1, 1024, 1024, NMPWAIT_USE_DEFAULT_WAIT, NULL);
    ok(hnp == INVALID_HANDLE_VALUE && GetLastError() == ERROR_PATH_NOT_FOUND,
91
        "CreateNamedPipe should fail if name is NULL\n");
92

Dan Kegel's avatar
Dan Kegel committed
93 94 95
    hFile = CreateFileA(PIPENAME, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
    ok(hFile == INVALID_HANDLE_VALUE
        && GetLastError() == ERROR_FILE_NOT_FOUND,
96
        "connecting to nonexistent named pipe should fail with ERROR_FILE_NOT_FOUND\n");
97

98 99
    /* Functional checks */

100
    hnp = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX, pipemode | PIPE_WAIT,
Dan Kegel's avatar
Dan Kegel committed
101 102 103 104 105
        /* nMaxInstances */ 1,
        /* nOutBufSize */ 1024,
        /* nInBufSize */ 1024,
        /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
        /* lpSecurityAttrib */ NULL);
106
    ok(hnp != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
Dan Kegel's avatar
Dan Kegel committed
107

108 109
    ret = WaitNamedPipeA(PIPENAME, 2000);
    ok(ret, "WaitNamedPipe failed (%d)\n", GetLastError());
110

Dan Kegel's avatar
Dan Kegel committed
111
    hFile = CreateFileA(PIPENAME, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
112
    ok(hFile != INVALID_HANDLE_VALUE, "CreateFile failed (%d)\n", GetLastError());
Dan Kegel's avatar
Dan Kegel committed
113

114
    ok(!WaitNamedPipeA(PIPENAME, 1000), "WaitNamedPipe succeeded\n");
115

116 117
    ok(GetLastError() == ERROR_SEM_TIMEOUT, "wrong error %u\n", GetLastError());

Dan Kegel's avatar
Dan Kegel committed
118 119 120 121 122 123
    /* don't try to do i/o if one side couldn't be opened, as it hangs */
    if (hFile != INVALID_HANDLE_VALUE) {
        HANDLE hFile2;

        /* Make sure we can read and write a few bytes in both directions */
        memset(ibuf, 0, sizeof(ibuf));
124
        ok(WriteFile(hnp, obuf, sizeof(obuf), &written, NULL), "WriteFile\n");
125 126
        ok(written == sizeof(obuf), "write file len 1\n");
        ok(PeekNamedPipe(hFile, NULL, 0, NULL, &readden, NULL), "Peek\n");
127
        ok(readden == sizeof(obuf), "peek 1 got %d bytes\n", readden);
128
        ok(ReadFile(hFile, ibuf, sizeof(ibuf), &readden, NULL), "ReadFile\n");
129
        ok(readden == sizeof(obuf), "read 1 got %d bytes\n", readden);
130
        ok(memcmp(obuf, ibuf, written) == 0, "content 1 check\n");
Dan Kegel's avatar
Dan Kegel committed
131 132

        memset(ibuf, 0, sizeof(ibuf));
133 134 135
        ok(WriteFile(hFile, obuf2, sizeof(obuf2), &written, NULL), "WriteFile\n");
        ok(written == sizeof(obuf2), "write file len 2\n");
        ok(PeekNamedPipe(hnp, NULL, 0, NULL, &readden, NULL), "Peek\n");
136
        ok(readden == sizeof(obuf2), "peek 2 got %d bytes\n", readden);
137
        ok(PeekNamedPipe(hnp, (LPVOID)1, 0, NULL, &readden, NULL), "Peek\n");
138
        ok(readden == sizeof(obuf2), "peek 2 got %d bytes\n", readden);
139
        ok(ReadFile(hnp, ibuf, sizeof(ibuf), &readden, NULL), "ReadFile\n");
140
        ok(readden == sizeof(obuf2), "read 2 got %d bytes\n", readden);
141 142 143 144 145 146 147 148 149 150
        ok(memcmp(obuf2, ibuf, written) == 0, "content 2 check\n");

        /* Test reading of multiple writes */
        memset(ibuf, 0, sizeof(ibuf));
        ok(WriteFile(hnp, obuf, sizeof(obuf), &written, NULL), "WriteFile3a\n");
        ok(written == sizeof(obuf), "write file len 3a\n");
        ok(WriteFile(hnp, obuf2, sizeof(obuf2), &written, NULL), " WriteFile3b\n");
        ok(written == sizeof(obuf2), "write file len 3b\n");
        ok(PeekNamedPipe(hFile, ibuf, sizeof(ibuf), &readden, &avail, NULL), "Peek3\n");
        if (pipemode == PIPE_TYPE_BYTE) {
151
            if (readden != sizeof(obuf))  /* Linux only returns the first message */
152
                ok(readden == sizeof(obuf) + sizeof(obuf2), "peek3 got %d bytes\n", readden);
153 154
            else
                todo_wine ok(readden == sizeof(obuf) + sizeof(obuf2), "peek3 got %d bytes\n", readden);
155 156
        }
        else
157 158 159 160 161 162
        {
            if (readden != sizeof(obuf) + sizeof(obuf2))  /* MacOS returns both messages */
                ok(readden == sizeof(obuf), "peek3 got %d bytes\n", readden);
            else
                todo_wine ok(readden == sizeof(obuf), "peek3 got %d bytes\n", readden);
        }
163
        if (avail != sizeof(obuf)) /* older Linux kernels only return the first write here */
164
            ok(avail == sizeof(obuf) + sizeof(obuf2), "peek3 got %d bytes available\n", avail);
165 166
        pbuf = ibuf;
        ok(memcmp(obuf, pbuf, sizeof(obuf)) == 0, "pipe content 3a check\n");
167 168 169
        if (pipemode == PIPE_TYPE_BYTE && readden >= sizeof(obuf)+sizeof(obuf2)) {
            pbuf += sizeof(obuf);
            ok(memcmp(obuf2, pbuf, sizeof(obuf2)) == 0, "pipe content 3b check\n");
170 171
        }
        ok(ReadFile(hFile, ibuf, sizeof(ibuf), &readden, NULL), "ReadFile\n");
172
        ok(readden == sizeof(obuf) + sizeof(obuf2), "read 3 got %d bytes\n", readden);
173 174 175 176 177 178 179 180 181 182 183 184 185
        pbuf = ibuf;
        ok(memcmp(obuf, pbuf, sizeof(obuf)) == 0, "content 3a check\n");
        pbuf += sizeof(obuf);
        ok(memcmp(obuf2, pbuf, sizeof(obuf2)) == 0, "content 3b check\n");

        /* Multiple writes in the reverse direction */
        memset(ibuf, 0, sizeof(ibuf));
        ok(WriteFile(hFile, obuf, sizeof(obuf), &written, NULL), "WriteFile4a\n");
        ok(written == sizeof(obuf), "write file len 4a\n");
        ok(WriteFile(hFile, obuf2, sizeof(obuf2), &written, NULL), " WriteFile4b\n");
        ok(written == sizeof(obuf2), "write file len 4b\n");
        ok(PeekNamedPipe(hnp, ibuf, sizeof(ibuf), &readden, &avail, NULL), "Peek4\n");
        if (pipemode == PIPE_TYPE_BYTE) {
186
            if (readden != sizeof(obuf))  /* Linux only returns the first message */
187
                /* should return all 23 bytes */
188
                ok(readden == sizeof(obuf) + sizeof(obuf2), "peek4 got %d bytes\n", readden);
189 190
            else
                todo_wine ok(readden == sizeof(obuf) + sizeof(obuf2), "peek4 got %d bytes\n", readden);
191 192
        }
        else
193 194 195 196 197 198
        {
            if (readden != sizeof(obuf) + sizeof(obuf2))  /* MacOS returns both messages */
                ok(readden == sizeof(obuf), "peek4 got %d bytes\n", readden);
            else
                todo_wine ok(readden == sizeof(obuf), "peek4 got %d bytes\n", readden);
        }
199
        if (avail != sizeof(obuf)) /* older Linux kernels only return the first write here */
200
            ok(avail == sizeof(obuf) + sizeof(obuf2), "peek4 got %d bytes available\n", avail);
201 202
        pbuf = ibuf;
        ok(memcmp(obuf, pbuf, sizeof(obuf)) == 0, "pipe content 4a check\n");
203 204 205
        if (pipemode == PIPE_TYPE_BYTE && readden >= sizeof(obuf)+sizeof(obuf2)) {
            pbuf += sizeof(obuf);
            ok(memcmp(obuf2, pbuf, sizeof(obuf2)) == 0, "pipe content 4b check\n");
206 207 208
        }
        ok(ReadFile(hnp, ibuf, sizeof(ibuf), &readden, NULL), "ReadFile\n");
        if (pipemode == PIPE_TYPE_BYTE) {
209
            ok(readden == sizeof(obuf) + sizeof(obuf2), "read 4 got %d bytes\n", readden);
210 211 212
        }
        else {
            todo_wine {
213
                ok(readden == sizeof(obuf), "read 4 got %d bytes\n", readden);
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
            }
        }
        pbuf = ibuf;
        ok(memcmp(obuf, pbuf, sizeof(obuf)) == 0, "content 4a check\n");
        if (pipemode == PIPE_TYPE_BYTE) {
            pbuf += sizeof(obuf);
            ok(memcmp(obuf2, pbuf, sizeof(obuf2)) == 0, "content 4b check\n");
        }

        /* Test reading of multiple writes after a mode change
          (CreateFile always creates a byte mode pipe) */
        lpmode = PIPE_READMODE_MESSAGE;
        if (pipemode == PIPE_TYPE_BYTE) {
            /* trying to change the client end of a byte pipe to message mode should fail */
            ok(!SetNamedPipeHandleState(hFile, &lpmode, NULL, NULL), "Change mode\n");
        }
        else {
            todo_wine {
                ok(SetNamedPipeHandleState(hFile, &lpmode, NULL, NULL), "Change mode\n");
            }
        
            memset(ibuf, 0, sizeof(ibuf));
            ok(WriteFile(hnp, obuf, sizeof(obuf), &written, NULL), "WriteFile5a\n");
            ok(written == sizeof(obuf), "write file len 3a\n");
            ok(WriteFile(hnp, obuf2, sizeof(obuf2), &written, NULL), " WriteFile5b\n");
            ok(written == sizeof(obuf2), "write file len 3b\n");
            ok(PeekNamedPipe(hFile, ibuf, sizeof(ibuf), &readden, &avail, NULL), "Peek5\n");
241 242 243 244
            if (readden != sizeof(obuf) + sizeof(obuf2))  /* MacOS returns both writes */
                ok(readden == sizeof(obuf), "peek5 got %d bytes\n", readden);
            else
                todo_wine ok(readden == sizeof(obuf), "peek5 got %d bytes\n", readden);
245
            if (avail != sizeof(obuf)) /* older Linux kernels only return the first write here */
246
                ok(avail == sizeof(obuf) + sizeof(obuf2), "peek5 got %d bytes available\n", avail);
247 248
            else
                todo_wine ok(avail == sizeof(obuf) + sizeof(obuf2), "peek5 got %d bytes available\n", avail);
249 250 251 252
            pbuf = ibuf;
            ok(memcmp(obuf, pbuf, sizeof(obuf)) == 0, "content 5a check\n");
            ok(ReadFile(hFile, ibuf, sizeof(ibuf), &readden, NULL), "ReadFile\n");
            todo_wine {
253
                ok(readden == sizeof(obuf), "read 5 got %d bytes\n", readden);
254 255 256 257 258 259 260 261
            }
            pbuf = ibuf;
            ok(memcmp(obuf, pbuf, sizeof(obuf)) == 0, "content 5a check\n");
    
            /* Multiple writes in the reverse direction */
            /* the write of obuf2 from write4 should still be in the buffer */
            ok(PeekNamedPipe(hnp, ibuf, sizeof(ibuf), &readden, &avail, NULL), "Peek6a\n");
            todo_wine {
262 263
                ok(readden == sizeof(obuf2), "peek6a got %d bytes\n", readden);
                ok(avail == sizeof(obuf2), "peek6a got %d bytes available\n", avail);
264 265 266
            }
            if (avail > 0) {
                ok(ReadFile(hnp, ibuf, sizeof(ibuf), &readden, NULL), "ReadFile\n");
267
                ok(readden == sizeof(obuf2), "read 6a got %d bytes\n", readden);
268 269 270 271 272 273 274 275 276
                pbuf = ibuf;
                ok(memcmp(obuf2, pbuf, sizeof(obuf2)) == 0, "content 6a check\n");
            }
            memset(ibuf, 0, sizeof(ibuf));
            ok(WriteFile(hFile, obuf, sizeof(obuf), &written, NULL), "WriteFile6a\n");
            ok(written == sizeof(obuf), "write file len 6a\n");
            ok(WriteFile(hFile, obuf2, sizeof(obuf2), &written, NULL), " WriteFile6b\n");
            ok(written == sizeof(obuf2), "write file len 6b\n");
            ok(PeekNamedPipe(hnp, ibuf, sizeof(ibuf), &readden, &avail, NULL), "Peek6\n");
277 278 279 280
            if (readden != sizeof(obuf) + sizeof(obuf2))  /* MacOS returns both writes */
                ok(readden == sizeof(obuf), "peek6 got %d bytes\n", readden);
            else
                todo_wine ok(readden == sizeof(obuf), "peek6 got %d bytes\n", readden);
281
            if (avail != sizeof(obuf)) /* older Linux kernels only return the first write here */
282
                ok(avail == sizeof(obuf) + sizeof(obuf2), "peek6b got %d bytes available\n", avail);
283 284 285 286
            pbuf = ibuf;
            ok(memcmp(obuf, pbuf, sizeof(obuf)) == 0, "content 6a check\n");
            ok(ReadFile(hnp, ibuf, sizeof(ibuf), &readden, NULL), "ReadFile\n");
            todo_wine {
287
                ok(readden == sizeof(obuf), "read 6b got %d bytes\n", readden);
288 289 290 291
            }
            pbuf = ibuf;
            ok(memcmp(obuf, pbuf, sizeof(obuf)) == 0, "content 6a check\n");
        }
Dan Kegel's avatar
Dan Kegel committed
292 293 294 295 296 297 298 299 300 301

        /* Picky conformance tests */

        /* Verify that you can't connect to pipe again
         * until server calls DisconnectNamedPipe+ConnectNamedPipe
         * or creates a new pipe
         * case 1: other client not yet closed
         */
        hFile2 = CreateFileA(PIPENAME, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
        ok(hFile2 == INVALID_HANDLE_VALUE,
302
            "connecting to named pipe after other client closes but before DisconnectNamedPipe should fail\n");
Dan Kegel's avatar
Dan Kegel committed
303
        ok(GetLastError() == ERROR_PIPE_BUSY,
304
            "connecting to named pipe before other client closes should fail with ERROR_PIPE_BUSY\n");
Dan Kegel's avatar
Dan Kegel committed
305

306
        ok(CloseHandle(hFile), "CloseHandle\n");
Dan Kegel's avatar
Dan Kegel committed
307 308 309 310

        /* case 2: other client already closed */
        hFile = CreateFileA(PIPENAME, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
        ok(hFile == INVALID_HANDLE_VALUE,
311
            "connecting to named pipe after other client closes but before DisconnectNamedPipe should fail\n");
Dan Kegel's avatar
Dan Kegel committed
312
        ok(GetLastError() == ERROR_PIPE_BUSY,
313
            "connecting to named pipe after other client closes but before DisconnectNamedPipe should fail with ERROR_PIPE_BUSY\n");
Dan Kegel's avatar
Dan Kegel committed
314

315
        ok(DisconnectNamedPipe(hnp), "DisconnectNamedPipe\n");
Dan Kegel's avatar
Dan Kegel committed
316 317 318 319

        /* case 3: server has called DisconnectNamedPipe but not ConnectNamed Pipe */
        hFile = CreateFileA(PIPENAME, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
        ok(hFile == INVALID_HANDLE_VALUE,
320
            "connecting to named pipe after other client closes but before DisconnectNamedPipe should fail\n");
Dan Kegel's avatar
Dan Kegel committed
321
        ok(GetLastError() == ERROR_PIPE_BUSY,
322
            "connecting to named pipe after other client closes but before ConnectNamedPipe should fail with ERROR_PIPE_BUSY\n");
Dan Kegel's avatar
Dan Kegel committed
323 324 325 326 327 328 329 330

        /* to be complete, we'd call ConnectNamedPipe here and loop,
         * but by default that's blocking, so we'd either have
         * to turn on the uncommon nonblocking mode, or
         * use another thread.
         */
    }

331
    ok(CloseHandle(hnp), "CloseHandle\n");
Dan Kegel's avatar
Dan Kegel committed
332

333
    trace("test_CreateNamedPipe returning\n");
Dan Kegel's avatar
Dan Kegel committed
334 335
}

336
static void test_CreateNamedPipe_instances_must_match(void)
Dan Kegel's avatar
Dan Kegel committed
337 338 339 340 341 342 343 344 345 346
{
    HANDLE hnp, hnp2;

    /* Check no mismatch */
    hnp = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_WAIT,
        /* nMaxInstances */ 2,
        /* nOutBufSize */ 1024,
        /* nInBufSize */ 1024,
        /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
        /* lpSecurityAttrib */ NULL);
347
    ok(hnp != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
Dan Kegel's avatar
Dan Kegel committed
348 349 350 351 352 353 354

    hnp2 = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_WAIT,
        /* nMaxInstances */ 2,
        /* nOutBufSize */ 1024,
        /* nInBufSize */ 1024,
        /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
        /* lpSecurityAttrib */ NULL);
355
    ok(hnp2 != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
Dan Kegel's avatar
Dan Kegel committed
356

357 358
    ok(CloseHandle(hnp), "CloseHandle\n");
    ok(CloseHandle(hnp2), "CloseHandle\n");
Dan Kegel's avatar
Dan Kegel committed
359 360 361 362 363 364 365 366

    /* Check nMaxInstances */
    hnp = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_WAIT,
        /* nMaxInstances */ 1,
        /* nOutBufSize */ 1024,
        /* nInBufSize */ 1024,
        /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
        /* lpSecurityAttrib */ NULL);
367
    ok(hnp != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
Dan Kegel's avatar
Dan Kegel committed
368 369 370 371 372 373 374 375

    hnp2 = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_WAIT,
        /* nMaxInstances */ 1,
        /* nOutBufSize */ 1024,
        /* nInBufSize */ 1024,
        /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
        /* lpSecurityAttrib */ NULL);
    ok(hnp2 == INVALID_HANDLE_VALUE
376
        && GetLastError() == ERROR_PIPE_BUSY, "nMaxInstances not obeyed\n");
Dan Kegel's avatar
Dan Kegel committed
377

378
    ok(CloseHandle(hnp), "CloseHandle\n");
Dan Kegel's avatar
Dan Kegel committed
379 380 381 382 383 384 385 386

    /* Check PIPE_ACCESS_* */
    hnp = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_WAIT,
        /* nMaxInstances */ 2,
        /* nOutBufSize */ 1024,
        /* nInBufSize */ 1024,
        /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
        /* lpSecurityAttrib */ NULL);
387
    ok(hnp != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
Dan Kegel's avatar
Dan Kegel committed
388 389

    hnp2 = CreateNamedPipe(PIPENAME, PIPE_ACCESS_INBOUND, PIPE_TYPE_BYTE | PIPE_WAIT,
390
        /* nMaxInstances */ 2,
Dan Kegel's avatar
Dan Kegel committed
391 392 393 394 395
        /* nOutBufSize */ 1024,
        /* nInBufSize */ 1024,
        /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
        /* lpSecurityAttrib */ NULL);
    ok(hnp2 == INVALID_HANDLE_VALUE
396
        && GetLastError() == ERROR_ACCESS_DENIED, "PIPE_ACCESS_* mismatch allowed\n");
Dan Kegel's avatar
Dan Kegel committed
397

398
    ok(CloseHandle(hnp), "CloseHandle\n");
Dan Kegel's avatar
Dan Kegel committed
399

400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
    /* check everything else */
    hnp = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_WAIT,
        /* nMaxInstances */ 4,
        /* nOutBufSize */ 1024,
        /* nInBufSize */ 1024,
        /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
        /* lpSecurityAttrib */ NULL);
    ok(hnp != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");

    hnp2 = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE,
        /* nMaxInstances */ 3,
        /* nOutBufSize */ 102,
        /* nInBufSize */ 24,
        /* nDefaultWait */ 1234,
        /* lpSecurityAttrib */ NULL);
    ok(hnp2 != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");

    ok(CloseHandle(hnp), "CloseHandle\n");
    ok(CloseHandle(hnp2), "CloseHandle\n");
Dan Kegel's avatar
Dan Kegel committed
419 420 421 422 423
}

/** implementation of alarm() */
static DWORD CALLBACK alarmThreadMain(LPVOID arg)
{
424
    DWORD_PTR timeout = (DWORD_PTR) arg;
425
    trace("alarmThreadMain\n");
426 427 428 429 430
    if (WaitForSingleObject( alarm_event, timeout ) == WAIT_TIMEOUT)
    {
        ok(FALSE, "alarm\n");
        ExitProcess(1);
    }
Dan Kegel's avatar
Dan Kegel committed
431 432 433
    return 1;
}

434
static HANDLE hnp = INVALID_HANDLE_VALUE;
Dan Kegel's avatar
Dan Kegel committed
435 436 437 438 439 440

/** Trivial byte echo server - disconnects after each session */
static DWORD CALLBACK serverThreadMain1(LPVOID arg)
{
    int i;

441
    trace("serverThreadMain1 start\n");
Dan Kegel's avatar
Dan Kegel committed
442 443 444 445 446 447 448 449 450
    /* Set up a simple echo server */
    hnp = CreateNamedPipe(PIPENAME "serverThreadMain1", PIPE_ACCESS_DUPLEX,
        PIPE_TYPE_BYTE | PIPE_WAIT,
        /* nMaxInstances */ 1,
        /* nOutBufSize */ 1024,
        /* nInBufSize */ 1024,
        /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
        /* lpSecurityAttrib */ NULL);

451
    ok(hnp != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
452
    for (i = 0; i < NB_SERVER_LOOPS; i++) {
Dan Kegel's avatar
Dan Kegel committed
453 454 455 456 457 458
        char buf[512];
        DWORD written;
        DWORD readden;
        DWORD success;

        /* Wait for client to connect */
459
        trace("Server calling ConnectNamedPipe...\n");
Dan Kegel's avatar
Dan Kegel committed
460
        ok(ConnectNamedPipe(hnp, NULL)
461
            || GetLastError() == ERROR_PIPE_CONNECTED, "ConnectNamedPipe\n");
462
        trace("ConnectNamedPipe returned.\n");
Dan Kegel's avatar
Dan Kegel committed
463 464 465 466

        /* Echo bytes once */
        memset(buf, 0, sizeof(buf));

467
        trace("Server reading...\n");
Dan Kegel's avatar
Dan Kegel committed
468
        success = ReadFile(hnp, buf, sizeof(buf), &readden, NULL);
469
        trace("Server done reading.\n");
470 471
        ok(success, "ReadFile\n");
        ok(readden, "short read\n");
Dan Kegel's avatar
Dan Kegel committed
472

473
        trace("Server writing...\n");
474
        ok(WriteFile(hnp, buf, readden, &written, NULL), "WriteFile\n");
475
        trace("Server done writing.\n");
476
        ok(written == readden, "write file len\n");
Dan Kegel's avatar
Dan Kegel committed
477 478

        /* finish this connection, wait for next one */
479
        ok(FlushFileBuffers(hnp), "FlushFileBuffers\n");
480
        trace("Server done flushing.\n");
481
        ok(DisconnectNamedPipe(hnp), "DisconnectNamedPipe\n");
482
        trace("Server done disconnecting.\n");
Dan Kegel's avatar
Dan Kegel committed
483
    }
484
    return 0;
Dan Kegel's avatar
Dan Kegel committed
485 486 487 488 489 490 491 492
}

/** Trivial byte echo server - closes after each connection */
static DWORD CALLBACK serverThreadMain2(LPVOID arg)
{
    int i;
    HANDLE hnpNext = 0;

493
    trace("serverThreadMain2\n");
Dan Kegel's avatar
Dan Kegel committed
494 495 496 497 498 499 500 501
    /* Set up a simple echo server */
    hnp = CreateNamedPipe(PIPENAME "serverThreadMain2", PIPE_ACCESS_DUPLEX,
        PIPE_TYPE_BYTE | PIPE_WAIT,
        /* nMaxInstances */ 2,
        /* nOutBufSize */ 1024,
        /* nInBufSize */ 1024,
        /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
        /* lpSecurityAttrib */ NULL);
502
    ok(hnp != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
Dan Kegel's avatar
Dan Kegel committed
503

504
    for (i = 0; i < NB_SERVER_LOOPS; i++) {
Dan Kegel's avatar
Dan Kegel committed
505 506 507 508 509
        char buf[512];
        DWORD written;
        DWORD readden;
        DWORD success;

510 511 512
        user_apc_ran = FALSE;
        if (i == 0 && pQueueUserAPC) {
            trace("Queueing an user APC\n"); /* verify the pipe is non alerable */
513 514
            success = pQueueUserAPC(&user_apc, GetCurrentThread(), 0);
            ok(success, "QueueUserAPC failed: %d\n", GetLastError());
515 516
        }

Dan Kegel's avatar
Dan Kegel committed
517
        /* Wait for client to connect */
518
        trace("Server calling ConnectNamedPipe...\n");
Dan Kegel's avatar
Dan Kegel committed
519
        ok(ConnectNamedPipe(hnp, NULL)
520
            || GetLastError() == ERROR_PIPE_CONNECTED, "ConnectNamedPipe\n");
521
        trace("ConnectNamedPipe returned.\n");
Dan Kegel's avatar
Dan Kegel committed
522 523 524 525

        /* Echo bytes once */
        memset(buf, 0, sizeof(buf));

526
        trace("Server reading...\n");
Dan Kegel's avatar
Dan Kegel committed
527
        success = ReadFile(hnp, buf, sizeof(buf), &readden, NULL);
528
        trace("Server done reading.\n");
529
        ok(success, "ReadFile\n");
Dan Kegel's avatar
Dan Kegel committed
530

531
        trace("Server writing...\n");
532
        ok(WriteFile(hnp, buf, readden, &written, NULL), "WriteFile\n");
533
        trace("Server done writing.\n");
534
        ok(written == readden, "write file len\n");
Dan Kegel's avatar
Dan Kegel committed
535 536

        /* finish this connection, wait for next one */
537 538
        ok(FlushFileBuffers(hnp), "FlushFileBuffers\n");
        ok(DisconnectNamedPipe(hnp), "DisconnectNamedPipe\n");
Dan Kegel's avatar
Dan Kegel committed
539

540 541 542 543 544
        ok(user_apc_ran == FALSE, "UserAPC ran, pipe using alertable io mode\n");

        if (i == 0 && pQueueUserAPC)
            SleepEx(0, TRUE); /* get rid of apc */

Dan Kegel's avatar
Dan Kegel committed
545 546 547 548 549 550 551 552 553 554
        /* Set up next echo server */
        hnpNext =
            CreateNamedPipe(PIPENAME "serverThreadMain2", PIPE_ACCESS_DUPLEX,
            PIPE_TYPE_BYTE | PIPE_WAIT,
            /* nMaxInstances */ 2,
            /* nOutBufSize */ 1024,
            /* nInBufSize */ 1024,
            /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
            /* lpSecurityAttrib */ NULL);

555
        ok(hnpNext != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
Dan Kegel's avatar
Dan Kegel committed
556

557
        ok(CloseHandle(hnp), "CloseHandle\n");
Dan Kegel's avatar
Dan Kegel committed
558 559
        hnp = hnpNext;
    }
560
    return 0;
Dan Kegel's avatar
Dan Kegel committed
561 562 563 564 565 566 567 568
}

/** Trivial byte echo server - uses overlapped named pipe calls */
static DWORD CALLBACK serverThreadMain3(LPVOID arg)
{
    int i;
    HANDLE hEvent;

569
    trace("serverThreadMain3\n");
Dan Kegel's avatar
Dan Kegel committed
570 571 572
    /* Set up a simple echo server */
    hnp = CreateNamedPipe(PIPENAME "serverThreadMain3", PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
        PIPE_TYPE_BYTE | PIPE_WAIT,
573 574 575 576 577
        /* nMaxInstances */ 1,
        /* nOutBufSize */ 1024,
        /* nInBufSize */ 1024,
        /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
        /* lpSecurityAttrib */ NULL);
578
    ok(hnp != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");
579

Dan Kegel's avatar
Dan Kegel committed
580 581 582 583
    hEvent = CreateEvent(NULL,  /* security attribute */
        TRUE,                   /* manual reset event */
        FALSE,                  /* initial state */
        NULL);                  /* name */
584
    ok(hEvent != NULL, "CreateEvent\n");
Dan Kegel's avatar
Dan Kegel committed
585

586
    for (i = 0; i < NB_SERVER_LOOPS; i++) {
Dan Kegel's avatar
Dan Kegel committed
587 588 589 590 591 592 593 594
        char buf[512];
        DWORD written;
        DWORD readden;
        DWORD dummy;
        DWORD success;
        OVERLAPPED oOverlap;
        int letWFSOEwait = (i & 2);
        int letGORwait = (i & 1);
595
        DWORD err;
Dan Kegel's avatar
Dan Kegel committed
596 597 598 599 600

        memset(&oOverlap, 0, sizeof(oOverlap));
        oOverlap.hEvent = hEvent;

        /* Wait for client to connect */
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
        if (i == 0) {
            trace("Server calling non-overlapped ConnectNamedPipe on overlapped pipe...\n");
            success = ConnectNamedPipe(hnp, NULL);
            err = GetLastError();
            ok(success || (err == ERROR_PIPE_CONNECTED), "ConnectNamedPipe failed: %d\n", err);
            trace("ConnectNamedPipe operation complete.\n");
        } else {
            trace("Server calling overlapped ConnectNamedPipe...\n");
            success = ConnectNamedPipe(hnp, &oOverlap);
            err = GetLastError();
            ok(!success && (err == ERROR_IO_PENDING || err == ERROR_PIPE_CONNECTED), "overlapped ConnectNamedPipe\n");
            trace("overlapped ConnectNamedPipe returned.\n");
            if (!success && (err == ERROR_IO_PENDING)) {
                if (letWFSOEwait)
                {
                    DWORD ret;
                    do {
                        ret = WaitForSingleObjectEx(hEvent, INFINITE, TRUE);
                    } while (ret == WAIT_IO_COMPLETION);
                    ok(ret == 0, "wait ConnectNamedPipe returned %x\n", ret);
                }
                success = GetOverlappedResult(hnp, &oOverlap, &dummy, letGORwait);
                if (!letGORwait && !letWFSOEwait && !success) {
                    ok(GetLastError() == ERROR_IO_INCOMPLETE, "GetOverlappedResult\n");
                    success = GetOverlappedResult(hnp, &oOverlap, &dummy, TRUE);
                }
627
            }
628 629
            ok(success || (err == ERROR_PIPE_CONNECTED), "GetOverlappedResult ConnectNamedPipe\n");
            trace("overlapped ConnectNamedPipe operation complete.\n");
630
        }
Dan Kegel's avatar
Dan Kegel committed
631 632 633 634

        /* Echo bytes once */
        memset(buf, 0, sizeof(buf));

635
        trace("Server reading...\n");
636
        success = ReadFile(hnp, buf, sizeof(buf), &readden, &oOverlap);
637
        trace("Server ReadFile returned...\n");
Dan Kegel's avatar
Dan Kegel committed
638
        err = GetLastError();
639
        ok(success || err == ERROR_IO_PENDING, "overlapped ReadFile\n");
640
        trace("overlapped ReadFile returned.\n");
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
        if (!success && (err == ERROR_IO_PENDING)) {
            if (letWFSOEwait)
            {
                DWORD ret;
                do {
                    ret = WaitForSingleObjectEx(hEvent, INFINITE, TRUE);
                } while (ret == WAIT_IO_COMPLETION);
                ok(ret == 0, "wait ReadFile returned %x\n", ret);
            }
            success = GetOverlappedResult(hnp, &oOverlap, &readden, letGORwait);
            if (!letGORwait && !letWFSOEwait && !success) {
                ok(GetLastError() == ERROR_IO_INCOMPLETE, "GetOverlappedResult\n");
                success = GetOverlappedResult(hnp, &oOverlap, &readden, TRUE);
            }
        }
656
        trace("Server done reading.\n");
657
        ok(success, "overlapped ReadFile\n");
Dan Kegel's avatar
Dan Kegel committed
658

659
        trace("Server writing...\n");
660
        success = WriteFile(hnp, buf, readden, &written, &oOverlap);
661
        trace("Server WriteFile returned...\n");
Dan Kegel's avatar
Dan Kegel committed
662
        err = GetLastError();
663
        ok(success || err == ERROR_IO_PENDING, "overlapped WriteFile\n");
664
        trace("overlapped WriteFile returned.\n");
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
        if (!success && (err == ERROR_IO_PENDING)) {
            if (letWFSOEwait)
            {
                DWORD ret;
                do {
                    ret = WaitForSingleObjectEx(hEvent, INFINITE, TRUE);
                } while (ret == WAIT_IO_COMPLETION);
                ok(ret == 0, "wait WriteFile returned %x\n", ret);
            }
            success = GetOverlappedResult(hnp, &oOverlap, &written, letGORwait);
            if (!letGORwait && !letWFSOEwait && !success) {
                ok(GetLastError() == ERROR_IO_INCOMPLETE, "GetOverlappedResult\n");
                success = GetOverlappedResult(hnp, &oOverlap, &written, TRUE);
            }
        }
680
        trace("Server done writing.\n");
681 682
        ok(success, "overlapped WriteFile\n");
        ok(written == readden, "write file len\n");
Dan Kegel's avatar
Dan Kegel committed
683 684

        /* finish this connection, wait for next one */
685 686
        ok(FlushFileBuffers(hnp), "FlushFileBuffers\n");
        ok(DisconnectNamedPipe(hnp), "DisconnectNamedPipe\n");
Dan Kegel's avatar
Dan Kegel committed
687
    }
688
    return 0;
Dan Kegel's avatar
Dan Kegel committed
689 690
}

691 692 693 694 695
/** Trivial byte echo server - uses i/o completion ports */
static DWORD CALLBACK serverThreadMain4(LPVOID arg)
{
    int i;
    HANDLE hcompletion;
696
    BOOL ret;
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732

    trace("serverThreadMain4\n");
    /* Set up a simple echo server */
    hnp = CreateNamedPipe(PIPENAME "serverThreadMain4", PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
        PIPE_TYPE_BYTE | PIPE_WAIT,
        /* nMaxInstances */ 1,
        /* nOutBufSize */ 1024,
        /* nInBufSize */ 1024,
        /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
        /* lpSecurityAttrib */ NULL);
    ok(hnp != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");

    hcompletion = CreateIoCompletionPort(hnp, NULL, 12345, 1);
    ok(hcompletion != NULL, "CreateIoCompletionPort failed, error=%i\n", GetLastError());

    for (i = 0; i < NB_SERVER_LOOPS; i++) {
        char buf[512];
        DWORD written;
        DWORD readden;
        DWORD dummy;
        DWORD success;
        OVERLAPPED oConnect;
        OVERLAPPED oRead;
        OVERLAPPED oWrite;
        OVERLAPPED *oResult;
        DWORD err;
        ULONG_PTR compkey;

        memset(&oConnect, 0, sizeof(oConnect));
        memset(&oRead, 0, sizeof(oRead));
        memset(&oWrite, 0, sizeof(oWrite));

        /* Wait for client to connect */
        trace("Server calling overlapped ConnectNamedPipe...\n");
        success = ConnectNamedPipe(hnp, &oConnect);
        err = GetLastError();
733 734
        ok(!success && (err == ERROR_IO_PENDING || err == ERROR_PIPE_CONNECTED),
           "overlapped ConnectNamedPipe got %u err %u\n", success, err );
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
        if (!success && err == ERROR_IO_PENDING) {
            trace("ConnectNamedPipe GetQueuedCompletionStatus\n");
            success = GetQueuedCompletionStatus(hcompletion, &dummy, &compkey, &oResult, 0);
            if (!success)
            {
                ok( GetLastError() == WAIT_TIMEOUT,
                    "ConnectNamedPipe GetQueuedCompletionStatus wrong error %u\n", GetLastError());
                success = GetQueuedCompletionStatus(hcompletion, &dummy, &compkey, &oResult, 10000);
            }
            ok(success, "ConnectNamedPipe GetQueuedCompletionStatus failed, errno=%i\n", GetLastError());
            if (success)
            {
                ok(compkey == 12345, "got completion key %i instead of 12345\n", (int)compkey);
                ok(oResult == &oConnect, "got overlapped pointer %p instead of %p\n", oResult, &oConnect);
            }
        }
        trace("overlapped ConnectNamedPipe operation complete.\n");

        /* Echo bytes once */
        memset(buf, 0, sizeof(buf));

        trace("Server reading...\n");
        success = ReadFile(hnp, buf, sizeof(buf), &readden, &oRead);
        trace("Server ReadFile returned...\n");
        err = GetLastError();
        ok(success || err == ERROR_IO_PENDING, "overlapped ReadFile, err=%i\n", err);
        success = GetQueuedCompletionStatus(hcompletion, &readden, &compkey,
            &oResult, 10000);
        ok(success, "ReadFile GetQueuedCompletionStatus failed, errno=%i\n", GetLastError());
        if (success)
        {
            ok(compkey == 12345, "got completion key %i instead of 12345\n", (int)compkey);
            ok(oResult == &oRead, "got overlapped pointer %p instead of %p\n", oResult, &oRead);
        }
        trace("Server done reading.\n");

        trace("Server writing...\n");
        success = WriteFile(hnp, buf, readden, &written, &oWrite);
        trace("Server WriteFile returned...\n");
        err = GetLastError();
775
        ok(success || err == ERROR_IO_PENDING, "overlapped WriteFile failed, err=%u\n", err);
776 777 778 779 780 781 782 783 784 785 786 787 788
        success = GetQueuedCompletionStatus(hcompletion, &written, &compkey,
            &oResult, 10000);
        ok(success, "WriteFile GetQueuedCompletionStatus failed, errno=%i\n", GetLastError());
        if (success)
        {
            ok(compkey == 12345, "got completion key %i instead of 12345\n", (int)compkey);
            ok(oResult == &oWrite, "got overlapped pointer %p instead of %p\n", oResult, &oWrite);
            ok(written == readden, "write file len\n");
        }
        trace("Server done writing.\n");

        /* finish this connection, wait for next one */
        ok(FlushFileBuffers(hnp), "FlushFileBuffers\n");
789 790
        success = DisconnectNamedPipe(hnp);
        ok(success, "DisconnectNamedPipe failed, err %u\n", GetLastError());
791 792
    }

793 794 795 796
    ret = CloseHandle(hnp);
    ok(ret, "CloseHandle named pipe failed, err=%i\n", GetLastError());
    ret = CloseHandle(hcompletion);
    ok(ret, "CloseHandle completion failed, err=%i\n", GetLastError());
797 798 799 800

    return 0;
}

801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
static int completion_called;
static DWORD completion_errorcode;
static DWORD completion_num_bytes;
static LPOVERLAPPED completion_lpoverlapped;

static VOID WINAPI completion_routine(DWORD errorcode, DWORD num_bytes, LPOVERLAPPED lpoverlapped)
{
    completion_called++;
    completion_errorcode = errorcode;
    completion_num_bytes = num_bytes;
    completion_lpoverlapped = lpoverlapped;
    SetEvent(lpoverlapped->hEvent);
}

/** Trivial byte echo server - uses ReadFileEx/WriteFileEx */
static DWORD CALLBACK serverThreadMain5(LPVOID arg)
{
    int i;
    HANDLE hEvent;

    trace("serverThreadMain5\n");
    /* Set up a simple echo server */
    hnp = CreateNamedPipe(PIPENAME "serverThreadMain5", PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
        PIPE_TYPE_BYTE | PIPE_WAIT,
        /* nMaxInstances */ 1,
        /* nOutBufSize */ 1024,
        /* nInBufSize */ 1024,
        /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
        /* lpSecurityAttrib */ NULL);
    ok(hnp != INVALID_HANDLE_VALUE, "CreateNamedPipe failed\n");

    hEvent = CreateEvent(NULL,  /* security attribute */
        TRUE,                   /* manual reset event */
        FALSE,                  /* initial state */
        NULL);                  /* name */
    ok(hEvent != NULL, "CreateEvent\n");

    for (i = 0; i < NB_SERVER_LOOPS; i++) {
        char buf[512];
        DWORD readden;
        DWORD success;
        OVERLAPPED oOverlap;
        DWORD err;

        memset(&oOverlap, 0, sizeof(oOverlap));
        oOverlap.hEvent = hEvent;

        /* Wait for client to connect */
        trace("Server calling ConnectNamedPipe...\n");
        success = ConnectNamedPipe(hnp, NULL);
        err = GetLastError();
        ok(success || (err == ERROR_PIPE_CONNECTED), "ConnectNamedPipe failed: %d\n", err);
        trace("ConnectNamedPipe operation complete.\n");

        /* Echo bytes once */
        memset(buf, 0, sizeof(buf));

        trace("Server reading...\n");
        completion_called = 0;
        ResetEvent(hEvent);
        success = ReadFileEx(hnp, buf, sizeof(buf), &oOverlap, completion_routine);
        trace("Server ReadFileEx returned...\n");
        ok(success, "ReadFileEx failed, err=%i\n", GetLastError());
        ok(completion_called == 0, "completion routine called before ReadFileEx return\n");
        trace("ReadFileEx returned.\n");
        if (success) {
            DWORD ret;
            do {
                ret = WaitForSingleObjectEx(hEvent, INFINITE, TRUE);
            } while (ret == WAIT_IO_COMPLETION);
            ok(ret == 0, "wait ReadFileEx returned %x\n", ret);
        }
        ok(completion_called == 1, "completion routine called %i times\n", completion_called);
        ok(completion_errorcode == ERROR_SUCCESS, "completion routine got error %d\n", completion_errorcode);
875
        ok(completion_num_bytes != 0, "read 0 bytes\n");
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
        ok(completion_lpoverlapped == &oOverlap, "got wrong overlapped pointer %p\n", completion_lpoverlapped);
        readden = completion_num_bytes;
        trace("Server done reading.\n");

        trace("Server writing...\n");
        completion_called = 0;
        ResetEvent(hEvent);
        success = WriteFileEx(hnp, buf, readden, &oOverlap, completion_routine);
        trace("Server WriteFileEx returned...\n");
        ok(success, "WriteFileEx failed, err=%i\n", GetLastError());
        ok(completion_called == 0, "completion routine called before ReadFileEx return\n");
        trace("overlapped WriteFile returned.\n");
        if (success) {
            DWORD ret;
            do {
                ret = WaitForSingleObjectEx(hEvent, INFINITE, TRUE);
            } while (ret == WAIT_IO_COMPLETION);
            ok(ret == 0, "wait WriteFileEx returned %x\n", ret);
        }
        trace("Server done writing.\n");
        ok(completion_called == 1, "completion routine called %i times\n", completion_called);
        ok(completion_errorcode == ERROR_SUCCESS, "completion routine got error %d\n", completion_errorcode);
        ok(completion_num_bytes == readden, "read %i bytes wrote %i\n", readden, completion_num_bytes);
        ok(completion_lpoverlapped == &oOverlap, "got wrong overlapped pointer %p\n", completion_lpoverlapped);

        /* finish this connection, wait for next one */
        ok(FlushFileBuffers(hnp), "FlushFileBuffers\n");
        ok(DisconnectNamedPipe(hnp), "DisconnectNamedPipe\n");
    }
    return 0;
}

Dan Kegel's avatar
Dan Kegel committed
908 909 910 911
static void exercizeServer(const char *pipename, HANDLE serverThread)
{
    int i;

912
    trace("exercizeServer starting\n");
913
    for (i = 0; i < NB_SERVER_LOOPS; i++) {
914
        HANDLE hFile=INVALID_HANDLE_VALUE;
915
        static const char obuf[] = "Bit Bucket";
Dan Kegel's avatar
Dan Kegel committed
916 917 918 919 920 921 922
        char ibuf[32];
        DWORD written;
        DWORD readden;
        int loop;

        for (loop = 0; loop < 3; loop++) {
	    DWORD err;
923
            trace("Client connecting...\n");
Dan Kegel's avatar
Dan Kegel committed
924 925 926 927 928 929 930
            /* Connect to the server */
            hFile = CreateFileA(pipename, GENERIC_READ | GENERIC_WRITE, 0,
                NULL, OPEN_EXISTING, 0, 0);
            if (hFile != INVALID_HANDLE_VALUE)
                break;
	    err = GetLastError();
	    if (loop == 0)
931
	        ok(err == ERROR_PIPE_BUSY || err == ERROR_FILE_NOT_FOUND, "connecting to pipe\n");
Dan Kegel's avatar
Dan Kegel committed
932
	    else
933
	        ok(err == ERROR_PIPE_BUSY, "connecting to pipe\n");
934
            trace("connect failed, retrying\n");
Dan Kegel's avatar
Dan Kegel committed
935 936
            Sleep(200);
        }
937
        ok(hFile != INVALID_HANDLE_VALUE, "client opening named pipe\n");
Dan Kegel's avatar
Dan Kegel committed
938 939 940

        /* Make sure it can echo */
        memset(ibuf, 0, sizeof(ibuf));
941
        trace("Client writing...\n");
942 943
        ok(WriteFile(hFile, obuf, sizeof(obuf), &written, NULL), "WriteFile to client end of pipe\n");
        ok(written == sizeof(obuf), "write file len\n");
944
        trace("Client reading...\n");
945 946 947
        ok(ReadFile(hFile, ibuf, sizeof(obuf), &readden, NULL), "ReadFile from client end of pipe\n");
        ok(readden == sizeof(obuf), "read file len\n");
        ok(memcmp(obuf, ibuf, written) == 0, "content check\n");
Dan Kegel's avatar
Dan Kegel committed
948

949
        trace("Client closing...\n");
950
        ok(CloseHandle(hFile), "CloseHandle\n");
Dan Kegel's avatar
Dan Kegel committed
951 952
    }

953
    ok(WaitForSingleObject(serverThread,INFINITE) == WAIT_OBJECT_0, "WaitForSingleObject\n");
Dan Kegel's avatar
Dan Kegel committed
954
    CloseHandle(hnp);
955
    trace("exercizeServer returning\n");
Dan Kegel's avatar
Dan Kegel committed
956 957
}

958
static void test_NamedPipe_2(void)
Dan Kegel's avatar
Dan Kegel committed
959 960 961 962 963 964
{
    HANDLE serverThread;
    DWORD serverThreadId;
    HANDLE alarmThread;
    DWORD alarmThreadId;

965
    trace("test_NamedPipe_2 starting\n");
966
    /* Set up a twenty second timeout */
967
    alarm_event = CreateEvent( NULL, TRUE, FALSE, NULL );
968
    SetLastError(0xdeadbeef);
969
    alarmThread = CreateThread(NULL, 0, alarmThreadMain, (void *) 20000, 0, &alarmThreadId);
970
    ok(alarmThread != NULL, "CreateThread failed: %d\n", GetLastError());
Dan Kegel's avatar
Dan Kegel committed
971

972 973
    /* The servers we're about to exercise do try to clean up carefully,
     * but to reduce the chance of a test failure due to a pipe handle
Dan Kegel's avatar
Dan Kegel committed
974 975 976 977
     * leak in the test code, we'll use a different pipe name for each server.
     */

    /* Try server #1 */
978
    SetLastError(0xdeadbeef);
979
    serverThread = CreateThread(NULL, 0, serverThreadMain1, (void *)8, 0, &serverThreadId);
980
    ok(serverThread != NULL, "CreateThread failed: %d\n", GetLastError());
Dan Kegel's avatar
Dan Kegel committed
981 982 983
    exercizeServer(PIPENAME "serverThreadMain1", serverThread);

    /* Try server #2 */
984
    SetLastError(0xdeadbeef);
Dan Kegel's avatar
Dan Kegel committed
985
    serverThread = CreateThread(NULL, 0, serverThreadMain2, 0, 0, &serverThreadId);
986
    ok(serverThread != NULL, "CreateThread failed: %d\n", GetLastError());
Dan Kegel's avatar
Dan Kegel committed
987 988 989
    exercizeServer(PIPENAME "serverThreadMain2", serverThread);

    /* Try server #3 */
990
    SetLastError(0xdeadbeef);
Dan Kegel's avatar
Dan Kegel committed
991
    serverThread = CreateThread(NULL, 0, serverThreadMain3, 0, 0, &serverThreadId);
992
    ok(serverThread != NULL, "CreateThread failed: %d\n", GetLastError());
Dan Kegel's avatar
Dan Kegel committed
993 994
    exercizeServer(PIPENAME "serverThreadMain3", serverThread);

995
    /* Try server #4 */
996
    SetLastError(0xdeadbeef);
997
    serverThread = CreateThread(NULL, 0, serverThreadMain4, 0, 0, &serverThreadId);
998
    ok(serverThread != NULL, "CreateThread failed: %d\n", GetLastError());
999 1000
    exercizeServer(PIPENAME "serverThreadMain4", serverThread);

1001 1002 1003 1004 1005 1006
    /* Try server #5 */
    SetLastError(0xdeadbeef);
    serverThread = CreateThread(NULL, 0, serverThreadMain5, 0, 0, &serverThreadId);
    ok(serverThread != NULL, "CreateThread failed: %d\n", GetLastError());
    exercizeServer(PIPENAME "serverThreadMain5", serverThread);

1007 1008
    ok(SetEvent( alarm_event ), "SetEvent\n");
    CloseHandle( alarm_event );
1009
    trace("test_NamedPipe_2 returning\n");
Dan Kegel's avatar
Dan Kegel committed
1010 1011
}

1012
static int test_DisconnectNamedPipe(void)
Dan Kegel's avatar
Dan Kegel committed
1013 1014 1015
{
    HANDLE hnp;
    HANDLE hFile;
1016
    static const char obuf[] = "Bit Bucket";
Dan Kegel's avatar
Dan Kegel committed
1017 1018 1019
    char ibuf[32];
    DWORD written;
    DWORD readden;
1020
    DWORD ret;
Dan Kegel's avatar
Dan Kegel committed
1021

1022
    SetLastError(0xdeadbeef);
Dan Kegel's avatar
Dan Kegel committed
1023 1024 1025 1026 1027 1028
    hnp = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_WAIT,
        /* nMaxInstances */ 1,
        /* nOutBufSize */ 1024,
        /* nInBufSize */ 1024,
        /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
        /* lpSecurityAttrib */ NULL);
1029 1030 1031 1032
    if ((hnp == INVALID_HANDLE_VALUE /* Win98 */ || !hnp /* Win95 */)
        && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED) {

        win_skip("Named pipes are not implemented\n");
1033 1034
        return 1;
    }
Dan Kegel's avatar
Dan Kegel committed
1035 1036

    ok(WriteFile(hnp, obuf, sizeof(obuf), &written, NULL) == 0
1037
        && GetLastError() == ERROR_PIPE_LISTENING, "WriteFile to not-yet-connected pipe\n");
Dan Kegel's avatar
Dan Kegel committed
1038
    ok(ReadFile(hnp, ibuf, sizeof(ibuf), &readden, NULL) == 0
1039
        && GetLastError() == ERROR_PIPE_LISTENING, "ReadFile from not-yet-connected pipe\n");
Dan Kegel's avatar
Dan Kegel committed
1040 1041

    hFile = CreateFileA(PIPENAME, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
1042
    ok(hFile != INVALID_HANDLE_VALUE, "CreateFile failed\n");
1043 1044 1045

    /* don't try to do i/o if one side couldn't be opened, as it hangs */
    if (hFile != INVALID_HANDLE_VALUE) {
Dan Kegel's avatar
Dan Kegel committed
1046 1047 1048 1049 1050

        /* see what happens if server calls DisconnectNamedPipe
         * when there are bytes in the pipe
         */

1051 1052 1053
        ok(WriteFile(hFile, obuf, sizeof(obuf), &written, NULL), "WriteFile\n");
        ok(written == sizeof(obuf), "write file len\n");
        ok(DisconnectNamedPipe(hnp), "DisconnectNamedPipe while messages waiting\n");
Dan Kegel's avatar
Dan Kegel committed
1054
        ok(WriteFile(hFile, obuf, sizeof(obuf), &written, NULL) == 0
1055
            && GetLastError() == ERROR_PIPE_NOT_CONNECTED, "WriteFile to disconnected pipe\n");
Dan Kegel's avatar
Dan Kegel committed
1056 1057
        ok(ReadFile(hnp, ibuf, sizeof(ibuf), &readden, NULL) == 0
            && GetLastError() == ERROR_PIPE_NOT_CONNECTED,
1058
            "ReadFile from disconnected pipe with bytes waiting\n");
1059 1060
        ok(!DisconnectNamedPipe(hnp) && GetLastError() == ERROR_PIPE_NOT_CONNECTED,
           "DisconnectNamedPipe worked twice\n");
1061 1062
        ret = WaitForSingleObject(hFile, 0);
        ok(ret == WAIT_TIMEOUT, "WaitForSingleObject returned %X\n", ret);
1063
        ok(CloseHandle(hFile), "CloseHandle\n");
1064 1065
    }

1066
    ok(CloseHandle(hnp), "CloseHandle\n");
Dan Kegel's avatar
Dan Kegel committed
1067

1068
    return 0;
1069
}
Uwe Bonnes's avatar
Uwe Bonnes committed
1070 1071 1072 1073 1074 1075
static void test_CreatePipe(void)
{
    SECURITY_ATTRIBUTES pipe_attr;
    HANDLE piperead, pipewrite;
    DWORD written;
    DWORD read;
1076 1077
    DWORD i, size;
    BYTE *buffer;
Uwe Bonnes's avatar
Uwe Bonnes committed
1078 1079
    char readbuf[32];

1080 1081 1082 1083
    user_apc_ran = FALSE;
    if (pQueueUserAPC)
        ok(pQueueUserAPC(user_apc, GetCurrentThread(), 0), "couldn't create user apc\n");

Uwe Bonnes's avatar
Uwe Bonnes committed
1084 1085
    pipe_attr.nLength = sizeof(SECURITY_ATTRIBUTES); 
    pipe_attr.bInheritHandle = TRUE; 
1086
    pipe_attr.lpSecurityDescriptor = NULL;
Uwe Bonnes's avatar
Uwe Bonnes committed
1087 1088
    ok(CreatePipe(&piperead, &pipewrite, &pipe_attr, 0) != 0, "CreatePipe failed\n");
    ok(WriteFile(pipewrite,PIPENAME,sizeof(PIPENAME), &written, NULL), "Write to anonymous pipe failed\n");
1089
    ok(written == sizeof(PIPENAME), "Write to anonymous pipe wrote %d bytes\n", written);
Uwe Bonnes's avatar
Uwe Bonnes committed
1090
    ok(ReadFile(piperead,readbuf,sizeof(readbuf),&read, NULL), "Read from non empty pipe failed\n");
1091
    ok(read == sizeof(PIPENAME), "Read from  anonymous pipe got %d bytes\n", read);
1092 1093
    ok(CloseHandle(pipewrite), "CloseHandle for the write pipe failed\n");
    ok(CloseHandle(piperead), "CloseHandle for the read pipe failed\n");
Uwe Bonnes's avatar
Uwe Bonnes committed
1094 1095 1096 1097

    /* Now write another chunk*/
    ok(CreatePipe(&piperead, &pipewrite, &pipe_attr, 0) != 0, "CreatePipe failed\n");
    ok(WriteFile(pipewrite,PIPENAME,sizeof(PIPENAME), &written, NULL), "Write to anonymous pipe failed\n");
1098
    ok(written == sizeof(PIPENAME), "Write to anonymous pipe wrote %d bytes\n", written);
Uwe Bonnes's avatar
Uwe Bonnes committed
1099 1100 1101
    /* and close the write end, read should still succeed*/
    ok(CloseHandle(pipewrite), "CloseHandle for the Write Pipe failed\n");
    ok(ReadFile(piperead,readbuf,sizeof(readbuf),&read, NULL), "Read from broken pipe withe with pending data failed\n");
1102
    ok(read == sizeof(PIPENAME), "Read from  anonymous pipe got %d bytes\n", read);
Uwe Bonnes's avatar
Uwe Bonnes committed
1103
    /* But now we need to get informed that the pipe is closed */
1104
    ok(ReadFile(piperead,readbuf,sizeof(readbuf),&read, NULL) == 0, "Broken pipe not detected\n");
1105 1106 1107 1108 1109 1110
    ok(CloseHandle(piperead), "CloseHandle for the read pipe failed\n");

    /* Try bigger chunks */
    size = 32768;
    buffer = HeapAlloc( GetProcessHeap(), 0, size );
    for (i = 0; i < size; i++) buffer[i] = i;
1111
    ok(CreatePipe(&piperead, &pipewrite, &pipe_attr, (size + 24)) != 0, "CreatePipe failed\n");
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
    ok(WriteFile(pipewrite, buffer, size, &written, NULL), "Write to anonymous pipe failed\n");
    ok(written == size, "Write to anonymous pipe wrote %d bytes\n", written);
    /* and close the write end, read should still succeed*/
    ok(CloseHandle(pipewrite), "CloseHandle for the Write Pipe failed\n");
    memset( buffer, 0, size );
    ok(ReadFile(piperead, buffer, size, &read, NULL), "Read from broken pipe withe with pending data failed\n");
    ok(read == size, "Read from  anonymous pipe got %d bytes\n", read);
    for (i = 0; i < size; i++) ok( buffer[i] == (BYTE)i, "invalid data %x at %x\n", buffer[i], i );
    /* But now we need to get informed that the pipe is closed */
    ok(ReadFile(piperead,readbuf,sizeof(readbuf),&read, NULL) == 0, "Broken pipe not detected\n");
    ok(CloseHandle(piperead), "CloseHandle for the read pipe failed\n");
1123
    HeapFree(GetProcessHeap(), 0, buffer);
1124 1125 1126

    ok(user_apc_ran == FALSE, "user apc ran, pipe using alertable io mode\n");
    SleepEx(0, TRUE); /* get rid of apc */
Uwe Bonnes's avatar
Uwe Bonnes committed
1127
}
1128

1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
struct named_pipe_client_params
{
    DWORD security_flags;
    HANDLE token;
    BOOL revert;
};

#define PIPE_NAME "\\\\.\\pipe\\named_pipe_test"

static DWORD CALLBACK named_pipe_client_func(LPVOID p)
{
1140
    struct named_pipe_client_params *params = p;
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
    HANDLE pipe;
    BOOL ret;
    const char message[] = "Test";
    DWORD bytes_read, bytes_written;
    char dummy;
    TOKEN_PRIVILEGES *Privileges = NULL;

    if (params->token)
    {
        if (params->revert)
        {
            /* modify the token so we can tell if the pipe impersonation
             * token reverts to the process token */
            ret = AdjustTokenPrivileges(params->token, TRUE, NULL, 0, NULL, NULL);
            ok(ret, "AdjustTokenPrivileges failed with error %d\n", GetLastError());
        }
        ret = SetThreadToken(NULL, params->token);
        ok(ret, "SetThreadToken failed with error %d\n", GetLastError());
    }
    else
    {
        DWORD Size = 0;
        HANDLE process_token;

        ret = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES, &process_token);
        ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());

        ret = GetTokenInformation(process_token, TokenPrivileges, NULL, 0, &Size);
        ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "GetTokenInformation(TokenPrivileges) failed with %d\n", GetLastError());
1170
        Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
        ret = GetTokenInformation(process_token, TokenPrivileges, Privileges, Size, &Size);
        ok(ret, "GetTokenInformation(TokenPrivileges) failed with %d\n", GetLastError());

        ret = AdjustTokenPrivileges(process_token, TRUE, NULL, 0, NULL, NULL);
        ok(ret, "AdjustTokenPrivileges failed with error %d\n", GetLastError());

        CloseHandle(process_token);
    }

    pipe = CreateFile(PIPE_NAME, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, params->security_flags, NULL);
    ok(pipe != INVALID_HANDLE_VALUE, "CreateFile for pipe failed with error %d\n", GetLastError());

    ret = WriteFile(pipe, message, sizeof(message), &bytes_written, NULL);
    ok(ret, "WriteFile failed with error %d\n", GetLastError());

    ret = ReadFile(pipe, &dummy, sizeof(dummy), &bytes_read, NULL);
    ok(ret, "ReadFile failed with error %d\n", GetLastError());

    if (params->token)
    {
        if (params->revert)
        {
            ret = RevertToSelf();
            ok(ret, "RevertToSelf failed with error %d\n", GetLastError());
        }
        else
        {
            ret = AdjustTokenPrivileges(params->token, TRUE, NULL, 0, NULL, NULL);
            ok(ret, "AdjustTokenPrivileges failed with error %d\n", GetLastError());
        }
    }
    else
    {
        HANDLE process_token;

        ret = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &process_token);
        ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());

        ret = AdjustTokenPrivileges(process_token, FALSE, Privileges, 0, NULL, NULL);
        ok(ret, "AdjustTokenPrivileges failed with error %d\n", GetLastError());

        HeapFree(GetProcessHeap(), 0, Privileges);

        CloseHandle(process_token);
    }

    ret = WriteFile(pipe, message, sizeof(message), &bytes_written, NULL);
    ok(ret, "WriteFile failed with error %d\n", GetLastError());

    ret = ReadFile(pipe, &dummy, sizeof(dummy), &bytes_read, NULL);
    ok(ret, "ReadFile failed with error %d\n", GetLastError());

    CloseHandle(pipe);

    return 0;
}

static HANDLE make_impersonation_token(DWORD Access, SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
{
    HANDLE ProcessToken;
    HANDLE Token = NULL;
    BOOL ret;

    ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &ProcessToken);
    ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());

1237
    ret = pDuplicateTokenEx(ProcessToken, Access, NULL, ImpersonationLevel, TokenImpersonation, &Token);
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
    ok(ret, "DuplicateToken failed with error %d\n", GetLastError());

    CloseHandle(ProcessToken);

    return Token;
}

static void test_ImpersonateNamedPipeClient(HANDLE hClientToken, DWORD security_flags, BOOL revert, void (*test_func)(int, HANDLE))
{
    HANDLE hPipeServer;
    BOOL ret;
    DWORD dwTid;
    HANDLE hThread;
    char buffer[256];
    DWORD dwBytesRead;
    DWORD error;
    struct named_pipe_client_params params;
    char dummy = 0;
    DWORD dwBytesWritten;
    HANDLE hToken = NULL;
    SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
    DWORD size;

    hPipeServer = CreateNamedPipe(PIPE_NAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, 1, 100, 100, NMPWAIT_USE_DEFAULT_WAIT, NULL);
    ok(hPipeServer != INVALID_HANDLE_VALUE, "CreateNamedPipe failed with error %d\n", GetLastError());

    params.security_flags = security_flags;
    params.token = hClientToken;
    params.revert = revert;
    hThread = CreateThread(NULL, 0, named_pipe_client_func, &params, 0, &dwTid);
    ok(hThread != NULL, "CreateThread failed with error %d\n", GetLastError());

    SetLastError(0xdeadbeef);
    ret = ImpersonateNamedPipeClient(hPipeServer);
    error = GetLastError();
1273
    ok(ret /* win2k3 */ || (error == ERROR_CANNOT_IMPERSONATE),
1274
       "ImpersonateNamedPipeClient should have failed with ERROR_CANNOT_IMPERSONATE instead of %d\n", GetLastError());
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289

    ret = ConnectNamedPipe(hPipeServer, NULL);
    ok(ret || (GetLastError() == ERROR_PIPE_CONNECTED), "ConnectNamedPipe failed with error %d\n", GetLastError());

    ret = ReadFile(hPipeServer, buffer, sizeof(buffer), &dwBytesRead, NULL);
    ok(ret, "ReadFile failed with error %d\n", GetLastError());

    ret = ImpersonateNamedPipeClient(hPipeServer);
    ok(ret, "ImpersonateNamedPipeClient failed with error %d\n", GetLastError());

    ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, FALSE, &hToken);
    ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());

    (*test_func)(0, hToken);

1290
    ImpersonationLevel = 0xdeadbeef; /* to avoid false positives */
1291 1292
    ret = GetTokenInformation(hToken, TokenImpersonationLevel, &ImpersonationLevel, sizeof(ImpersonationLevel), &size);
    ok(ret, "GetTokenInformation(TokenImpersonationLevel) failed with error %d\n", GetLastError());
1293
    ok(ImpersonationLevel == SecurityImpersonation, "ImpersonationLevel should have been SecurityImpersonation(%d) instead of %d\n", SecurityImpersonation, ImpersonationLevel);
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343

    CloseHandle(hToken);

    RevertToSelf();

    ret = WriteFile(hPipeServer, &dummy, sizeof(dummy), &dwBytesWritten, NULL);
    ok(ret, "WriteFile failed with error %d\n", GetLastError());

    ret = ReadFile(hPipeServer, buffer, sizeof(buffer), &dwBytesRead, NULL);
    ok(ret, "ReadFile failed with error %d\n", GetLastError());

    ret = ImpersonateNamedPipeClient(hPipeServer);
    ok(ret, "ImpersonateNamedPipeClient failed with error %d\n", GetLastError());

    ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, FALSE, &hToken);
    ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());

    (*test_func)(1, hToken);

    CloseHandle(hToken);

    RevertToSelf();

    ret = WriteFile(hPipeServer, &dummy, sizeof(dummy), &dwBytesWritten, NULL);
    ok(ret, "WriteFile failed with error %d\n", GetLastError());

    WaitForSingleObject(hThread, INFINITE);

    ret = ImpersonateNamedPipeClient(hPipeServer);
    ok(ret, "ImpersonateNamedPipeClient failed with error %d\n", GetLastError());

    RevertToSelf();

    CloseHandle(hThread);
    CloseHandle(hPipeServer);
}

static BOOL are_all_privileges_disabled(HANDLE hToken)
{
    BOOL ret;
    TOKEN_PRIVILEGES *Privileges = NULL;
    DWORD Size = 0;
    BOOL all_privs_disabled = TRUE;
    DWORD i;

    ret = GetTokenInformation(hToken, TokenPrivileges, NULL, 0, &Size);
    if (!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
    {
        Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
        ret = GetTokenInformation(hToken, TokenPrivileges, Privileges, Size, &Size);
1344 1345 1346 1347 1348
        if (!ret)
        {
            HeapFree(GetProcessHeap(), 0, Privileges);
            return FALSE;
        }
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
    }
    else
        return FALSE;

    for (i = 0; i < Privileges->PrivilegeCount; i++)
    {
        if (Privileges->Privileges[i].Attributes & SE_PRIVILEGE_ENABLED)
        {
            all_privs_disabled = FALSE;
            break;
        }
    }

    HeapFree(GetProcessHeap(), 0, Privileges);

    return all_privs_disabled;
}

static DWORD get_privilege_count(HANDLE hToken)
{
    TOKEN_STATISTICS Statistics;
    DWORD Size = sizeof(Statistics);
    BOOL ret;

    ret = GetTokenInformation(hToken, TokenStatistics, &Statistics, Size, &Size);
    ok(ret, "GetTokenInformation(TokenStatistics)\n");
    if (!ret) return -1;

    return Statistics.PrivilegeCount;
}

static void test_no_sqos_no_token(int call_index, HANDLE hToken)
{
    DWORD priv_count;

    switch (call_index)
    {
    case 0:
        priv_count = get_privilege_count(hToken);
        todo_wine
        ok(priv_count == 0, "privilege count should have been 0 instead of %d\n", priv_count);
        break;
    case 1:
        priv_count = get_privilege_count(hToken);
        ok(priv_count > 0, "privilege count should now be > 0 instead of 0\n");
        ok(!are_all_privileges_disabled(hToken), "impersonated token should not have been modified\n");
        break;
    default:
        ok(0, "shouldn't happen\n");
    }
}

static void test_no_sqos(int call_index, HANDLE hToken)
{
    switch (call_index)
    {
    case 0:
        ok(!are_all_privileges_disabled(hToken), "token should be a copy of the process one\n");
        break;
    case 1:
        todo_wine
        ok(are_all_privileges_disabled(hToken), "impersonated token should have been modified\n");
        break;
    default:
        ok(0, "shouldn't happen\n");
    }
}

static void test_static_context(int call_index, HANDLE hToken)
{
    switch (call_index)
    {
    case 0:
        ok(!are_all_privileges_disabled(hToken), "token should be a copy of the process one\n");
        break;
    case 1:
        ok(!are_all_privileges_disabled(hToken), "impersonated token should not have been modified\n");
        break;
    default:
        ok(0, "shouldn't happen\n");
    }
}

static void test_dynamic_context(int call_index, HANDLE hToken)
{
    switch (call_index)
    {
    case 0:
        ok(!are_all_privileges_disabled(hToken), "token should be a copy of the process one\n");
        break;
    case 1:
        todo_wine
        ok(are_all_privileges_disabled(hToken), "impersonated token should have been modified\n");
        break;
    default:
        ok(0, "shouldn't happen\n");
    }
}

static void test_dynamic_context_no_token(int call_index, HANDLE hToken)
{
    switch (call_index)
    {
    case 0:
        ok(are_all_privileges_disabled(hToken), "token should be a copy of the process one\n");
        break;
    case 1:
        ok(!are_all_privileges_disabled(hToken), "process token modification should have been detected and impersonation token updated\n");
        break;
    default:
        ok(0, "shouldn't happen\n");
    }
}

static void test_no_sqos_revert(int call_index, HANDLE hToken)
{
    DWORD priv_count;
    switch (call_index)
    {
    case 0:
        priv_count = get_privilege_count(hToken);
        todo_wine
        ok(priv_count == 0, "privilege count should have been 0 instead of %d\n", priv_count);
        break;
    case 1:
        priv_count = get_privilege_count(hToken);
        ok(priv_count > 0, "privilege count should now be > 0 instead of 0\n");
        ok(!are_all_privileges_disabled(hToken), "impersonated token should not have been modified\n");
        break;
    default:
        ok(0, "shouldn't happen\n");
    }
}

static void test_static_context_revert(int call_index, HANDLE hToken)
{
    switch (call_index)
    {
    case 0:
        todo_wine
        ok(are_all_privileges_disabled(hToken), "privileges should have been disabled\n");
        break;
    case 1:
        todo_wine
        ok(are_all_privileges_disabled(hToken), "impersonated token should not have been modified\n");
        break;
    default:
        ok(0, "shouldn't happen\n");
    }
}

static void test_dynamic_context_revert(int call_index, HANDLE hToken)
{
    switch (call_index)
    {
    case 0:
        todo_wine
        ok(are_all_privileges_disabled(hToken), "privileges should have been disabled\n");
        break;
    case 1:
        ok(!are_all_privileges_disabled(hToken), "impersonated token should now be process token\n");
        break;
    default:
        ok(0, "shouldn't happen\n");
    }
}

static void test_impersonation(void)
{
    HANDLE hClientToken;
    HANDLE hProcessToken;
    BOOL ret;

1522 1523 1524 1525 1526
    if( !pDuplicateTokenEx ) {
        skip("DuplicateTokenEx not found\n");
        return;
    }

1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
    ret = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hProcessToken);
    if (!ret)
    {
        skip("couldn't open process token, skipping impersonation tests\n");
        return;
    }

    if (!get_privilege_count(hProcessToken) || are_all_privileges_disabled(hProcessToken))
    {
        skip("token didn't have any privileges or they were all disabled. token not suitable for impersonation tests\n");
        CloseHandle(hProcessToken);
        return;
    }
    CloseHandle(hProcessToken);

    test_ImpersonateNamedPipeClient(NULL, 0, FALSE, test_no_sqos_no_token);
    hClientToken = make_impersonation_token(TOKEN_IMPERSONATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, SecurityImpersonation);
    test_ImpersonateNamedPipeClient(hClientToken, 0, FALSE, test_no_sqos);
    CloseHandle(hClientToken);
    hClientToken = make_impersonation_token(TOKEN_IMPERSONATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, SecurityImpersonation);
    test_ImpersonateNamedPipeClient(hClientToken,
        SECURITY_SQOS_PRESENT | SECURITY_IMPERSONATION, FALSE,
        test_static_context);
    CloseHandle(hClientToken);
    hClientToken = make_impersonation_token(TOKEN_IMPERSONATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, SecurityImpersonation);
    test_ImpersonateNamedPipeClient(hClientToken,
        SECURITY_SQOS_PRESENT | SECURITY_CONTEXT_TRACKING | SECURITY_IMPERSONATION,
        FALSE, test_dynamic_context);
    CloseHandle(hClientToken);
    test_ImpersonateNamedPipeClient(NULL,
        SECURITY_SQOS_PRESENT | SECURITY_CONTEXT_TRACKING | SECURITY_IMPERSONATION,
        FALSE, test_dynamic_context_no_token);

    hClientToken = make_impersonation_token(TOKEN_IMPERSONATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, SecurityImpersonation);
    test_ImpersonateNamedPipeClient(hClientToken, 0, TRUE, test_no_sqos_revert);
    CloseHandle(hClientToken);
    hClientToken = make_impersonation_token(TOKEN_IMPERSONATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, SecurityImpersonation);
    test_ImpersonateNamedPipeClient(hClientToken,
        SECURITY_SQOS_PRESENT | SECURITY_IMPERSONATION, TRUE,
        test_static_context_revert);
    CloseHandle(hClientToken);
    hClientToken = make_impersonation_token(TOKEN_IMPERSONATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, SecurityImpersonation);
    test_ImpersonateNamedPipeClient(hClientToken,
        SECURITY_SQOS_PRESENT | SECURITY_CONTEXT_TRACKING | SECURITY_IMPERSONATION,
        TRUE, test_dynamic_context_revert);
    CloseHandle(hClientToken);
}

1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
struct overlapped_server_args
{
    HANDLE pipe_created;
};

static DWORD CALLBACK overlapped_server(LPVOID arg)
{
    OVERLAPPED ol;
    HANDLE pipe;
    int ret, err;
1585
    struct overlapped_server_args *a = arg;
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
    DWORD num;
    char buf[100];

    pipe = CreateNamedPipeA("\\\\.\\pipe\\my pipe", FILE_FLAG_OVERLAPPED | PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE, 1, 0, 0, 100000, NULL);
    ok(pipe != NULL, "pipe NULL\n");

    ol.hEvent = CreateEventA(0, 1, 0, 0);
    ok(ol.hEvent != NULL, "event NULL\n");
    ret = ConnectNamedPipe(pipe, &ol);
    err = GetLastError();
    ok(ret == 0, "ret %d\n", ret);
    ok(err == ERROR_IO_PENDING, "gle %d\n", err);
    SetEvent(a->pipe_created);

    ret = WaitForSingleObjectEx(ol.hEvent, INFINITE, 1);
1601
    ok(ret == WAIT_OBJECT_0, "ret %x\n", ret);
1602 1603 1604 1605 1606 1607

    ret = GetOverlappedResult(pipe, &ol, &num, 1);
    ok(ret == 1, "ret %d\n", ret);

    /* This should block */
    ret = ReadFile(pipe, buf, sizeof(buf), &num, NULL);
1608
    ok(ret == 1, "ret %d\n", ret);
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619

    DisconnectNamedPipe(pipe);
    CloseHandle(ol.hEvent);
    CloseHandle(pipe);
    return 1;
}

static void test_overlapped(void)
{
    DWORD tid, num;
    HANDLE thread, pipe;
1620
    BOOL ret;
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
    struct overlapped_server_args args;

    args.pipe_created = CreateEventA(0, 1, 0, 0);
    thread = CreateThread(NULL, 0, overlapped_server, &args, 0, &tid);

    WaitForSingleObject(args.pipe_created, INFINITE);
    pipe = CreateFileA("\\\\.\\pipe\\my pipe", GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
    ok(pipe != INVALID_HANDLE_VALUE, "cf failed\n");

    /* Sleep to try to get the ReadFile in the server to occur before the following WriteFile */
    Sleep(1);

    ret = WriteFile(pipe, "x", 1, &num, NULL);
1634
    ok(ret, "WriteFile failed with error %d\n", GetLastError());
1635 1636 1637 1638 1639 1640 1641

    WaitForSingleObject(thread, INFINITE);
    CloseHandle(pipe);
    CloseHandle(args.pipe_created);
    CloseHandle(thread);
}

1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752
static void test_NamedPipeHandleState(void)
{
    HANDLE server, client;
    BOOL ret;
    DWORD state, instances, maxCollectionCount, collectDataTimeout;
    char userName[MAX_PATH];

    server = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX,
        /* dwOpenMode */ PIPE_TYPE_BYTE | PIPE_WAIT,
        /* nMaxInstances */ 1,
        /* nOutBufSize */ 1024,
        /* nInBufSize */ 1024,
        /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
        /* lpSecurityAttrib */ NULL);
    ok(server != INVALID_HANDLE_VALUE, "cf failed\n");
    ret = GetNamedPipeHandleState(server, NULL, NULL, NULL, NULL, NULL, 0);
    todo_wine
    ok(ret, "GetNamedPipeHandleState failed: %d\n", GetLastError());
    ret = GetNamedPipeHandleState(server, &state, &instances, NULL, NULL, NULL,
        0);
    todo_wine
    ok(ret, "GetNamedPipeHandleState failed: %d\n", GetLastError());
    if (ret)
    {
        ok(state == 0, "unexpected state %08x\n", state);
        ok(instances == 1, "expected 1 instances, got %d\n", instances);
    }
    /* Some parameters have no meaning, and therefore can't be retrieved,
     * on a local pipe.
     */
    SetLastError(0xdeadbeef);
    ret = GetNamedPipeHandleState(server, &state, &instances,
        &maxCollectionCount, &collectDataTimeout, userName,
        sizeof(userName) / sizeof(userName[0]));
    todo_wine
    ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
       "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
    /* A byte-mode pipe server can't be changed to message mode. */
    state = PIPE_READMODE_MESSAGE;
    SetLastError(0xdeadbeef);
    ret = SetNamedPipeHandleState(server, &state, NULL, NULL);
    todo_wine
    ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
       "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());

    client = CreateFileA(PIPENAME, GENERIC_READ|GENERIC_WRITE, 0, NULL,
        OPEN_EXISTING, 0, NULL);
    ok(client != INVALID_HANDLE_VALUE, "cf failed\n");

    state = PIPE_READMODE_BYTE;
    ret = SetNamedPipeHandleState(client, &state, NULL, NULL);
    todo_wine
    ok(ret, "SetNamedPipeHandleState failed: %d\n", GetLastError());
    /* A byte-mode pipe client can't be changed to message mode, either. */
    state = PIPE_READMODE_MESSAGE;
    SetLastError(0xdeadbeef);
    ret = SetNamedPipeHandleState(server, &state, NULL, NULL);
    todo_wine
    ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
       "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());

    CloseHandle(client);
    CloseHandle(server);

    server = CreateNamedPipe(PIPENAME, PIPE_ACCESS_DUPLEX,
        /* dwOpenMode */ PIPE_TYPE_MESSAGE | PIPE_WAIT,
        /* nMaxInstances */ 1,
        /* nOutBufSize */ 1024,
        /* nInBufSize */ 1024,
        /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
        /* lpSecurityAttrib */ NULL);
    ok(server != INVALID_HANDLE_VALUE, "cf failed\n");
    ret = GetNamedPipeHandleState(server, NULL, NULL, NULL, NULL, NULL, 0);
    todo_wine
    ok(ret, "GetNamedPipeHandleState failed: %d\n", GetLastError());
    ret = GetNamedPipeHandleState(server, &state, &instances, NULL, NULL, NULL,
        0);
    todo_wine
    ok(ret, "GetNamedPipeHandleState failed: %d\n", GetLastError());
    if (ret)
    {
        ok(state == 0, "unexpected state %08x\n", state);
        ok(instances == 1, "expected 1 instances, got %d\n", instances);
    }
    /* In contrast to byte-mode pipes, a message-mode pipe server can be
     * changed to byte mode.
     */
    state = PIPE_READMODE_BYTE;
    ret = SetNamedPipeHandleState(server, &state, NULL, NULL);
    todo_wine
    ok(ret, "SetNamedPipeHandleState failed: %d\n", GetLastError());

    client = CreateFileA(PIPENAME, GENERIC_READ|GENERIC_WRITE, 0, NULL,
        OPEN_EXISTING, 0, NULL);
    ok(client != INVALID_HANDLE_VALUE, "cf failed\n");

    state = PIPE_READMODE_MESSAGE;
    ret = SetNamedPipeHandleState(client, &state, NULL, NULL);
    todo_wine
    ok(ret, "SetNamedPipeHandleState failed: %d\n", GetLastError());
    /* A message-mode pipe client can also be changed to byte mode.
     */
    state = PIPE_READMODE_BYTE;
    ret = SetNamedPipeHandleState(client, &state, NULL, NULL);
    todo_wine
    ok(ret, "SetNamedPipeHandleState failed: %d\n", GetLastError());

    CloseHandle(client);
    CloseHandle(server);
}

1753 1754 1755 1756 1757 1758 1759 1760
static void test_readfileex_pending(void)
{
    HANDLE server, client, event;
    BOOL ret;
    DWORD err, wait, num_bytes;
    OVERLAPPED overlapped;
    char read_buf[1024];
    char write_buf[1024];
1761
    const char test_string[] = "test";
1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
    int i;

    server = CreateNamedPipe(PIPENAME, FILE_FLAG_OVERLAPPED | PIPE_ACCESS_DUPLEX,
        /* dwOpenMode */ PIPE_TYPE_BYTE | PIPE_WAIT,
        /* nMaxInstances */ 1,
        /* nOutBufSize */ 1024,
        /* nInBufSize */ 1024,
        /* nDefaultWait */ NMPWAIT_USE_DEFAULT_WAIT,
        /* lpSecurityAttrib */ NULL);
    ok(server != INVALID_HANDLE_VALUE, "cf failed\n");

    event = CreateEventA(NULL, TRUE, FALSE, NULL);
    ok(event != NULL, "CreateEventA failed\n");

    memset(&overlapped, 0, sizeof(overlapped));
    overlapped.hEvent = event;

    ret = ConnectNamedPipe(server, &overlapped);
    err = GetLastError();
    ok(ret == FALSE, "ConnectNamedPipe succeeded\n");
    ok(err == ERROR_IO_PENDING, "ConnectNamedPipe set error %i\n", err);

    wait = WaitForSingleObject(event, 0);
    ok(wait == WAIT_TIMEOUT, "WaitForSingleObject returned %x\n", wait);

    client = CreateFileA(PIPENAME, GENERIC_READ|GENERIC_WRITE, 0, NULL,
        OPEN_EXISTING, 0, NULL);
    ok(client != INVALID_HANDLE_VALUE, "cf failed\n");

    wait = WaitForSingleObject(event, 0);
    ok(wait == WAIT_OBJECT_0, "WaitForSingleObject returned %x\n", wait);

    /* Start a read that can't complete immediately. */
    completion_called = 0;
    ResetEvent(event);
    ret = ReadFileEx(server, read_buf, sizeof(read_buf), &overlapped, completion_routine);
1798
    ok(ret == TRUE, "ReadFileEx failed, err=%i\n", GetLastError());
1799 1800
    ok(completion_called == 0, "completion routine called before ReadFileEx returned\n");

1801
    ret = WriteFile(client, test_string, strlen(test_string), &num_bytes, NULL);
1802
    ok(ret == TRUE, "WriteFile failed\n");
1803
    ok(num_bytes == strlen(test_string), "only %i bytes written\n", num_bytes);
1804 1805 1806 1807 1808 1809 1810 1811

    ok(completion_called == 0, "completion routine called during WriteFile\n");

    wait = WaitForSingleObjectEx(event, 0, TRUE);
    ok(wait == WAIT_IO_COMPLETION || wait == WAIT_OBJECT_0, "WaitForSingleObjectEx returned %x\n", wait);

    ok(completion_called == 1, "completion not called after writing pipe\n");
    ok(completion_errorcode == 0, "completion called with error %x\n", completion_errorcode);
1812
    ok(completion_num_bytes == strlen(test_string), "ReadFileEx returned only %d bytes\n", completion_num_bytes);
1813
    ok(completion_lpoverlapped == &overlapped, "completion called with wrong overlapped pointer\n");
1814
    ok(!memcmp(test_string, read_buf, strlen(test_string)), "ReadFileEx read wrong bytes\n");
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839

    /* Make writes until the pipe is full and the write fails */
    memset(write_buf, 0xaa, sizeof(write_buf));
    for (i=0; i<256; i++)
    {
        completion_called = 0;
        ResetEvent(event);
        ret = WriteFileEx(server, write_buf, sizeof(write_buf), &overlapped, completion_routine);
        err = GetLastError();

        ok(completion_called == 0, "completion routine called during WriteFileEx\n");

        wait = WaitForSingleObjectEx(event, 0, TRUE);

        if (wait == WAIT_TIMEOUT)
            /* write couldn't complete immediately, presumably the pipe is full */
            break;

        ok(wait == WAIT_IO_COMPLETION || wait == WAIT_OBJECT_0, "WaitForSingleObject returned %x\n", wait);

        ok(ret == TRUE, "WriteFileEx failed, err=%i\n", err);
        ok(completion_errorcode == 0, "completion called with error %x\n", completion_errorcode);
        ok(completion_lpoverlapped == &overlapped, "completion called with wrong overlapped pointer\n");
    }

1840
    ok(ret == TRUE, "WriteFileEx failed, err=%i\n", err);
1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
    ok(completion_called == 0, "completion routine called but wait timed out\n");
    ok(completion_errorcode == 0, "completion called with error %x\n", completion_errorcode);
    ok(completion_lpoverlapped == &overlapped, "completion called with wrong overlapped pointer\n");

    /* free up some space in the pipe */
    ret = ReadFile(client, read_buf, sizeof(read_buf), &num_bytes, NULL);
    ok(ret == TRUE, "ReadFile failed\n");

    ok(completion_called == 0, "completion routine called during ReadFile\n");

    wait = WaitForSingleObjectEx(event, 0, TRUE);
    ok(wait == WAIT_IO_COMPLETION || wait == WAIT_OBJECT_0, "WaitForSingleObject returned %x\n", wait);

    ok(completion_called == 1, "completion routine not called\n");
    ok(completion_errorcode == 0, "completion called with error %x\n", completion_errorcode);
    ok(completion_lpoverlapped == &overlapped, "completion called with wrong overlapped pointer\n");

    CloseHandle(client);
    CloseHandle(server);
    CloseHandle(event);
}

1863 1864
START_TEST(pipe)
{
1865 1866 1867 1868
    HMODULE hmod;

    hmod = GetModuleHandle("advapi32.dll");
    pDuplicateTokenEx = (void *) GetProcAddress(hmod, "DuplicateTokenEx");
1869 1870
    hmod = GetModuleHandle("kernel32.dll");
    pQueueUserAPC = (void *) GetProcAddress(hmod, "QueueUserAPC");
1871

1872 1873
    if (test_DisconnectNamedPipe())
        return;
Dan Kegel's avatar
Dan Kegel committed
1874 1875
    test_CreateNamedPipe_instances_must_match();
    test_NamedPipe_2();
1876 1877
    test_CreateNamedPipe(PIPE_TYPE_BYTE);
    test_CreateNamedPipe(PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE);
Uwe Bonnes's avatar
Uwe Bonnes committed
1878
    test_CreatePipe();
1879
    test_impersonation();
1880
    test_overlapped();
1881
    test_NamedPipeHandleState();
1882
    test_readfileex_pending();
1883
}