file.c 82.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * Copyright 1999, 2000 Juergen Schmied
 *
 * 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
16
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17 18
 */

19 20 21
#include "config.h"
#include "wine/port.h"

Juergen Schmied's avatar
Juergen Schmied committed
22 23
#include <stdlib.h>
#include <string.h>
24 25
#include <stdio.h>
#include <errno.h>
26
#include <assert.h>
27 28 29
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
30 31 32
#ifdef HAVE_SYS_ERRNO_H
#include <sys/errno.h>
#endif
33 34 35
#ifdef HAVE_LINUX_MAJOR_H
# include <linux/major.h>
#endif
36 37 38 39 40 41
#ifdef HAVE_SYS_STATVFS_H
# include <sys/statvfs.h>
#endif
#ifdef HAVE_SYS_PARAM_H
# include <sys/param.h>
#endif
42 43 44
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
45 46 47
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
48 49 50 51 52 53 54 55 56
#ifdef HAVE_POLL_H
#include <poll.h>
#endif
#ifdef HAVE_SYS_POLL_H
#include <sys/poll.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
57 58 59
#ifdef HAVE_UTIME_H
# include <utime.h>
#endif
60
#ifdef HAVE_SYS_VFS_H
61
# include <sys/vfs.h>
62 63 64 65 66 67
#endif
#ifdef HAVE_SYS_MOUNT_H
# include <sys/mount.h>
#endif
#ifdef HAVE_SYS_STATFS_H
# include <sys/statfs.h>
68
#endif
69 70 71

#define NONAMELESSUNION
#define NONAMELESSSTRUCT
72 73
#include "ntstatus.h"
#define WIN32_NO_STATUS
74
#include "wine/unicode.h"
75
#include "wine/debug.h"
76
#include "wine/server.h"
77
#include "ntdll_misc.h"
Juergen Schmied's avatar
Juergen Schmied committed
78

79
#include "winternl.h"
80
#include "winioctl.h"
81
#include "ddk/ntddser.h"
Juergen Schmied's avatar
Juergen Schmied committed
82

83
WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
84

85 86 87 88 89
mode_t FILE_umask = 0;

#define SECSPERDAY         86400
#define SECS_1601_TO_1970  ((369 * 365 + 89) * (ULONGLONG)SECSPERDAY)

Juergen Schmied's avatar
Juergen Schmied committed
90
/**************************************************************************
91
 *                 NtOpenFile				[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
92
 *                 ZwOpenFile				[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
93 94 95 96
 *
 * Open a file.
 *
 * PARAMS
97 98
 *  handle    [O] Variable that receives the file handle on return
 *  access    [I] Access desired by the caller to the file
99
 *  attr      [I] Structure describing the file to be opened
100 101 102
 *  io        [O] Receives details about the result of the operation
 *  sharing   [I] Type of shared access the caller requires
 *  options   [I] Options for the file open
Jon Griffiths's avatar
Jon Griffiths committed
103 104 105 106
 *
 * RETURNS
 *  Success: 0. FileHandle and IoStatusBlock are updated.
 *  Failure: An NTSTATUS error code describing the error.
Juergen Schmied's avatar
Juergen Schmied committed
107
 */
108 109 110
NTSTATUS WINAPI NtOpenFile( PHANDLE handle, ACCESS_MASK access,
                            POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK io,
                            ULONG sharing, ULONG options )
Juergen Schmied's avatar
Juergen Schmied committed
111
{
112 113
    return NtCreateFile( handle, access, attr, io, NULL, 0,
                         sharing, FILE_OPEN, options, NULL, 0 );
Juergen Schmied's avatar
Juergen Schmied committed
114 115 116
}

/**************************************************************************
117
 *		NtCreateFile				[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
118
 *		ZwCreateFile				[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
119 120 121 122 123
 *
 * Either create a new file or directory, or open an existing file, device,
 * directory or volume.
 *
 * PARAMS
124 125 126 127 128 129 130 131 132
 *	handle       [O] Points to a variable which receives the file handle on return
 *	access       [I] Desired access to the file
 *	attr         [I] Structure describing the file
 *	io           [O] Receives information about the operation on return
 *	alloc_size   [I] Initial size of the file in bytes
 *	attributes   [I] Attributes to create the file with
 *	sharing      [I] Type of shared access the caller would like to the file
 *	disposition  [I] Specifies what to do, depending on whether the file already exists
 *	options      [I] Options for creating a new file
133
 *	ea_buffer    [I] Pointer to an extended attributes buffer
134
 *	ea_length    [I] Length of ea_buffer
Jon Griffiths's avatar
Jon Griffiths committed
135 136
 *
 * RETURNS
137
 *  Success: 0. handle and io are updated.
Jon Griffiths's avatar
Jon Griffiths committed
138
 *  Failure: An NTSTATUS error code describing the error.
Juergen Schmied's avatar
Juergen Schmied committed
139
 */
140 141 142 143
NTSTATUS WINAPI NtCreateFile( PHANDLE handle, ACCESS_MASK access, POBJECT_ATTRIBUTES attr,
                              PIO_STATUS_BLOCK io, PLARGE_INTEGER alloc_size,
                              ULONG attributes, ULONG sharing, ULONG disposition,
                              ULONG options, PVOID ea_buffer, ULONG ea_length )
Juergen Schmied's avatar
Juergen Schmied committed
144
{
145
    ANSI_STRING unix_name;
146
    int created = FALSE;
147

148 149
    TRACE("handle=%p access=%08x name=%s objattr=%08x root=%p sec=%p io=%p alloc_size=%p\n"
          "attr=%08x sharing=%08x disp=%d options=%08x ea=%p.0x%08x\n",
150 151 152 153
          handle, access, debugstr_us(attr->ObjectName), attr->Attributes,
          attr->RootDirectory, attr->SecurityDescriptor, io, alloc_size,
          attributes, sharing, disposition, options, ea_buffer, ea_length );

154 155
    if (!attr || !attr->ObjectName) return STATUS_INVALID_PARAMETER;

156 157
    if (alloc_size) FIXME( "alloc_size not supported\n" );

158 159 160 161 162 163
    if (attr->RootDirectory)
    {
        FIXME( "RootDirectory %p not supported\n", attr->RootDirectory );
        return STATUS_OBJECT_NAME_NOT_FOUND;
    }

164
    io->u.Status = wine_nt_to_unix_file_name( attr->ObjectName, &unix_name, disposition,
165
                                              !(attr->Attributes & OBJ_CASE_INSENSITIVE) );
166

167 168 169 170 171 172 173 174
    if (io->u.Status == STATUS_BAD_DEVICE_TYPE)
    {
        SERVER_START_REQ( open_file_object )
        {
            req->access     = access;
            req->attributes = attr->Attributes;
            req->rootdir    = attr->RootDirectory;
            req->sharing    = sharing;
175
            req->options    = options;
176 177 178 179 180
            wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
            io->u.Status = wine_server_call( req );
            *handle = reply->handle;
        }
        SERVER_END_REQ;
181
        if (io->u.Status == STATUS_SUCCESS) io->Information = FILE_OPENED;
182 183 184
        return io->u.Status;
    }

185 186
    if (io->u.Status == STATUS_NO_SUCH_FILE &&
        disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
187 188 189 190 191 192
    {
        created = TRUE;
        io->u.Status = STATUS_SUCCESS;
    }

    if (io->u.Status == STATUS_SUCCESS)
193
    {
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
        struct security_descriptor *sd = NULL;
        struct object_attributes objattr;

        objattr.rootdir = 0;
        objattr.sd_len = 0;
        objattr.name_len = 0;
        if (attr)
        {
            io->u.Status = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
            if (io->u.Status != STATUS_SUCCESS)
            {
                RtlFreeAnsiString( &unix_name );
                return io->u.Status;
            }
        }

210 211 212
        SERVER_START_REQ( create_file )
        {
            req->access     = access;
213
            req->attributes = attr->Attributes;
214 215 216 217
            req->sharing    = sharing;
            req->create     = disposition;
            req->options    = options;
            req->attrs      = attributes;
218 219
            wine_server_add_data( req, &objattr, sizeof(objattr) );
            if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
220 221 222 223 224
            wine_server_add_data( req, unix_name.Buffer, unix_name.Length );
            io->u.Status = wine_server_call( req );
            *handle = reply->handle;
        }
        SERVER_END_REQ;
225
        NTDLL_free_struct_sd( sd );
226 227
        RtlFreeAnsiString( &unix_name );
    }
228
    else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), io->u.Status );
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251

    if (io->u.Status == STATUS_SUCCESS)
    {
        if (created) io->Information = FILE_CREATED;
        else switch(disposition)
        {
        case FILE_SUPERSEDE:
            io->Information = FILE_SUPERSEDED;
            break;
        case FILE_CREATE:
            io->Information = FILE_CREATED;
            break;
        case FILE_OPEN:
        case FILE_OPEN_IF:
            io->Information = FILE_OPENED;
            break;
        case FILE_OVERWRITE:
        case FILE_OVERWRITE_IF:
            io->Information = FILE_OVERWRITTEN;
            break;
        }
    }

252
    return io->u.Status;
Juergen Schmied's avatar
Juergen Schmied committed
253 254
}

255 256 257 258
/***********************************************************************
 *                  Asynchronous file I/O                              *
 */

259
struct async_fileio
260
{
261
    HANDLE              handle;
262 263 264 265 266 267 268
    PIO_APC_ROUTINE     apc;
    void               *apc_arg;
};

typedef struct
{
    struct async_fileio io;
269
    char*               buffer;
270
    unsigned int        already;
271 272
    unsigned int        count;
    BOOL                avail_mode;
273
} async_fileio_read;
274

275
typedef struct
276
{
277
    struct async_fileio io;
278 279 280 281
    const char         *buffer;
    unsigned int        already;
    unsigned int        count;
} async_fileio_write;
282

283

284 285 286 287 288 289 290 291
/* callback for file I/O user APC */
static void WINAPI fileio_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
{
    struct async_fileio *async = arg;
    if (async->apc) async->apc( async->apc_arg, io, reserved );
    RtlFreeHeap( GetProcessHeap(), 0, async );
}

292 293 294 295 296 297
/***********************************************************************
 *           FILE_GetNtStatus(void)
 *
 * Retrieve the Nt Status code from errno.
 * Try to be consistent with FILE_SetDosError().
 */
298
NTSTATUS FILE_GetNtStatus(void)
299 300 301 302 303 304
{
    int err = errno;

    TRACE( "errno = %d\n", errno );
    switch (err)
    {
305 306
    case EAGAIN:    return STATUS_SHARING_VIOLATION;
    case EBADF:     return STATUS_INVALID_HANDLE;
307
    case EBUSY:     return STATUS_DEVICE_BUSY;
308
    case ENOSPC:    return STATUS_DISK_FULL;
309 310
    case EPERM:
    case EROFS:
311 312 313 314
    case EACCES:    return STATUS_ACCESS_DENIED;
    case ENOTDIR:   return STATUS_OBJECT_PATH_NOT_FOUND;
    case ENOENT:    return STATUS_OBJECT_NAME_NOT_FOUND;
    case EISDIR:    return STATUS_FILE_IS_A_DIRECTORY;
315
    case EMFILE:
316 317 318
    case ENFILE:    return STATUS_TOO_MANY_OPENED_FILES;
    case EINVAL:    return STATUS_INVALID_PARAMETER;
    case ENOTEMPTY: return STATUS_DIRECTORY_NOT_EMPTY;
319
    case EPIPE:     return STATUS_PIPE_DISCONNECTED;
320
    case EIO:       return STATUS_DEVICE_NOT_READY;
321 322 323
#ifdef ENOMEDIUM
    case ENOMEDIUM: return STATUS_NO_MEDIA_IN_DEVICE;
#endif
324
    case ENXIO:     return STATUS_NO_SUCH_DEVICE;
325 326
    case ENOTTY:
    case EOPNOTSUPP:return STATUS_NOT_SUPPORTED;
327
    case ECONNRESET:return STATUS_PIPE_DISCONNECTED;
328
    case EFAULT:    return STATUS_ACCESS_VIOLATION;
329
    case ESPIPE:    return STATUS_ILLEGAL_FUNCTION;
330 331
    case ENOEXEC:   /* ?? */
    case EEXIST:    /* ?? */
332 333
    default:
        FIXME( "Converting errno %d to STATUS_UNSUCCESSFUL\n", err );
334
        return STATUS_UNSUCCESSFUL;
335 336 337 338 339 340
    }
}

