file.c 127 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_LINUX_MAJOR_H
# include <linux/major.h>
#endif
33 34 35 36 37 38
#ifdef HAVE_SYS_STATVFS_H
# include <sys/statvfs.h>
#endif
#ifdef HAVE_SYS_PARAM_H
# include <sys/param.h>
#endif
39 40 41
#ifdef HAVE_SYS_SYSCALL_H
# include <sys/syscall.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
#ifdef HAVE_SYS_FILIO_H
# include <sys/filio.h>
#endif
51 52 53 54 55 56 57 58 59
#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
60 61 62 63 64
#ifdef MAJOR_IN_MKDEV
# include <sys/mkdev.h>
#elif defined(MAJOR_IN_SYSMACROS)
# include <sys/sysmacros.h>
#endif
65 66 67
#ifdef HAVE_UTIME_H
# include <utime.h>
#endif
68
#ifdef HAVE_SYS_VFS_H
69 70 71 72 73 74 75 76
/* Work around a conflict with Solaris' system list defined in sys/list.h. */
#define list SYSLIST
#define list_next SYSLIST_NEXT
#define list_prev SYSLIST_PREV
#define list_head SYSLIST_HEAD
#define list_tail SYSLIST_TAIL
#define list_move_tail SYSLIST_MOVE_TAIL
#define list_remove SYSLIST_REMOVE
77
# include <sys/vfs.h>
78 79 80 81 82 83 84
#undef list
#undef list_next
#undef list_prev
#undef list_head
#undef list_tail
#undef list_move_tail
#undef list_remove
85 86 87 88 89 90
#endif
#ifdef HAVE_SYS_MOUNT_H
# include <sys/mount.h>
#endif
#ifdef HAVE_SYS_STATFS_H
# include <sys/statfs.h>
91
#endif
92 93 94
#ifdef HAVE_TERMIOS_H
#include <termios.h>
#endif
95 96 97
#ifdef HAVE_VALGRIND_MEMCHECK_H
# include <valgrind/memcheck.h>
#endif
98

99 100
#include "ntstatus.h"
#define WIN32_NO_STATUS
101
#define NONAMELESSUNION
102
#include "wine/unicode.h"
103
#include "wine/debug.h"
104
#include "wine/server.h"
105
#include "ntdll_misc.h"
Juergen Schmied's avatar
Juergen Schmied committed
106

107
#include "winternl.h"
108
#include "winioctl.h"
109
#include "ddk/ntddk.h"
110
#include "ddk/ntddser.h"
Juergen Schmied's avatar
Juergen Schmied committed
111

112
WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
113
WINE_DECLARE_DEBUG_CHANNEL(winediag);
114

115 116 117 118 119
mode_t FILE_umask = 0;

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

120 121 122
#define FILE_WRITE_TO_END_OF_FILE      ((LONGLONG)-1)
#define FILE_USE_FILE_POINTER_POSITION ((LONGLONG)-2)

123
static const WCHAR ntfsW[] = {'N','T','F','S'};
Juergen Schmied's avatar
Juergen Schmied committed
124

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
/* fetch the attributes of a file */
static inline ULONG get_file_attributes( const struct stat *st )
{
    ULONG attr;

    if (S_ISDIR(st->st_mode))
        attr = FILE_ATTRIBUTE_DIRECTORY;
    else
        attr = FILE_ATTRIBUTE_ARCHIVE;
    if (!(st->st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
        attr |= FILE_ATTRIBUTE_READONLY;
    return attr;
}

/* get the stat info and file attributes for a file (by file descriptor) */
int fd_get_file_info( int fd, struct stat *st, ULONG *attr )
{
    int ret;

    *attr = 0;
    ret = fstat( fd, st );
    if (ret == -1) return ret;
    *attr |= get_file_attributes( st );
    return ret;
}

/* get the stat info and file attributes for a file (by name) */
int get_file_info( const char *path, struct stat *st, ULONG *attr )
{
    int ret;

    *attr = 0;
    ret = lstat( path, st );
    if (ret == -1) return ret;
    if (S_ISLNK( st->st_mode ))
    {
        ret = stat( path, st );
        if (ret == -1) return ret;
        /* is a symbolic link and a directory, consider these "reparse points" */
        if (S_ISDIR( st->st_mode )) *attr |= FILE_ATTRIBUTE_REPARSE_POINT;
    }
    *attr |= get_file_attributes( st );
    return ret;
}

Juergen Schmied's avatar
Juergen Schmied committed
170
/**************************************************************************
171 172
 *                 FILE_CreateFile                    (internal)
 * Open a file.
Jon Griffiths's avatar
Jon Griffiths committed
173
 *
174
 * Parameter set fully identical with NtCreateFile
Juergen Schmied's avatar
Juergen Schmied committed
175
 */
176 177 178 179
static NTSTATUS FILE_CreateFile( 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
180
{
181
    ANSI_STRING unix_name;
182
    BOOL created = FALSE;
183

184
    TRACE("handle=%p access=%08x name=%s objattr=%08x root=%p sec=%p io=%p alloc_size=%p "
185
          "attr=%08x sharing=%08x disp=%d options=%08x ea=%p.0x%08x\n",
186 187 188 189
          handle, access, debugstr_us(attr->ObjectName), attr->Attributes,
          attr->RootDirectory, attr->SecurityDescriptor, io, alloc_size,
          attributes, sharing, disposition, options, ea_buffer, ea_length );

190 191
    if (!attr || !attr->ObjectName) return STATUS_INVALID_PARAMETER;

192 193
    if (alloc_size) FIXME( "alloc_size not supported\n" );

194 195 196 197 198 199
    if (options & FILE_OPEN_BY_FILE_ID)
        io->u.Status = file_id_to_unix_file_name( attr, &unix_name );
    else
        io->u.Status = nt_to_unix_file_name_attr( attr, &unix_name, disposition );

    if (io->u.Status == STATUS_BAD_DEVICE_TYPE)
200 201 202 203 204
    {
        SERVER_START_REQ( open_file_object )
        {
            req->access     = access;
            req->attributes = attr->Attributes;
205
            req->rootdir    = wine_server_obj_handle( attr->RootDirectory );
206
            req->sharing    = sharing;
207
            req->options    = options;
208 209
            wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
            io->u.Status = wine_server_call( req );
210
            *handle = wine_server_ptr_handle( reply->handle );
211 212
        }
        SERVER_END_REQ;
213
        if (io->u.Status == STATUS_SUCCESS) io->Information = FILE_OPENED;
214 215 216
        return io->u.Status;
    }

217 218
    if (io->u.Status == STATUS_NO_SUCH_FILE &&
        disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
219 220 221 222 223 224
    {
        created = TRUE;
        io->u.Status = STATUS_SUCCESS;
    }

    if (io->u.Status == STATUS_SUCCESS)
225
    {
226
        static UNICODE_STRING empty_string;
227 228 229
        OBJECT_ATTRIBUTES unix_attr = *attr;
        data_size_t len;
        struct object_attributes *objattr;
230

231
        unix_attr.ObjectName = &empty_string;  /* we send the unix name instead */
232
        if ((io->u.Status = alloc_object_attributes( &unix_attr, &objattr, &len )))
233
        {
234 235
            RtlFreeAnsiString( &unix_name );
            return io->u.Status;
236 237
        }

238 239 240 241 242 243 244
        SERVER_START_REQ( create_file )
        {
            req->access     = access;
            req->sharing    = sharing;
            req->create     = disposition;
            req->options    = options;
            req->attrs      = attributes;
245
            wine_server_add_data( req, objattr, len );
246 247
            wine_server_add_data( req, unix_name.Buffer, unix_name.Length );
            io->u.Status = wine_server_call( req );
248
            *handle = wine_server_ptr_handle( reply->handle );
249 250
        }
        SERVER_END_REQ;
251
        RtlFreeHeap( GetProcessHeap(), 0, objattr );
252 253
        RtlFreeAnsiString( &unix_name );
    }
254
    else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), io->u.Status );
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276

    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;
        }
    }
277 278 279 280 281
    else if (io->u.Status == STATUS_TOO_MANY_OPENED_FILES)
    {
        static int once;
        if (!once++) ERR_(winediag)( "Too many open files, ulimit -n probably needs to be increased\n" );
    }
282

283
    return io->u.Status;
Juergen Schmied's avatar
Juergen Schmied committed
284 285
}

286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
/**************************************************************************
 *                 NtOpenFile				[NTDLL.@]
 *                 ZwOpenFile				[NTDLL.@]
 *
 * Open a file.
 *
 * PARAMS
 *  handle    [O] Variable that receives the file handle on return
 *  access    [I] Access desired by the caller to the file
 *  attr      [I] Structure describing the file to be opened
 *  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
 *
 * RETURNS
 *  Success: 0. FileHandle and IoStatusBlock are updated.
 *  Failure: An NTSTATUS error code describing the error.
 */
NTSTATUS WINAPI NtOpenFile( PHANDLE handle, ACCESS_MASK access,
                            POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK io,
                            ULONG sharing, ULONG options )
{
    return FILE_CreateFile( handle, access, attr, io, NULL, 0,
                            sharing, FILE_OPEN, options, NULL, 0 );
}

/**************************************************************************
 *		NtCreateFile				[NTDLL.@]
 *		ZwCreateFile				[NTDLL.@]
 *
 * Either create a new file or directory, or open an existing file, device,
 * directory or volume.
 *
 * PARAMS
 *	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
 *	ea_buffer    [I] Pointer to an extended attributes buffer
 *	ea_length    [I] Length of ea_buffer
 *
 * RETURNS
 *  Success: 0. handle and io are updated.
 *  Failure: An NTSTATUS error code describing the error.
 */
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 )
{
    return FILE_CreateFile( handle, access, attr, io, alloc_size, attributes,
                            sharing, disposition, options, ea_buffer, ea_length );
}

345 346 347 348
/***********************************************************************
 *                  Asynchronous file I/O                              *
 */

349
struct async_fileio
350
{
351 352 353 354
    struct async_fileio *next;
    HANDLE               handle;
    PIO_APC_ROUTINE      apc;
    void                *apc_arg;
355 356
};

357
struct async_fileio_read
358 359
{
    struct async_fileio io;
360
    char*               buffer;
361
    unsigned int        already;
362 363
    unsigned int        count;
    BOOL                avail_mode;
364
};
365

366
struct async_fileio_write
367
{
368
    struct async_fileio io;
369 370 371
    const char         *buffer;
    unsigned int        already;
    unsigned int        count;
372
};
373

374 375 376 377 378 379 380 381
struct async_irp
{
    struct async_fileio io;
    HANDLE              event;    /* async event */
    void               *buffer;   /* buffer for output */
    ULONG               size;     /* size of buffer */
};

382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
static struct async_fileio *fileio_freelist;

static void release_fileio( struct async_fileio *io )
{
    for (;;)
    {
        struct async_fileio *next = fileio_freelist;
        io->next = next;
        if (interlocked_cmpxchg_ptr( (void **)&fileio_freelist, io, next ) == next) return;
    }
}

static struct async_fileio *alloc_fileio( DWORD size, HANDLE handle, PIO_APC_ROUTINE apc, void *arg )
{
    /* first free remaining previous fileinfos */

    struct async_fileio *io = interlocked_xchg_ptr( (void **)&fileio_freelist, NULL );

    while (io)
    {
        struct async_fileio *next = io->next;
        RtlFreeHeap( GetProcessHeap(), 0, io );
        io = next;
    }

    if ((io = RtlAllocateHeap( GetProcessHeap(), 0, size )))
    {
        io->handle  = handle;
        io->apc     = apc;
        io->apc_arg = arg;
    }
    return io;
}
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
/* callback for irp async I/O completion */
static NTSTATUS irp_completion( void *user, IO_STATUS_BLOCK *io, NTSTATUS status, void **apc, void **arg )
{
    struct async_irp *async = user;

    if (status == STATUS_ALERTED)
    {
        SERVER_START_REQ( get_irp_result )
        {
            req->handle   = wine_server_obj_handle( async->io.handle );
            req->user_arg = wine_server_client_ptr( async );
            wine_server_set_reply( req, async->buffer, async->size );
            status = wine_server_call( req );
            if (status != STATUS_PENDING) io->Information = reply->size;
        }
        SERVER_END_REQ;
    }
    if (status != STATUS_PENDING)
    {
        io->u.Status = status;
        *apc = async->io.apc;
        *arg = async->io.apc_arg;
        release_fileio( &async->io );
    }
    return status;
}

443 444 445 446 447 448
/***********************************************************************
 *           FILE_GetNtStatus(void)
 *
 * Retrieve the Nt Status code from errno.
 * Try to be consistent with FILE_SetDosError().
 */
449
NTSTATUS FILE_GetNtStatus(void)
450 451 452 453 454 455
{
    int err = errno;

    TRACE( "errno = %d\n", errno );
    switch (err)
    {
456 457
    case EAGAIN:    return STATUS_SHARING_VIOLATION;
    case EBADF:     return STATUS_INVALID_HANDLE;
458
    case EBUSY:     return STATUS_DEVICE_BUSY;
459
    case ENOSPC:    return STATUS_DISK_FULL;
460 461
    case EPERM:
    case EROFS:
462 463 464 465
    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;
466
    case EMFILE:
467 468 469
    case ENFILE:    return STATUS_TOO_MANY_OPENED_FILES;
    case EINVAL:    return STATUS_INVALID_PARAMETER;
    case ENOTEMPTY: return STATUS_DIRECTORY_NOT_EMPTY;
470
    case EPIPE:     return STATUS_PIPE_DISCONNECTED;
471
    case EIO:       return STATUS_DEVICE_NOT_READY;
472 473 474
#ifdef ENOMEDIUM
    case ENOMEDIUM: return STATUS_NO_MEDIA_IN_DEVICE;
#endif
475
    case ENXIO:     return STATUS_NO_SUCH_DEVICE;
476 477
    case ENOTTY:
    case EOPNOTSUPP:return STATUS_NOT_SUPPORTED;
478
    case ECONNRESET:return STATUS_PIPE_DISCONNECTED;
479
    case EFAULT:    return STATUS_ACCESS_VIOLATION;
480
    case ESPIPE:    return STATUS_ILLEGAL_FUNCTION;
481
#ifdef ETIME /* Missing on FreeBSD */
482
    case ETIME:     return STATUS_IO_TIMEOUT;
483
#endif
484 485
    case ENOEXEC:   /* ?? */
    case EEXIST:    /* ?? */
486 487
    default:
        FIXME( "Converting errno %d to STATUS_UNSUCCESSFUL\n", err );
488
        return STATUS_UNSUCCESSFUL;
489 490 491 492 493 494
    }
}