/***********************************************************************
 *             FILE_AsyncReadService      (INTERNAL)
 */
341
static NTSTATUS FILE_AsyncReadService(void *user, PIO_STATUS_BLOCK iosb, NTSTATUS status, ULONG_PTR *total)
342
{
343
    async_fileio_read *fileio = user;
344
    int fd, needs_close, result;
345

346
    switch (status)
347
    {
348 349
    case STATUS_ALERTED: /* got some new data */
        /* check to see if the data is ready (non-blocking) */
350
        if ((status = server_get_unix_fd( fileio->io.handle, FILE_READ_DATA, &fd,
351
                                          &needs_close, NULL, NULL )))
352
            break;
353

354
        result = read(fd, &fileio->buffer[fileio->already], fileio->count - fileio->already);
355
        if (needs_close) close( fd );
356

357 358 359
        if (result < 0)
        {
            if (errno == EAGAIN || errno == EINTR)
360
                status = STATUS_PENDING;
361
            else /* check to see if the transfer is complete */
362
                status = FILE_GetNtStatus();
363 364 365
        }
        else if (result == 0)
        {
366
            status = fileio->already ? STATUS_SUCCESS : STATUS_PIPE_BROKEN;
367 368 369
        }
        else
        {
370 371
            fileio->already += result;
            if (fileio->already >= fileio->count || fileio->avail_mode)
372
                status = STATUS_SUCCESS;
373 374 375 376 377 378
            else
            {
                /* if we only have to read the available data, and none is available,
                 * simply cancel the request. If data was available, it has been read
                 * while in by previous call (NtDelayExecution)
                 */
379
                status = (fileio->avail_mode) ? STATUS_SUCCESS : STATUS_PENDING;
380 381 382
            }
        }
        break;
383 384 385 386

    case STATUS_TIMEOUT:
    case STATUS_IO_TIMEOUT:
        if (fileio->already) status = STATUS_SUCCESS;
387
        break;
388
    }
389 390 391
    if (status != STATUS_PENDING)
    {
        iosb->u.Status = status;
392
        iosb->Information = *total = fileio->already;
393
    }
394
    return status;
395 396
}

397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
struct io_timeouts
{
    int interval;   /* max interval between two bytes */
    int total;      /* total timeout for the whole operation */
    int end_time;   /* absolute time of end of operation */
};

/* retrieve the I/O timeouts to use for a given handle */
static NTSTATUS get_io_timeouts( HANDLE handle, enum server_fd_type type, ULONG count, BOOL is_read,
                                 struct io_timeouts *timeouts )
{
    NTSTATUS status = STATUS_SUCCESS;

    timeouts->interval = timeouts->total = -1;

    switch(type)
    {
    case FD_TYPE_SERIAL:
        {
            /* GetCommTimeouts */
            SERIAL_TIMEOUTS st;
            IO_STATUS_BLOCK io;

            status = NtDeviceIoControlFile( handle, NULL, NULL, NULL, &io,
                                            IOCTL_SERIAL_GET_TIMEOUTS, NULL, 0, &st, sizeof(st) );
            if (status) break;

            if (is_read)
            {
                if (st.ReadIntervalTimeout)
                    timeouts->interval = st.ReadIntervalTimeout;

                if (st.ReadTotalTimeoutMultiplier || st.ReadTotalTimeoutConstant)
                {
                    timeouts->total = st.ReadTotalTimeoutConstant;
                    if (st.ReadTotalTimeoutMultiplier != MAXDWORD)
                        timeouts->total += count * st.ReadTotalTimeoutMultiplier;
                }
                else if (st.ReadIntervalTimeout == MAXDWORD)
                    timeouts->interval = 0;
            }
            else  /* write */
            {
                if (st.WriteTotalTimeoutMultiplier || st.WriteTotalTimeoutConstant)
                {
                    timeouts->total = st.WriteTotalTimeoutConstant;
                    if (st.WriteTotalTimeoutMultiplier != MAXDWORD)
                        timeouts->total += count * st.WriteTotalTimeoutMultiplier;
                }
            }
        }
        break;
    case FD_TYPE_MAILSLOT:
        if (is_read)
        {
            timeouts->interval = 0;  /* return as soon as we got something */
            SERVER_START_REQ( set_mailslot_info )
            {
                req->handle = handle;
                req->flags = 0;
457 458 459
                if (!(status = wine_server_call( req )) &&
                    reply->read_timeout != TIMEOUT_INFINITE)
                    timeouts->total = reply->read_timeout / -10000;
460 461 462 463 464 465
            }
            SERVER_END_REQ;
        }
        break;
    case FD_TYPE_SOCKET:
    case FD_TYPE_PIPE:
466
    case FD_TYPE_CHAR:
467 468 469 470 471 472 473 474 475 476 477
        if (is_read) timeouts->interval = 0;  /* return as soon as we got something */
        break;
    default:
        break;
    }
    if (timeouts->total != -1) timeouts->end_time = NtGetTickCount() + timeouts->total;
    return STATUS_SUCCESS;
}


/* retrieve the timeout for the next wait, in milliseconds */
478
static inline int get_next_io_timeout( const struct io_timeouts *timeouts, ULONG already )
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
{
    int ret = -1;

    if (timeouts->total != -1)
    {
        ret = timeouts->end_time - NtGetTickCount();
        if (ret < 0) ret = 0;
    }
    if (already && timeouts->interval != -1)
    {
        if (ret == -1 || ret > timeouts->interval) ret = timeouts->interval;
    }
    return ret;
}

494

495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
/* retrieve the avail_mode flag for async reads */
static NTSTATUS get_io_avail_mode( HANDLE handle, enum server_fd_type type, BOOL *avail_mode )
{
    NTSTATUS status = STATUS_SUCCESS;

    switch(type)
    {
    case FD_TYPE_SERIAL:
        {
            /* GetCommTimeouts */
            SERIAL_TIMEOUTS st;
            IO_STATUS_BLOCK io;

            status = NtDeviceIoControlFile( handle, NULL, NULL, NULL, &io,
                                            IOCTL_SERIAL_GET_TIMEOUTS, NULL, 0, &st, sizeof(st) );
            if (status) break;
            *avail_mode = (!st.ReadTotalTimeoutMultiplier &&
                           !st.ReadTotalTimeoutConstant &&
                           st.ReadIntervalTimeout == MAXDWORD);
        }
        break;
    case FD_TYPE_MAILSLOT:
    case FD_TYPE_SOCKET:
    case FD_TYPE_PIPE:
519
    case FD_TYPE_CHAR:
520 521 522 523 524 525 526 527 528 529
        *avail_mode = TRUE;
        break;
    default:
        *avail_mode = FALSE;
        break;
    }
    return status;
}


Juergen Schmied's avatar
Juergen Schmied committed
530
/******************************************************************************
531
 *  NtReadFile					[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
532
 *  ZwReadFile					[NTDLL.@]
Juergen Schmied's avatar
Juergen Schmied committed
533
 *
Jon Griffiths's avatar
Jon Griffiths committed
534
 * Read from an open file handle.
535
 *
Jon Griffiths's avatar
Jon Griffiths committed
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
 * PARAMS
 *  FileHandle    [I] Handle returned from ZwOpenFile() or ZwCreateFile()
 *  Event         [I] Event to signal upon completion (or NULL)
 *  ApcRoutine    [I] Callback to call upon completion (or NULL)
 *  ApcContext    [I] Context for ApcRoutine (or NULL)
 *  IoStatusBlock [O] Receives information about the operation on return
 *  Buffer        [O] Destination for the data read
 *  Length        [I] Size of Buffer
 *  ByteOffset    [O] Destination for the new file pointer position (or NULL)
 *  Key           [O] Function unknown (may be NULL)
 *
 * RETURNS
 *  Success: 0. IoStatusBlock is updated, and the Information member contains
 *           The number of bytes read.
 *  Failure: An NTSTATUS error code describing the error.
Juergen Schmied's avatar
Juergen Schmied committed
551
 */
Jon Griffiths's avatar
Jon Griffiths committed
552 553
NTSTATUS WINAPI NtReadFile(HANDLE hFile, HANDLE hEvent,
                           PIO_APC_ROUTINE apc, void* apc_user,
554 555
                           PIO_STATUS_BLOCK io_status, void* buffer, ULONG length,
                           PLARGE_INTEGER offset, PULONG key)
556
{
557 558
    int result, unix_handle, needs_close, timeout_init_done = 0;
    unsigned int options;
559
    struct io_timeouts timeouts;
560
    NTSTATUS status;
561
    ULONG total = 0;
562
    enum server_fd_type type;
563
    ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
564

565
    TRACE("(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
566 567
          hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);

568 569
    if (!io_status) return STATUS_ACCESS_VIOLATION;

570
    status = server_get_unix_fd( hFile, FILE_READ_DATA, &unix_handle,
571
                                 &needs_close, &type, &options );
572
    if (status) return status;
573

574
    if (type == FD_TYPE_FILE && offset && offset->QuadPart != (LONGLONG)-2 /* FILE_USE_FILE_POINTER_POSITION */ )
575 576
    {
        /* async I/O doesn't make sense on regular files */
577
        while ((result = pread( unix_handle, buffer, length, offset->QuadPart )) == -1)
578
        {
579
            if (errno != EINTR)
580
            {
581
                status = FILE_GetNtStatus();
582 583
                goto done;
            }
584
        }
585 586
        if (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT))
            /* update file pointer position */
587 588 589 590 591 592 593 594 595 596 597 598 599
            lseek( unix_handle, offset->QuadPart + result, SEEK_SET );

        total = result;
        status = total ? STATUS_SUCCESS : STATUS_END_OF_FILE;
        goto done;
    }

    for (;;)
    {
        if ((result = read( unix_handle, (char *)buffer + total, length - total )) >= 0)
        {
            total += result;
            if (!result || total == length)
600
            {
601 602 603
                if (total)
                    status = STATUS_SUCCESS;
                else
604
                    status = (type == FD_TYPE_FILE || type == FD_TYPE_CHAR) ? STATUS_END_OF_FILE : STATUS_PIPE_BROKEN;
605 606 607 608 609
                goto done;
            }
        }
        else
        {
610 611
            if (errno == EINTR) continue;
            if (errno != EAGAIN)
612
            {
613
                status = FILE_GetNtStatus();
614 615 616
                goto done;
            }
        }
617

618
        if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
619
        {
620
            async_fileio_read *fileio;
621
            BOOL avail_mode;
Jon Griffiths's avatar
Jon Griffiths committed
622

623
            if ((status = get_io_avail_mode( hFile, type, &avail_mode )))
624
                goto err;
625
            if (total && avail_mode)
626 627 628 629
            {
                status = STATUS_SUCCESS;
                goto done;
            }
630

631
            if (!(fileio = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(*fileio))))
632 633
            {
                status = STATUS_NO_MEMORY;
634
                goto err;
635
            }
636 637 638
            fileio->io.handle  = hFile;
            fileio->io.apc     = apc;
            fileio->io.apc_arg = apc_user;
639 640 641
            fileio->already = total;
            fileio->count = length;
            fileio->buffer = buffer;
642
            fileio->avail_mode = avail_mode;
643 644 645 646 647 648 649 650 651

            SERVER_START_REQ( register_async )
            {
                req->handle = hFile;
                req->type   = ASYNC_TYPE_READ;
                req->count  = length;
                req->async.callback = FILE_AsyncReadService;
                req->async.iosb     = io_status;
                req->async.arg      = fileio;
652
                req->async.apc      = fileio_apc;
653
                req->async.event    = hEvent;
654
                req->async.cvalue   = cvalue;
655 656 657 658 659
                status = wine_server_call( req );
            }
            SERVER_END_REQ;

            if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
660
            goto err;
661
        }