/***********************************************************************
 *             FILE_AsyncReadService      (INTERNAL)
 */
495 496
static NTSTATUS FILE_AsyncReadService( void *user, IO_STATUS_BLOCK *iosb,
                                       NTSTATUS status, void **apc, void **arg )
497
{
498
    struct async_fileio_read *fileio = user;
499
    int fd, needs_close, result;
500

501
    switch (status)
502
    {
503 504
    case STATUS_ALERTED: /* got some new data */
        /* check to see if the data is ready (non-blocking) */
505
        if ((status = server_get_unix_fd( fileio->io.handle, FILE_READ_DATA, &fd,
506
                                          &needs_close, NULL, NULL )))
507
            break;
508

509
        result = read(fd, &fileio->buffer[fileio->already], fileio->count - fileio->already);
510
        if (needs_close) close( fd );
511

512 513 514
        if (result < 0)
        {
            if (errno == EAGAIN || errno == EINTR)
515
                status = STATUS_PENDING;
516
            else /* check to see if the transfer is complete */
517
                status = FILE_GetNtStatus();
518 519 520
        }
        else if (result == 0)
        {
521
            status = fileio->already ? STATUS_SUCCESS : STATUS_PIPE_BROKEN;
522 523 524
        }
        else
        {
525 526
            fileio->already += result;
            if (fileio->already >= fileio->count || fileio->avail_mode)
527
                status = STATUS_SUCCESS;
528
            else
529
                status = STATUS_PENDING;
530 531
        }
        break;
532 533 534 535

    case STATUS_TIMEOUT:
    case STATUS_IO_TIMEOUT:
        if (fileio->already) status = STATUS_SUCCESS;
536
        break;
537
    }
538 539 540
    if (status != STATUS_PENDING)
    {
        iosb->u.Status = status;
541
        iosb->Information = fileio->already;
542 543 544
        *apc = fileio->io.apc;
        *arg = fileio->io.apc_arg;
        release_fileio( &fileio->io );
545
    }
546
    return status;
547 548
}

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
/* do a read call through the server */
static NTSTATUS server_read_file( HANDLE handle, HANDLE event, PIO_APC_ROUTINE apc, void *apc_context,
                                  IO_STATUS_BLOCK *io, void *buffer, ULONG size,
                                  LARGE_INTEGER *offset, ULONG *key )
{
    struct async_irp *async;
    NTSTATUS status;
    HANDLE wait_handle;
    ULONG options;
    ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;

    if (!(async = (struct async_irp *)alloc_fileio( sizeof(*async), handle, apc, apc_context )))
        return STATUS_NO_MEMORY;

    async->event   = event;
    async->buffer  = buffer;
    async->size    = size;

    SERVER_START_REQ( read )
    {
        req->blocking       = !apc && !event && !cvalue;
        req->async.handle   = wine_server_obj_handle( handle );
        req->async.callback = wine_server_client_ptr( irp_completion );
        req->async.iosb     = wine_server_client_ptr( io );
        req->async.arg      = wine_server_client_ptr( async );
        req->async.event    = wine_server_obj_handle( event );
        req->async.cvalue   = cvalue;
        req->pos            = offset ? offset->QuadPart : 0;
        wine_server_set_reply( req, buffer, size );
        status = wine_server_call( req );
        wait_handle = wine_server_ptr_handle( reply->wait );
        options     = reply->options;
        if (status != STATUS_PENDING) io->Information = wine_server_reply_size( reply );
    }
    SERVER_END_REQ;

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

    if (wait_handle)
    {
        NtWaitForSingleObject( wait_handle, (options & FILE_SYNCHRONOUS_IO_ALERT), NULL );
        status = io->u.Status;
        NtClose( wait_handle );
    }

    return status;
}

/* do a write call through the server */
static NTSTATUS server_write_file( HANDLE handle, HANDLE event, PIO_APC_ROUTINE apc, void *apc_context,
                                   IO_STATUS_BLOCK *io, const void *buffer, ULONG size,
                                   LARGE_INTEGER *offset, ULONG *key )
{
    struct async_irp *async;
    NTSTATUS status;
    HANDLE wait_handle;
    ULONG options;
    ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;

    if (!(async = (struct async_irp *)alloc_fileio( sizeof(*async), handle, apc, apc_context )))
        return STATUS_NO_MEMORY;

    async->event   = event;
    async->buffer  = NULL;
    async->size    = 0;

    SERVER_START_REQ( write )
    {
        req->blocking       = !apc && !event && !cvalue;
        req->async.handle   = wine_server_obj_handle( handle );
        req->async.callback = wine_server_client_ptr( irp_completion );
        req->async.iosb     = wine_server_client_ptr( io );
        req->async.arg      = wine_server_client_ptr( async );
        req->async.event    = wine_server_obj_handle( event );
        req->async.cvalue   = cvalue;
        req->pos            = offset ? offset->QuadPart : 0;
        wine_server_add_data( req, buffer, size );
        status = wine_server_call( req );
        wait_handle = wine_server_ptr_handle( reply->wait );
        options     = reply->options;
        if (status != STATUS_PENDING) io->Information = reply->size;
    }
    SERVER_END_REQ;

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

    if (wait_handle)
    {
        NtWaitForSingleObject( wait_handle, (options & FILE_SYNCHRONOUS_IO_ALERT), NULL );
        status = io->u.Status;
        NtClose( wait_handle );
    }

    return status;
}

645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
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)
684
                    timeouts->interval = timeouts->total = 0;
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
            }
            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 )
            {
703
                req->handle = wine_server_obj_handle( handle );
704
                req->flags = 0;
705 706 707
                if (!(status = wine_server_call( req )) &&
                    reply->read_timeout != TIMEOUT_INFINITE)
                    timeouts->total = reply->read_timeout / -10000;
708 709 710 711 712 713
            }
            SERVER_END_REQ;
        }
        break;
    case FD_TYPE_SOCKET:
    case FD_TYPE_PIPE:
714
    case FD_TYPE_CHAR:
715 716 717 718 719 720 721 722 723 724 725
        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 */
726
static inline int get_next_io_timeout( const struct io_timeouts *timeouts, ULONG already )
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
{
    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;
}

742

743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
/* 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:
767
    case FD_TYPE_CHAR:
768 769 770 771 772 773 774 775 776
        *avail_mode = TRUE;
        break;
    default:
        *avail_mode = FALSE;
        break;
    }
    return status;
}

777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
/* register an async I/O for a file read; helper for NtReadFile */
static NTSTATUS register_async_file_read( HANDLE handle, HANDLE event,
                                          PIO_APC_ROUTINE apc, void *apc_user,
                                          IO_STATUS_BLOCK *iosb, void *buffer,
                                          ULONG already, ULONG length, BOOL avail_mode )
{
    ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
    struct async_fileio_read *fileio;
    NTSTATUS status;

    if (!(fileio = (struct async_fileio_read *)alloc_fileio( sizeof(*fileio), handle, apc, apc_user )))
        return STATUS_NO_MEMORY;

    fileio->already = already;
    fileio->count = length;
    fileio->buffer = buffer;
    fileio->avail_mode = avail_mode;

    SERVER_START_REQ( register_async )
    {
        req->type   = ASYNC_TYPE_READ;
        req->count  = length;
        req->async.handle   = wine_server_obj_handle( handle );
        req->async.event    = wine_server_obj_handle( event );
        req->async.callback = wine_server_client_ptr( FILE_AsyncReadService );
        req->async.iosb     = wine_server_client_ptr( iosb );
        req->async.arg      = wine_server_client_ptr( fileio );
        req->async.cvalue   = cvalue;
        status = wine_server_call( req );
    }
    SERVER_END_REQ;

    if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
    return status;
}

813

Juergen Schmied's avatar
Juergen Schmied committed
814
/******************************************************************************
815
 *  NtReadFile					[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
816
 *  ZwReadFile					[NTDLL.@]
Juergen Schmied's avatar
Juergen Schmied committed
817
 *
Jon Griffiths's avatar
Jon Griffiths committed
818
 * Read from an open file handle.
819
 *
Jon Griffiths's avatar
Jon Griffiths committed
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
 * 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
835
 */
Jon Griffiths's avatar
Jon Griffiths committed
836 837
NTSTATUS WINAPI NtReadFile(HANDLE hFile, HANDLE hEvent,
                           PIO_APC_ROUTINE apc, void* apc_user,
838 839
                           PIO_STATUS_BLOCK io_status, void* buffer, ULONG length,
                           PLARGE_INTEGER offset, PULONG key)
840
{
841
    int result, unix_handle, needs_close;
842
    unsigned int options;
843
    struct io_timeouts timeouts;
844
    NTSTATUS status;
845
    ULONG total = 0;
846
    enum server_fd_type type;
847
    ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
848
    BOOL send_completion = FALSE, async_read, timeout_init_done = FALSE;
849

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

853 854
    if (!io_status) return STATUS_ACCESS_VIOLATION;

855
    status = server_get_unix_fd( hFile, FILE_READ_DATA, &unix_handle,
856
                                 &needs_close, &type, &options );
857 858 859
    if (status == STATUS_BAD_DEVICE_TYPE)
        return server_read_file( hFile, hEvent, apc, apc_user, io_status, buffer, length, offset, key );

860
    if (status) return status;
861

862 863
    async_read = !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));

864 865 866 867 868 869
    if (!virtual_check_buffer_for_write( buffer, length ))
    {
        status = STATUS_ACCESS_VIOLATION;
        goto done;
    }

870
    if (type == FD_TYPE_FILE)
871
    {
872
        if (async_read && (!offset || offset->QuadPart < 0))
873
        {
874 875 876 877
            status = STATUS_INVALID_PARAMETER;
            goto done;
        }

878
        if (offset && offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
879 880 881
        {
            /* async I/O doesn't make sense on regular files */
            while ((result = pread( unix_handle, buffer, length, offset->QuadPart )) == -1)
882
            {
883 884 885 886 887
                if (errno != EINTR)
                {
                    status = FILE_GetNtStatus();
                    goto done;
                }
888
            }
889
            if (!async_read)
890 891
                /* update file pointer position */
                lseek( unix_handle, offset->QuadPart + result, SEEK_SET );
892

893
            total = result;
894
            status = (total || !length) ? STATUS_SUCCESS : STATUS_END_OF_FILE;
895 896
            goto done;
        }
897
    }
898
    else if (type == FD_TYPE_SERIAL || type == FD_TYPE_DEVICE)
899
    {
900
        if (async_read && (!offset || offset->QuadPart < 0))
901 902 903 904 905
        {
            status = STATUS_INVALID_PARAMETER;
            goto done;
        }
    }
906

907 908 909 910 911 912 913 914 915 916 917 918 919 920
    if (type == FD_TYPE_SERIAL && async_read && length)
    {
        /* an asynchronous serial port read with a read interval timeout needs to
           skip the synchronous read to make sure that the server starts the read
           interval timer after the first read */
        if ((status = get_io_timeouts( hFile, type, length, TRUE, &timeouts ))) goto err;
        if (timeouts.interval)
        {
            status = register_async_file_read( hFile, hEvent, apc, apc_user, io_status,
                                               buffer, total, length, FALSE );
            goto err;
        }
    }

921 922 923 924 925 926
    for (;;)
    {
        if ((result = read( unix_handle, (char *)buffer + total, length - total )) >= 0)
        {
            total += result;
            if (!result || total == length)
927
            {
928
                if (total)
929
                {
930
                    status = STATUS_SUCCESS;
931 932 933 934 935 936
                    goto done;
                }
                switch (type)
                {
                case FD_TYPE_FILE:
                case FD_TYPE_CHAR:
937
                case FD_TYPE_DEVICE:
938
                    status = length ? STATUS_END_OF_FILE : STATUS_SUCCESS;
939 940
                    goto done;
                case FD_TYPE_SERIAL:
941 942 943 944 945
                    if (!length)
                    {
                        status = STATUS_SUCCESS;
                        goto done;
                    }
946 947 948 949 950
                    break;
                default:
                    status = STATUS_PIPE_BROKEN;
                    goto done;
                }
951
            }
952
            else if (type == FD_TYPE_FILE) continue;  /* no async I/O on regular files */
953
        }
954
        else if (errno != EAGAIN)
955
        {
956
            if (errno == EINTR) continue;
957 958
            if (!total) status = FILE_GetNtStatus();
            goto done;
959
        }
960

961
        if (async_read)
962
        {
963
            BOOL avail_mode;
Jon Griffiths's avatar
Jon Griffiths committed
964

965
            if ((status = get_io_avail_mode( hFile, type, &avail_mode )))
966
                goto err;
967
            if (total && avail_mode)
968 969 970 971
            {
                status = STATUS_SUCCESS;
                goto done;
            }
972 973
            status = register_async_file_read( hFile, hEvent, apc, apc_user, io_status,
                                               buffer, total, length, avail_mode );
974
            goto err;
975
        }
976
        else  /* synchronous read, wait for the fd to become ready */
977
        {
978 979 980 981 982
            struct pollfd pfd;
            int ret, timeout;

            if (!timeout_init_done)
            {
983
                timeout_init_done = TRUE;
984
                if ((status = get_io_timeouts( hFile, type, length, TRUE, &timeouts )))
985
                    goto err;
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
                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 */
1007
        }
1008
    }
1009

1010
done:
1011
    send_completion = cvalue != 0;
1012 1013

err:
1014
    if (needs_close) close( unix_handle );
1015
    if (status == STATUS_SUCCESS || (status == STATUS_END_OF_FILE && !async_read))
1016
    {
1017 1018 1019 1020
        io_status->u.Status = status;
        io_status->Information = total;
        TRACE("= SUCCESS (%u)\n", total);
        if (hEvent) NtSetEvent( hEvent, NULL );
1021 1022
        if (apc && !status) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
                                              (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
1023
    }
1024
    else
1025
    {
1026 1027
        TRACE("= 0x%08x\n", status);
        if (status != STATUS_PENDING && hEvent) NtResetEvent( hEvent, NULL );
1028
    }
1029 1030 1031

    if (send_completion) NTDLL_AddCompletion( hFile, cvalue, status, total );

1032
    return status;
1033
}
1034

1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049

/******************************************************************************
 *  NtReadFileScatter   [NTDLL.@]
 *  ZwReadFileScatter   [NTDLL.@]
 */
NTSTATUS WINAPI NtReadFileScatter( HANDLE file, HANDLE event, PIO_APC_ROUTINE apc, void *apc_user,
                                   PIO_STATUS_BLOCK io_status, FILE_SEGMENT_ELEMENT *segments,
                                   ULONG length, PLARGE_INTEGER offset, PULONG key )
{
    int result, unix_handle, needs_close;
    unsigned int options;
    NTSTATUS status;
    ULONG pos = 0, total = 0;
    enum server_fd_type type;
    ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
1050
    BOOL send_completion = FALSE;
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071

    TRACE( "(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
           file, event, apc, apc_user, io_status, segments, length, offset, key);

    if (length % page_size) return STATUS_INVALID_PARAMETER;
    if (!io_status) return STATUS_ACCESS_VIOLATION;

    status = server_get_unix_fd( file, FILE_READ_DATA, &unix_handle,
                                 &needs_close, &type, &options );
    if (status) return status;

    if ((type != FD_TYPE_FILE) ||
        (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) ||
        !(options & FILE_NO_INTERMEDIATE_BUFFERING))
    {
        status = STATUS_INVALID_PARAMETER;
        goto error;
    }

    while (length)
    {
1072
        if (offset && offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
            result = pread( unix_handle, (char *)segments->Buffer + pos,
                            page_size - pos, offset->QuadPart + total );
        else
            result = read( unix_handle, (char *)segments->Buffer + pos, page_size - pos );

        if (result == -1)
        {
            if (errno == EINTR) continue;
            status = FILE_GetNtStatus();
            break;
        }
        if (!result)
        {
            status = STATUS_END_OF_FILE;
            break;
        }
        total += result;
        length -= result;
        if ((pos += result) == page_size)
        {
            pos = 0;
            segments++;
        }
    }

1098
    send_completion = cvalue != 0;
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115

 error:
    if (needs_close) close( unix_handle );
    if (status == STATUS_SUCCESS)
    {
        io_status->u.Status = status;
        io_status->Information = total;
        TRACE("= SUCCESS (%u)\n", total);
        if (event) NtSetEvent( event, 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 && event) NtResetEvent( event, NULL );
    }
1116 1117 1118

    if (send_completion) NTDLL_AddCompletion( file, cvalue, status, total );

1119 1120 1121 1122
    return status;
}


1123 1124 1125
/***********************************************************************
 *             FILE_AsyncWriteService      (INTERNAL)
 */
1126 1127
static NTSTATUS FILE_AsyncWriteService( void *user, IO_STATUS_BLOCK *iosb,
                                        NTSTATUS status, void **apc, void **arg )
1128
{
1129
    struct async_fileio_write *fileio = user;
1130
    int result, fd, needs_close;
1131
    enum server_fd_type type;
1132

1133
    switch (status)
1134
    {
1135 1136
    case STATUS_ALERTED:
        /* write some data (non-blocking) */
1137
        if ((status = server_get_unix_fd( fileio->io.handle, FILE_WRITE_DATA, &fd,
1138
                                          &needs_close, &type, NULL )))
1139
            break;
1140

1141 1142 1143 1144 1145
        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 );

1146
        if (needs_close) close( fd );
1147

1148 1149
        if (result < 0)
        {
1150 1151
            if (errno == EAGAIN || errno == EINTR) status = STATUS_PENDING;
            else status = FILE_GetNtStatus();
1152 1153 1154
        }
        else
        {
1155 1156
            fileio->already += result;
            status = (fileio->already < fileio->count) ? STATUS_PENDING : STATUS_SUCCESS;
1157 1158
        }
        break;
1159 1160 1161 1162

    case STATUS_TIMEOUT:
    case STATUS_IO_TIMEOUT:
        if (fileio->already) status = STATUS_SUCCESS;
1163
        break;
1164
    }
1165 1166 1167
    if (status != STATUS_PENDING)
    {
        iosb->u.Status = status;
1168
        iosb->Information = fileio->already;
1169 1170 1171
        *apc = fileio->io.apc;
        *arg = fileio->io.apc_arg;
        release_fileio( &fileio->io );
1172
    }
1173
    return status;
1174 1175
}

1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
static NTSTATUS set_pending_write( HANDLE device )
{
    NTSTATUS status;

    SERVER_START_REQ( set_serial_info )
    {
        req->handle = wine_server_obj_handle( device );
        req->flags  = SERIALINFO_PENDING_WRITE;
        status = wine_server_call( req );
    }
    SERVER_END_REQ;
    return status;
}

1190 1191 1192 1193
/******************************************************************************
 *  NtWriteFile					[NTDLL.@]
 *  ZwWriteFile					[NTDLL.@]
 *
Jon Griffiths's avatar
Jon Griffiths committed
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
 * 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.
1211
 */
1212 1213 1214 1215 1216
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
1217
{
1218
    int result, unix_handle, needs_close;
1219
    unsigned int options;
1220
    struct io_timeouts timeouts;
1221
    NTSTATUS status;
1222
    ULONG total = 0;
1223
    enum server_fd_type type;
1224
    ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
1225
    BOOL send_completion = FALSE, async_write, append_write = FALSE, timeout_init_done = FALSE;
1226
    LARGE_INTEGER offset_eof;
1227

1228
    TRACE("(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p)!\n",
1229 1230
          hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);

1231 1232
    if (!io_status) return STATUS_ACCESS_VIOLATION;

1233
    status = server_get_unix_fd( hFile, FILE_WRITE_DATA, &unix_handle,
1234
                                 &needs_close, &type, &options );
1235 1236 1237
    if (status == STATUS_BAD_DEVICE_TYPE)
        return server_write_file( hFile, hEvent, apc, apc_user, io_status, buffer, length, offset, key );

1238 1239 1240 1241 1242 1243
    if (status == STATUS_ACCESS_DENIED)
    {
        status = server_get_unix_fd( hFile, FILE_APPEND_DATA, &unix_handle,
                                     &needs_close, &type, &options );
        append_write = TRUE;
    }
1244
    if (status) return status;
1245

1246 1247 1248 1249 1250 1251
    if (!virtual_check_buffer_for_read( buffer, length ))
    {
        status = STATUS_INVALID_USER_BUFFER;
        goto done;
    }

1252 1253
    async_write = !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));

1254
    if (type == FD_TYPE_FILE)
1255
    {
1256
        if (async_write &&
1257
            (!offset || (offset->QuadPart < 0 && offset->QuadPart != FILE_WRITE_TO_END_OF_FILE)))
1258
        {
1259 1260 1261 1262
            status = STATUS_INVALID_PARAMETER;
            goto done;
        }

1263 1264
        if (append_write)
        {
1265
            offset_eof.QuadPart = FILE_WRITE_TO_END_OF_FILE;
1266 1267 1268
            offset = &offset_eof;
        }

1269
        if (offset && offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
1270
        {
1271 1272
            off_t off = offset->QuadPart;

1273
            if (offset->QuadPart == FILE_WRITE_TO_END_OF_FILE)
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
            {
                struct stat st;

                if (fstat( unix_handle, &st ) == -1)
                {
                    status = FILE_GetNtStatus();
                    goto done;
                }
                off = st.st_size;
            }
1284 1285 1286 1287 1288
            else if (offset->QuadPart < 0)
            {
                status = STATUS_INVALID_PARAMETER;
                goto done;
            }
1289

1290
            /* async I/O doesn't make sense on regular files */
1291
            while ((result = pwrite( unix_handle, buffer, length, off )) == -1)
1292
            {
1293 1294 1295 1296 1297 1298
                if (errno != EINTR)
                {
                    if (errno == EFAULT) status = STATUS_INVALID_USER_BUFFER;
                    else status = FILE_GetNtStatus();
                    goto done;
                }
1299
            }
1300

1301
            if (!async_write)
1302
                /* update file pointer position */
1303
                lseek( unix_handle, off + result, SEEK_SET );
1304

1305 1306 1307 1308
            total = result;
            status = STATUS_SUCCESS;
            goto done;
        }
1309
    }
1310
    else if (type == FD_TYPE_SERIAL || type == FD_TYPE_DEVICE)
1311
    {
1312
        if (async_write &&
1313
            (!offset || (offset->QuadPart < 0 && offset->QuadPart != FILE_WRITE_TO_END_OF_FILE)))
1314 1315 1316 1317 1318
        {
            status = STATUS_INVALID_PARAMETER;
            goto done;
        }
    }
1319 1320 1321

    for (;;)
    {
1322 1323 1324 1325 1326 1327 1328
        /* 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)
1329 1330 1331
        {
            total += result;
            if (total == length)
1332
            {
1333
                status = STATUS_SUCCESS;
1334 1335
                goto done;
            }
1336
            if (type == FD_TYPE_FILE) continue;  /* no async I/O on regular files */
1337
        }
1338
        else if (errno != EAGAIN)
1339
        {
1340
            if (errno == EINTR) continue;
1341
            if (!total)
1342
            {
1343 1344
                if (errno == EFAULT) status = STATUS_INVALID_USER_BUFFER;
                else status = FILE_GetNtStatus();
1345
            }
1346
            goto done;
1347
        }
1348

1349
        if (async_write)
1350
        {
1351
            struct async_fileio_write *fileio;
1352

1353 1354
            fileio = (struct async_fileio_write *)alloc_fileio( sizeof(*fileio), hFile, apc, apc_user );
            if (!fileio)
1355 1356
            {
                status = STATUS_NO_MEMORY;
1357
                goto err;
1358 1359 1360
            }
            fileio->already = total;
            fileio->count = length;
1361 1362 1363 1364 1365 1366
            fileio->buffer = buffer;

            SERVER_START_REQ( register_async )
            {
                req->type   = ASYNC_TYPE_WRITE;
                req->count  = length;
1367 1368
                req->async.handle   = wine_server_obj_handle( hFile );
                req->async.event    = wine_server_obj_handle( hEvent );
1369 1370 1371
                req->async.callback = wine_server_client_ptr( FILE_AsyncWriteService );
                req->async.iosb     = wine_server_client_ptr( io_status );
                req->async.arg      = wine_server_client_ptr( fileio );
1372
                req->async.cvalue   = cvalue;
1373 1374 1375 1376 1377
                status = wine_server_call( req );
            }
            SERVER_END_REQ;

            if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
1378
            goto err;
1379
        }
1380
        else  /* synchronous write, wait for the fd to become ready */
1381
        {
1382 1383 1384 1385 1386
            struct pollfd pfd;
            int ret, timeout;

            if (!timeout_init_done)
            {
1387
                timeout_init_done = TRUE;
1388
                if ((status = get_io_timeouts( hFile, type, length, FALSE, &timeouts )))
1389
                    goto err;
1390 1391 1392 1393 1394
                if (hEvent) NtResetEvent( hEvent, NULL );
            }
            timeout = get_next_io_timeout( &timeouts, total );

            pfd.fd = unix_handle;
1395
            pfd.events = POLLOUT;
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408

            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 */
1409
        }
1410 1411
    }

1412
done:
1413
    send_completion = cvalue != 0;
1414 1415

err:
1416
    if (needs_close) close( unix_handle );
1417 1418 1419 1420

    if (type == FD_TYPE_SERIAL && (status == STATUS_SUCCESS || status == STATUS_PENDING))
        set_pending_write( hFile );

1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
    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 );
    }
1435 1436 1437

    if (send_completion) NTDLL_AddCompletion( hFile, cvalue, status, total );

1438
    return status;
Juergen Schmied's avatar
Juergen Schmied committed
1439 1440
}

1441

1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
/******************************************************************************
 *  NtWriteFileGather   [NTDLL.@]
 *  ZwWriteFileGather   [NTDLL.@]
 */
NTSTATUS WINAPI NtWriteFileGather( HANDLE file, HANDLE event, PIO_APC_ROUTINE apc, void *apc_user,
                                   PIO_STATUS_BLOCK io_status, FILE_SEGMENT_ELEMENT *segments,
                                   ULONG length, PLARGE_INTEGER offset, PULONG key )
{
    int result, unix_handle, needs_close;
    unsigned int options;
    NTSTATUS status;
    ULONG pos = 0, total = 0;
    enum server_fd_type type;
    ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
1456
    BOOL send_completion = FALSE;
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477

    TRACE( "(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
           file, event, apc, apc_user, io_status, segments, length, offset, key);

    if (length % page_size) return STATUS_INVALID_PARAMETER;
    if (!io_status) return STATUS_ACCESS_VIOLATION;

    status = server_get_unix_fd( file, FILE_WRITE_DATA, &unix_handle,
                                 &needs_close, &type, &options );
    if (status) return status;

    if ((type != FD_TYPE_FILE) ||
        (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) ||
        !(options & FILE_NO_INTERMEDIATE_BUFFERING))
    {
        status = STATUS_INVALID_PARAMETER;
        goto error;
    }

    while (length)
    {
1478
        if (offset && offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
            result = pwrite( unix_handle, (char *)segments->Buffer + pos,
                             page_size - pos, offset->QuadPart + total );
        else
            result = write( unix_handle, (char *)segments->Buffer + pos, page_size - pos );

        if (result == -1)
        {
            if (errno == EINTR) continue;
            if (errno == EFAULT)
            {
                status = STATUS_INVALID_USER_BUFFER;
                goto error;
            }
            status = FILE_GetNtStatus();
            break;
        }
        if (!result)
        {
            status = STATUS_DISK_FULL;
            break;
        }
        total += result;
        length -= result;
        if ((pos += result) == page_size)
        {
            pos = 0;
            segments++;
        }
    }

1509
    send_completion = cvalue != 0;
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526

 error:
    if (needs_close) close( unix_handle );
    if (status == STATUS_SUCCESS)
    {
        io_status->u.Status = status;
        io_status->Information = total;
        TRACE("= SUCCESS (%u)\n", total);
        if (event) NtSetEvent( event, 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 && event) NtResetEvent( event, NULL );
    }
1527 1528 1529

    if (send_completion) NTDLL_AddCompletion( file, cvalue, status, total );

1530 1531 1532 1533
    return status;
}


1534
/* do an ioctl call through the server */
1535 1536 1537
static NTSTATUS server_ioctl_file( HANDLE handle, HANDLE event,
                                   PIO_APC_ROUTINE apc, PVOID apc_context,
                                   IO_STATUS_BLOCK *io, ULONG code,
1538
                                   const void *in_buffer, ULONG in_size,
1539 1540
                                   PVOID out_buffer, ULONG out_size )
{
1541
    struct async_irp *async;
1542
    NTSTATUS status;
1543 1544
    HANDLE wait_handle;
    ULONG options;
1545
    ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;
1546

1547
    if (!(async = (struct async_irp *)alloc_fileio( sizeof(*async), handle, apc, apc_context )))
1548
        return STATUS_NO_MEMORY;
1549
    async->event   = event;
1550 1551
    async->buffer  = out_buffer;
    async->size    = out_size;
1552

1553 1554 1555
    SERVER_START_REQ( ioctl )
    {
        req->code           = code;
1556
        req->blocking       = !apc && !event && !cvalue;
1557
        req->async.handle   = wine_server_obj_handle( handle );
1558
        req->async.callback = wine_server_client_ptr( irp_completion );
1559 1560
        req->async.iosb     = wine_server_client_ptr( io );
        req->async.arg      = wine_server_client_ptr( async );
1561
        req->async.event    = wine_server_obj_handle( event );
1562
        req->async.cvalue   = cvalue;
1563 1564
        wine_server_add_data( req, in_buffer, in_size );
        wine_server_set_reply( req, out_buffer, out_size );
1565
        status = wine_server_call( req );
1566
        wait_handle = wine_server_ptr_handle( reply->wait );
1567
        options     = reply->options;
1568
        if (status != STATUS_PENDING) io->Information = wine_server_reply_size( reply );
1569 1570 1571 1572 1573 1574 1575
    }
    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);

1576 1577
    if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, async );