662
        else  /* synchronous read, wait for the fd to become ready */
663
        {
664 665 666 667 668 669 670
            struct pollfd pfd;
            int ret, timeout;

            if (!timeout_init_done)
            {
                timeout_init_done = 1;
                if ((status = get_io_timeouts( hFile, type, length, TRUE, &timeouts )))
671
                    goto err;
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
                if (hEvent) NtResetEvent( hEvent, NULL );
            }
            timeout = get_next_io_timeout( &timeouts, total );

            pfd.fd = unix_handle;
            pfd.events = POLLIN;

            if (!timeout || !(ret = poll( &pfd, 1, timeout )))
            {
                if (total)  /* return with what we got so far */
                    status = STATUS_SUCCESS;
                else
                    status = (type == FD_TYPE_MAILSLOT) ? STATUS_IO_TIMEOUT : STATUS_TIMEOUT;
                goto done;
            }
            if (ret == -1 && errno != EINTR)
            {
                status = FILE_GetNtStatus();
                goto done;
            }
            /* will now restart the read */
693
        }
694
    }
695

696
done:
697 698 699
    if (cvalue) NTDLL_AddCompletion( hFile, cvalue, status, total );

err:
700 701
    if (needs_close) close( unix_handle );
    if (status == STATUS_SUCCESS)
702
    {
703 704 705 706 707 708
        io_status->u.Status = status;
        io_status->Information = total;
        TRACE("= SUCCESS (%u)\n", total);
        if (hEvent) NtSetEvent( hEvent, NULL );
        if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
                                   (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
709
    }
710
    else
711
    {
712 713
        TRACE("= 0x%08x\n", status);
        if (status != STATUS_PENDING && hEvent) NtResetEvent( hEvent, NULL );
714
    }
715
    return status;
716
}
717

718 719 720
/***********************************************************************
 *             FILE_AsyncWriteService      (INTERNAL)
 */
721
static NTSTATUS FILE_AsyncWriteService(void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status, ULONG_PTR *total)
722
{
723
    async_fileio_write *fileio = user;
724
    int result, fd, needs_close;
725
    enum server_fd_type type;
726

727
    switch (status)
728
    {
729 730
    case STATUS_ALERTED:
        /* write some data (non-blocking) */
731
        if ((status = server_get_unix_fd( fileio->io.handle, FILE_WRITE_DATA, &fd,
732
                                          &needs_close, &type, NULL )))
733
            break;
734

735 736 737 738 739
        if (!fileio->count && (type == FD_TYPE_MAILSLOT || type == FD_TYPE_PIPE || type == FD_TYPE_SOCKET))
            result = send( fd, fileio->buffer, 0, 0 );
        else
            result = write( fd, &fileio->buffer[fileio->already], fileio->count - fileio->already );

740
        if (needs_close) close( fd );
741

742 743
        if (result < 0)
        {
744 745
            if (errno == EAGAIN || errno == EINTR) status = STATUS_PENDING;
            else status = FILE_GetNtStatus();
746 747 748
        }
        else
        {
749 750
            fileio->already += result;
            status = (fileio->already < fileio->count) ? STATUS_PENDING : STATUS_SUCCESS;
751 752
        }
        break;
753 754 755 756

    case STATUS_TIMEOUT:
    case STATUS_IO_TIMEOUT:
        if (fileio->already) status = STATUS_SUCCESS;
757
        break;
758
    }
759 760 761
    if (status != STATUS_PENDING)
    {
        iosb->u.Status = status;
762
        iosb->Information = *total = fileio->already;
763
    }
764
    return status;
765 766 767 768 769 770
}

/******************************************************************************
 *  NtWriteFile					[NTDLL.@]
 *  ZwWriteFile					[NTDLL.@]
 *
Jon Griffiths's avatar
Jon Griffiths committed
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
 * Write to an open file handle.
 *
 * PARAMS
 *  FileHandle    [I] Handle returned from ZwOpenFile() or ZwCreateFile()
 *  Event         [I] Event to signal upon completion (or NULL)
 *  ApcRoutine    [I] Callback to call upon completion (or NULL)
 *  ApcContext    [I] Context for ApcRoutine (or NULL)
 *  IoStatusBlock [O] Receives information about the operation on return
 *  Buffer        [I] Source for the data to write
 *  Length        [I] Size of Buffer
 *  ByteOffset    [O] Destination for the new file pointer position (or NULL)
 *  Key           [O] Function unknown (may be NULL)
 *
 * RETURNS
 *  Success: 0. IoStatusBlock is updated, and the Information member contains
 *           The number of bytes written.
 *  Failure: An NTSTATUS error code describing the error.
788
 */
789 790 791 792 793
NTSTATUS WINAPI NtWriteFile(HANDLE hFile, HANDLE hEvent,
                            PIO_APC_ROUTINE apc, void* apc_user,
                            PIO_STATUS_BLOCK io_status, 
                            const void* buffer, ULONG length,
                            PLARGE_INTEGER offset, PULONG key)
Juergen Schmied's avatar
Juergen Schmied committed
794
{
795 796
    int result, unix_handle, needs_close, timeout_init_done = 0;
    unsigned int options;
797
    struct io_timeouts timeouts;
798
    NTSTATUS status;
799
    ULONG total = 0;
800
    enum server_fd_type type;
801
    ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
802

803
    TRACE("(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p)!\n",
804 805
          hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);

806 807
    if (!io_status) return STATUS_ACCESS_VIOLATION;

808
    status = server_get_unix_fd( hFile, FILE_WRITE_DATA, &unix_handle,
809
                                 &needs_close, &type, &options );
810
    if (status) return status;
811

812
    if (type == FD_TYPE_FILE && offset && offset->QuadPart != (LONGLONG)-2 /* FILE_USE_FILE_POINTER_POSITION */ )
813
    {
814 815
        /* async I/O doesn't make sense on regular files */
        while ((result = pwrite( unix_handle, buffer, length, offset->QuadPart )) == -1)
816
        {
817
            if (errno != EINTR)
818
            {
819 820
                if (errno == EFAULT) status = STATUS_INVALID_USER_BUFFER;
                else status = FILE_GetNtStatus();
821 822
                goto done;
            }
823 824
        }

825 826
        if (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT))
            /* update file pointer position */
827 828 829 830 831 832 833 834 835
            lseek( unix_handle, offset->QuadPart + result, SEEK_SET );

        total = result;
        status = STATUS_SUCCESS;
        goto done;
    }

    for (;;)
    {
836 837 838 839 840 841 842
        /* zero-length writes on sockets may not work with plain write(2) */
        if (!length && (type == FD_TYPE_MAILSLOT || type == FD_TYPE_PIPE || type == FD_TYPE_SOCKET))
            result = send( unix_handle, buffer, 0, 0 );
        else
            result = write( unix_handle, (const char *)buffer + total, length - total );

        if (result >= 0)
843 844 845
        {
            total += result;
            if (total == length)
846
            {
847
                status = STATUS_SUCCESS;
848 849 850 851 852
                goto done;
            }
        }
        else
        {
853 854
            if (errno == EINTR) continue;
            if (errno != EAGAIN)
855
            {
856 857 858 859 860 861
                if (errno == EFAULT)
                {
                    status = STATUS_INVALID_USER_BUFFER;
                    goto err;
                }
                status = FILE_GetNtStatus();
862 863 864
                goto done;
            }
        }
865

866
        if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
867
        {
868
            async_fileio_write *fileio;
869

870
            if (!(fileio = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(*fileio))))
871 872
            {
                status = STATUS_NO_MEMORY;
873
                goto err;
874
            }
875 876 877
            fileio->io.handle  = hFile;
            fileio->io.apc     = apc;
            fileio->io.apc_arg = apc_user;
878 879
            fileio->already = total;
            fileio->count = length;
880 881 882 883 884 885 886 887 888 889
            fileio->buffer = buffer;

            SERVER_START_REQ( register_async )
            {
                req->handle = hFile;
                req->type   = ASYNC_TYPE_WRITE;
                req->count  = length;
                req->async.callback = FILE_AsyncWriteService;
                req->async.iosb     = io_status;
                req->async.arg      = fileio;
890
                req->async.apc      = fileio_apc;
891
                req->async.event    = hEvent;
892
                req->async.cvalue   = cvalue;
893 894 895 896 897
                status = wine_server_call( req );
            }
            SERVER_END_REQ;

            if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
898
            goto err;
899
        }
900
        else  /* synchronous write, wait for the fd to become ready */
901
        {
902 903 904 905 906 907 908
            struct pollfd pfd;
            int ret, timeout;

            if (!timeout_init_done)
            {
                timeout_init_done = 1;
                if ((status = get_io_timeouts( hFile, type, length, FALSE, &timeouts )))
909
                    goto err;
910 911 912 913 914
                if (hEvent) NtResetEvent( hEvent, NULL );
            }
            timeout = get_next_io_timeout( &timeouts, total );

            pfd.fd = unix_handle;
915
            pfd.events = POLLOUT;
916 917 918 919 920 921 922 923 924 925 926 927 928

            if (!timeout || !(ret = poll( &pfd, 1, timeout )))
            {
                /* return with what we got so far */
                status = total ? STATUS_SUCCESS : STATUS_TIMEOUT;
                goto done;
            }
            if (ret == -1 && errno != EINTR)
            {
                status = FILE_GetNtStatus();
                goto done;
            }
            /* will now restart the write */
929
        }
930 931
    }

932
done:
933 934 935
    if (cvalue) NTDLL_AddCompletion( hFile, cvalue, status, total );

err:
936
    if (needs_close) close( unix_handle );
937 938 939 940 941 942 943 944 945 946 947 948 949 950
    if (status == STATUS_SUCCESS)
    {
        io_status->u.Status = status;
        io_status->Information = total;
        TRACE("= SUCCESS (%u)\n", total);
        if (hEvent) NtSetEvent( hEvent, NULL );
        if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
                                   (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
    }
    else
    {
        TRACE("= 0x%08x\n", status);
        if (status != STATUS_PENDING && hEvent) NtResetEvent( hEvent, NULL );
    }
951
    return status;
Juergen Schmied's avatar
Juergen Schmied committed
952 953
}

954

955 956
struct async_ioctl
{
957 958 959 960 961
    HANDLE          handle;   /* handle to the device */
    void           *buffer;   /* buffer for output */
    ULONG           size;     /* size of buffer */
    PIO_APC_ROUTINE apc;      /* user apc params */
    void           *apc_arg;
962 963
};