1578 1579 1580 1581 1582 1583 1584
    if (wait_handle)
    {
        NtWaitForSingleObject( wait_handle, (options & FILE_SYNCHRONOUS_IO_ALERT), NULL );
        status = io->u.Status;
        NtClose( wait_handle );
    }

1585 1586 1587
    return status;
}

1588 1589 1590 1591 1592 1593 1594 1595
/* Tell Valgrind to ignore any holes in structs we will be passing to the
 * server */
static void ignore_server_ioctl_struct_holes (ULONG code, const void *in_buffer,
                                              ULONG in_size)
{
#ifdef VALGRIND_MAKE_MEM_DEFINED
# define IGNORE_STRUCT_HOLE(buf, size, t, f1, f2) \
    do { \
1596 1597 1598 1599 1600
        if (FIELD_OFFSET(t, f1) + sizeof(((t *)0)->f1) < FIELD_OFFSET(t, f2)) \
            if ((size) >= FIELD_OFFSET(t, f2)) \
                VALGRIND_MAKE_MEM_DEFINED( \
                    (const char *)(buf) + FIELD_OFFSET(t, f1) + sizeof(((t *)0)->f1), \
                    FIELD_OFFSET(t, f2) - FIELD_OFFSET(t, f1) + sizeof(((t *)0)->f1)); \
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
    } while (0)

    switch (code)
    {
    case FSCTL_PIPE_WAIT:
        IGNORE_STRUCT_HOLE(in_buffer, in_size, FILE_PIPE_WAIT_FOR_BUFFER, TimeoutSpecified, Name);
        break;
    }
#endif
}

1612

Juergen Schmied's avatar
Juergen Schmied committed
1613
/**************************************************************************
1614
 *		NtDeviceIoControlFile			[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
1615
 *		ZwDeviceIoControlFile			[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
1616 1617 1618 1619
 *
 * Perform an I/O control operation on an open file handle.
 *
 * PARAMS
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
 *  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
1630 1631 1632 1633
 *
 * RETURNS
 *  Success: 0. IoStatusBlock is updated.
 *  Failure: An NTSTATUS error code describing the error.
Juergen Schmied's avatar
Juergen Schmied committed
1634
 */
1635 1636 1637 1638 1639
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
1640
{
1641
    ULONG device = (code >> 16);
1642
    NTSTATUS status = STATUS_NOT_SUPPORTED;
1643

1644
    TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1645 1646 1647 1648
          handle, event, apc, apc_context, io, code,
          in_buffer, in_size, out_buffer, out_size);

    switch(device)
1649
    {
1650 1651 1652 1653 1654
    case FILE_DEVICE_DISK:
    case FILE_DEVICE_CD_ROM:
    case FILE_DEVICE_DVD:
    case FILE_DEVICE_CONTROLLER:
    case FILE_DEVICE_MASS_STORAGE:
1655 1656
        status = CDROM_DeviceIoControl(handle, event, apc, apc_context, io, code,
                                       in_buffer, in_size, out_buffer, out_size);
1657 1658
        break;
    case FILE_DEVICE_SERIAL_PORT:
1659 1660
        status = COMM_DeviceIoControl(handle, event, apc, apc_context, io, code,
                                      in_buffer, in_size, out_buffer, out_size);
1661
        break;
1662
    case FILE_DEVICE_TAPE:
1663 1664
        status = TAPE_DeviceIoControl(handle, event, apc, apc_context, io, code,
                                      in_buffer, in_size, out_buffer, out_size);
1665
        break;
1666 1667
    }

1668
    if (status == STATUS_NOT_SUPPORTED || status == STATUS_BAD_DEVICE_TYPE)
1669 1670
        status = server_ioctl_file( handle, event, apc, apc_context, io, code,
                                    in_buffer, in_size, out_buffer, out_size );
1671

1672 1673
    if (status != STATUS_PENDING) io->u.Status = status;
    return status;
Juergen Schmied's avatar
Juergen Schmied committed
1674 1675
}

1676 1677 1678 1679 1680 1681 1682 1683

/**************************************************************************
 *              NtFsControlFile                 [NTDLL.@]
 *              ZwFsControlFile                 [NTDLL.@]
 *
 * Perform a file system control operation on an open file handle.
 *
 * PARAMS
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693
 *  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
1694 1695 1696 1697
 *
 * RETURNS
 *  Success: 0. IoStatusBlock is updated.
 *  Failure: An NTSTATUS error code describing the error.
Juergen Schmied's avatar
Juergen Schmied committed
1698
 */
1699 1700 1701
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
1702
{
1703 1704
    NTSTATUS status;

1705
    TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1706 1707
          handle, event, apc, apc_context, io, code,
          in_buffer, in_size, out_buffer, out_size);
1708

1709
    if (!io) return STATUS_INVALID_PARAMETER;
1710

1711 1712
    ignore_server_ioctl_struct_holes( code, in_buffer, in_size );

1713
    switch(code)
1714
    {
1715
    case FSCTL_DISMOUNT_VOLUME:
1716 1717 1718
        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 );
1719
        break;
1720

1721 1722 1723
    case FSCTL_PIPE_PEEK:
        {
            FILE_PIPE_PEEK_BUFFER *buffer = out_buffer;
1724
            int avail = 0, fd, needs_close;
1725 1726 1727

            if (out_size < FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data ))
            {
1728
                status = STATUS_INFO_LENGTH_MISMATCH;
1729 1730 1731
                break;
            }

1732
            if ((status = server_get_unix_fd( handle, FILE_READ_DATA, &fd, &needs_close, NULL, NULL )))
1733 1734 1735 1736 1737 1738
                break;

#ifdef FIONREAD
            if (ioctl( fd, FIONREAD, &avail ) != 0)
            {
                TRACE("FIONREAD failed reason: %s\n",strerror(errno));
1739
                if (needs_close) close( fd );
1740
                status = FILE_GetNtStatus();
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
                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))))
                {
1755
                    if (needs_close) close( fd );
1756
                    status = STATUS_PIPE_BROKEN;
1757 1758 1759 1760 1761 1762 1763 1764
                    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 );
1765
            status = STATUS_SUCCESS;
1766 1767 1768 1769 1770 1771 1772 1773 1774
            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;
                }
            }
1775
            if (needs_close) close( fd );
1776 1777 1778
        }
        break;

1779
    case FSCTL_PIPE_DISCONNECT:
1780 1781 1782
        status = server_ioctl_file( handle, event, apc, apc_context, io, code,
                                    in_buffer, in_size, out_buffer, out_size );
        if (!status)
1783
        {
1784 1785
            int fd = server_remove_fd_from_cache( handle );
            if (fd != -1) close( fd );
1786 1787 1788
        }
        break;

1789 1790 1791 1792 1793
    case FSCTL_PIPE_LISTEN:
        status = server_ioctl_file( handle, event, apc, apc_context, io, code,
                                    in_buffer, in_size, out_buffer, out_size );
        return status;

1794
    case FSCTL_PIPE_IMPERSONATE:
1795
        FIXME("FSCTL_PIPE_IMPERSONATE: impersonating self\n");
1796 1797 1798
        status = RtlImpersonateSelf( SecurityImpersonation );
        break;

1799
    case FSCTL_IS_VOLUME_MOUNTED:
1800 1801
    case FSCTL_LOCK_VOLUME:
    case FSCTL_UNLOCK_VOLUME:
1802
        FIXME("stub! return success - Unsupported fsctl %x (device=%x access=%x func=%x method=%x)\n",
1803
              code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
1804
        status = STATUS_SUCCESS;
1805 1806
        break;

1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828
    case FSCTL_GET_RETRIEVAL_POINTERS:
    {
        RETRIEVAL_POINTERS_BUFFER *buffer = (RETRIEVAL_POINTERS_BUFFER *)out_buffer;

        FIXME("stub: FSCTL_GET_RETRIEVAL_POINTERS\n");

        if (out_size >= sizeof(RETRIEVAL_POINTERS_BUFFER))
        {
            buffer->ExtentCount                 = 1;
            buffer->StartingVcn.QuadPart        = 1;
            buffer->Extents[0].NextVcn.QuadPart = 0;
            buffer->Extents[0].Lcn.QuadPart     = 0;
            io->Information = sizeof(RETRIEVAL_POINTERS_BUFFER);
            status = STATUS_SUCCESS;
        }
        else
        {
            io->Information = 0;
            status = STATUS_BUFFER_TOO_SMALL;
        }
        break;
    }
1829 1830 1831 1832 1833
    case FSCTL_SET_SPARSE:
        TRACE("FSCTL_SET_SPARSE: Ignoring request\n");
        io->Information = 0;
        status = STATUS_SUCCESS;
        break;
1834
    case FSCTL_PIPE_WAIT:
1835
    default:
1836 1837
        status = server_ioctl_file( handle, event, apc, apc_context, io, code,
                                    in_buffer, in_size, out_buffer, out_size );
1838
        break;
1839
    }
1840 1841 1842

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

1845 1846 1847 1848 1849 1850 1851 1852 1853 1854

struct read_changes_fileio
{
    struct async_fileio io;
    void               *buffer;
    ULONG               buffer_size;
    ULONG               data_size;
    char                data[1];
};

1855 1856
static NTSTATUS read_changes_apc( void *user, IO_STATUS_BLOCK *iosb,
                                  NTSTATUS status, void **apc, void **arg )
1857 1858
{
    struct read_changes_fileio *fileio = user;
1859
    int size = 0;
1860

1861
    if (status == STATUS_ALERTED)
1862
    {
1863
        SERVER_START_REQ( read_change )
1864
        {
1865 1866 1867 1868
            req->handle = wine_server_obj_handle( fileio->io.handle );
            wine_server_set_reply( req, fileio->data, fileio->data_size );
            status = wine_server_call( req );
            size = wine_server_reply_size( reply );
1869
        }
1870
        SERVER_END_REQ;
1871

1872
        if (status == STATUS_SUCCESS && fileio->buffer)
1873
        {
1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913
            FILE_NOTIFY_INFORMATION *pfni = fileio->buffer;
            int i, left = fileio->buffer_size;
            DWORD *last_entry_offset = NULL;
            struct filesystem_event *event = (struct filesystem_event*)fileio->data;

            while (size && left >= sizeof(*pfni))
            {
                /* convert to an NT style path */
                for (i = 0; i < event->len; i++)
                    if (event->name[i] == '/') event->name[i] = '\\';

                pfni->Action = event->action;
                pfni->FileNameLength = ntdll_umbstowcs( 0, event->name, event->len, pfni->FileName,
                             (left - offsetof(FILE_NOTIFY_INFORMATION, FileName)) / sizeof(WCHAR));
                last_entry_offset = &pfni->NextEntryOffset;

                if (pfni->FileNameLength == -1 || pfni->FileNameLength == -2) break;

                i = offsetof(FILE_NOTIFY_INFORMATION, FileName[pfni->FileNameLength]);
                pfni->FileNameLength *= sizeof(WCHAR);
                pfni->NextEntryOffset = i;
                pfni = (FILE_NOTIFY_INFORMATION*)((char*)pfni + i);
                left -= i;

                i = (offsetof(struct filesystem_event, name[event->len])
                     + sizeof(int)-1) / sizeof(int) * sizeof(int);
                event = (struct filesystem_event*)((char*)event + i);
                size -= i;
            }

            if (size)
            {
                status = STATUS_NOTIFY_ENUM_DIR;
                size = 0;
            }
            else
            {
                if (last_entry_offset) *last_entry_offset = 0;
                size = fileio->buffer_size - left;
            }
1914 1915 1916
        }
        else
        {
1917 1918
            status = STATUS_NOTIFY_ENUM_DIR;
            size = 0;
1919 1920
        }
    }
1921 1922

    if (status != STATUS_PENDING)
1923
    {
1924 1925 1926 1927 1928
        iosb->u.Status = status;
        iosb->Information = size;
        *apc = fileio->io.apc;
        *arg = fileio->io.apc_arg;
        release_fileio( &fileio->io );
1929
    }
1930
    return status;
1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
}

#define FILE_NOTIFY_ALL        (  \
 FILE_NOTIFY_CHANGE_FILE_NAME   | \
 FILE_NOTIFY_CHANGE_DIR_NAME    | \
 FILE_NOTIFY_CHANGE_ATTRIBUTES  | \
 FILE_NOTIFY_CHANGE_SIZE        | \
 FILE_NOTIFY_CHANGE_LAST_WRITE  | \
 FILE_NOTIFY_CHANGE_LAST_ACCESS | \
 FILE_NOTIFY_CHANGE_CREATION    | \
 FILE_NOTIFY_CHANGE_SECURITY   )

/******************************************************************************
 *  NtNotifyChangeDirectoryFile [NTDLL.@]
 */
NTSTATUS WINAPI NtNotifyChangeDirectoryFile( HANDLE handle, HANDLE event, PIO_APC_ROUTINE apc,
                                             void *apc_context, PIO_STATUS_BLOCK iosb, void *buffer,
                                             ULONG buffer_size, ULONG filter, BOOLEAN subtree )
{
    struct read_changes_fileio *fileio;
    NTSTATUS status;
    ULONG size = max( 4096, buffer_size );
    ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;

    TRACE( "%p %p %p %p %p %p %u %u %d\n",
           handle, event, apc, apc_context, iosb, buffer, buffer_size, filter, subtree );

    if (!iosb) return STATUS_ACCESS_VIOLATION;
    if (filter == 0 || (filter & ~FILE_NOTIFY_ALL)) return STATUS_INVALID_PARAMETER;

1961 1962 1963
    fileio = (struct read_changes_fileio *)alloc_fileio( offsetof(struct read_changes_fileio, data[size]),
                                                         handle, apc, apc_context );
    if (!fileio) return STATUS_NO_MEMORY;
1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987

    fileio->buffer      = buffer;
    fileio->buffer_size = buffer_size;
    fileio->data_size   = size;

    SERVER_START_REQ( read_directory_changes )
    {
        req->filter         = filter;
        req->want_data      = (buffer != NULL);
        req->subtree        = subtree;
        req->async.handle   = wine_server_obj_handle( handle );
        req->async.callback = wine_server_client_ptr( read_changes_apc );
        req->async.iosb     = wine_server_client_ptr( iosb );
        req->async.arg      = wine_server_client_ptr( fileio );
        req->async.event    = wine_server_obj_handle( event );
        req->async.cvalue   = cvalue;
        status = wine_server_call( req );
    }
    SERVER_END_REQ;

    if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
    return status;
}

Juergen Schmied's avatar
Juergen Schmied committed
1988
/******************************************************************************
1989
 *  NtSetVolumeInformationFile		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
1990
 *  ZwSetVolumeInformationFile		[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
 *
 * 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
2004 2005 2006
 */
NTSTATUS WINAPI NtSetVolumeInformationFile(
	IN HANDLE FileHandle,
2007 2008 2009
	PIO_STATUS_BLOCK IoStatusBlock,
	PVOID FsInformation,
        ULONG Length,
2010
	FS_INFORMATION_CLASS FsInformationClass)
Juergen Schmied's avatar
Juergen Schmied committed
2011
{
2012
	FIXME("(%p,%p,%p,0x%08x,0x%08x) stub\n",
2013
	FileHandle,IoStatusBlock,FsInformation,Length,FsInformationClass);
Juergen Schmied's avatar
Juergen Schmied committed
2014 2015 2016
	return 0;
}

2017 2018 2019 2020 2021 2022 2023 2024
#if defined(__ANDROID__) && !defined(HAVE_FUTIMENS)
static int futimens( int fd, const struct timespec spec[2] )
{
    return syscall( __NR_utimensat, fd, NULL, spec, 0 );
}
#define HAVE_FUTIMENS
#endif  /* __ANDROID__ */

2025 2026 2027 2028
#ifndef UTIME_OMIT
#define UTIME_OMIT ((1 << 30) - 2)
#endif

2029 2030
static NTSTATUS set_file_times( int fd, const LARGE_INTEGER *mtime, const LARGE_INTEGER *atime )
{
2031 2032
    NTSTATUS status = STATUS_SUCCESS;

2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
#ifdef HAVE_FUTIMENS
    struct timespec tv[2];

    tv[0].tv_sec = tv[1].tv_sec = 0;
    tv[0].tv_nsec = tv[1].tv_nsec = UTIME_OMIT;
    if (atime->QuadPart)
    {
        tv[0].tv_sec = atime->QuadPart / 10000000 - SECS_1601_TO_1970;
        tv[0].tv_nsec = (atime->QuadPart % 10000000) * 100;
    }
    if (mtime->QuadPart)
    {
        tv[1].tv_sec = mtime->QuadPart / 10000000 - SECS_1601_TO_1970;
        tv[1].tv_nsec = (mtime->QuadPart % 10000000) * 100;
    }
    if (futimens( fd, tv ) == -1) status = FILE_GetNtStatus();

#elif defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT)
2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
    struct timeval tv[2];
    struct stat st;

    if (!atime->QuadPart || !mtime->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;
#ifdef HAVE_STRUCT_STAT_ST_ATIM
            tv[0].tv_usec = st.st_atim.tv_nsec / 1000;
2065 2066
#elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC)
            tv[0].tv_usec = st.st_atimespec.tv_nsec / 1000;
2067 2068 2069
#endif
#ifdef HAVE_STRUCT_STAT_ST_MTIM
            tv[1].tv_usec = st.st_mtim.tv_nsec / 1000;
2070 2071
#elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC)
            tv[1].tv_usec = st.st_mtimespec.tv_nsec / 1000;
2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
#endif
        }
    }
    if (atime->QuadPart)
    {
        tv[0].tv_sec = atime->QuadPart / 10000000 - SECS_1601_TO_1970;
        tv[0].tv_usec = (atime->QuadPart % 10000000) / 10;
    }
    if (mtime->QuadPart)
    {
        tv[1].tv_sec = mtime->QuadPart / 10000000 - SECS_1601_TO_1970;
        tv[1].tv_usec = (mtime->QuadPart % 10000000) / 10;
    }
2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
#ifdef HAVE_FUTIMES
    if (futimes( fd, tv ) == -1) status = FILE_GetNtStatus();
#elif defined(HAVE_FUTIMESAT)
    if (futimesat( fd, NULL, tv ) == -1) status = FILE_GetNtStatus();
#endif

#else  /* HAVE_FUTIMES || HAVE_FUTIMESAT */
    FIXME( "setting file times not supported\n" );
    status = STATUS_NOT_IMPLEMENTED;
#endif
    return status;
2096 2097
}

2098 2099 2100 2101 2102 2103 2104 2105
static inline void get_file_times( const struct stat *st, LARGE_INTEGER *mtime, LARGE_INTEGER *ctime,
                                   LARGE_INTEGER *atime, LARGE_INTEGER *creation )
{
    RtlSecondsSince1970ToTime( st->st_mtime, mtime );
    RtlSecondsSince1970ToTime( st->st_ctime, ctime );
    RtlSecondsSince1970ToTime( st->st_atime, atime );
#ifdef HAVE_STRUCT_STAT_ST_MTIM
    mtime->QuadPart += st->st_mtim.tv_nsec / 100;
2106 2107
#elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC)
    mtime->QuadPart += st->st_mtimespec.tv_nsec / 100;
2108 2109 2110
#endif
#ifdef HAVE_STRUCT_STAT_ST_CTIM
    ctime->QuadPart += st->st_ctim.tv_nsec / 100;
2111 2112
#elif defined(HAVE_STRUCT_STAT_ST_CTIMESPEC)
    ctime->QuadPart += st->st_ctimespec.tv_nsec / 100;
2113 2114 2115
#endif
#ifdef HAVE_STRUCT_STAT_ST_ATIM
    atime->QuadPart += st->st_atim.tv_nsec / 100;
2116 2117
#elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC)
    atime->QuadPart += st->st_atimespec.tv_nsec / 100;
2118
#endif
2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131
#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
    RtlSecondsSince1970ToTime( st->st_birthtime, creation );
#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIM
    creation->QuadPart += st->st_birthtim.tv_nsec / 100;
#elif defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC)
    creation->QuadPart += st->st_birthtimespec.tv_nsec / 100;
#endif
#elif defined(HAVE_STRUCT_STAT___ST_BIRTHTIME)
    RtlSecondsSince1970ToTime( st->__st_birthtime, creation );
#ifdef HAVE_STRUCT_STAT___ST_BIRTHTIM
    creation->QuadPart += st->__st_birthtim.tv_nsec / 100;
#endif
#else
2132
    *creation = *mtime;
2133
#endif
2134 2135
}

2136 2137 2138
/* fill in the file information that depends on the stat and attribute info */
NTSTATUS fill_file_info( const struct stat *st, ULONG attr, void *ptr,
                         FILE_INFORMATION_CLASS class )
2139 2140 2141 2142 2143 2144 2145
{
    switch (class)
    {
    case FileBasicInformation:
        {
            FILE_BASIC_INFORMATION *info = ptr;

2146 2147
            get_file_times( st, &info->LastWriteTime, &info->ChangeTime,
                            &info->LastAccessTime, &info->CreationTime );
2148
            info->FileAttributes = attr;
2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
        }
        break;
    case FileStandardInformation:
        {
            FILE_STANDARD_INFORMATION *info = ptr;

            if ((info->Directory = S_ISDIR(st->st_mode)))
            {
                info->AllocationSize.QuadPart = 0;
                info->EndOfFile.QuadPart      = 0;
                info->NumberOfLinks           = 1;
            }
            else
            {
                info->AllocationSize.QuadPart = (ULONGLONG)st->st_blocks * 512;
                info->EndOfFile.QuadPart      = st->st_size;
                info->NumberOfLinks           = st->st_nlink;
            }
        }
        break;
    case FileInternalInformation:
        {
            FILE_INTERNAL_INFORMATION *info = ptr;
            info->IndexNumber.QuadPart = st->st_ino;
        }
        break;
    case FileEndOfFileInformation:
        {
            FILE_END_OF_FILE_INFORMATION *info = ptr;
            info->EndOfFile.QuadPart = S_ISDIR(st->st_mode) ? 0 : st->st_size;
        }
        break;
    case FileAllInformation:
        {
            FILE_ALL_INFORMATION *info = ptr;
2184 2185 2186
            fill_file_info( st, attr, &info->BasicInformation, FileBasicInformation );
            fill_file_info( st, attr, &info->StandardInformation, FileStandardInformation );
            fill_file_info( st, attr, &info->InternalInformation, FileInternalInformation );
2187 2188
        }
        break;
2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
    /* all directory structures start with the FileDirectoryInformation layout */
    case FileBothDirectoryInformation:
    case FileFullDirectoryInformation:
    case FileDirectoryInformation:
        {
            FILE_DIRECTORY_INFORMATION *info = ptr;

            get_file_times( st, &info->LastWriteTime, &info->ChangeTime,
                            &info->LastAccessTime, &info->CreationTime );
            if (S_ISDIR(st->st_mode))
            {
                info->AllocationSize.QuadPart = 0;
                info->EndOfFile.QuadPart      = 0;
            }
            else
            {
                info->AllocationSize.QuadPart = (ULONGLONG)st->st_blocks * 512;
                info->EndOfFile.QuadPart      = st->st_size;
            }
2208
            info->FileAttributes = attr;
2209 2210 2211 2212 2213 2214
        }
        break;
    case FileIdFullDirectoryInformation:
        {
            FILE_ID_FULL_DIRECTORY_INFORMATION *info = ptr;
            info->FileId.QuadPart = st->st_ino;
2215
            fill_file_info( st, attr, info, FileDirectoryInformation );
2216 2217 2218 2219 2220 2221
        }
        break;
    case FileIdBothDirectoryInformation:
        {
            FILE_ID_BOTH_DIRECTORY_INFORMATION *info = ptr;
            info->FileId.QuadPart = st->st_ino;
2222
            fill_file_info( st, attr, info, FileDirectoryInformation );
2223 2224
        }
        break;
2225 2226 2227 2228 2229 2230 2231
    case FileIdGlobalTxDirectoryInformation:
        {
            FILE_ID_GLOBAL_TX_DIR_INFORMATION *info = ptr;
            info->FileId.QuadPart = st->st_ino;
            fill_file_info( st, attr, info, FileDirectoryInformation );
        }
        break;
2232 2233 2234 2235 2236 2237 2238

    default:
        return STATUS_INVALID_INFO_CLASS;
    }
    return STATUS_SUCCESS;
}

2239
NTSTATUS server_get_unix_name( HANDLE handle, ANSI_STRING *unix_name )
2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272
{
    data_size_t size = 1024;
    NTSTATUS ret;
    char *name;

    for (;;)
    {
        name = RtlAllocateHeap( GetProcessHeap(), 0, size + 1 );
        if (!name) return STATUS_NO_MEMORY;
        unix_name->MaximumLength = size + 1;

        SERVER_START_REQ( get_handle_unix_name )
        {
            req->handle = wine_server_obj_handle( handle );
            wine_server_set_reply( req, name, size );
            ret = wine_server_call( req );
            size = reply->name_len;
        }
        SERVER_END_REQ;

        if (!ret)
        {
            name[size] = 0;
            unix_name->Buffer = name;
            unix_name->Length = size;
            break;
        }
        RtlFreeHeap( GetProcessHeap(), 0, name );
        if (ret != STATUS_BUFFER_OVERFLOW) break;
    }
    return ret;
}

2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299
static NTSTATUS fill_name_info( const ANSI_STRING *unix_name, FILE_NAME_INFORMATION *info, LONG *name_len )
{
    UNICODE_STRING nt_name;
    NTSTATUS status;

    if (!(status = wine_unix_to_nt_file_name( unix_name, &nt_name )))
    {
        const WCHAR *ptr = nt_name.Buffer;
        const WCHAR *end = ptr + (nt_name.Length / sizeof(WCHAR));

        /* Skip the volume mount point. */
        while (ptr != end && *ptr == '\\') ++ptr;
        while (ptr != end && *ptr != '\\') ++ptr;
        while (ptr != end && *ptr == '\\') ++ptr;
        while (ptr != end && *ptr != '\\') ++ptr;

        info->FileNameLength = (end - ptr) * sizeof(WCHAR);
        if (*name_len < info->FileNameLength) status = STATUS_BUFFER_OVERFLOW;
        else *name_len = info->FileNameLength;

        memcpy( info->FileName, ptr, *name_len );
        RtlFreeUnicodeString( &nt_name );
    }

    return status;
}

Juergen Schmied's avatar
Juergen Schmied committed
2300
/******************************************************************************
2301
 *  NtQueryInformationFile		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
2302
 *  ZwQueryInformationFile		[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
2303 2304 2305 2306
 *
 * Get information about an open file handle.
 *
 * PARAMS
2307 2308 2309 2310 2311
 *  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
2312 2313 2314 2315
 *
 * RETURNS
 *  Success: 0. IoStatusBlock and FileInformation are updated.
 *  Failure: An NTSTATUS error code describing the error.
Juergen Schmied's avatar
Juergen Schmied committed
2316
 */
2317 2318
NTSTATUS WINAPI NtQueryInformationFile( HANDLE hFile, PIO_STATUS_BLOCK io,
                                        PVOID ptr, LONG len, FILE_INFORMATION_CLASS class )