964 965 966
/* callback for ioctl async I/O completion */
static NTSTATUS ioctl_completion( void *arg, IO_STATUS_BLOCK *io, NTSTATUS status )
{
967 968 969 970 971 972 973 974 975 976 977 978 979 980
    struct async_ioctl *async = arg;

    if (status == STATUS_ALERTED)
    {
        SERVER_START_REQ( get_ioctl_result )
        {
            req->handle   = async->handle;
            req->user_arg = async;
            wine_server_set_reply( req, async->buffer, async->size );
            if (!(status = wine_server_call( req )))
                io->Information = wine_server_reply_size( reply );
        }
        SERVER_END_REQ;
    }
981
    if (status != STATUS_PENDING) io->u.Status = status;
982 983 984
    return status;
}

985 986 987 988 989 990 991 992
/* callback for ioctl user APC */
static void WINAPI ioctl_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
{
    struct async_ioctl *async = arg;
    if (async->apc) async->apc( async->apc_arg, io, reserved );
    RtlFreeHeap( GetProcessHeap(), 0, async );
}

993 994 995 996
/* do a ioctl call through the server */
static NTSTATUS server_ioctl_file( HANDLE handle, HANDLE event,
                                   PIO_APC_ROUTINE apc, PVOID apc_context,
                                   IO_STATUS_BLOCK *io, ULONG code,
997
                                   const void *in_buffer, ULONG in_size,
998 999
                                   PVOID out_buffer, ULONG out_size )
{
1000
    struct async_ioctl *async;
1001
    NTSTATUS status;
1002 1003
    HANDLE wait_handle;
    ULONG options;
1004
    ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;
1005

1006 1007
    if (!(async = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*async) )))
        return STATUS_NO_MEMORY;
1008 1009 1010 1011 1012
    async->handle  = handle;
    async->buffer  = out_buffer;
    async->size    = out_size;
    async->apc     = apc;
    async->apc_arg = apc_context;
1013

1014 1015 1016 1017 1018 1019
    SERVER_START_REQ( ioctl )
    {
        req->handle         = handle;
        req->code           = code;
        req->async.callback = ioctl_completion;
        req->async.iosb     = io;
1020
        req->async.arg      = async;
1021
        req->async.apc      = (apc || event) ? ioctl_apc : NULL;
1022
        req->async.event    = event;
1023
        req->async.cvalue   = cvalue;
1024 1025 1026 1027
        wine_server_add_data( req, in_buffer, in_size );
        wine_server_set_reply( req, out_buffer, out_size );
        if (!(status = wine_server_call( req )))
            io->Information = wine_server_reply_size( reply );
1028 1029
        wait_handle = reply->wait;
        options     = reply->options;
1030 1031 1032 1033 1034 1035 1036
    }
    SERVER_END_REQ;

    if (status == STATUS_NOT_SUPPORTED)
        FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
              code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);

1037 1038
    if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, async );

1039 1040 1041 1042 1043
    if (wait_handle)
    {
        NtWaitForSingleObject( wait_handle, (options & FILE_SYNCHRONOUS_IO_ALERT), NULL );
        status = io->u.Status;
        NtClose( wait_handle );
1044
        RtlFreeHeap( GetProcessHeap(), 0, async );
1045 1046
    }

1047 1048 1049 1050
    return status;
}


Juergen Schmied's avatar
Juergen Schmied committed
1051
/**************************************************************************
1052
 *		NtDeviceIoControlFile			[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
1053
 *		ZwDeviceIoControlFile			[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
1054 1055 1056 1057
 *
 * Perform an I/O control operation on an open file handle.
 *
 * PARAMS
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
 *  handle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
 *  event          [I] Event to signal upon completion (or NULL)
 *  apc            [I] Callback to call upon completion (or NULL)
 *  apc_context    [I] Context for ApcRoutine (or NULL)
 *  io             [O] Receives information about the operation on return
 *  code           [I] Control code for the operation to perform
 *  in_buffer      [I] Source for any input data required (or NULL)
 *  in_size        [I] Size of InputBuffer
 *  out_buffer     [O] Source for any output data returned (or NULL)
 *  out_size       [I] Size of OutputBuffer
Jon Griffiths's avatar
Jon Griffiths committed
1068 1069 1070 1071
 *
 * RETURNS
 *  Success: 0. IoStatusBlock is updated.
 *  Failure: An NTSTATUS error code describing the error.
Juergen Schmied's avatar
Juergen Schmied committed
1072
 */
1073 1074 1075 1076 1077
NTSTATUS WINAPI NtDeviceIoControlFile(HANDLE handle, HANDLE event,
                                      PIO_APC_ROUTINE apc, PVOID apc_context,
                                      PIO_STATUS_BLOCK io, ULONG code,
                                      PVOID in_buffer, ULONG in_size,
                                      PVOID out_buffer, ULONG out_size)
Juergen Schmied's avatar
Juergen Schmied committed
1078
{
1079
    ULONG device = (code >> 16);
1080
    NTSTATUS status = STATUS_NOT_SUPPORTED;
1081

1082
    TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1083 1084 1085 1086
          handle, event, apc, apc_context, io, code,
          in_buffer, in_size, out_buffer, out_size);

    switch(device)
1087
    {
1088 1089 1090 1091 1092
    case FILE_DEVICE_DISK:
    case FILE_DEVICE_CD_ROM:
    case FILE_DEVICE_DVD:
    case FILE_DEVICE_CONTROLLER:
    case FILE_DEVICE_MASS_STORAGE:
1093 1094
        status = CDROM_DeviceIoControl(handle, event, apc, apc_context, io, code,
                                       in_buffer, in_size, out_buffer, out_size);
1095 1096
        break;
    case FILE_DEVICE_SERIAL_PORT:
1097 1098
        status = COMM_DeviceIoControl(handle, event, apc, apc_context, io, code,
                                      in_buffer, in_size, out_buffer, out_size);
1099
        break;
1100
    case FILE_DEVICE_TAPE:
1101 1102
        status = TAPE_DeviceIoControl(handle, event, apc, apc_context, io, code,
                                      in_buffer, in_size, out_buffer, out_size);
1103
        break;
1104 1105
    }

1106
    if (status == STATUS_NOT_SUPPORTED || status == STATUS_BAD_DEVICE_TYPE)
1107 1108
        status = server_ioctl_file( handle, event, apc, apc_context, io, code,
                                    in_buffer, in_size, out_buffer, out_size );
1109

1110 1111
    if (status != STATUS_PENDING) io->u.Status = status;
    return status;
Juergen Schmied's avatar
Juergen Schmied committed
1112 1113
}

1114 1115 1116 1117 1118 1119 1120 1121

/**************************************************************************
 *              NtFsControlFile                 [NTDLL.@]
 *              ZwFsControlFile                 [NTDLL.@]
 *
 * Perform a file system control operation on an open file handle.
 *
 * PARAMS
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
 *  handle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
 *  event          [I] Event to signal upon completion (or NULL)
 *  apc            [I] Callback to call upon completion (or NULL)
 *  apc_context    [I] Context for ApcRoutine (or NULL)
 *  io             [O] Receives information about the operation on return
 *  code           [I] Control code for the operation to perform
 *  in_buffer      [I] Source for any input data required (or NULL)
 *  in_size        [I] Size of InputBuffer
 *  out_buffer     [O] Source for any output data returned (or NULL)
 *  out_size       [I] Size of OutputBuffer
1132 1133 1134 1135
 *
 * RETURNS
 *  Success: 0. IoStatusBlock is updated.
 *  Failure: An NTSTATUS error code describing the error.
Juergen Schmied's avatar
Juergen Schmied committed
1136
 */
1137 1138 1139
NTSTATUS WINAPI NtFsControlFile(HANDLE handle, HANDLE event, PIO_APC_ROUTINE apc,
                                PVOID apc_context, PIO_STATUS_BLOCK io, ULONG code,
                                PVOID in_buffer, ULONG in_size, PVOID out_buffer, ULONG out_size)
Juergen Schmied's avatar
Juergen Schmied committed
1140
{
1141 1142
    NTSTATUS status;

1143
    TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1144 1145
          handle, event, apc, apc_context, io, code,
          in_buffer, in_size, out_buffer, out_size);
1146

1147
    if (!io) return STATUS_INVALID_PARAMETER;
1148

1149
    switch(code)
1150
    {
1151
    case FSCTL_DISMOUNT_VOLUME:
1152 1153 1154
        status = server_ioctl_file( handle, event, apc, apc_context, io, code,
                                    in_buffer, in_size, out_buffer, out_size );
        if (!status) status = DIR_unmount_device( handle );
1155
        break;
1156

1157 1158 1159
    case FSCTL_PIPE_PEEK:
        {
            FILE_PIPE_PEEK_BUFFER *buffer = out_buffer;
1160
            int avail = 0, fd, needs_close;
1161 1162 1163

            if (out_size < FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data ))
            {
1164
                status = STATUS_INFO_LENGTH_MISMATCH;
1165 1166 1167
                break;
            }

1168
            if ((status = server_get_unix_fd( handle, FILE_READ_DATA, &fd, &needs_close, NULL, NULL )))
1169 1170 1171 1172 1173 1174
                break;

#ifdef FIONREAD
            if (ioctl( fd, FIONREAD, &avail ) != 0)
            {
                TRACE("FIONREAD failed reason: %s\n",strerror(errno));
1175
                if (needs_close) close( fd );
1176
                status = FILE_GetNtStatus();
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
                break;
            }
#endif
            if (!avail)  /* check for closed pipe */
            {
                struct pollfd pollfd;
                int ret;

                pollfd.fd = fd;
                pollfd.events = POLLIN;
                pollfd.revents = 0;
                ret = poll( &pollfd, 1, 0 );
                if (ret == -1 || (ret == 1 && (pollfd.revents & (POLLHUP|POLLERR))))
                {
1191
                    if (needs_close) close( fd );
1192
                    status = STATUS_PIPE_BROKEN;
1193 1194 1195 1196 1197 1198 1199 1200
                    break;
                }
            }
            buffer->NamedPipeState    = 0;  /* FIXME */
            buffer->ReadDataAvailable = avail;
            buffer->NumberOfMessages  = 0;  /* FIXME */
            buffer->MessageLength     = 0;  /* FIXME */
            io->Information = FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data );
1201
            status = STATUS_SUCCESS;
1202 1203 1204 1205 1206 1207 1208 1209 1210
            if (avail)
            {
                ULONG data_size = out_size - FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data );
                if (data_size)
                {
                    int res = recv( fd, buffer->Data, data_size, MSG_PEEK );
                    if (res >= 0) io->Information += res;
                }
            }
1211
            if (needs_close) close( fd );
1212 1213 1214
        }
        break;

1215
    case FSCTL_PIPE_DISCONNECT:
1216 1217 1218
        status = server_ioctl_file( handle, event, apc, apc_context, io, code,
                                    in_buffer, in_size, out_buffer, out_size );
        if (!status)
1219
        {
1220 1221
            int fd = server_remove_fd_from_cache( handle );
            if (fd != -1) close( fd );
1222 1223 1224
        }
        break;

1225
    case FSCTL_PIPE_IMPERSONATE:
1226
        FIXME("FSCTL_PIPE_IMPERSONATE: impersonating self\n");
1227 1228 1229
        status = RtlImpersonateSelf( SecurityImpersonation );
        break;

1230 1231
    case FSCTL_LOCK_VOLUME:
    case FSCTL_UNLOCK_VOLUME:
1232
        FIXME("stub! return success - Unsupported fsctl %x (device=%x access=%x func=%x method=%x)\n",
1233
              code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
1234
        status = STATUS_SUCCESS;
1235 1236
        break;

1237
    case FSCTL_PIPE_LISTEN:
1238
    case FSCTL_PIPE_WAIT:
1239
    default:
1240 1241
        status = server_ioctl_file( handle, event, apc, apc_context, io, code,
                                    in_buffer, in_size, out_buffer, out_size );
1242
        break;
1243
    }
1244 1245 1246

    if (status != STATUS_PENDING) io->u.Status = status;
    return status;
Juergen Schmied's avatar
Juergen Schmied committed
1247 1248 1249
}

/******************************************************************************
1250
 *  NtSetVolumeInformationFile		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
1251
 *  ZwSetVolumeInformationFile		[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
 *
 * Set volume information for an open file handle.
 *
 * PARAMS
 *  FileHandle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
 *  IoStatusBlock      [O] Receives information about the operation on return
 *  FsInformation      [I] Source for volume information
 *  Length             [I] Size of FsInformation
 *  FsInformationClass [I] Type of volume information to set
 *
 * RETURNS
 *  Success: 0. IoStatusBlock is updated.
 *  Failure: An NTSTATUS error code describing the error.
Juergen Schmied's avatar
Juergen Schmied committed
1265 1266 1267
 */
NTSTATUS WINAPI NtSetVolumeInformationFile(
	IN HANDLE FileHandle,
1268 1269 1270
	PIO_STATUS_BLOCK IoStatusBlock,
	PVOID FsInformation,
        ULONG Length,
1271
	FS_INFORMATION_CLASS FsInformationClass)
Juergen Schmied's avatar
Juergen Schmied committed
1272
{
1273
	FIXME("(%p,%p,%p,0x%08x,0x%08x) stub\n",
1274
	FileHandle,IoStatusBlock,FsInformation,Length,FsInformationClass);
Juergen Schmied's avatar
Juergen Schmied committed
1275 1276 1277 1278
	return 0;
}

/******************************************************************************
1279
 *  NtQueryInformationFile		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
1280
 *  ZwQueryInformationFile		[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
1281 1282 1283 1284
 *
 * Get information about an open file handle.
 *
 * PARAMS
1285 1286 1287 1288 1289
 *  hFile    [I] Handle returned from ZwOpenFile() or ZwCreateFile()
 *  io       [O] Receives information about the operation on return
 *  ptr      [O] Destination for file information
 *  len      [I] Size of FileInformation
 *  class    [I] Type of file information to get
Jon Griffiths's avatar
Jon Griffiths committed
1290 1291 1292 1293
 *
 * RETURNS
 *  Success: 0. IoStatusBlock and FileInformation are updated.
 *  Failure: An NTSTATUS error code describing the error.
Juergen Schmied's avatar
Juergen Schmied committed
1294
 */
1295 1296
NTSTATUS WINAPI NtQueryInformationFile( HANDLE hFile, PIO_STATUS_BLOCK io,
                                        PVOID ptr, LONG len, FILE_INFORMATION_CLASS class )
Juergen Schmied's avatar
Juergen Schmied committed
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
    static const size_t info_sizes[] =
    {
        0,
        sizeof(FILE_DIRECTORY_INFORMATION),            /* FileDirectoryInformation */
        sizeof(FILE_FULL_DIRECTORY_INFORMATION),       /* FileFullDirectoryInformation */
        sizeof(FILE_BOTH_DIRECTORY_INFORMATION),       /* FileBothDirectoryInformation */
        sizeof(FILE_BASIC_INFORMATION),                /* FileBasicInformation */
        sizeof(FILE_STANDARD_INFORMATION),             /* FileStandardInformation */
        sizeof(FILE_INTERNAL_INFORMATION),             /* FileInternalInformation */
        sizeof(FILE_EA_INFORMATION),                   /* FileEaInformation */
        sizeof(FILE_ACCESS_INFORMATION),               /* FileAccessInformation */
        sizeof(FILE_NAME_INFORMATION)-sizeof(WCHAR),   /* FileNameInformation */
        sizeof(FILE_RENAME_INFORMATION)-sizeof(WCHAR), /* FileRenameInformation */
        0,                                             /* FileLinkInformation */
        sizeof(FILE_NAMES_INFORMATION)-sizeof(WCHAR),  /* FileNamesInformation */
        sizeof(FILE_DISPOSITION_INFORMATION),          /* FileDispositionInformation */
        sizeof(FILE_POSITION_INFORMATION),             /* FilePositionInformation */
        sizeof(FILE_FULL_EA_INFORMATION),              /* FileFullEaInformation */
        sizeof(FILE_MODE_INFORMATION),                 /* FileModeInformation */
        sizeof(FILE_ALIGNMENT_INFORMATION),            /* FileAlignmentInformation */
        sizeof(FILE_ALL_INFORMATION)-sizeof(WCHAR),    /* FileAllInformation */
        sizeof(FILE_ALLOCATION_INFORMATION),           /* FileAllocationInformation */
        sizeof(FILE_END_OF_FILE_INFORMATION),          /* FileEndOfFileInformation */
        0,                                             /* FileAlternateNameInformation */
        sizeof(FILE_STREAM_INFORMATION)-sizeof(WCHAR), /* FileStreamInformation */
        0,                                             /* FilePipeInformation */
1324
        sizeof(FILE_PIPE_LOCAL_INFORMATION),           /* FilePipeLocalInformation */
1325
        0,                                             /* FilePipeRemoteInformation */
1326
        sizeof(FILE_MAILSLOT_QUERY_INFORMATION),       /* FileMailslotQueryInformation */
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
        0,                                             /* FileMailslotSetInformation */
        0,                                             /* FileCompressionInformation */
        0,                                             /* FileObjectIdInformation */
        0,                                             /* FileCompletionInformation */
        0,                                             /* FileMoveClusterInformation */
        0,                                             /* FileQuotaInformation */
        0,                                             /* FileReparsePointInformation */
        0,                                             /* FileNetworkOpenInformation */
        0,                                             /* FileAttributeTagInformation */
        0                                              /* FileTrackingInformation */
    };

    struct stat st;
1340
    int fd, needs_close = FALSE;
1341

1342
    TRACE("(%p,%p,%p,0x%08x,0x%08x)\n", hFile, io, ptr, len, class);
1343

1344
    io->Information = 0;
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355

    if (class <= 0 || class >= FileMaximumInformation)
        return io->u.Status = STATUS_INVALID_INFO_CLASS;
    if (!info_sizes[class])
    {
        FIXME("Unsupported class (%d)\n", class);
        return io->u.Status = STATUS_NOT_IMPLEMENTED;
    }
    if (len < info_sizes[class])
        return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;

1356 1357
    if (class != FilePipeLocalInformation)
    {
1358
        if ((io->u.Status = server_get_unix_fd( hFile, 0, &fd, &needs_close, NULL, NULL )))
1359
            return io->u.Status;
1360
    }
1361 1362 1363 1364 1365

    switch (class)
    {
    case FileBasicInformation:
        {
1366
            FILE_BASIC_INFORMATION *info = ptr;
1367

1368 1369 1370 1371
            if (fstat( fd, &st ) == -1)
                io->u.Status = FILE_GetNtStatus();
            else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
                io->u.Status = STATUS_INVALID_INFO_CLASS;
1372
            else
1373
            {
1374 1375
                if (S_ISDIR(st.st_mode)) info->FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
                else info->FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1376 1377
                if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
                    info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
1378 1379 1380 1381
                RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime);
                RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime);
                RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime);
                RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime);
1382 1383 1384 1385 1386
            }
        }
        break;
    case FileStandardInformation:
        {
1387
            FILE_STANDARD_INFORMATION *info = ptr;
1388

1389
            if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1390
            else
1391
            {
1392 1393 1394 1395 1396 1397 1398
                if ((info->Directory = S_ISDIR(st.st_mode)))
                {
                    info->AllocationSize.QuadPart = 0;
                    info->EndOfFile.QuadPart      = 0;
                    info->NumberOfLinks           = 1;
                    info->DeletePending           = FALSE;
                }
1399
                else
1400
                {
1401 1402 1403 1404
                    info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
                    info->EndOfFile.QuadPart      = st.st_size;
                    info->NumberOfLinks           = st.st_nlink;
                    info->DeletePending           = FALSE; /* FIXME */
1405 1406 1407 1408 1409 1410
                }
            }
        }
        break;
    case FilePositionInformation:
        {
1411
            FILE_POSITION_INFORMATION *info = ptr;
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
            off_t res = lseek( fd, 0, SEEK_CUR );
            if (res == (off_t)-1) io->u.Status = FILE_GetNtStatus();
            else info->CurrentByteOffset.QuadPart = res;
        }
        break;
    case FileInternalInformation:
        {
            FILE_INTERNAL_INFORMATION *info = ptr;

            if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
            else info->IndexNumber.QuadPart = st.st_ino;
        }
        break;
    case FileEaInformation:
        {
            FILE_EA_INFORMATION *info = ptr;
            info->EaSize = 0;
        }
        break;
    case FileEndOfFileInformation:
        {
            FILE_END_OF_FILE_INFORMATION *info = ptr;
1434

1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
            if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
            else info->EndOfFile.QuadPart = S_ISDIR(st.st_mode) ? 0 : st.st_size;
        }
        break;
    case FileAllInformation:
        {
            FILE_ALL_INFORMATION *info = ptr;

            if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
            else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
                io->u.Status = STATUS_INVALID_INFO_CLASS;
1446
            else
1447
            {
1448 1449 1450 1451 1452 1453 1454 1455
                if ((info->StandardInformation.Directory = S_ISDIR(st.st_mode)))
                {
                    info->BasicInformation.FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
                    info->StandardInformation.AllocationSize.QuadPart = 0;
                    info->StandardInformation.EndOfFile.QuadPart      = 0;
                    info->StandardInformation.NumberOfLinks           = 1;
                    info->StandardInformation.DeletePending           = FALSE;
                }
1456
                else
1457
                {
1458 1459 1460 1461 1462
                    info->BasicInformation.FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
                    info->StandardInformation.AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
                    info->StandardInformation.EndOfFile.QuadPart      = st.st_size;
                    info->StandardInformation.NumberOfLinks           = st.st_nlink;
                    info->StandardInformation.DeletePending           = FALSE; /* FIXME */
1463
                }
1464
                if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
                    info->BasicInformation.FileAttributes |= FILE_ATTRIBUTE_READONLY;
                RtlSecondsSince1970ToTime( st.st_mtime, &info->BasicInformation.CreationTime);
                RtlSecondsSince1970ToTime( st.st_mtime, &info->BasicInformation.LastWriteTime);
                RtlSecondsSince1970ToTime( st.st_ctime, &info->BasicInformation.ChangeTime);
                RtlSecondsSince1970ToTime( st.st_atime, &info->BasicInformation.LastAccessTime);
                info->InternalInformation.IndexNumber.QuadPart = st.st_ino;
                info->EaInformation.EaSize = 0;
                info->AccessInformation.AccessFlags = 0;  /* FIXME */
                info->PositionInformation.CurrentByteOffset.QuadPart = lseek( fd, 0, SEEK_CUR );
                info->ModeInformation.Mode = 0;  /* FIXME */
                info->AlignmentInformation.AlignmentRequirement = 1;  /* FIXME */
                info->NameInformation.FileNameLength = 0;
                io->Information = sizeof(*info) - sizeof(WCHAR);
1478 1479 1480
            }
        }
        break;
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
    case FileMailslotQueryInformation:
        {
            FILE_MAILSLOT_QUERY_INFORMATION *info = ptr;

            SERVER_START_REQ( set_mailslot_info )
            {
                req->handle = hFile;
                req->flags = 0;
                io->u.Status = wine_server_call( req );
                if( io->u.Status == STATUS_SUCCESS )
                {
                    info->MaximumMessageSize = reply->max_msgsize;
                    info->MailslotQuota = 0;
1494 1495
                    info->NextMessageSize = 0;
                    info->MessagesAvailable = 0;
1496
                    info->ReadTimeout.QuadPart = reply->read_timeout;
1497 1498 1499
                }
            }
            SERVER_END_REQ;
1500 1501
            if (!io->u.Status)
            {
1502
                char *tmpbuf;
1503
                ULONG size = info->MaximumMessageSize ? info->MaximumMessageSize : 0x10000;
1504 1505
                if (size > 0x10000) size = 0x10000;
                if ((tmpbuf = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1506 1507
                {
                    int fd, needs_close;
1508
                    if (!server_get_unix_fd( hFile, FILE_READ_DATA, &fd, &needs_close, NULL, NULL ))
1509 1510 1511 1512 1513 1514 1515 1516 1517
                    {
                        int res = recv( fd, tmpbuf, size, MSG_PEEK );
                        info->MessagesAvailable = (res > 0);
                        info->NextMessageSize = (res >= 0) ? res : MAILSLOT_NO_MESSAGE;
                        if (needs_close) close( fd );
                    }
                    RtlFreeHeap( GetProcessHeap(), 0, tmpbuf );
                }
            }
1518 1519
        }
        break;
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
    case FilePipeLocalInformation:
        {
            FILE_PIPE_LOCAL_INFORMATION* pli = ptr;

            SERVER_START_REQ( get_named_pipe_info )
            {
                req->handle = hFile;
                if (!(io->u.Status = wine_server_call( req )))
                {
                    pli->NamedPipeType = (reply->flags & NAMED_PIPE_MESSAGE_STREAM_WRITE) ? 
                        FILE_PIPE_TYPE_MESSAGE : FILE_PIPE_TYPE_BYTE;
                    pli->NamedPipeConfiguration = 0; /* FIXME */
                    pli->MaximumInstances = reply->maxinstances;
                    pli->CurrentInstances = reply->instances;
                    pli->InboundQuota = reply->insize;
                    pli->ReadDataAvailable = 0; /* FIXME */
                    pli->OutboundQuota = reply->outsize;
                    pli->WriteQuotaAvailable = 0; /* FIXME */
                    pli->NamedPipeState = 0; /* FIXME */
                    pli->NamedPipeEnd = (reply->flags & NAMED_PIPE_SERVER_END) ?
                        FILE_PIPE_SERVER_END : FILE_PIPE_CLIENT_END;
                }
            }
            SERVER_END_REQ;
        }
        break;
1546 1547
    default:
        FIXME("Unsupported class (%d)\n", class);
1548 1549
        io->u.Status = STATUS_NOT_IMPLEMENTED;
        break;
1550
    }
1551
    if (needs_close) close( fd );
1552
    if (io->u.Status == STATUS_SUCCESS && !io->Information) io->Information = info_sizes[class];
1553
    return io->u.Status;
Juergen Schmied's avatar
Juergen Schmied committed
1554 1555 1556
}

/******************************************************************************
1557
 *  NtSetInformationFile		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
1558
 *  ZwSetInformationFile		[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
1559 1560 1561 1562
 *
 * Set information about an open file handle.
 *
 * PARAMS
1563 1564 1565 1566 1567
 *  handle  [I] Handle returned from ZwOpenFile() or ZwCreateFile()
 *  io      [O] Receives information about the operation on return
 *  ptr     [I] Source for file information
 *  len     [I] Size of FileInformation
 *  class   [I] Type of file information to set
Jon Griffiths's avatar
Jon Griffiths committed
1568 1569
 *
 * RETURNS
1570
 *  Success: 0. io is updated.
Jon Griffiths's avatar
Jon Griffiths committed
1571
 *  Failure: An NTSTATUS error code describing the error.
Juergen Schmied's avatar
Juergen Schmied committed
1572
 */
1573 1574
NTSTATUS WINAPI NtSetInformationFile(HANDLE handle, PIO_STATUS_BLOCK io,
                                     PVOID ptr, ULONG len, FILE_INFORMATION_CLASS class)
Juergen Schmied's avatar
Juergen Schmied committed
1575
{
1576
    int fd, needs_close;
1577

1578
    TRACE("(%p,%p,%p,0x%08x,0x%08x)\n", handle, io, ptr, len, class);
1579 1580

    io->u.Status = STATUS_SUCCESS;
1581
    switch (class)
Jon Griffiths's avatar
Jon Griffiths committed
1582
    {
1583 1584
    case FileBasicInformation:
        if (len >= sizeof(FILE_BASIC_INFORMATION))
1585
        {
1586 1587
            struct stat st;
            const FILE_BASIC_INFORMATION *info = ptr;
1588

1589 1590 1591
            if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
                return io->u.Status;

1592
            if (info->LastAccessTime.QuadPart || info->LastWriteTime.QuadPart)
1593
            {
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
                ULONGLONG sec, nsec;
                struct timeval tv[2];

                if (!info->LastAccessTime.QuadPart || !info->LastWriteTime.QuadPart)
                {

                    tv[0].tv_sec = tv[0].tv_usec = 0;
                    tv[1].tv_sec = tv[1].tv_usec = 0;
                    if (!fstat( fd, &st ))
                    {
                        tv[0].tv_sec = st.st_atime;
                        tv[1].tv_sec = st.st_mtime;
                    }
                }
                if (info->LastAccessTime.QuadPart)
                {
                    sec = RtlLargeIntegerDivide( info->LastAccessTime.QuadPart, 10000000, &nsec );
                    tv[0].tv_sec = sec - SECS_1601_TO_1970;
                    tv[0].tv_usec = (UINT)nsec / 10;
                }
                if (info->LastWriteTime.QuadPart)
                {
                    sec = RtlLargeIntegerDivide( info->LastWriteTime.QuadPart, 10000000, &nsec );
                    tv[1].tv_sec = sec - SECS_1601_TO_1970;
                    tv[1].tv_usec = (UINT)nsec / 10;
                }
                if (futimes( fd, tv ) == -1) io->u.Status = FILE_GetNtStatus();
1621
            }
1622

1623 1624 1625 1626 1627 1628 1629
            if (io->u.Status == STATUS_SUCCESS && info->FileAttributes)
            {
                if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
                else
                {
                    if (info->FileAttributes & FILE_ATTRIBUTE_READONLY)
                    {
1630 1631 1632 1633
                        if (S_ISDIR( st.st_mode))
                            WARN("FILE_ATTRIBUTE_READONLY ignored for directory.\n");
                        else
                            st.st_mode &= ~0222; /* clear write permission bits */
1634 1635 1636 1637 1638 1639 1640 1641 1642
                    }
                    else
                    {
                        /* add write permission only where we already have read permission */
                        st.st_mode |= (0600 | ((st.st_mode & 044) >> 1)) & (~FILE_umask);
                    }
                    if (fchmod( fd, st.st_mode ) == -1) io->u.Status = FILE_GetNtStatus();
                }
            }
1643 1644

            if (needs_close) close( fd );
1645 1646 1647 1648 1649 1650 1651 1652 1653
        }
        else io->u.Status = STATUS_INVALID_PARAMETER_3;
        break;

    case FilePositionInformation:
        if (len >= sizeof(FILE_POSITION_INFORMATION))
        {
            const FILE_POSITION_INFORMATION *info = ptr;

1654 1655 1656
            if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
                return io->u.Status;

1657 1658
            if (lseek( fd, info->CurrentByteOffset.QuadPart, SEEK_SET ) == (off_t)-1)
                io->u.Status = FILE_GetNtStatus();
1659 1660

            if (needs_close) close( fd );
1661
        }
1662
        else io->u.Status = STATUS_INVALID_PARAMETER_3;
1663
        break;
1664

1665 1666 1667
    case FileEndOfFileInformation:
        if (len >= sizeof(FILE_END_OF_FILE_INFORMATION))
        {
1668
            struct stat st;
1669 1670
            const FILE_END_OF_FILE_INFORMATION *info = ptr;

1671 1672 1673
            if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
                return io->u.Status;

1674 1675 1676 1677 1678
            /* first try normal truncate */
            if (ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;

            /* now check for the need to extend the file */
            if (fstat( fd, &st ) != -1 && (off_t)info->EndOfFile.QuadPart > st.st_size)
1679 1680 1681 1682 1683
            {
                static const char zero;

                /* extend the file one byte beyond the requested size and then truncate it */
                /* this should work around ftruncate implementations that can't extend files */
1684 1685
                if (pwrite( fd, &zero, 1, (off_t)info->EndOfFile.QuadPart ) != -1 &&
                    ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
1686
            }
1687
            io->u.Status = FILE_GetNtStatus();
1688 1689

            if (needs_close) close( fd );
1690 1691 1692 1693
        }
        else io->u.Status = STATUS_INVALID_PARAMETER_3;
        break;

1694 1695 1696 1697 1698 1699 1700 1701
    case FileMailslotSetInformation:
        {
            FILE_MAILSLOT_SET_INFORMATION *info = ptr;

            SERVER_START_REQ( set_mailslot_info )
            {
                req->handle = handle;
                req->flags = MAILSLOT_SET_READ_TIMEOUT;
1702
                req->read_timeout = info->ReadTimeout.QuadPart;
1703 1704 1705 1706 1707 1708
                io->u.Status = wine_server_call( req );
            }
            SERVER_END_REQ;
        }
        break;

1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725
    case FileCompletionInformation:
        if (len >= sizeof(FILE_COMPLETION_INFORMATION))
        {
            FILE_COMPLETION_INFORMATION *info = (FILE_COMPLETION_INFORMATION *)ptr;

            SERVER_START_REQ( set_completion_info )
            {
                req->handle   = handle;
                req->chandle  = info->CompletionPort;
                req->ckey     = info->CompletionKey;
                io->u.Status  = wine_server_call( req );
            }
            SERVER_END_REQ;
        } else
            io->u.Status = STATUS_INVALID_PARAMETER_3;
        break;

1726 1727
    default:
        FIXME("Unsupported class (%d)\n", class);
1728 1729
        io->u.Status = STATUS_NOT_IMPLEMENTED;
        break;
1730
    }
1731 1732 1733 1734 1735 1736
    io->Information = 0;
    return io->u.Status;
}


/******************************************************************************
1737
 *              NtQueryFullAttributesFile   (NTDLL.@)
1738
 */
1739 1740
NTSTATUS WINAPI NtQueryFullAttributesFile( const OBJECT_ATTRIBUTES *attr,
                                           FILE_NETWORK_OPEN_INFORMATION *info )
1741 1742 1743 1744
{
    ANSI_STRING unix_name;
    NTSTATUS status;

1745 1746
    if (!(status = wine_nt_to_unix_file_name( attr->ObjectName, &unix_name, FILE_OPEN,
                                              !(attr->Attributes & OBJ_CASE_INSENSITIVE) )))
1747 1748 1749 1750 1751 1752 1753 1754 1755
    {
        struct stat st;

        if (stat( unix_name.Buffer, &st ) == -1)
            status = FILE_GetNtStatus();
        else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
            status = STATUS_INVALID_INFO_CLASS;
        else
        {
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
            if (S_ISDIR(st.st_mode))
            {
                info->FileAttributes          = FILE_ATTRIBUTE_DIRECTORY;
                info->AllocationSize.QuadPart = 0;
                info->EndOfFile.QuadPart      = 0;
            }
            else
            {
                info->FileAttributes          = FILE_ATTRIBUTE_ARCHIVE;
                info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
                info->EndOfFile.QuadPart      = st.st_size;
            }
1768 1769
            if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
                info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
1770 1771 1772 1773 1774 1775 1776 1777 1778
            RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
            RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
            RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
            RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
            if (DIR_is_hidden_file( attr->ObjectName ))
                info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
        }
        RtlFreeAnsiString( &unix_name );
    }
1779
    else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), status );
1780
    return status;
Juergen Schmied's avatar
Juergen Schmied committed
1781 1782
}