Juergen Schmied's avatar
Juergen Schmied committed
2319
{
2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330
    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 */
2331
        sizeof(FILE_NAME_INFORMATION),                 /* FileNameInformation */
2332 2333 2334 2335 2336 2337 2338 2339
        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 */
2340
        sizeof(FILE_ALL_INFORMATION),                  /* FileAllInformation */
2341 2342 2343 2344
        sizeof(FILE_ALLOCATION_INFORMATION),           /* FileAllocationInformation */
        sizeof(FILE_END_OF_FILE_INFORMATION),          /* FileEndOfFileInformation */
        0,                                             /* FileAlternateNameInformation */
        sizeof(FILE_STREAM_INFORMATION)-sizeof(WCHAR), /* FileStreamInformation */
2345
        sizeof(FILE_PIPE_INFORMATION),                 /* FilePipeInformation */
2346
        sizeof(FILE_PIPE_LOCAL_INFORMATION),           /* FilePipeLocalInformation */
2347
        0,                                             /* FilePipeRemoteInformation */
2348
        sizeof(FILE_MAILSLOT_QUERY_INFORMATION),       /* FileMailslotQueryInformation */
2349 2350 2351 2352 2353 2354 2355
        0,                                             /* FileMailslotSetInformation */
        0,                                             /* FileCompressionInformation */
        0,                                             /* FileObjectIdInformation */
        0,                                             /* FileCompletionInformation */
        0,                                             /* FileMoveClusterInformation */
        0,                                             /* FileQuotaInformation */
        0,                                             /* FileReparsePointInformation */
2356
        sizeof(FILE_NETWORK_OPEN_INFORMATION),         /* FileNetworkOpenInformation */
2357
        0,                                             /* FileAttributeTagInformation */
2358 2359 2360 2361 2362
        0,                                             /* FileTrackingInformation */
        0,                                             /* FileIdBothDirectoryInformation */
        0,                                             /* FileIdFullDirectoryInformation */
        0,                                             /* FileValidDataLengthInformation */
        0,                                             /* FileShortNameInformation */
2363 2364 2365
        0,                                             /* FileIoCompletionNotificationInformation, */
        0,                                             /* FileIoStatusBlockRangeInformation */
        0,                                             /* FileIoPriorityHintInformation */
2366 2367 2368
        0,                                             /* FileSfioReserveInformation */
        0,                                             /* FileSfioVolumeInformation */
        0,                                             /* FileHardLinkInformation */
2369
        0,                                             /* FileProcessIdsUsingFileInformation */
2370
        0,                                             /* FileNormalizedNameInformation */
2371
        0,                                             /* FileNetworkPhysicalNameInformation */
2372
        0,                                             /* FileIdGlobalTxDirectoryInformation */
2373 2374 2375 2376 2377 2378
        0,                                             /* FileIsRemoteDeviceInformation */
        0,                                             /* FileAttributeCacheInformation */
        0,                                             /* FileNumaNodeInformation */
        0,                                             /* FileStandardLinkInformation */
        0,                                             /* FileRemoteProtocolInformation */
        0,                                             /* FileReplaceCompletionInformation */
2379 2380 2381
    };

    struct stat st;
2382
    int fd, needs_close = FALSE;
2383
    ULONG attr;
2384

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

2387
    io->Information = 0;
2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398

    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;

2399
    if (class != FilePipeInformation && class != FilePipeLocalInformation)
2400
    {
2401
        if ((io->u.Status = server_get_unix_fd( hFile, 0, &fd, &needs_close, NULL, NULL )))
2402
            return io->u.Status;
2403
    }
2404 2405 2406 2407

    switch (class)
    {
    case FileBasicInformation:
2408
        if (fd_get_file_info( fd, &st, &attr ) == -1)
2409 2410 2411 2412
            io->u.Status = FILE_GetNtStatus();
        else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
            io->u.Status = STATUS_INVALID_INFO_CLASS;
        else
2413
            fill_file_info( &st, attr, ptr, class );
2414 2415 2416
        break;
    case FileStandardInformation:
        {
2417
            FILE_STANDARD_INFORMATION *info = ptr;
2418

2419
            if (fd_get_file_info( fd, &st, &attr ) == -1) io->u.Status = FILE_GetNtStatus();
2420
            else
2421
            {
2422
                fill_file_info( &st, attr, info, class );
2423
                info->DeletePending = FALSE; /* FIXME */
2424 2425 2426 2427 2428
            }
        }
        break;
    case FilePositionInformation:
        {
2429
            FILE_POSITION_INFORMATION *info = ptr;
2430 2431 2432 2433 2434 2435
            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:
2436 2437
        if (fd_get_file_info( fd, &st, &attr ) == -1) io->u.Status = FILE_GetNtStatus();
        else fill_file_info( &st, attr, ptr, class );
2438 2439 2440 2441 2442 2443 2444 2445
        break;
    case FileEaInformation:
        {
            FILE_EA_INFORMATION *info = ptr;
            info->EaSize = 0;
        }
        break;
    case FileEndOfFileInformation:
2446 2447
        if (fd_get_file_info( fd, &st, &attr ) == -1) io->u.Status = FILE_GetNtStatus();
        else fill_file_info( &st, attr, ptr, class );
2448 2449 2450 2451
        break;
    case FileAllInformation:
        {
            FILE_ALL_INFORMATION *info = ptr;
2452
            ANSI_STRING unix_name;
2453

2454
            if (fd_get_file_info( fd, &st, &attr ) == -1) io->u.Status = FILE_GetNtStatus();
2455 2456
            else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
                io->u.Status = STATUS_INVALID_INFO_CLASS;
2457
            else if (!(io->u.Status = server_get_unix_name( hFile, &unix_name )))
2458
            {
2459 2460
                LONG name_len = len - FIELD_OFFSET(FILE_ALL_INFORMATION, NameInformation.FileName);

2461
                fill_file_info( &st, attr, info, FileAllInformation );
2462
                info->StandardInformation.DeletePending = FALSE; /* FIXME */
2463 2464 2465 2466 2467
                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 */
2468 2469 2470 2471

                io->u.Status = fill_name_info( &unix_name, &info->NameInformation, &name_len );
                RtlFreeAnsiString( &unix_name );
                io->Information = FIELD_OFFSET(FILE_ALL_INFORMATION, NameInformation.FileName) + name_len;
2472 2473 2474
            }
        }
        break;
2475 2476 2477 2478 2479 2480
    case FileMailslotQueryInformation:
        {
            FILE_MAILSLOT_QUERY_INFORMATION *info = ptr;

            SERVER_START_REQ( set_mailslot_info )
            {
2481
                req->handle = wine_server_obj_handle( hFile );
2482 2483 2484 2485 2486 2487
                req->flags = 0;
                io->u.Status = wine_server_call( req );
                if( io->u.Status == STATUS_SUCCESS )
                {
                    info->MaximumMessageSize = reply->max_msgsize;
                    info->MailslotQuota = 0;
2488 2489
                    info->NextMessageSize = 0;
                    info->MessagesAvailable = 0;
2490
                    info->ReadTimeout.QuadPart = reply->read_timeout;
2491 2492 2493
                }
            }
            SERVER_END_REQ;
2494 2495
            if (!io->u.Status)
            {
2496
                char *tmpbuf;
2497
                ULONG size = info->MaximumMessageSize ? info->MaximumMessageSize : 0x10000;
2498 2499
                if (size > 0x10000) size = 0x10000;
                if ((tmpbuf = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2500
                {
2501
                    if (!server_get_unix_fd( hFile, FILE_READ_DATA, &fd, &needs_close, NULL, NULL ))
2502 2503 2504 2505 2506 2507 2508 2509 2510
                    {
                        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 );
                }
            }
2511 2512
        }
        break;
2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530
    case FilePipeInformation:
        {
            FILE_PIPE_INFORMATION* pi = ptr;

            SERVER_START_REQ( get_named_pipe_info )
            {
                req->handle = wine_server_obj_handle( hFile );
                if (!(io->u.Status = wine_server_call( req )))
                {
                    pi->ReadMode       = (reply->flags & NAMED_PIPE_MESSAGE_STREAM_READ) ?
                        FILE_PIPE_MESSAGE_MODE : FILE_PIPE_BYTE_STREAM_MODE;
                    pi->CompletionMode = (reply->flags & NAMED_PIPE_NONBLOCKING_MODE) ?
                        FILE_PIPE_COMPLETE_OPERATION : FILE_PIPE_QUEUE_OPERATION;
                }
            }
            SERVER_END_REQ;
        }
        break;
2531 2532 2533 2534 2535 2536
    case FilePipeLocalInformation:
        {
            FILE_PIPE_LOCAL_INFORMATION* pli = ptr;

            SERVER_START_REQ( get_named_pipe_info )
            {
2537
                req->handle = wine_server_obj_handle( hFile );
2538 2539 2540 2541
                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;
2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553
                    switch (reply->sharing)
                    {
                        case FILE_SHARE_READ:
                            pli->NamedPipeConfiguration = FILE_PIPE_OUTBOUND;
                            break;
                        case FILE_SHARE_WRITE:
                            pli->NamedPipeConfiguration = FILE_PIPE_INBOUND;
                            break;
                        case FILE_SHARE_READ | FILE_SHARE_WRITE:
                            pli->NamedPipeConfiguration = FILE_PIPE_FULL_DUPLEX;
                            break;
                    }
2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567
                    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;
2568 2569 2570 2571 2572 2573 2574 2575
    case FileNameInformation:
        {
            FILE_NAME_INFORMATION *info = ptr;
            ANSI_STRING unix_name;

            if (!(io->u.Status = server_get_unix_name( hFile, &unix_name )))
            {
                LONG name_len = len - FIELD_OFFSET(FILE_NAME_INFORMATION, FileName);
2576
                io->u.Status = fill_name_info( &unix_name, info, &name_len );
2577
                RtlFreeAnsiString( &unix_name );
2578
                io->Information = FIELD_OFFSET(FILE_NAME_INFORMATION, FileName) + name_len;
2579 2580 2581
            }
        }
        break;
2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615
    case FileNetworkOpenInformation:
        {
            FILE_NETWORK_OPEN_INFORMATION *info = ptr;
            ANSI_STRING unix_name;

            if (!(io->u.Status = server_get_unix_name( hFile, &unix_name )))
            {
                ULONG attributes;
                struct stat st;

                if (get_file_info( unix_name.Buffer, &st, &attributes ) == -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;
                else
                {
                    FILE_BASIC_INFORMATION basic;
                    FILE_STANDARD_INFORMATION std;

                    fill_file_info( &st, attributes, &basic, FileBasicInformation );
                    fill_file_info( &st, attributes, &std, FileStandardInformation );

                    info->CreationTime   = basic.CreationTime;
                    info->LastAccessTime = basic.LastAccessTime;
                    info->LastWriteTime  = basic.LastWriteTime;
                    info->ChangeTime     = basic.ChangeTime;
                    info->AllocationSize = std.AllocationSize;
                    info->EndOfFile      = std.EndOfFile;
                    info->FileAttributes = basic.FileAttributes;
                }
                RtlFreeAnsiString( &unix_name );
            }
        }
        break;
2616 2617
    default:
        FIXME("Unsupported class (%d)\n", class);
2618 2619
        io->u.Status = STATUS_NOT_IMPLEMENTED;
        break;
2620
    }
2621
    if (needs_close) close( fd );
2622
    if (io->u.Status == STATUS_SUCCESS && !io->Information) io->Information = info_sizes[class];
2623
    return io->u.Status;
Juergen Schmied's avatar
Juergen Schmied committed
2624 2625 2626
}

/******************************************************************************
2627
 *  NtSetInformationFile		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
2628
 *  ZwSetInformationFile		[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
2629 2630 2631 2632
 *
 * Set information about an open file handle.
 *
 * PARAMS
2633 2634 2635 2636 2637
 *  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
2638 2639
 *
 * RETURNS
2640
 *  Success: 0. io is updated.
Jon Griffiths's avatar
Jon Griffiths committed
2641
 *  Failure: An NTSTATUS error code describing the error.
Juergen Schmied's avatar
Juergen Schmied committed
2642
 */
2643 2644
NTSTATUS WINAPI NtSetInformationFile(HANDLE handle, PIO_STATUS_BLOCK io,
                                     PVOID ptr, ULONG len, FILE_INFORMATION_CLASS class)
Juergen Schmied's avatar
Juergen Schmied committed
2645
{
2646
    int fd, needs_close;
2647

2648
    TRACE("(%p,%p,%p,0x%08x,0x%08x)\n", handle, io, ptr, len, class);
2649 2650

    io->u.Status = STATUS_SUCCESS;
2651
    switch (class)
Jon Griffiths's avatar
Jon Griffiths committed
2652
    {
2653 2654
    case FileBasicInformation:
        if (len >= sizeof(FILE_BASIC_INFORMATION))
2655
        {
2656 2657
            struct stat st;
            const FILE_BASIC_INFORMATION *info = ptr;
2658

2659 2660 2661
            if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
                return io->u.Status;

2662
            if (info->LastAccessTime.QuadPart || info->LastWriteTime.QuadPart)
2663
                io->u.Status = set_file_times( fd, &info->LastWriteTime, &info->LastAccessTime );
2664

2665 2666 2667 2668 2669 2670 2671
            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)
                    {
2672 2673 2674 2675
                        if (S_ISDIR( st.st_mode))
                            WARN("FILE_ATTRIBUTE_READONLY ignored for directory.\n");
                        else
                            st.st_mode &= ~0222; /* clear write permission bits */
2676 2677 2678 2679 2680 2681 2682 2683 2684
                    }
                    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();
                }
            }
2685 2686

            if (needs_close) close( fd );
2687 2688 2689 2690 2691 2692 2693 2694 2695
        }
        else io->u.Status = STATUS_INVALID_PARAMETER_3;
        break;

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

2696 2697 2698
            if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
                return io->u.Status;

2699 2700
            if (lseek( fd, info->CurrentByteOffset.QuadPart, SEEK_SET ) == (off_t)-1)
                io->u.Status = FILE_GetNtStatus();
2701 2702

            if (needs_close) close( fd );
2703
        }
2704
        else io->u.Status = STATUS_INVALID_PARAMETER_3;
2705
        break;
2706

2707 2708 2709
    case FileEndOfFileInformation:
        if (len >= sizeof(FILE_END_OF_FILE_INFORMATION))
        {
2710
            struct stat st;
2711 2712
            const FILE_END_OF_FILE_INFORMATION *info = ptr;

2713 2714 2715
            if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
                return io->u.Status;

2716 2717 2718 2719 2720
            /* 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)
2721 2722 2723 2724 2725
            {
                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 */
2726 2727
                if (pwrite( fd, &zero, 1, (off_t)info->EndOfFile.QuadPart ) != -1 &&
                    ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
2728
            }
2729
            io->u.Status = FILE_GetNtStatus();
2730 2731

            if (needs_close) close( fd );
2732 2733 2734 2735
        }
        else io->u.Status = STATUS_INVALID_PARAMETER_3;
        break;

2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758
    case FilePipeInformation:
        if (len >= sizeof(FILE_PIPE_INFORMATION))
        {
            FILE_PIPE_INFORMATION *info = ptr;

            if ((info->CompletionMode | info->ReadMode) & ~1)
            {
                io->u.Status = STATUS_INVALID_PARAMETER;
                break;
            }

            SERVER_START_REQ( set_named_pipe_info )
            {
                req->handle = wine_server_obj_handle( handle );
                req->flags  = (info->CompletionMode ? NAMED_PIPE_NONBLOCKING_MODE    : 0) |
                              (info->ReadMode       ? NAMED_PIPE_MESSAGE_STREAM_READ : 0);
                io->u.Status = wine_server_call( req );
            }
            SERVER_END_REQ;
        }
        else io->u.Status = STATUS_INVALID_PARAMETER_3;
        break;

2759 2760 2761 2762 2763 2764
    case FileMailslotSetInformation:
        {
            FILE_MAILSLOT_SET_INFORMATION *info = ptr;

            SERVER_START_REQ( set_mailslot_info )
            {
2765
                req->handle = wine_server_obj_handle( handle );
2766
                req->flags = MAILSLOT_SET_READ_TIMEOUT;
2767
                req->read_timeout = info->ReadTimeout.QuadPart;
2768 2769 2770 2771 2772 2773
                io->u.Status = wine_server_call( req );
            }
            SERVER_END_REQ;
        }
        break;

2774 2775 2776
    case FileCompletionInformation:
        if (len >= sizeof(FILE_COMPLETION_INFORMATION))
        {
2777
            FILE_COMPLETION_INFORMATION *info = ptr;
2778 2779 2780

            SERVER_START_REQ( set_completion_info )
            {
2781 2782
                req->handle   = wine_server_obj_handle( handle );
                req->chandle  = wine_server_obj_handle( info->CompletionPort );
2783 2784 2785 2786 2787 2788 2789 2790
                req->ckey     = info->CompletionKey;
                io->u.Status  = wine_server_call( req );
            }
            SERVER_END_REQ;
        } else
            io->u.Status = STATUS_INVALID_PARAMETER_3;
        break;

2791 2792 2793 2794
    case FileAllInformation:
        io->u.Status = STATUS_INVALID_INFO_CLASS;
        break;

2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824
    case FileValidDataLengthInformation:
        if (len >= sizeof(FILE_VALID_DATA_LENGTH_INFORMATION))
        {
            struct stat st;
            const FILE_VALID_DATA_LENGTH_INFORMATION *info = ptr;

            if ((io->u.Status = server_get_unix_fd( handle, FILE_WRITE_DATA, &fd, &needs_close, NULL, NULL )))
                return io->u.Status;

            if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
            else if (info->ValidDataLength.QuadPart <= 0 || (off_t)info->ValidDataLength.QuadPart > st.st_size)
                io->u.Status = STATUS_INVALID_PARAMETER;
            else
            {
#ifdef HAVE_FALLOCATE
                if (fallocate( fd, 0, 0, (off_t)info->ValidDataLength.QuadPart ) == -1)
                {
                    NTSTATUS status = FILE_GetNtStatus();
                    if (status == STATUS_NOT_SUPPORTED) WARN( "fallocate not supported on this filesystem\n" );
                    else io->u.Status = status;
                }
#else
                FIXME( "setting valid data length not supported\n" );
#endif
            }
            if (needs_close) close( fd );
        }
        else io->u.Status = STATUS_INVALID_PARAMETER_3;
        break;

2825 2826 2827 2828 2829
    case FileDispositionInformation:
        if (len >= sizeof(FILE_DISPOSITION_INFORMATION))
        {
            FILE_DISPOSITION_INFORMATION *info = ptr;

2830
            SERVER_START_REQ( set_fd_disp_info )
2831 2832 2833 2834 2835 2836 2837 2838 2839 2840
            {
                req->handle   = wine_server_obj_handle( handle );
                req->unlink   = info->DoDeleteFile;
                io->u.Status  = wine_server_call( req );
            }
            SERVER_END_REQ;
        } else
            io->u.Status = STATUS_INVALID_PARAMETER_3;
        break;

2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872
    case FileRenameInformation:
        if (len >= sizeof(FILE_RENAME_INFORMATION))
        {
            FILE_RENAME_INFORMATION *info = ptr;
            UNICODE_STRING name_str;
            OBJECT_ATTRIBUTES attr;
            ANSI_STRING unix_name;

            name_str.Buffer = info->FileName;
            name_str.Length = info->FileNameLength;
            name_str.MaximumLength = info->FileNameLength + sizeof(WCHAR);

            attr.Length = sizeof(attr);
            attr.ObjectName = &name_str;
            attr.RootDirectory = info->RootDir;
            attr.Attributes = OBJ_CASE_INSENSITIVE;

            io->u.Status = nt_to_unix_file_name_attr( &attr, &unix_name, FILE_OPEN_IF );
            if (io->u.Status != STATUS_SUCCESS && io->u.Status != STATUS_NO_SUCH_FILE)
                break;

            if (!info->Replace && io->u.Status == STATUS_SUCCESS)
            {
                RtlFreeAnsiString( &unix_name );
                io->u.Status = STATUS_OBJECT_NAME_COLLISION;
                break;
            }

            SERVER_START_REQ( set_fd_name_info )
            {
                req->handle   = wine_server_obj_handle( handle );
                req->rootdir  = wine_server_obj_handle( attr.RootDirectory );
2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916
                req->link     = FALSE;
                wine_server_add_data( req, unix_name.Buffer, unix_name.Length );
                io->u.Status = wine_server_call( req );
            }
            SERVER_END_REQ;

            RtlFreeAnsiString( &unix_name );
        }
        else io->u.Status = STATUS_INVALID_PARAMETER_3;
        break;

    case FileLinkInformation:
        if (len >= sizeof(FILE_LINK_INFORMATION))
        {
            FILE_LINK_INFORMATION *info = ptr;
            UNICODE_STRING name_str;
            OBJECT_ATTRIBUTES attr;
            ANSI_STRING unix_name;

            name_str.Buffer = info->FileName;
            name_str.Length = info->FileNameLength;
            name_str.MaximumLength = info->FileNameLength + sizeof(WCHAR);

            attr.Length = sizeof(attr);
            attr.ObjectName = &name_str;
            attr.RootDirectory = info->RootDirectory;
            attr.Attributes = OBJ_CASE_INSENSITIVE;

            io->u.Status = nt_to_unix_file_name_attr( &attr, &unix_name, FILE_OPEN_IF );
            if (io->u.Status != STATUS_SUCCESS && io->u.Status != STATUS_NO_SUCH_FILE)
                break;

            if (!info->ReplaceIfExists && io->u.Status == STATUS_SUCCESS)
            {
                RtlFreeAnsiString( &unix_name );
                io->u.Status = STATUS_OBJECT_NAME_COLLISION;
                break;
            }

            SERVER_START_REQ( set_fd_name_info )
            {
                req->handle   = wine_server_obj_handle( handle );
                req->rootdir  = wine_server_obj_handle( attr.RootDirectory );
                req->link     = TRUE;
2917 2918 2919 2920 2921 2922 2923 2924 2925 2926
                wine_server_add_data( req, unix_name.Buffer, unix_name.Length );
                io->u.Status  = wine_server_call( req );
            }
            SERVER_END_REQ;

            RtlFreeAnsiString( &unix_name );
        }
        else io->u.Status = STATUS_INVALID_PARAMETER_3;
        break;

2927 2928
    default:
        FIXME("Unsupported class (%d)\n", class);
2929 2930
        io->u.Status = STATUS_NOT_IMPLEMENTED;
        break;
2931
    }
2932 2933 2934 2935 2936 2937
    io->Information = 0;
    return io->u.Status;
}


/******************************************************************************
2938
 *              NtQueryFullAttributesFile   (NTDLL.@)
2939
 */
2940 2941
NTSTATUS WINAPI NtQueryFullAttributesFile( const OBJECT_ATTRIBUTES *attr,
                                           FILE_NETWORK_OPEN_INFORMATION *info )
2942 2943 2944 2945
{
    ANSI_STRING unix_name;
    NTSTATUS status;

2946
    if (!(status = nt_to_unix_file_name_attr( attr, &unix_name, FILE_OPEN )))
2947
    {
2948
        ULONG attributes;
2949 2950
        struct stat st;

2951
        if (get_file_info( unix_name.Buffer, &st, &attributes ) == -1)
2952 2953 2954 2955 2956
            status = FILE_GetNtStatus();
        else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
            status = STATUS_INVALID_INFO_CLASS;
        else
        {
2957 2958 2959
            FILE_BASIC_INFORMATION basic;
            FILE_STANDARD_INFORMATION std;

2960 2961
            fill_file_info( &st, attributes, &basic, FileBasicInformation );
            fill_file_info( &st, attributes, &std, FileStandardInformation );
2962 2963 2964 2965 2966 2967 2968 2969

            info->CreationTime   = basic.CreationTime;
            info->LastAccessTime = basic.LastAccessTime;
            info->LastWriteTime  = basic.LastWriteTime;
            info->ChangeTime     = basic.ChangeTime;
            info->AllocationSize = std.AllocationSize;
            info->EndOfFile      = std.EndOfFile;
            info->FileAttributes = basic.FileAttributes;
2970 2971 2972 2973 2974
            if (DIR_is_hidden_file( attr->ObjectName ))
                info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
        }
        RtlFreeAnsiString( &unix_name );
    }
2975
    else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), status );