1783

1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804
/******************************************************************************
 *              NtQueryAttributesFile   (NTDLL.@)
 *              ZwQueryAttributesFile   (NTDLL.@)
 */
NTSTATUS WINAPI NtQueryAttributesFile( const OBJECT_ATTRIBUTES *attr, FILE_BASIC_INFORMATION *info )
{
    FILE_NETWORK_OPEN_INFORMATION full_info;
    NTSTATUS status;

    if (!(status = NtQueryFullAttributesFile( attr, &full_info )))
    {
        info->CreationTime.QuadPart   = full_info.CreationTime.QuadPart;
        info->LastAccessTime.QuadPart = full_info.LastAccessTime.QuadPart;
        info->LastWriteTime.QuadPart  = full_info.LastWriteTime.QuadPart;
        info->ChangeTime.QuadPart     = full_info.ChangeTime.QuadPart;
        info->FileAttributes          = full_info.FileAttributes;
    }
    return status;
}


1805 1806
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__APPLE__)
/* helper for FILE_GetDeviceInfo to hide some platform differences in fstatfs */
1807
static inline void get_device_info_fstatfs( FILE_FS_DEVICE_INFORMATION *info, const char *fstypename,
1808
                                            unsigned int flags )
1809
{
1810
    if (!strcmp("cd9660", fstypename) || !strcmp("udf", fstypename))
1811 1812 1813 1814 1815
    {
        info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
        /* Don't assume read-only, let the mount options set it below */
        info->Characteristics |= FILE_REMOVABLE_MEDIA;
    }
1816 1817
    else if (!strcmp("nfs", fstypename) || !strcmp("nwfs", fstypename) ||
             !strcmp("smbfs", fstypename) || !strcmp("afpfs", fstypename))
1818 1819 1820 1821
    {
        info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
        info->Characteristics |= FILE_REMOTE_DEVICE;
    }
1822
    else if (!strcmp("procfs", fstypename))
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
        info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
    else
        info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;

    if (flags & MNT_RDONLY)
        info->Characteristics |= FILE_READ_ONLY_DEVICE;

    if (!(flags & MNT_LOCAL))
    {
        info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
        info->Characteristics |= FILE_REMOTE_DEVICE;
    }
}
#endif

1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
static inline int is_device_placeholder( int fd )
{
    static const char wine_placeholder[] = "Wine device placeholder";
    char buffer[sizeof(wine_placeholder)-1];

    if (pread( fd, buffer, sizeof(wine_placeholder) - 1, 0 ) != sizeof(wine_placeholder) - 1)
        return 0;
    return !memcmp( buffer, wine_placeholder, sizeof(wine_placeholder) - 1 );
}

1848
/******************************************************************************
1849
 *              get_device_info
1850 1851 1852
 *
 * Implementation of the FileFsDeviceInformation query for NtQueryVolumeInformationFile.
 */
1853
static NTSTATUS get_device_info( int fd, FILE_FS_DEVICE_INFORMATION *info )
1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873
{
    struct stat st;

    info->Characteristics = 0;
    if (fstat( fd, &st ) < 0) return FILE_GetNtStatus();
    if (S_ISCHR( st.st_mode ))
    {
        info->DeviceType = FILE_DEVICE_UNKNOWN;
#ifdef linux
        switch(major(st.st_rdev))
        {
        case MEM_MAJOR:
            info->DeviceType = FILE_DEVICE_NULL;
            break;
        case TTY_MAJOR:
            info->DeviceType = FILE_DEVICE_SERIAL_PORT;
            break;
        case LP_MAJOR:
            info->DeviceType = FILE_DEVICE_PARALLEL_PORT;
            break;
1874 1875 1876
        case SCSI_TAPE_MAJOR:
            info->DeviceType = FILE_DEVICE_TAPE;
            break;
1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
        }
#endif
    }
    else if (S_ISBLK( st.st_mode ))
    {
        info->DeviceType = FILE_DEVICE_DISK;
    }
    else if (S_ISFIFO( st.st_mode ) || S_ISSOCK( st.st_mode ))
    {
        info->DeviceType = FILE_DEVICE_NAMED_PIPE;
    }
1888 1889 1890 1891
    else if (is_device_placeholder( fd ))
    {
        info->DeviceType = FILE_DEVICE_DISK;
    }
1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904
    else  /* regular file or directory */
    {
#if defined(linux) && defined(HAVE_FSTATFS)
        struct statfs stfs;

        /* check for floppy disk */
        if (major(st.st_dev) == FLOPPY_MAJOR)
            info->Characteristics |= FILE_REMOVABLE_MEDIA;

        if (fstatfs( fd, &stfs ) < 0) stfs.f_type = 0;
        switch (stfs.f_type)
        {
        case 0x9660:      /* iso9660 */
1905
        case 0x9fa1:      /* supermount */
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925
        case 0x15013346:  /* udf */
            info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
            info->Characteristics |= FILE_REMOVABLE_MEDIA|FILE_READ_ONLY_DEVICE;
            break;
        case 0x6969:  /* nfs */
        case 0x517B:  /* smbfs */
        case 0x564c:  /* ncpfs */
            info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
            info->Characteristics |= FILE_REMOTE_DEVICE;
            break;
        case 0x01021994:  /* tmpfs */
        case 0x28cd3d45:  /* cramfs */
        case 0x1373:      /* devfs */
        case 0x9fa0:      /* procfs */
            info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
            break;
        default:
            info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
            break;
        }
1926
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__APPLE__)
1927 1928 1929 1930 1931
        struct statfs stfs;

        if (fstatfs( fd, &stfs ) < 0)
            info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
        else
1932
            get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flags );
1933 1934 1935 1936
#elif defined(__NetBSD__)
        struct statvfs stfs;

        if (fstatvfs( fd, &stfs) < 0)
1937
            info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1938
        else
1939
            get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flag );
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981
#elif defined(sun)
        /* Use dkio to work out device types */
        {
# include <sys/dkio.h>
# include <sys/vtoc.h>
            struct dk_cinfo dkinf;
            int retval = ioctl(fd, DKIOCINFO, &dkinf);
            if(retval==-1){
                WARN("Unable to get disk device type information - assuming a disk like device\n");
                info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
            }
            switch (dkinf.dki_ctype)
            {
            case DKC_CDROM:
                info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
                info->Characteristics |= FILE_REMOVABLE_MEDIA|FILE_READ_ONLY_DEVICE;
                break;
            case DKC_NCRFLOPPY:
            case DKC_SMSFLOPPY:
            case DKC_INTEL82072:
            case DKC_INTEL82077:
                info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
                info->Characteristics |= FILE_REMOVABLE_MEDIA;
                break;
            case DKC_MD:
                info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
                break;
            default:
                info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
            }
        }
#else
        static int warned;
        if (!warned++) FIXME( "device info not properly supported on this platform\n" );
        info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
#endif
        info->Characteristics |= FILE_DEVICE_IS_MOUNTED;
    }
    return STATUS_SUCCESS;
}


1982
/******************************************************************************
1983
 *  NtQueryVolumeInformationFile		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
1984
 *  ZwQueryVolumeInformationFile		[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
1985 1986 1987 1988
 *
 * Get volume information for an open file handle.
 *
 * PARAMS
1989 1990 1991 1992 1993
 *  handle      [I] Handle returned from ZwOpenFile() or ZwCreateFile()
 *  io          [O] Receives information about the operation on return
 *  buffer      [O] Destination for volume information
 *  length      [I] Size of FsInformation
 *  info_class  [I] Type of volume information to set
Jon Griffiths's avatar
Jon Griffiths committed
1994 1995
 *
 * RETURNS
1996
 *  Success: 0. io and buffer are updated.
Jon Griffiths's avatar
Jon Griffiths committed
1997
 *  Failure: An NTSTATUS error code describing the error.
1998
 */
1999 2000 2001
NTSTATUS WINAPI NtQueryVolumeInformationFile( HANDLE handle, PIO_STATUS_BLOCK io,
                                              PVOID buffer, ULONG length,
                                              FS_INFORMATION_CLASS info_class )
2002
{
2003
    int fd, needs_close;
2004
    struct stat st;
2005

2006
    if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
2007
        return io->u.Status;
2008

2009 2010
    io->u.Status = STATUS_NOT_IMPLEMENTED;
    io->Information = 0;
2011

2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025
    switch( info_class )
    {
    case FileFsVolumeInformation:
        FIXME( "%p: volume info not supported\n", handle );
        break;
    case FileFsLabelInformation:
        FIXME( "%p: label info not supported\n", handle );
        break;
    case FileFsSizeInformation:
        if (length < sizeof(FILE_FS_SIZE_INFORMATION))
            io->u.Status = STATUS_BUFFER_TOO_SMALL;
        else
        {
            FILE_FS_SIZE_INFORMATION *info = buffer;
2026

2027 2028 2029 2030 2031 2032 2033 2034 2035
            if (fstat( fd, &st ) < 0)
            {
                io->u.Status = FILE_GetNtStatus();
                break;
            }
            if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
            {
                io->u.Status = STATUS_INVALID_DEVICE_REQUEST;
            }
2036 2037
            else
            {
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058
                /* Linux's fstatvfs is buggy */
#if !defined(linux) || !defined(HAVE_FSTATFS)
                struct statvfs stfs;

                if (fstatvfs( fd, &stfs ) < 0)
                {
                    io->u.Status = FILE_GetNtStatus();
                    break;
                }
                info->BytesPerSector = stfs.f_frsize;
#else
                struct statfs stfs;
                if (fstatfs( fd, &stfs ) < 0)
                {
                    io->u.Status = FILE_GetNtStatus();
                    break;
                }
                info->BytesPerSector = stfs.f_bsize;
#endif
                info->TotalAllocationUnits.QuadPart = stfs.f_blocks;
                info->AvailableAllocationUnits.QuadPart = stfs.f_bavail;
2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
                info->SectorsPerAllocationUnit = 1;
                io->Information = sizeof(*info);
                io->u.Status = STATUS_SUCCESS;
            }
        }
        break;
    case FileFsDeviceInformation:
        if (length < sizeof(FILE_FS_DEVICE_INFORMATION))
            io->u.Status = STATUS_BUFFER_TOO_SMALL;
        else
        {
            FILE_FS_DEVICE_INFORMATION *info = buffer;

2072
            if ((io->u.Status = get_device_info( fd, info )) == STATUS_SUCCESS)
2073
                io->Information = sizeof(*info);
2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
        }
        break;
    case FileFsAttributeInformation:
        FIXME( "%p: attribute info not supported\n", handle );
        break;
    case FileFsControlInformation:
        FIXME( "%p: control info not supported\n", handle );
        break;
    case FileFsFullSizeInformation:
        FIXME( "%p: full size info not supported\n", handle );
        break;
    case FileFsObjectIdInformation:
        FIXME( "%p: object id info not supported\n", handle );
        break;
    case FileFsMaximumInformation:
        FIXME( "%p: maximum info not supported\n", handle );
        break;
    default:
        io->u.Status = STATUS_INVALID_PARAMETER;
        break;
    }
2095
    if (needs_close) close( fd );
2096
    return io->u.Status;
2097
}
2098