2976
    return status;
Juergen Schmied's avatar
Juergen Schmied committed
2977 2978
}

2979

2980 2981 2982 2983 2984 2985
/******************************************************************************
 *              NtQueryAttributesFile   (NTDLL.@)
 *              ZwQueryAttributesFile   (NTDLL.@)
 */
NTSTATUS WINAPI NtQueryAttributesFile( const OBJECT_ATTRIBUTES *attr, FILE_BASIC_INFORMATION *info )
{
2986
    ANSI_STRING unix_name;
2987 2988
    NTSTATUS status;

2989
    if (!(status = nt_to_unix_file_name_attr( attr, &unix_name, FILE_OPEN )))
2990
    {
2991
        ULONG attributes;
2992 2993
        struct stat st;

2994
        if (get_file_info( unix_name.Buffer, &st, &attributes ) == -1)
2995 2996 2997 2998 2999
            status = FILE_GetNtStatus();
        else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
            status = STATUS_INVALID_INFO_CLASS;
        else
        {
3000
            status = fill_file_info( &st, attributes, info, FileBasicInformation );
3001 3002 3003 3004
            if (DIR_is_hidden_file( attr->ObjectName ))
                info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
        }
        RtlFreeAnsiString( &unix_name );
3005
    }
3006
    else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), status );
3007 3008 3009 3010
    return status;
}


3011
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
3012
/* helper for FILE_GetDeviceInfo to hide some platform differences in fstatfs */
3013
static inline void get_device_info_fstatfs( FILE_FS_DEVICE_INFORMATION *info, const char *fstypename,
3014
                                            unsigned int flags )
3015
{
3016
    if (!strcmp("cd9660", fstypename) || !strcmp("udf", fstypename))
3017 3018 3019 3020 3021
    {
        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;
    }
3022 3023
    else if (!strcmp("nfs", fstypename) || !strcmp("nwfs", fstypename) ||
             !strcmp("smbfs", fstypename) || !strcmp("afpfs", fstypename))
3024 3025 3026 3027
    {
        info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
        info->Characteristics |= FILE_REMOTE_DEVICE;
    }
3028
    else if (!strcmp("procfs", fstypename))
3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043
        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

3044
static inline BOOL is_device_placeholder( int fd )
3045 3046 3047 3048 3049
{
    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)
3050
        return FALSE;
3051 3052 3053
    return !memcmp( buffer, wine_placeholder, sizeof(wine_placeholder) - 1 );
}

3054
/******************************************************************************
3055
 *              get_device_info
3056 3057 3058
 *
 * Implementation of the FileFsDeviceInformation query for NtQueryVolumeInformationFile.
 */
3059
static NTSTATUS get_device_info( int fd, FILE_FS_DEVICE_INFORMATION *info )
3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079
{
    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;
3080 3081 3082
        case SCSI_TAPE_MAJOR:
            info->DeviceType = FILE_DEVICE_TAPE;
            break;
3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093
        }
#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;
    }
3094 3095 3096 3097
    else if (is_device_placeholder( fd ))
    {
        info->DeviceType = FILE_DEVICE_DISK;
    }
3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110
    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 */
3111
        case 0x9fa1:      /* supermount */
3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131
        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;
        }
3132
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
3133 3134 3135 3136 3137
        struct statfs stfs;

        if (fstatfs( fd, &stfs ) < 0)
            info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
        else
3138
            get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flags );
3139 3140 3141 3142
#elif defined(__NetBSD__)
        struct statvfs stfs;

        if (fstatvfs( fd, &stfs) < 0)
3143
            info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
3144
        else
3145
            get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flag );
3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187
#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;
}


3188
/******************************************************************************
3189
 *  NtQueryVolumeInformationFile		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
3190
 *  ZwQueryVolumeInformationFile		[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
3191 3192 3193 3194
 *
 * Get volume information for an open file handle.
 *
 * PARAMS
3195 3196 3197 3198 3199
 *  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
3200 3201
 *
 * RETURNS
3202
 *  Success: 0. io and buffer are updated.
Jon Griffiths's avatar
Jon Griffiths committed
3203
 *  Failure: An NTSTATUS error code describing the error.
3204
 */
3205 3206 3207
NTSTATUS WINAPI NtQueryVolumeInformationFile( HANDLE handle, PIO_STATUS_BLOCK io,
                                              PVOID buffer, ULONG length,
                                              FS_INFORMATION_CLASS info_class )
3208
{
3209
    int fd, needs_close;
3210
    struct stat st;
3211
    static int once;
3212

3213
    if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
3214
        return io->u.Status;
3215

3216 3217
    io->u.Status = STATUS_NOT_IMPLEMENTED;
    io->Information = 0;
3218

3219 3220 3221
    switch( info_class )
    {
    case FileFsVolumeInformation:
3222
        if (!once++) FIXME( "%p: volume info not supported\n", handle );
3223 3224 3225 3226 3227 3228 3229 3230 3231 3232
        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;
3233

3234 3235 3236 3237 3238 3239 3240 3241 3242
            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;
            }
3243 3244
            else
            {
3245
                ULONGLONG bsize;
3246 3247 3248 3249 3250 3251 3252 3253 3254
                /* 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;
                }
3255
                bsize = stfs.f_frsize;
3256 3257 3258 3259 3260 3261 3262
#else
                struct statfs stfs;
                if (fstatfs( fd, &stfs ) < 0)
                {
                    io->u.Status = FILE_GetNtStatus();
                    break;
                }
3263
                bsize = stfs.f_bsize;
3264
#endif
3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276
                if (bsize == 2048)  /* assume CD-ROM */
                {
                    info->BytesPerSector = 2048;
                    info->SectorsPerAllocationUnit = 1;
                }
                else
                {
                    info->BytesPerSector = 512;
                    info->SectorsPerAllocationUnit = 8;
                }
                info->TotalAllocationUnits.QuadPart = bsize * stfs.f_blocks / (info->BytesPerSector * info->SectorsPerAllocationUnit);
                info->AvailableAllocationUnits.QuadPart = bsize * stfs.f_bavail / (info->BytesPerSector * info->SectorsPerAllocationUnit);
3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288
                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;

3289
            if ((io->u.Status = get_device_info( fd, info )) == STATUS_SUCCESS)
3290
                io->Information = sizeof(*info);
3291 3292 3293
        }
        break;
    case FileFsAttributeInformation:
3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310
        if (length < offsetof( FILE_FS_ATTRIBUTE_INFORMATION, FileSystemName[sizeof(ntfsW)/sizeof(WCHAR)] ))
            io->u.Status = STATUS_BUFFER_TOO_SMALL;
        else
        {
            FILE_FS_ATTRIBUTE_INFORMATION *info = buffer;

            FIXME( "%p: faking attribute info\n", handle );
            info->FileSystemAttribute = FILE_SUPPORTS_ENCRYPTION | FILE_FILE_COMPRESSION |
                                        FILE_PERSISTENT_ACLS | FILE_UNICODE_ON_DISK |
                                        FILE_CASE_PRESERVED_NAMES | FILE_CASE_SENSITIVE_SEARCH;
            info->MaximumComponentNameLength = MAXIMUM_FILENAME_LENGTH - 1;
            info->FileSystemNameLength = sizeof(ntfsW);
            memcpy(info->FileSystemName, ntfsW, sizeof(ntfsW));

            io->Information = sizeof(*info);
            io->u.Status = STATUS_SUCCESS;
        }
3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327
        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;
    }
3328
    if (needs_close) close( fd );
3329
    return io->u.Status;
3330
}
3331

3332

3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385
/******************************************************************
 *		NtQueryEaFile  (NTDLL.@)
 *
 * Read extended attributes from NTFS files.
 *
 * PARAMS
 *  hFile         [I] File handle, must be opened with FILE_READ_EA access
 *  iosb          [O] Receives information about the operation on return
 *  buffer        [O] Output buffer
 *  length        [I] Length of output buffer
 *  single_entry  [I] Only read and return one entry
 *  ea_list       [I] Optional list with names of EAs to return
 *  ea_list_len   [I] Length of ea_list in bytes
 *  ea_index      [I] Optional pointer to 1-based index of attribute to return
 *  restart       [I] restart EA scan
 *
 * RETURNS
 *  Success: 0. Atrributes read into buffer
 *  Failure: An NTSTATUS error code describing the error.
 */
NTSTATUS WINAPI NtQueryEaFile( HANDLE hFile, PIO_STATUS_BLOCK iosb, PVOID buffer, ULONG length,
                               BOOLEAN single_entry, PVOID ea_list, ULONG ea_list_len,
                               PULONG ea_index, BOOLEAN restart )
{
    FIXME("(%p,%p,%p,%d,%d,%p,%d,%p,%d) stub\n",
            hFile, iosb, buffer, length, single_entry, ea_list,
            ea_list_len, ea_index, restart);
    return STATUS_ACCESS_DENIED;
}


/******************************************************************
 *		NtSetEaFile  (NTDLL.@)
 *
 * Update extended attributes for NTFS files.
 *
 * PARAMS
 *  hFile         [I] File handle, must be opened with FILE_READ_EA access
 *  iosb          [O] Receives information about the operation on return
 *  buffer        [I] Buffer with EA information
 *  length        [I] Length of buffer
 *
 * RETURNS
 *  Success: 0. Attributes are updated
 *  Failure: An NTSTATUS error code describing the error.
 */
NTSTATUS WINAPI NtSetEaFile( HANDLE hFile, PIO_STATUS_BLOCK iosb, PVOID buffer, ULONG length )
{
    FIXME("(%p,%p,%p,%d) stub\n", hFile, iosb, buffer, length);
    return STATUS_ACCESS_DENIED;
}


3386 3387
/******************************************************************
 *		NtFlushBuffersFile  (NTDLL.@)
Jon Griffiths's avatar
Jon Griffiths committed
3388 3389 3390 3391 3392 3393 3394 3395 3396 3397
 *
 * 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.
3398 3399 3400 3401
 */
NTSTATUS WINAPI NtFlushBuffersFile( HANDLE hFile, IO_STATUS_BLOCK* IoStatusBlock )
{
    NTSTATUS ret;
3402
    HANDLE hEvent = NULL;
3403 3404
    enum server_fd_type type;
    int fd, needs_close;
3405

3406 3407 3408
    ret = server_get_unix_fd( hFile, FILE_WRITE_DATA, &fd, &needs_close, &type, NULL );

    if (!ret && type == FD_TYPE_SERIAL)
3409
    {
3410
        ret = COMM_FlushBuffersFile( fd );
3411
    }
3412
    else
3413
    {
3414
        SERVER_START_REQ( flush )
3415
        {
3416 3417 3418
            req->blocking     = 1;  /* always blocking */
            req->async.handle = wine_server_obj_handle( hFile );
            req->async.iosb   = wine_server_client_ptr( IoStatusBlock );
3419 3420 3421 3422
            ret = wine_server_call( req );
            hEvent = wine_server_ptr_handle( reply->event );
        }
        SERVER_END_REQ;
3423 3424

        if (hEvent)
3425
        {
3426
            NtWaitForSingleObject( hEvent, FALSE, NULL );
3427
            NtClose( hEvent );
3428
            ret = STATUS_SUCCESS;
3429
        }
3430
    }
3431 3432

    if (needs_close) close( fd );
3433 3434
    return ret;
}
3435 3436 3437 3438 3439 3440 3441

/******************************************************************
 *		NtLockFile       (NTDLL.@)
 *
 *
 */
NTSTATUS WINAPI NtLockFile( HANDLE hFile, HANDLE lock_granted_event,
Jon Griffiths's avatar
Jon Griffiths committed
3442 3443
                            PIO_APC_ROUTINE apc, void* apc_user,
                            PIO_STATUS_BLOCK io_status, PLARGE_INTEGER offset,
3444 3445 3446 3447 3448 3449
                            PLARGE_INTEGER count, ULONG* key, BOOLEAN dont_wait,
                            BOOLEAN exclusive )
{
    NTSTATUS    ret;
    HANDLE      handle;
    BOOLEAN     async;
3450
    static BOOLEAN     warn = TRUE;
3451 3452 3453 3454 3455 3456 3457

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

3458 3459 3460 3461 3462
    if (apc_user && warn)
    {
        FIXME("I/O completion on lock not implemented yet\n");
        warn = FALSE;
    }
3463

3464 3465 3466 3467
    for (;;)
    {
        SERVER_START_REQ( lock_file )
        {
3468
            req->handle      = wine_server_obj_handle( hFile );
3469 3470
            req->offset      = offset->QuadPart;
            req->count       = count->QuadPart;
3471 3472 3473
            req->shared      = !exclusive;
            req->wait        = !dont_wait;
            ret = wine_server_call( req );
3474
            handle = wine_server_ptr_handle( reply->handle );
3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501
            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;
3502
            NtDelayExecution( FALSE, &time );
3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518
        }
    }
}


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

3519
    TRACE( "%p %x%08x %x%08x\n",
3520
           hFile, offset->u.HighPart, offset->u.LowPart, count->u.HighPart, count->u.LowPart );
3521 3522 3523 3524 3525 3526 3527 3528 3529

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

    SERVER_START_REQ( unlock_file )
    {
3530
        req->handle = wine_server_obj_handle( hFile );
3531 3532
        req->offset = offset->QuadPart;
        req->count  = count->QuadPart;
3533 3534 3535 3536 3537
        status = wine_server_call( req );
    }
    SERVER_END_REQ;
    return status;
}
3538 3539 3540 3541 3542 3543

/******************************************************************
 *		NtCreateNamedPipeFile    (NTDLL.@)
 *
 *
 */
3544
NTSTATUS WINAPI NtCreateNamedPipeFile( PHANDLE handle, ULONG access,
3545
                                       POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK iosb,
3546 3547 3548 3549 3550
                                       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)
3551
{
3552
    NTSTATUS status;
3553 3554
    data_size_t len;
    struct object_attributes *objattr;
3555

3556
    TRACE("(%p %x %s %p %x %d %x %d %d %d %d %d %d %p)\n",
3557
          handle, access, debugstr_w(attr->ObjectName->Buffer), iosb, sharing, dispo,
3558 3559
          options, pipe_type, read_mode, completion_mode, max_inst, inbound_quota,
          outbound_quota, timeout);
3560

3561 3562
    if (!attr) return STATUS_INVALID_PARAMETER;

3563 3564
    /* assume we only get relative timeout */
    if (timeout->QuadPart > 0)
3565 3566
        FIXME("Wrong time %s\n", wine_dbgstr_longlong(timeout->QuadPart));

3567
    if ((status = alloc_object_attributes( attr, &objattr, &len ))) return status;
3568

3569 3570
    SERVER_START_REQ( create_named_pipe )
    {
3571 3572
        req->access  = access;
        req->options = options;
3573
        req->sharing = sharing;
3574
        req->flags = 
3575 3576 3577
            (pipe_type ? NAMED_PIPE_MESSAGE_STREAM_WRITE   : 0) |
            (read_mode ? NAMED_PIPE_MESSAGE_STREAM_READ    : 0) |
            (completion_mode ? NAMED_PIPE_NONBLOCKING_MODE : 0);
3578 3579 3580
        req->maxinstances = max_inst;
        req->outsize = outbound_quota;
        req->insize  = inbound_quota;
3581
        req->timeout = timeout->QuadPart;
3582
        wine_server_add_data( req, objattr, len );
3583
        status = wine_server_call( req );
3584
        if (!status) *handle = wine_server_ptr_handle( reply->handle );
3585 3586
    }
    SERVER_END_REQ;
3587

3588
    RtlFreeHeap( GetProcessHeap(), 0, objattr );
3589
    return status;
3590
}
3591 3592 3593 3594 3595 3596 3597 3598

/******************************************************************
 *		NtDeleteFile    (NTDLL.@)
 *
 *
 */
NTSTATUS WINAPI NtDeleteFile( POBJECT_ATTRIBUTES ObjectAttributes )
{
3599 3600 3601 3602 3603
    NTSTATUS status;
    HANDLE hFile;
    IO_STATUS_BLOCK io;

    TRACE("%p\n", ObjectAttributes);
3604 3605
    status = NtCreateFile( &hFile, GENERIC_READ | GENERIC_WRITE | DELETE,
                           ObjectAttributes, &io, NULL, 0,
3606 3607 3608 3609
                           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;
3610 3611
}

3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628
/******************************************************************
 *		NtCancelIoFileEx    (NTDLL.@)
 *
 *
 */
NTSTATUS WINAPI NtCancelIoFileEx( HANDLE hFile, PIO_STATUS_BLOCK iosb, PIO_STATUS_BLOCK io_status )
{
    TRACE("%p %p %p\n", hFile, iosb, io_status );

    SERVER_START_REQ( cancel_async )
    {
        req->handle      = wine_server_obj_handle( hFile );
        req->iosb        = wine_server_client_ptr( iosb );
        req->only_thread = FALSE;
        io_status->u.Status = wine_server_call( req );
    }
    SERVER_END_REQ;
3629

3630 3631 3632
    return io_status->u.Status;
}

3633 3634 3635 3636 3637
/******************************************************************
 *		NtCancelIoFile    (NTDLL.@)
 *
 *
 */
3638
NTSTATUS WINAPI NtCancelIoFile( HANDLE hFile, PIO_STATUS_BLOCK io_status )
3639
{
3640 3641 3642 3643
    TRACE("%p %p\n", hFile, io_status );

    SERVER_START_REQ( cancel_async )
    {
3644 3645 3646 3647
        req->handle      = wine_server_obj_handle( hFile );
        req->iosb        = 0;
        req->only_thread = TRUE;
        io_status->u.Status = wine_server_call( req );
3648 3649
    }
    SERVER_END_REQ;
3650

3651
    return io_status->u.Status;
3652
}
3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675

/******************************************************************************
 *  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)
{
3676
    LARGE_INTEGER timeout;
3677
    NTSTATUS ret;
3678 3679
    data_size_t len;
    struct object_attributes *objattr;
3680

3681
    TRACE("%p %08x %p %p %08x %08x %08x %p\n",
3682 3683 3684
              pHandle, DesiredAccess, attr, IoStatusBlock,
              CreateOptions, MailslotQuota, MaxMessageSize, TimeOut);

3685
    if (!pHandle) return STATUS_ACCESS_VIOLATION;
3686 3687
    if (!attr) return STATUS_INVALID_PARAMETER;

3688 3689
    if ((ret = alloc_object_attributes( attr, &objattr, &len ))) return ret;

3690 3691 3692 3693 3694 3695 3696 3697
    /*
     *  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
3698 3699
    SERVER_START_REQ( create_mailslot )
    {
3700
        req->access = DesiredAccess;
Mike McCormack's avatar
Mike McCormack committed
3701
        req->max_msgsize = MaxMessageSize;
3702
        req->read_timeout = timeout.QuadPart;
3703
        wine_server_add_data( req, objattr, len );
Mike McCormack's avatar
Mike McCormack committed
3704 3705
        ret = wine_server_call( req );
        if( ret == STATUS_SUCCESS )
3706
            *pHandle = wine_server_ptr_handle( reply->handle );
Mike McCormack's avatar
Mike McCormack committed
3707 3708
    }
    SERVER_END_REQ;
3709 3710

    RtlFreeHeap( GetProcessHeap(), 0, objattr );
3711 3712
    return ret;
}