2099

2100 2101
/******************************************************************
 *		NtFlushBuffersFile  (NTDLL.@)
Jon Griffiths's avatar
Jon Griffiths committed
2102 2103 2104 2105 2106 2107 2108 2109 2110 2111
 *
 * Flush any buffered data on an open file handle.
 *
 * PARAMS
 *  FileHandle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
 *  IoStatusBlock      [O] Receives information about the operation on return
 *
 * RETURNS
 *  Success: 0. IoStatusBlock is updated.
 *  Failure: An NTSTATUS error code describing the error.
2112 2113 2114 2115
 */
NTSTATUS WINAPI NtFlushBuffersFile( HANDLE hFile, IO_STATUS_BLOCK* IoStatusBlock )
{
    NTSTATUS ret;
2116 2117
    HANDLE hEvent = NULL;

2118 2119 2120 2121
    SERVER_START_REQ( flush_file )
    {
        req->handle = hFile;
        ret = wine_server_call( req );
2122
        hEvent = reply->event;
2123 2124
    }
    SERVER_END_REQ;
2125
    if (!ret && hEvent)
2126 2127 2128 2129
    {
        ret = NtWaitForSingleObject( hEvent, FALSE, NULL );
        NtClose( hEvent );
    }
2130 2131
    return ret;
}
2132 2133 2134 2135 2136 2137 2138

/******************************************************************
 *		NtLockFile       (NTDLL.@)
 *
 *
 */
NTSTATUS WINAPI NtLockFile( HANDLE hFile, HANDLE lock_granted_event,
Jon Griffiths's avatar
Jon Griffiths committed
2139 2140
                            PIO_APC_ROUTINE apc, void* apc_user,
                            PIO_STATUS_BLOCK io_status, PLARGE_INTEGER offset,
2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153
                            PLARGE_INTEGER count, ULONG* key, BOOLEAN dont_wait,
                            BOOLEAN exclusive )
{
    NTSTATUS    ret;
    HANDLE      handle;
    BOOLEAN     async;

    if (apc || io_status || key)
    {
        FIXME("Unimplemented yet parameter\n");
        return STATUS_NOT_IMPLEMENTED;
    }

2154 2155
    if (apc_user) FIXME("I/O completion on lock not implemented yet\n");

2156 2157 2158 2159 2160
    for (;;)
    {
        SERVER_START_REQ( lock_file )
        {
            req->handle      = hFile;
2161 2162
            req->offset      = offset->QuadPart;
            req->count       = count->QuadPart;
2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
            req->shared      = !exclusive;
            req->wait        = !dont_wait;
            ret = wine_server_call( req );
            handle = reply->handle;
            async  = reply->overlapped;
        }
        SERVER_END_REQ;
        if (ret != STATUS_PENDING)
        {
            if (!ret && lock_granted_event) NtSetEvent(lock_granted_event, NULL);
            return ret;
        }

        if (async)
        {
            FIXME( "Async I/O lock wait not implemented, might deadlock\n" );
            if (handle) NtClose( handle );
            return STATUS_PENDING;
        }
        if (handle)
        {
            NtWaitForSingleObject( handle, FALSE, NULL );
            NtClose( handle );
        }
        else
        {
            LARGE_INTEGER time;
    
            /* Unix lock conflict, sleep a bit and retry */
            time.QuadPart = 100 * (ULONGLONG)10000;
            time.QuadPart = -time.QuadPart;
2194
            NtDelayExecution( FALSE, &time );
2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
        }
    }
}


/******************************************************************
 *		NtUnlockFile    (NTDLL.@)
 *
 *
 */
NTSTATUS WINAPI NtUnlockFile( HANDLE hFile, PIO_STATUS_BLOCK io_status,
                              PLARGE_INTEGER offset, PLARGE_INTEGER count,
                              PULONG key )
{
    NTSTATUS status;

2211
    TRACE( "%p %x%08x %x%08x\n",
2212
           hFile, offset->u.HighPart, offset->u.LowPart, count->u.HighPart, count->u.LowPart );
2213 2214 2215 2216 2217 2218 2219 2220 2221

    if (io_status || key)
    {
        FIXME("Unimplemented yet parameter\n");
        return STATUS_NOT_IMPLEMENTED;
    }

    SERVER_START_REQ( unlock_file )
    {
2222 2223 2224
        req->handle = hFile;
        req->offset = offset->QuadPart;
        req->count  = count->QuadPart;
2225 2226 2227 2228 2229
        status = wine_server_call( req );
    }
    SERVER_END_REQ;
    return status;
}
2230 2231 2232 2233 2234 2235

/******************************************************************
 *		NtCreateNamedPipeFile    (NTDLL.@)
 *
 *
 */
2236
NTSTATUS WINAPI NtCreateNamedPipeFile( PHANDLE handle, ULONG access,
2237
                                       POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK iosb,
2238 2239 2240 2241 2242
                                       ULONG sharing, ULONG dispo, ULONG options,
                                       ULONG pipe_type, ULONG read_mode, 
                                       ULONG completion_mode, ULONG max_inst,
                                       ULONG inbound_quota, ULONG outbound_quota,
                                       PLARGE_INTEGER timeout)
2243
{
2244 2245
    NTSTATUS    status;

2246
    TRACE("(%p %x %s %p %x %d %x %d %d %d %d %d %d %p)\n",
2247
          handle, access, debugstr_w(attr->ObjectName->Buffer), iosb, sharing, dispo,
2248 2249
          options, pipe_type, read_mode, completion_mode, max_inst, inbound_quota,
          outbound_quota, timeout);
2250

2251 2252
    /* assume we only get relative timeout */
    if (timeout->QuadPart > 0)
2253 2254 2255 2256
        FIXME("Wrong time %s\n", wine_dbgstr_longlong(timeout->QuadPart));

    SERVER_START_REQ( create_named_pipe )
    {
2257
        req->access  = access;
2258 2259
        req->attributes = attr->Attributes;
        req->rootdir = attr->RootDirectory;
2260
        req->options = options;
2261 2262 2263 2264 2265 2266 2267
        req->flags = 
            (pipe_type) ? NAMED_PIPE_MESSAGE_STREAM_WRITE : 0 |
            (read_mode) ? NAMED_PIPE_MESSAGE_STREAM_READ  : 0 |
            (completion_mode) ? NAMED_PIPE_NONBLOCKING_MODE  : 0;
        req->maxinstances = max_inst;
        req->outsize = outbound_quota;
        req->insize  = inbound_quota;
2268
        req->timeout = timeout->QuadPart;
2269 2270
        wine_server_add_data( req, attr->ObjectName->Buffer,
                              attr->ObjectName->Length );
2271 2272 2273 2274 2275
        status = wine_server_call( req );
        if (!status) *handle = reply->handle;
    }
    SERVER_END_REQ;
    return status;
2276
}
2277 2278 2279 2280 2281 2282 2283 2284

/******************************************************************
 *		NtDeleteFile    (NTDLL.@)
 *
 *
 */
NTSTATUS WINAPI NtDeleteFile( POBJECT_ATTRIBUTES ObjectAttributes )
{
2285 2286 2287 2288 2289
    NTSTATUS status;
    HANDLE hFile;
    IO_STATUS_BLOCK io;

    TRACE("%p\n", ObjectAttributes);
2290 2291
    status = NtCreateFile( &hFile, GENERIC_READ | GENERIC_WRITE | DELETE,
                           ObjectAttributes, &io, NULL, 0,
2292 2293 2294 2295
                           FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 
                           FILE_OPEN, FILE_DELETE_ON_CLOSE, NULL, 0 );
    if (status == STATUS_SUCCESS) status = NtClose(hFile);
    return status;
2296 2297 2298 2299 2300 2301 2302
}

/******************************************************************
 *		NtCancelIoFile    (NTDLL.@)
 *
 *
 */
2303
NTSTATUS WINAPI NtCancelIoFile( HANDLE hFile, PIO_STATUS_BLOCK io_status )
2304
{
2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321
    LARGE_INTEGER timeout;

    TRACE("%p %p\n", hFile, io_status );

    SERVER_START_REQ( cancel_async )
    {
        req->handle = hFile;
        wine_server_call( req );
    }
    SERVER_END_REQ;
    /* Let some APC be run, so that we can run the remaining APCs on hFile
     * either the cancelation of the pending one, but also the execution
     * of the queued APC, but not yet run. This is needed to ensure proper
     * clean-up of allocated data.
     */
    timeout.u.LowPart = timeout.u.HighPart = 0;
    return io_status->u.Status = NtDelayExecution( TRUE, &timeout );
2322
}
2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345

/******************************************************************************
 *  NtCreateMailslotFile	[NTDLL.@]
 *  ZwCreateMailslotFile	[NTDLL.@]
 *
 * PARAMS
 *  pHandle          [O] pointer to receive the handle created
 *  DesiredAccess    [I] access mode (read, write, etc)
 *  ObjectAttributes [I] fully qualified NT path of the mailslot
 *  IoStatusBlock    [O] receives completion status and other info
 *  CreateOptions    [I]
 *  MailslotQuota    [I]
 *  MaxMessageSize   [I]
 *  TimeOut          [I]
 *
 * RETURNS
 *  An NT status code
 */
NTSTATUS WINAPI NtCreateMailslotFile(PHANDLE pHandle, ULONG DesiredAccess,
     POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK IoStatusBlock,
     ULONG CreateOptions, ULONG MailslotQuota, ULONG MaxMessageSize,
     PLARGE_INTEGER TimeOut)
{
2346
    LARGE_INTEGER timeout;
2347 2348
    NTSTATUS ret;

2349
    TRACE("%p %08x %p %p %08x %08x %08x %p\n",
2350 2351 2352
              pHandle, DesiredAccess, attr, IoStatusBlock,
              CreateOptions, MailslotQuota, MaxMessageSize, TimeOut);

2353
    if (!pHandle) return STATUS_ACCESS_VIOLATION;
2354 2355 2356
    if (!attr) return STATUS_INVALID_PARAMETER;
    if (!attr->ObjectName) return STATUS_OBJECT_PATH_SYNTAX_BAD;

2357 2358 2359 2360 2361 2362 2363 2364
    /*
     *  For a NULL TimeOut pointer set the default timeout value
     */
    if  (!TimeOut)
        timeout.QuadPart = -1;
    else
        timeout.QuadPart = TimeOut->QuadPart;

Mike McCormack's avatar
Mike McCormack committed
2365 2366
    SERVER_START_REQ( create_mailslot )
    {
2367
        req->access = DesiredAccess;
2368 2369
        req->attributes = attr->Attributes;
        req->rootdir = attr->RootDirectory;
Mike McCormack's avatar
Mike McCormack committed
2370
        req->max_msgsize = MaxMessageSize;
2371
        req->read_timeout = timeout.QuadPart;
2372 2373
        wine_server_add_data( req, attr->ObjectName->Buffer,
                              attr->ObjectName->Length );
Mike McCormack's avatar
Mike McCormack committed
2374 2375 2376 2377 2378 2379
        ret = wine_server_call( req );
        if( ret == STATUS_SUCCESS )
            *pHandle = reply->handle;
    }
    SERVER_END_REQ;
 
2380 2381
    return ret;
}