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

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

Juergen Schmied's avatar
Juergen Schmied committed
22 23
#include <stdlib.h>
#include <string.h>
24 25
#include <stdio.h>
#include <errno.h>
26
#include <assert.h>
27 28 29
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
30 31 32
#ifdef HAVE_SYS_ERRNO_H
#include <sys/errno.h>
#endif
33 34 35
#ifdef HAVE_LINUX_MAJOR_H
# include <linux/major.h>
#endif
36 37 38 39 40 41
#ifdef HAVE_SYS_STATVFS_H
# include <sys/statvfs.h>
#endif
#ifdef HAVE_SYS_PARAM_H
# include <sys/param.h>
#endif
42 43 44
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
45 46 47
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
48 49 50
#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
#ifdef HAVE_UTIME_H
# include <utime.h>
#endif
63
#ifdef HAVE_SYS_VFS_H
64
# include <sys/vfs.h>
65 66 67 68 69 70
#endif
#ifdef HAVE_SYS_MOUNT_H
# include <sys/mount.h>
#endif
#ifdef HAVE_SYS_STATFS_H
# include <sys/statfs.h>
71
#endif
72 73 74
#ifdef HAVE_VALGRIND_MEMCHECK_H
# include <valgrind/memcheck.h>
#endif
75 76 77

#define NONAMELESSUNION
#define NONAMELESSSTRUCT
78 79
#include "ntstatus.h"
#define WIN32_NO_STATUS
80
#include "wine/unicode.h"
81
#include "wine/debug.h"
82
#include "wine/server.h"
83
#include "ntdll_misc.h"
Juergen Schmied's avatar
Juergen Schmied committed
84

85
#include "winternl.h"
86
#include "winioctl.h"
87
#include "ddk/ntddser.h"
Juergen Schmied's avatar
Juergen Schmied committed
88

89
WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
90
WINE_DECLARE_DEBUG_CHANNEL(winediag);
91

92 93 94 95 96
mode_t FILE_umask = 0;

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

Juergen Schmied's avatar
Juergen Schmied committed
97 98

/**************************************************************************
99 100
 *                 FILE_CreateFile                    (internal)
 * Open a file.
Jon Griffiths's avatar
Jon Griffiths committed
101
 *
102
 * Parameter set fully identical with NtCreateFile
Juergen Schmied's avatar
Juergen Schmied committed
103
 */
104 105 106 107
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
108
{
109
    ANSI_STRING unix_name;
110
    int created = FALSE;
111

112
    TRACE("handle=%p access=%08x name=%s objattr=%08x root=%p sec=%p io=%p alloc_size=%p "
113
          "attr=%08x sharing=%08x disp=%d options=%08x ea=%p.0x%08x\n",
114 115 116 117
          handle, access, debugstr_us(attr->ObjectName), attr->Attributes,
          attr->RootDirectory, attr->SecurityDescriptor, io, alloc_size,
          attributes, sharing, disposition, options, ea_buffer, ea_length );

118 119
    if (!attr || !attr->ObjectName) return STATUS_INVALID_PARAMETER;

120 121
    if (alloc_size) FIXME( "alloc_size not supported\n" );

122 123 124 125 126 127
    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)
128 129 130 131 132
    {
        SERVER_START_REQ( open_file_object )
        {
            req->access     = access;
            req->attributes = attr->Attributes;
133
            req->rootdir    = wine_server_obj_handle( attr->RootDirectory );
134
            req->sharing    = sharing;
135
            req->options    = options;
136 137
            wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
            io->u.Status = wine_server_call( req );
138
            *handle = wine_server_ptr_handle( reply->handle );
139 140
        }
        SERVER_END_REQ;
141
        if (io->u.Status == STATUS_SUCCESS) io->Information = FILE_OPENED;
142 143 144
        return io->u.Status;
    }

145 146
    if (io->u.Status == STATUS_NO_SUCH_FILE &&
        disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
147 148 149 150 151 152
    {
        created = TRUE;
        io->u.Status = STATUS_SUCCESS;
    }

    if (io->u.Status == STATUS_SUCCESS)
153
    {
154
        struct security_descriptor *sd;
155 156
        struct object_attributes objattr;

157
        objattr.rootdir = wine_server_obj_handle( attr->RootDirectory );
158
        objattr.name_len = 0;
159 160
        io->u.Status = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
        if (io->u.Status != STATUS_SUCCESS)
161
        {
162 163
            RtlFreeAnsiString( &unix_name );
            return io->u.Status;
164 165
        }

166 167 168
        SERVER_START_REQ( create_file )
        {
            req->access     = access;
169
            req->attributes = attr->Attributes;
170 171 172 173
            req->sharing    = sharing;
            req->create     = disposition;
            req->options    = options;
            req->attrs      = attributes;
174 175
            wine_server_add_data( req, &objattr, sizeof(objattr) );
            if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
176 177
            wine_server_add_data( req, unix_name.Buffer, unix_name.Length );
            io->u.Status = wine_server_call( req );
178
            *handle = wine_server_ptr_handle( reply->handle );
179 180
        }
        SERVER_END_REQ;
181
        NTDLL_free_struct_sd( sd );
182 183
        RtlFreeAnsiString( &unix_name );
    }
184
    else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), io->u.Status );
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206

    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;
        }
    }
207 208 209 210 211
    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" );
    }
212

213
    return io->u.Status;
Juergen Schmied's avatar
Juergen Schmied committed
214 215
}

216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
/**************************************************************************
 *                 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 );
}

275 276 277 278
/***********************************************************************
 *                  Asynchronous file I/O                              *
 */

279
struct async_fileio
280
{
281
    HANDLE              handle;
282 283 284 285 286 287 288
    PIO_APC_ROUTINE     apc;
    void               *apc_arg;
};

typedef struct
{
    struct async_fileio io;
289
    char*               buffer;
290
    unsigned int        already;
291 292
    unsigned int        count;
    BOOL                avail_mode;
293
} async_fileio_read;
294

295
typedef struct
296
{
297
    struct async_fileio io;
298 299 300 301
    const char         *buffer;
    unsigned int        already;
    unsigned int        count;
} async_fileio_write;
302

303

304 305 306 307 308 309 310 311
/* callback for file I/O user APC */
static void WINAPI fileio_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
{
    struct async_fileio *async = arg;
    if (async->apc) async->apc( async->apc_arg, io, reserved );
    RtlFreeHeap( GetProcessHeap(), 0, async );
}

312 313 314 315 316 317
/***********************************************************************
 *           FILE_GetNtStatus(void)
 *
 * Retrieve the Nt Status code from errno.
 * Try to be consistent with FILE_SetDosError().
 */
318
NTSTATUS FILE_GetNtStatus(void)
319 320 321 322 323 324
{
    int err = errno;

    TRACE( "errno = %d\n", errno );
    switch (err)
    {
325 326
    case EAGAIN:    return STATUS_SHARING_VIOLATION;
    case EBADF:     return STATUS_INVALID_HANDLE;
327
    case EBUSY:     return STATUS_DEVICE_BUSY;
328
    case ENOSPC:    return STATUS_DISK_FULL;
329 330
    case EPERM:
    case EROFS:
331 332 333 334
    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;
335
    case EMFILE:
336 337 338
    case ENFILE:    return STATUS_TOO_MANY_OPENED_FILES;
    case EINVAL:    return STATUS_INVALID_PARAMETER;
    case ENOTEMPTY: return STATUS_DIRECTORY_NOT_EMPTY;
339
    case EPIPE:     return STATUS_PIPE_DISCONNECTED;
340
    case EIO:       return STATUS_DEVICE_NOT_READY;
341 342 343
#ifdef ENOMEDIUM
    case ENOMEDIUM: return STATUS_NO_MEDIA_IN_DEVICE;
#endif
344
    case ENXIO:     return STATUS_NO_SUCH_DEVICE;
345 346
    case ENOTTY:
    case EOPNOTSUPP:return STATUS_NOT_SUPPORTED;
347
    case ECONNRESET:return STATUS_PIPE_DISCONNECTED;
348
    case EFAULT:    return STATUS_ACCESS_VIOLATION;
349
    case ESPIPE:    return STATUS_ILLEGAL_FUNCTION;
350
#ifdef ETIME /* Missing on FreeBSD */
351
    case ETIME:     return STATUS_IO_TIMEOUT;
352
#endif
353 354
    case ENOEXEC:   /* ?? */
    case EEXIST:    /* ?? */
355 356
    default:
        FIXME( "Converting errno %d to STATUS_UNSUCCESSFUL\n", err );
357
        return STATUS_UNSUCCESSFUL;
358 359 360 361 362 363
    }
}

/***********************************************************************
 *             FILE_AsyncReadService      (INTERNAL)
 */
364
static NTSTATUS FILE_AsyncReadService(void *user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc)
365
{
366
    async_fileio_read *fileio = user;
367
    int fd, needs_close, result;
368

369
    switch (status)
370
    {
371 372
    case STATUS_ALERTED: /* got some new data */
        /* check to see if the data is ready (non-blocking) */
373
        if ((status = server_get_unix_fd( fileio->io.handle, FILE_READ_DATA, &fd,
374
                                          &needs_close, NULL, NULL )))
375
            break;
376

377
        result = read(fd, &fileio->buffer[fileio->already], fileio->count - fileio->already);
378
        if (needs_close) close( fd );
379

380 381 382
        if (result < 0)
        {
            if (errno == EAGAIN || errno == EINTR)
383
                status = STATUS_PENDING;
384
            else /* check to see if the transfer is complete */
385
                status = FILE_GetNtStatus();
386 387 388
        }
        else if (result == 0)
        {
389
            status = fileio->already ? STATUS_SUCCESS : STATUS_PIPE_BROKEN;
390 391 392
        }
        else
        {
393 394
            fileio->already += result;
            if (fileio->already >= fileio->count || fileio->avail_mode)
395
                status = STATUS_SUCCESS;
396 397 398 399 400 401
            else
            {
                /* if we only have to read the available data, and none is available,
                 * simply cancel the request. If data was available, it has been read
                 * while in by previous call (NtDelayExecution)
                 */
402
                status = (fileio->avail_mode) ? STATUS_SUCCESS : STATUS_PENDING;
403 404 405
            }
        }
        break;
406 407 408 409

    case STATUS_TIMEOUT:
    case STATUS_IO_TIMEOUT:
        if (fileio->already) status = STATUS_SUCCESS;
410
        break;
411
    }
412 413 414
    if (status != STATUS_PENDING)
    {
        iosb->u.Status = status;
415 416
        iosb->Information = fileio->already;
        *apc = fileio_apc;
417
    }
418
    return status;
419 420
}

421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
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)
460
                    timeouts->interval = timeouts->total = 0;
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
            }
            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 )
            {
479
                req->handle = wine_server_obj_handle( handle );
480
                req->flags = 0;
481 482 483
                if (!(status = wine_server_call( req )) &&
                    reply->read_timeout != TIMEOUT_INFINITE)
                    timeouts->total = reply->read_timeout / -10000;
484 485 486 487 488 489
            }
            SERVER_END_REQ;
        }
        break;
    case FD_TYPE_SOCKET:
    case FD_TYPE_PIPE:
490
    case FD_TYPE_CHAR:
491 492 493 494 495 496 497 498 499 500 501
        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 */
502
static inline int get_next_io_timeout( const struct io_timeouts *timeouts, ULONG already )
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
{
    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;
}

518

519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
/* 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:
543
    case FD_TYPE_CHAR:
544 545 546 547 548 549 550 551 552 553
        *avail_mode = TRUE;
        break;
    default:
        *avail_mode = FALSE;
        break;
    }
    return status;
}


Juergen Schmied's avatar
Juergen Schmied committed
554
/******************************************************************************
555
 *  NtReadFile					[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
556
 *  ZwReadFile					[NTDLL.@]
Juergen Schmied's avatar
Juergen Schmied committed
557
 *
Jon Griffiths's avatar
Jon Griffiths committed
558
 * Read from an open file handle.
559
 *
Jon Griffiths's avatar
Jon Griffiths committed
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
 * 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
575
 */
Jon Griffiths's avatar
Jon Griffiths committed
576 577
NTSTATUS WINAPI NtReadFile(HANDLE hFile, HANDLE hEvent,
                           PIO_APC_ROUTINE apc, void* apc_user,
578 579
                           PIO_STATUS_BLOCK io_status, void* buffer, ULONG length,
                           PLARGE_INTEGER offset, PULONG key)
580
{
581 582
    int result, unix_handle, needs_close, timeout_init_done = 0;
    unsigned int options;
583
    struct io_timeouts timeouts;
584
    NTSTATUS status;
585
    ULONG total = 0;
586
    enum server_fd_type type;
587
    ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
588
    BOOL send_completion = FALSE;
589

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

593 594
    if (!io_status) return STATUS_ACCESS_VIOLATION;

595
    status = server_get_unix_fd( hFile, FILE_READ_DATA, &unix_handle,
596
                                 &needs_close, &type, &options );
597
    if (status) return status;
598

599 600 601 602 603 604
    if (!virtual_check_buffer_for_write( buffer, length ))
    {
        status = STATUS_ACCESS_VIOLATION;
        goto done;
    }

605
    if (type == FD_TYPE_FILE && offset && offset->QuadPart != (LONGLONG)-2 /* FILE_USE_FILE_POINTER_POSITION */ )
606 607
    {
        /* async I/O doesn't make sense on regular files */
608
        while ((result = pread( unix_handle, buffer, length, offset->QuadPart )) == -1)
609
        {
610
            if (errno != EINTR)
611
            {
612
                status = FILE_GetNtStatus();
613 614
                goto done;
            }
615
        }
616 617
        if (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT))
            /* update file pointer position */
618 619 620 621 622 623 624 625 626 627 628 629 630
            lseek( unix_handle, offset->QuadPart + result, SEEK_SET );

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

    for (;;)
    {
        if ((result = read( unix_handle, (char *)buffer + total, length - total )) >= 0)
        {
            total += result;
            if (!result || total == length)
631
            {
632
                if (total)
633
                {
634
                    status = STATUS_SUCCESS;
635 636 637 638 639 640 641 642 643 644 645 646 647 648
                    goto done;
                }
                switch (type)
                {
                case FD_TYPE_FILE:
                case FD_TYPE_CHAR:
                    status = STATUS_END_OF_FILE;
                    goto done;
                case FD_TYPE_SERIAL:
                    break;
                default:
                    status = STATUS_PIPE_BROKEN;
                    goto done;
                }
649
            }
650
            else if (type == FD_TYPE_FILE) continue;  /* no async I/O on regular files */
651
        }
652
        else if (errno != EAGAIN)
653
        {
654
            if (errno == EINTR) continue;
655 656
            if (!total) status = FILE_GetNtStatus();
            goto done;
657
        }
658

659
        if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
660
        {
661
            async_fileio_read *fileio;
662
            BOOL avail_mode;
Jon Griffiths's avatar
Jon Griffiths committed
663

664
            if ((status = get_io_avail_mode( hFile, type, &avail_mode )))
665
                goto err;
666
            if (total && avail_mode)
667 668 669 670
            {
                status = STATUS_SUCCESS;
                goto done;
            }
671

672
            if (!(fileio = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(*fileio))))
673 674
            {
                status = STATUS_NO_MEMORY;
675
                goto err;
676
            }
677 678 679
            fileio->io.handle  = hFile;
            fileio->io.apc     = apc;
            fileio->io.apc_arg = apc_user;
680 681 682
            fileio->already = total;
            fileio->count = length;
            fileio->buffer = buffer;
683
            fileio->avail_mode = avail_mode;
684 685 686 687 688

            SERVER_START_REQ( register_async )
            {
                req->type   = ASYNC_TYPE_READ;
                req->count  = length;
689 690
                req->async.handle   = wine_server_obj_handle( hFile );
                req->async.event    = wine_server_obj_handle( hEvent );
691 692 693
                req->async.callback = wine_server_client_ptr( FILE_AsyncReadService );
                req->async.iosb     = wine_server_client_ptr( io_status );
                req->async.arg      = wine_server_client_ptr( fileio );
694
                req->async.cvalue   = cvalue;
695 696 697 698 699
                status = wine_server_call( req );
            }
            SERVER_END_REQ;

            if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
700
            goto err;
701
        }
702
        else  /* synchronous read, wait for the fd to become ready */
703
        {
704 705 706 707 708 709 710
            struct pollfd pfd;
            int ret, timeout;

            if (!timeout_init_done)
            {
                timeout_init_done = 1;
                if ((status = get_io_timeouts( hFile, type, length, TRUE, &timeouts )))
711
                    goto err;
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
                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 */
733
        }
734
    }
735

736
done:
737
    send_completion = cvalue != 0;
738 739

err:
740 741
    if (needs_close) close( unix_handle );
    if (status == STATUS_SUCCESS)
742
    {
743 744 745 746 747 748
        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 );
749
    }
750
    else
751
    {
752 753
        TRACE("= 0x%08x\n", status);
        if (status != STATUS_PENDING && hEvent) NtResetEvent( hEvent, NULL );
754
    }
755 756 757

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

758
    return status;
759
}
760

761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776

/******************************************************************************
 *  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 )
{
    size_t page_size = getpagesize();
    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;
777
    BOOL send_completion = FALSE;
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 813 814 815 816 817 818 819 820 821 822 823 824

    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)
    {
        if (offset && offset->QuadPart != (LONGLONG)-2 /* FILE_USE_FILE_POINTER_POSITION */)
            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++;
        }
    }

825
    send_completion = cvalue != 0;
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842

 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 );
    }
843 844 845

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

846 847 848 849
    return status;
}


850 851 852
/***********************************************************************
 *             FILE_AsyncWriteService      (INTERNAL)
 */
853
static NTSTATUS FILE_AsyncWriteService(void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc)
854
{
855
    async_fileio_write *fileio = user;
856
    int result, fd, needs_close;
857
    enum server_fd_type type;
858

859
    switch (status)
860
    {
861 862
    case STATUS_ALERTED:
        /* write some data (non-blocking) */
863
        if ((status = server_get_unix_fd( fileio->io.handle, FILE_WRITE_DATA, &fd,
864
                                          &needs_close, &type, NULL )))
865
            break;
866

867 868 869 870 871
        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 );

872
        if (needs_close) close( fd );
873

874 875
        if (result < 0)
        {
876 877
            if (errno == EAGAIN || errno == EINTR) status = STATUS_PENDING;
            else status = FILE_GetNtStatus();
878 879 880
        }
        else
        {
881 882
            fileio->already += result;
            status = (fileio->already < fileio->count) ? STATUS_PENDING : STATUS_SUCCESS;
883 884
        }
        break;
885 886 887 888

    case STATUS_TIMEOUT:
    case STATUS_IO_TIMEOUT:
        if (fileio->already) status = STATUS_SUCCESS;
889
        break;
890
    }
891 892 893
    if (status != STATUS_PENDING)
    {
        iosb->u.Status = status;
894 895
        iosb->Information = fileio->already;
        *apc = fileio_apc;
896
    }
897
    return status;
898 899 900 901 902 903
}

/******************************************************************************
 *  NtWriteFile					[NTDLL.@]
 *  ZwWriteFile					[NTDLL.@]
 *
Jon Griffiths's avatar
Jon Griffiths committed
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
 * 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.
921
 */
922 923 924 925 926
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
927
{
928 929
    int result, unix_handle, needs_close, timeout_init_done = 0;
    unsigned int options;
930
    struct io_timeouts timeouts;
931
    NTSTATUS status;
932
    ULONG total = 0;
933
    enum server_fd_type type;
934
    ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
935
    BOOL send_completion = FALSE;
936

937
    TRACE("(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p)!\n",
938 939
          hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);

940 941
    if (!io_status) return STATUS_ACCESS_VIOLATION;

942
    status = server_get_unix_fd( hFile, FILE_WRITE_DATA, &unix_handle,
943
                                 &needs_close, &type, &options );
944
    if (status) return status;
945

946 947 948 949 950 951
    if (!virtual_check_buffer_for_read( buffer, length ))
    {
        status = STATUS_INVALID_USER_BUFFER;
        goto done;
    }

952
    if (type == FD_TYPE_FILE && offset && offset->QuadPart != (LONGLONG)-2 /* FILE_USE_FILE_POINTER_POSITION */ )
953
    {
954 955
        /* async I/O doesn't make sense on regular files */
        while ((result = pwrite( unix_handle, buffer, length, offset->QuadPart )) == -1)
956
        {
957
            if (errno != EINTR)
958
            {
959 960
                if (errno == EFAULT) status = STATUS_INVALID_USER_BUFFER;
                else status = FILE_GetNtStatus();
961 962
                goto done;
            }
963 964
        }

965 966
        if (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT))
            /* update file pointer position */
967 968 969 970 971 972 973 974 975
            lseek( unix_handle, offset->QuadPart + result, SEEK_SET );

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

    for (;;)
    {
976 977 978 979 980 981 982
        /* 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)
983 984 985
        {
            total += result;
            if (total == length)
986
            {
987
                status = STATUS_SUCCESS;
988 989
                goto done;
            }
990
            if (type == FD_TYPE_FILE) continue;  /* no async I/O on regular files */
991
        }
992
        else if (errno != EAGAIN)
993
        {
994
            if (errno == EINTR) continue;
995
            if (!total)
996
            {
997 998
                if (errno == EFAULT) status = STATUS_INVALID_USER_BUFFER;
                else status = FILE_GetNtStatus();
999
            }
1000
            goto done;
1001
        }
1002

1003
        if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
1004
        {
1005
            async_fileio_write *fileio;
1006

1007
            if (!(fileio = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(*fileio))))
1008 1009
            {
                status = STATUS_NO_MEMORY;
1010
                goto err;
1011
            }
1012 1013 1014
            fileio->io.handle  = hFile;
            fileio->io.apc     = apc;
            fileio->io.apc_arg = apc_user;
1015 1016
            fileio->already = total;
            fileio->count = length;
1017 1018 1019 1020 1021 1022
            fileio->buffer = buffer;

            SERVER_START_REQ( register_async )
            {
                req->type   = ASYNC_TYPE_WRITE;
                req->count  = length;
1023 1024
                req->async.handle   = wine_server_obj_handle( hFile );
                req->async.event    = wine_server_obj_handle( hEvent );
1025 1026 1027
                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 );
1028
                req->async.cvalue   = cvalue;
1029 1030 1031 1032 1033
                status = wine_server_call( req );
            }
            SERVER_END_REQ;

            if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
1034
            goto err;
1035
        }
1036
        else  /* synchronous write, wait for the fd to become ready */
1037
        {
1038 1039 1040 1041 1042 1043 1044
            struct pollfd pfd;
            int ret, timeout;

            if (!timeout_init_done)
            {
                timeout_init_done = 1;
                if ((status = get_io_timeouts( hFile, type, length, FALSE, &timeouts )))
1045
                    goto err;
1046 1047 1048 1049 1050
                if (hEvent) NtResetEvent( hEvent, NULL );
            }
            timeout = get_next_io_timeout( &timeouts, total );

            pfd.fd = unix_handle;
1051
            pfd.events = POLLOUT;
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064

            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 */
1065
        }
1066 1067
    }

1068
done:
1069
    send_completion = cvalue != 0;
1070 1071

err:
1072
    if (needs_close) close( unix_handle );
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
    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 );
    }
1087 1088 1089

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

1090
    return status;
Juergen Schmied's avatar
Juergen Schmied committed
1091 1092
}

1093

1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
/******************************************************************************
 *  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 )
{
    size_t page_size = getpagesize();
    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;
1109
    BOOL send_completion = FALSE;
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161

    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)
    {
        if (offset && offset->QuadPart != (LONGLONG)-2 /* FILE_USE_FILE_POINTER_POSITION */)
            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++;
        }
    }

1162
    send_completion = cvalue != 0;
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179

 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 );
    }
1180 1181 1182

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

1183 1184 1185 1186
    return status;
}


1187 1188
struct async_ioctl
{
1189
    HANDLE          handle;   /* handle to the device */
1190
    HANDLE          event;    /* async event */
1191 1192 1193 1194
    void           *buffer;   /* buffer for output */
    ULONG           size;     /* size of buffer */
    PIO_APC_ROUTINE apc;      /* user apc params */
    void           *apc_arg;
1195 1196
};

1197 1198 1199 1200 1201 1202 1203 1204
/* callback for ioctl user APC */
static void WINAPI ioctl_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
{
    struct async_ioctl *async = arg;
    if (async->apc) async->apc( async->apc_arg, io, reserved );
    RtlFreeHeap( GetProcessHeap(), 0, async );
}

1205
/* callback for ioctl async I/O completion */
1206
static NTSTATUS ioctl_completion( void *arg, IO_STATUS_BLOCK *io, NTSTATUS status, void **apc )
1207
{
1208 1209 1210 1211 1212 1213
    struct async_ioctl *async = arg;

    if (status == STATUS_ALERTED)
    {
        SERVER_START_REQ( get_ioctl_result )
        {
1214
            req->handle   = wine_server_obj_handle( async->handle );
1215
            req->user_arg = wine_server_client_ptr( async );
1216
            wine_server_set_reply( req, async->buffer, async->size );
1217 1218
            status = wine_server_call( req );
            if (status != STATUS_PENDING) io->Information = wine_server_reply_size( reply );
1219 1220 1221
        }
        SERVER_END_REQ;
    }
1222 1223 1224 1225 1226
    if (status != STATUS_PENDING)
    {
        io->u.Status = status;
        if (async->apc || async->event) *apc = ioctl_apc;
    }
1227 1228 1229 1230 1231 1232 1233
    return status;
}

/* do a ioctl call through the server */
static NTSTATUS server_ioctl_file( HANDLE handle, HANDLE event,
                                   PIO_APC_ROUTINE apc, PVOID apc_context,
                                   IO_STATUS_BLOCK *io, ULONG code,
1234
                                   const void *in_buffer, ULONG in_size,
1235 1236
                                   PVOID out_buffer, ULONG out_size )
{
1237
    struct async_ioctl *async;
1238
    NTSTATUS status;
1239 1240
    HANDLE wait_handle;
    ULONG options;
1241
    ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;
1242

1243 1244
    if (!(async = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*async) )))
        return STATUS_NO_MEMORY;
1245
    async->handle  = handle;
1246
    async->event   = event;
1247 1248 1249 1250
    async->buffer  = out_buffer;
    async->size    = out_size;
    async->apc     = apc;
    async->apc_arg = apc_context;
1251

1252 1253 1254
    SERVER_START_REQ( ioctl )
    {
        req->code           = code;
1255
        req->blocking       = !apc && !event && !cvalue;
1256
        req->async.handle   = wine_server_obj_handle( handle );
1257 1258 1259
        req->async.callback = wine_server_client_ptr( ioctl_completion );
        req->async.iosb     = wine_server_client_ptr( io );
        req->async.arg      = wine_server_client_ptr( async );
1260
        req->async.event    = wine_server_obj_handle( event );
1261
        req->async.cvalue   = cvalue;
1262 1263
        wine_server_add_data( req, in_buffer, in_size );
        wine_server_set_reply( req, out_buffer, out_size );
1264
        status = wine_server_call( req );
1265
        wait_handle = wine_server_ptr_handle( reply->wait );
1266
        options     = reply->options;
1267
        if (status != STATUS_PENDING) io->Information = wine_server_reply_size( reply );
1268 1269 1270 1271 1272 1273 1274
    }
    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);

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

1277 1278 1279 1280 1281
    if (wait_handle)
    {
        NtWaitForSingleObject( wait_handle, (options & FILE_SYNCHRONOUS_IO_ALERT), NULL );
        status = io->u.Status;
        NtClose( wait_handle );
1282
        RtlFreeHeap( GetProcessHeap(), 0, async );
1283 1284
    }

1285 1286 1287
    return status;
}

1288 1289 1290 1291 1292 1293 1294 1295
/* 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 { \
1296 1297 1298 1299 1300
        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)); \
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
    } while (0)

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

1312

Juergen Schmied's avatar
Juergen Schmied committed
1313
/**************************************************************************
1314
 *		NtDeviceIoControlFile			[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
1315
 *		ZwDeviceIoControlFile			[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
1316 1317 1318 1319
 *
 * Perform an I/O control operation on an open file handle.
 *
 * PARAMS
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
 *  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
1330 1331 1332 1333
 *
 * RETURNS
 *  Success: 0. IoStatusBlock is updated.
 *  Failure: An NTSTATUS error code describing the error.
Juergen Schmied's avatar
Juergen Schmied committed
1334
 */
1335 1336 1337 1338 1339
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
1340
{
1341
    ULONG device = (code >> 16);
1342
    NTSTATUS status = STATUS_NOT_SUPPORTED;
1343

1344
    TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1345 1346 1347 1348
          handle, event, apc, apc_context, io, code,
          in_buffer, in_size, out_buffer, out_size);

    switch(device)
1349
    {
1350 1351 1352 1353 1354
    case FILE_DEVICE_DISK:
    case FILE_DEVICE_CD_ROM:
    case FILE_DEVICE_DVD:
    case FILE_DEVICE_CONTROLLER:
    case FILE_DEVICE_MASS_STORAGE:
1355 1356
        status = CDROM_DeviceIoControl(handle, event, apc, apc_context, io, code,
                                       in_buffer, in_size, out_buffer, out_size);
1357 1358
        break;
    case FILE_DEVICE_SERIAL_PORT:
1359 1360
        status = COMM_DeviceIoControl(handle, event, apc, apc_context, io, code,
                                      in_buffer, in_size, out_buffer, out_size);
1361
        break;
1362
    case FILE_DEVICE_TAPE:
1363 1364
        status = TAPE_DeviceIoControl(handle, event, apc, apc_context, io, code,
                                      in_buffer, in_size, out_buffer, out_size);
1365
        break;
1366 1367
    }

1368
    if (status == STATUS_NOT_SUPPORTED || status == STATUS_BAD_DEVICE_TYPE)
1369 1370
        status = server_ioctl_file( handle, event, apc, apc_context, io, code,
                                    in_buffer, in_size, out_buffer, out_size );
1371

1372 1373
    if (status != STATUS_PENDING) io->u.Status = status;
    return status;
Juergen Schmied's avatar
Juergen Schmied committed
1374 1375
}

1376 1377 1378 1379 1380 1381 1382 1383

/**************************************************************************
 *              NtFsControlFile                 [NTDLL.@]
 *              ZwFsControlFile                 [NTDLL.@]
 *
 * Perform a file system control operation on an open file handle.
 *
 * PARAMS
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
 *  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
1394 1395 1396 1397
 *
 * RETURNS
 *  Success: 0. IoStatusBlock is updated.
 *  Failure: An NTSTATUS error code describing the error.
Juergen Schmied's avatar
Juergen Schmied committed
1398
 */
1399 1400 1401
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
1402
{
1403 1404
    NTSTATUS status;

1405
    TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1406 1407
          handle, event, apc, apc_context, io, code,
          in_buffer, in_size, out_buffer, out_size);
1408

1409
    if (!io) return STATUS_INVALID_PARAMETER;
1410

1411 1412
    ignore_server_ioctl_struct_holes( code, in_buffer, in_size );

1413
    switch(code)
1414
    {
1415
    case FSCTL_DISMOUNT_VOLUME:
1416 1417 1418
        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 );
1419
        break;
1420

1421 1422 1423
    case FSCTL_PIPE_PEEK:
        {
            FILE_PIPE_PEEK_BUFFER *buffer = out_buffer;
1424
            int avail = 0, fd, needs_close;
1425 1426 1427

            if (out_size < FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data ))
            {
1428
                status = STATUS_INFO_LENGTH_MISMATCH;
1429 1430 1431
                break;
            }

1432
            if ((status = server_get_unix_fd( handle, FILE_READ_DATA, &fd, &needs_close, NULL, NULL )))
1433 1434 1435 1436 1437 1438
                break;

#ifdef FIONREAD
            if (ioctl( fd, FIONREAD, &avail ) != 0)
            {
                TRACE("FIONREAD failed reason: %s\n",strerror(errno));
1439
                if (needs_close) close( fd );
1440
                status = FILE_GetNtStatus();
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
                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))))
                {
1455
                    if (needs_close) close( fd );
1456
                    status = STATUS_PIPE_BROKEN;
1457 1458 1459 1460 1461 1462 1463 1464
                    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 );
1465
            status = STATUS_SUCCESS;
1466 1467 1468 1469 1470 1471 1472 1473 1474
            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;
                }
            }
1475
            if (needs_close) close( fd );
1476 1477 1478
        }
        break;

1479
    case FSCTL_PIPE_DISCONNECT:
1480 1481 1482
        status = server_ioctl_file( handle, event, apc, apc_context, io, code,
                                    in_buffer, in_size, out_buffer, out_size );
        if (!status)
1483
        {
1484 1485
            int fd = server_remove_fd_from_cache( handle );
            if (fd != -1) close( fd );
1486 1487 1488
        }
        break;

1489
    case FSCTL_PIPE_IMPERSONATE:
1490
        FIXME("FSCTL_PIPE_IMPERSONATE: impersonating self\n");
1491 1492 1493
        status = RtlImpersonateSelf( SecurityImpersonation );
        break;

1494 1495
    case FSCTL_LOCK_VOLUME:
    case FSCTL_UNLOCK_VOLUME:
1496
        FIXME("stub! return success - Unsupported fsctl %x (device=%x access=%x func=%x method=%x)\n",
1497
              code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
1498
        status = STATUS_SUCCESS;
1499 1500
        break;

1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
    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;
    }
1523
    case FSCTL_PIPE_LISTEN:
1524
    case FSCTL_PIPE_WAIT:
1525
    default:
1526 1527
        status = server_ioctl_file( handle, event, apc, apc_context, io, code,
                                    in_buffer, in_size, out_buffer, out_size );
1528
        break;
1529
    }
1530 1531 1532

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

/******************************************************************************
1536
 *  NtSetVolumeInformationFile		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
1537
 *  ZwSetVolumeInformationFile		[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
 *
 * 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
1551 1552 1553
 */
NTSTATUS WINAPI NtSetVolumeInformationFile(
	IN HANDLE FileHandle,
1554 1555 1556
	PIO_STATUS_BLOCK IoStatusBlock,
	PVOID FsInformation,
        ULONG Length,
1557
	FS_INFORMATION_CLASS FsInformationClass)
Juergen Schmied's avatar
Juergen Schmied committed
1558
{
1559
	FIXME("(%p,%p,%p,0x%08x,0x%08x) stub\n",
1560
	FileHandle,IoStatusBlock,FsInformation,Length,FsInformationClass);
Juergen Schmied's avatar
Juergen Schmied committed
1561 1562 1563
	return 0;
}

1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
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;
#endif
#ifdef HAVE_STRUCT_STAT_ST_CTIM
    ctime->QuadPart += st->st_ctim.tv_nsec / 100;
#endif
#ifdef HAVE_STRUCT_STAT_ST_ATIM
    atime->QuadPart += st->st_atim.tv_nsec / 100;
#endif
    *creation = *mtime;
}

1582
/* fill in the file information that depends on the stat info */
1583
NTSTATUS fill_stat_info( const struct stat *st, void *ptr, FILE_INFORMATION_CLASS class )
1584 1585 1586 1587 1588 1589 1590
{
    switch (class)
    {
    case FileBasicInformation:
        {
            FILE_BASIC_INFORMATION *info = ptr;

1591 1592
            get_file_times( st, &info->LastWriteTime, &info->ChangeTime,
                            &info->LastAccessTime, &info->CreationTime );
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
            if (S_ISDIR(st->st_mode)) info->FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
            else info->FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
            if (!(st->st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
                info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
        }
        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;
            fill_stat_info( st, &info->BasicInformation, FileBasicInformation );
            fill_stat_info( st, &info->StandardInformation, FileStandardInformation );
            fill_stat_info( st, &info->InternalInformation, FileInternalInformation );
        }
        break;
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
    /* 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;
                info->FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
            }
            else
            {
                info->AllocationSize.QuadPart = (ULONGLONG)st->st_blocks * 512;
                info->EndOfFile.QuadPart      = st->st_size;
                info->FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
            }
            if (!(st->st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
                info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
        }
        break;
    case FileIdFullDirectoryInformation:
        {
            FILE_ID_FULL_DIRECTORY_INFORMATION *info = ptr;
            info->FileId.QuadPart = st->st_ino;
            fill_stat_info( st, info, FileDirectoryInformation );
        }
        break;
    case FileIdBothDirectoryInformation:
        {
            FILE_ID_BOTH_DIRECTORY_INFORMATION *info = ptr;
            info->FileId.QuadPart = st->st_ino;
            fill_stat_info( st, info, FileDirectoryInformation );
        }
        break;
1676 1677 1678 1679 1680 1681 1682

    default:
        return STATUS_INVALID_INFO_CLASS;
    }
    return STATUS_SUCCESS;
}

1683
NTSTATUS server_get_unix_name( HANDLE handle, ANSI_STRING *unix_name )
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
{
    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;
}

1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
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
1744
/******************************************************************************
1745
 *  NtQueryInformationFile		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
1746
 *  ZwQueryInformationFile		[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
1747 1748 1749 1750
 *
 * Get information about an open file handle.
 *
 * PARAMS
1751 1752 1753 1754 1755
 *  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
1756 1757 1758 1759
 *
 * RETURNS
 *  Success: 0. IoStatusBlock and FileInformation are updated.
 *  Failure: An NTSTATUS error code describing the error.
Juergen Schmied's avatar
Juergen Schmied committed
1760
 */
1761 1762
NTSTATUS WINAPI NtQueryInformationFile( HANDLE hFile, PIO_STATUS_BLOCK io,
                                        PVOID ptr, LONG len, FILE_INFORMATION_CLASS class )
Juergen Schmied's avatar
Juergen Schmied committed
1763
{
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
    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 */
1775
        sizeof(FILE_NAME_INFORMATION),                 /* FileNameInformation */
1776 1777 1778 1779 1780 1781 1782 1783
        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 */
1784
        sizeof(FILE_ALL_INFORMATION),                  /* FileAllInformation */
1785 1786 1787 1788 1789
        sizeof(FILE_ALLOCATION_INFORMATION),           /* FileAllocationInformation */
        sizeof(FILE_END_OF_FILE_INFORMATION),          /* FileEndOfFileInformation */
        0,                                             /* FileAlternateNameInformation */
        sizeof(FILE_STREAM_INFORMATION)-sizeof(WCHAR), /* FileStreamInformation */
        0,                                             /* FilePipeInformation */
1790
        sizeof(FILE_PIPE_LOCAL_INFORMATION),           /* FilePipeLocalInformation */
1791
        0,                                             /* FilePipeRemoteInformation */
1792
        sizeof(FILE_MAILSLOT_QUERY_INFORMATION),       /* FileMailslotQueryInformation */
1793 1794 1795 1796 1797 1798 1799 1800 1801
        0,                                             /* FileMailslotSetInformation */
        0,                                             /* FileCompressionInformation */
        0,                                             /* FileObjectIdInformation */
        0,                                             /* FileCompletionInformation */
        0,                                             /* FileMoveClusterInformation */
        0,                                             /* FileQuotaInformation */
        0,                                             /* FileReparsePointInformation */
        0,                                             /* FileNetworkOpenInformation */
        0,                                             /* FileAttributeTagInformation */
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
        0,                                             /* FileTrackingInformation */
        0,                                             /* FileIdBothDirectoryInformation */
        0,                                             /* FileIdFullDirectoryInformation */
        0,                                             /* FileValidDataLengthInformation */
        0,                                             /* FileShortNameInformation */
        0,
        0,
        0,
        0,                                             /* FileSfioReserveInformation */
        0,                                             /* FileSfioVolumeInformation */
        0,                                             /* FileHardLinkInformation */
        0,
        0,                                             /* FileNormalizedNameInformation */
        0,
        0,                                             /* FileIdGlobalTxDirectoryInformation */
        0,
        0,
        0,
        0                                              /* FileStandardLinkInformation */
1821 1822 1823
    };

    struct stat st;
1824
    int fd, needs_close = FALSE;
1825

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

1828
    io->Information = 0;
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839

    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;

1840 1841
    if (class != FilePipeLocalInformation)
    {
1842
        if ((io->u.Status = server_get_unix_fd( hFile, 0, &fd, &needs_close, NULL, NULL )))
1843
            return io->u.Status;
1844
    }
1845 1846 1847 1848

    switch (class)
    {
    case FileBasicInformation:
1849 1850 1851 1852 1853 1854
        if (fstat( fd, &st ) == -1)
            io->u.Status = FILE_GetNtStatus();
        else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
            io->u.Status = STATUS_INVALID_INFO_CLASS;
        else
            fill_stat_info( &st, ptr, class );
1855 1856 1857
        break;
    case FileStandardInformation:
        {
1858
            FILE_STANDARD_INFORMATION *info = ptr;
1859

1860
            if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1861
            else
1862
            {
1863 1864
                fill_stat_info( &st, info, class );
                info->DeletePending = FALSE; /* FIXME */
1865 1866 1867 1868 1869
            }
        }
        break;
    case FilePositionInformation:
        {
1870
            FILE_POSITION_INFORMATION *info = ptr;
1871 1872 1873 1874 1875 1876
            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:
1877 1878
        if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
        else fill_stat_info( &st, ptr, class );
1879 1880 1881 1882 1883 1884 1885 1886
        break;
    case FileEaInformation:
        {
            FILE_EA_INFORMATION *info = ptr;
            info->EaSize = 0;
        }
        break;
    case FileEndOfFileInformation:
1887 1888
        if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
        else fill_stat_info( &st, ptr, class );
1889 1890 1891 1892
        break;
    case FileAllInformation:
        {
            FILE_ALL_INFORMATION *info = ptr;
1893
            ANSI_STRING unix_name;
1894 1895 1896 1897

            if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
            else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
                io->u.Status = STATUS_INVALID_INFO_CLASS;
1898
            else if (!(io->u.Status = server_get_unix_name( hFile, &unix_name )))
1899
            {
1900 1901
                LONG name_len = len - FIELD_OFFSET(FILE_ALL_INFORMATION, NameInformation.FileName);

1902 1903
                fill_stat_info( &st, info, FileAllInformation );
                info->StandardInformation.DeletePending = FALSE; /* FIXME */
1904 1905 1906 1907 1908
                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 */
1909 1910 1911 1912

                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;
1913 1914 1915
            }
        }
        break;
1916 1917 1918 1919 1920 1921
    case FileMailslotQueryInformation:
        {
            FILE_MAILSLOT_QUERY_INFORMATION *info = ptr;

            SERVER_START_REQ( set_mailslot_info )
            {
1922
                req->handle = wine_server_obj_handle( hFile );
1923 1924 1925 1926 1927 1928
                req->flags = 0;
                io->u.Status = wine_server_call( req );
                if( io->u.Status == STATUS_SUCCESS )
                {
                    info->MaximumMessageSize = reply->max_msgsize;
                    info->MailslotQuota = 0;
1929 1930
                    info->NextMessageSize = 0;
                    info->MessagesAvailable = 0;
1931
                    info->ReadTimeout.QuadPart = reply->read_timeout;
1932 1933 1934
                }
            }
            SERVER_END_REQ;
1935 1936
            if (!io->u.Status)
            {
1937
                char *tmpbuf;
1938
                ULONG size = info->MaximumMessageSize ? info->MaximumMessageSize : 0x10000;
1939 1940
                if (size > 0x10000) size = 0x10000;
                if ((tmpbuf = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1941 1942
                {
                    int fd, needs_close;
1943
                    if (!server_get_unix_fd( hFile, FILE_READ_DATA, &fd, &needs_close, NULL, NULL ))
1944 1945 1946 1947 1948 1949 1950 1951 1952
                    {
                        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 );
                }
            }
1953 1954
        }
        break;
1955 1956 1957 1958 1959 1960
    case FilePipeLocalInformation:
        {
            FILE_PIPE_LOCAL_INFORMATION* pli = ptr;

            SERVER_START_REQ( get_named_pipe_info )
            {
1961
                req->handle = wine_server_obj_handle( hFile );
1962 1963 1964 1965
                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;
1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
                    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;
                    }
1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991
                    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;
1992 1993 1994 1995 1996 1997 1998 1999
    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);
2000
                io->u.Status = fill_name_info( &unix_name, info, &name_len );
2001
                RtlFreeAnsiString( &unix_name );
2002
                io->Information = FIELD_OFFSET(FILE_NAME_INFORMATION, FileName) + name_len;
2003 2004 2005
            }
        }
        break;
2006 2007
    default:
        FIXME("Unsupported class (%d)\n", class);
2008 2009
        io->u.Status = STATUS_NOT_IMPLEMENTED;
        break;
2010
    }
2011
    if (needs_close) close( fd );
2012
    if (io->u.Status == STATUS_SUCCESS && !io->Information) io->Information = info_sizes[class];
2013
    return io->u.Status;
Juergen Schmied's avatar
Juergen Schmied committed
2014 2015 2016
}

/******************************************************************************
2017
 *  NtSetInformationFile		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
2018
 *  ZwSetInformationFile		[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
2019 2020 2021 2022
 *
 * Set information about an open file handle.
 *
 * PARAMS
2023 2024 2025 2026 2027
 *  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
2028 2029
 *
 * RETURNS
2030
 *  Success: 0. io is updated.
Jon Griffiths's avatar
Jon Griffiths committed
2031
 *  Failure: An NTSTATUS error code describing the error.
Juergen Schmied's avatar
Juergen Schmied committed
2032
 */
2033 2034
NTSTATUS WINAPI NtSetInformationFile(HANDLE handle, PIO_STATUS_BLOCK io,
                                     PVOID ptr, ULONG len, FILE_INFORMATION_CLASS class)
Juergen Schmied's avatar
Juergen Schmied committed
2035
{
2036
    int fd, needs_close;
2037

2038
    TRACE("(%p,%p,%p,0x%08x,0x%08x)\n", handle, io, ptr, len, class);
2039 2040

    io->u.Status = STATUS_SUCCESS;
2041
    switch (class)
Jon Griffiths's avatar
Jon Griffiths committed
2042
    {
2043 2044
    case FileBasicInformation:
        if (len >= sizeof(FILE_BASIC_INFORMATION))
2045
        {
2046 2047
            struct stat st;
            const FILE_BASIC_INFORMATION *info = ptr;
2048

2049 2050 2051
            if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
                return io->u.Status;

2052
            if (info->LastAccessTime.QuadPart || info->LastWriteTime.QuadPart)
2053
            {
2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068
                struct timeval tv[2];

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

                    tv[0].tv_sec = tv[0].tv_usec = 0;
                    tv[1].tv_sec = tv[1].tv_usec = 0;
                    if (!fstat( fd, &st ))
                    {
                        tv[0].tv_sec = st.st_atime;
                        tv[1].tv_sec = st.st_mtime;
                    }
                }
                if (info->LastAccessTime.QuadPart)
                {
2069 2070
                    ULONGLONG sec = info->LastAccessTime.QuadPart / 10000000;
                    UINT nsec = info->LastAccessTime.QuadPart % 10000000;
2071
                    tv[0].tv_sec = sec - SECS_1601_TO_1970;
2072
                    tv[0].tv_usec = nsec / 10;
2073 2074 2075
                }
                if (info->LastWriteTime.QuadPart)
                {
2076 2077
                    ULONGLONG sec = info->LastWriteTime.QuadPart / 10000000;
                    UINT nsec = info->LastWriteTime.QuadPart % 10000000;
2078
                    tv[1].tv_sec = sec - SECS_1601_TO_1970;
2079
                    tv[1].tv_usec = nsec / 10;
2080 2081
                }
                if (futimes( fd, tv ) == -1) io->u.Status = FILE_GetNtStatus();
2082
            }
2083

2084 2085 2086 2087 2088 2089 2090
            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)
                    {
2091 2092 2093 2094
                        if (S_ISDIR( st.st_mode))
                            WARN("FILE_ATTRIBUTE_READONLY ignored for directory.\n");
                        else
                            st.st_mode &= ~0222; /* clear write permission bits */
2095 2096 2097 2098 2099 2100 2101 2102 2103
                    }
                    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();
                }
            }
2104 2105

            if (needs_close) close( fd );
2106 2107 2108 2109 2110 2111 2112 2113 2114
        }
        else io->u.Status = STATUS_INVALID_PARAMETER_3;
        break;

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

2115 2116 2117
            if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
                return io->u.Status;

2118 2119
            if (lseek( fd, info->CurrentByteOffset.QuadPart, SEEK_SET ) == (off_t)-1)
                io->u.Status = FILE_GetNtStatus();
2120 2121

            if (needs_close) close( fd );
2122
        }
2123
        else io->u.Status = STATUS_INVALID_PARAMETER_3;
2124
        break;
2125

2126 2127 2128
    case FileEndOfFileInformation:
        if (len >= sizeof(FILE_END_OF_FILE_INFORMATION))
        {
2129
            struct stat st;
2130 2131
            const FILE_END_OF_FILE_INFORMATION *info = ptr;

2132 2133 2134
            if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
                return io->u.Status;

2135 2136 2137 2138 2139
            /* 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)
2140 2141 2142 2143 2144
            {
                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 */
2145 2146
                if (pwrite( fd, &zero, 1, (off_t)info->EndOfFile.QuadPart ) != -1 &&
                    ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
2147
            }
2148
            io->u.Status = FILE_GetNtStatus();
2149 2150

            if (needs_close) close( fd );
2151 2152 2153 2154
        }
        else io->u.Status = STATUS_INVALID_PARAMETER_3;
        break;

2155 2156 2157 2158 2159 2160
    case FileMailslotSetInformation:
        {
            FILE_MAILSLOT_SET_INFORMATION *info = ptr;

            SERVER_START_REQ( set_mailslot_info )
            {
2161
                req->handle = wine_server_obj_handle( handle );
2162
                req->flags = MAILSLOT_SET_READ_TIMEOUT;
2163
                req->read_timeout = info->ReadTimeout.QuadPart;
2164 2165 2166 2167 2168 2169
                io->u.Status = wine_server_call( req );
            }
            SERVER_END_REQ;
        }
        break;

2170 2171 2172
    case FileCompletionInformation:
        if (len >= sizeof(FILE_COMPLETION_INFORMATION))
        {
2173
            FILE_COMPLETION_INFORMATION *info = ptr;
2174 2175 2176

            SERVER_START_REQ( set_completion_info )
            {
2177 2178
                req->handle   = wine_server_obj_handle( handle );
                req->chandle  = wine_server_obj_handle( info->CompletionPort );
2179 2180 2181 2182 2183 2184 2185 2186
                req->ckey     = info->CompletionKey;
                io->u.Status  = wine_server_call( req );
            }
            SERVER_END_REQ;
        } else
            io->u.Status = STATUS_INVALID_PARAMETER_3;
        break;

2187 2188 2189 2190
    case FileAllInformation:
        io->u.Status = STATUS_INVALID_INFO_CLASS;
        break;

2191 2192
    default:
        FIXME("Unsupported class (%d)\n", class);
2193 2194
        io->u.Status = STATUS_NOT_IMPLEMENTED;
        break;
2195
    }
2196 2197 2198 2199 2200 2201
    io->Information = 0;
    return io->u.Status;
}


/******************************************************************************
2202
 *              NtQueryFullAttributesFile   (NTDLL.@)
2203
 */
2204 2205
NTSTATUS WINAPI NtQueryFullAttributesFile( const OBJECT_ATTRIBUTES *attr,
                                           FILE_NETWORK_OPEN_INFORMATION *info )
2206 2207 2208 2209
{
    ANSI_STRING unix_name;
    NTSTATUS status;

2210
    if (!(status = nt_to_unix_file_name_attr( attr, &unix_name, FILE_OPEN )))
2211 2212 2213 2214 2215 2216 2217 2218 2219
    {
        struct stat st;

        if (stat( unix_name.Buffer, &st ) == -1)
            status = FILE_GetNtStatus();
        else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
            status = STATUS_INVALID_INFO_CLASS;
        else
        {
2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232
            FILE_BASIC_INFORMATION basic;
            FILE_STANDARD_INFORMATION std;

            fill_stat_info( &st, &basic, FileBasicInformation );
            fill_stat_info( &st, &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;
2233 2234 2235 2236 2237
            if (DIR_is_hidden_file( attr->ObjectName ))
                info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
        }
        RtlFreeAnsiString( &unix_name );
    }
2238
    else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), status );
2239
    return status;
Juergen Schmied's avatar
Juergen Schmied committed
2240 2241
}

2242

2243 2244 2245 2246 2247 2248
/******************************************************************************
 *              NtQueryAttributesFile   (NTDLL.@)
 *              ZwQueryAttributesFile   (NTDLL.@)
 */
NTSTATUS WINAPI NtQueryAttributesFile( const OBJECT_ATTRIBUTES *attr, FILE_BASIC_INFORMATION *info )
{
2249
    ANSI_STRING unix_name;
2250 2251
    NTSTATUS status;

2252
    if (!(status = nt_to_unix_file_name_attr( attr, &unix_name, FILE_OPEN )))
2253
    {
2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
        struct stat st;

        if (stat( unix_name.Buffer, &st ) == -1)
            status = FILE_GetNtStatus();
        else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
            status = STATUS_INVALID_INFO_CLASS;
        else
        {
            status = fill_stat_info( &st, info, FileBasicInformation );
            if (DIR_is_hidden_file( attr->ObjectName ))
                info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
        }
        RtlFreeAnsiString( &unix_name );
2267
    }
2268
    else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), status );
2269 2270 2271 2272
    return status;
}


2273
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
2274
/* helper for FILE_GetDeviceInfo to hide some platform differences in fstatfs */
2275
static inline void get_device_info_fstatfs( FILE_FS_DEVICE_INFORMATION *info, const char *fstypename,
2276
                                            unsigned int flags )
2277
{
2278
    if (!strcmp("cd9660", fstypename) || !strcmp("udf", fstypename))
2279 2280 2281 2282 2283
    {
        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;
    }
2284 2285
    else if (!strcmp("nfs", fstypename) || !strcmp("nwfs", fstypename) ||
             !strcmp("smbfs", fstypename) || !strcmp("afpfs", fstypename))
2286 2287 2288 2289
    {
        info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
        info->Characteristics |= FILE_REMOTE_DEVICE;
    }
2290
    else if (!strcmp("procfs", fstypename))
2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305
        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

2306 2307 2308 2309 2310 2311 2312 2313 2314 2315
static inline int is_device_placeholder( int fd )
{
    static const char wine_placeholder[] = "Wine device placeholder";
    char buffer[sizeof(wine_placeholder)-1];

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

2316
/******************************************************************************
2317
 *              get_device_info
2318 2319 2320
 *
 * Implementation of the FileFsDeviceInformation query for NtQueryVolumeInformationFile.
 */
2321
static NTSTATUS get_device_info( int fd, FILE_FS_DEVICE_INFORMATION *info )
2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
{
    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;
2342 2343 2344
        case SCSI_TAPE_MAJOR:
            info->DeviceType = FILE_DEVICE_TAPE;
            break;
2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355
        }
#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;
    }
2356 2357 2358 2359
    else if (is_device_placeholder( fd ))
    {
        info->DeviceType = FILE_DEVICE_DISK;
    }
2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
    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 */
2373
        case 0x9fa1:      /* supermount */
2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393
        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;
        }
2394
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__) || defined(__APPLE__)
2395 2396 2397 2398 2399
        struct statfs stfs;

        if (fstatfs( fd, &stfs ) < 0)
            info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
        else
2400
            get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flags );
2401 2402 2403 2404
#elif defined(__NetBSD__)
        struct statvfs stfs;

        if (fstatvfs( fd, &stfs) < 0)
2405
            info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2406
        else
2407
            get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flag );
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449
#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;
}


2450
/******************************************************************************
2451
 *  NtQueryVolumeInformationFile		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
2452
 *  ZwQueryVolumeInformationFile		[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
2453 2454 2455 2456
 *
 * Get volume information for an open file handle.
 *
 * PARAMS
2457 2458 2459 2460 2461
 *  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
2462 2463
 *
 * RETURNS
2464
 *  Success: 0. io and buffer are updated.
Jon Griffiths's avatar
Jon Griffiths committed
2465
 *  Failure: An NTSTATUS error code describing the error.
2466
 */
2467 2468 2469
NTSTATUS WINAPI NtQueryVolumeInformationFile( HANDLE handle, PIO_STATUS_BLOCK io,
                                              PVOID buffer, ULONG length,
                                              FS_INFORMATION_CLASS info_class )
2470
{
2471
    int fd, needs_close;
2472
    struct stat st;
2473
    static int once;
2474

2475
    if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
2476
        return io->u.Status;
2477

2478 2479
    io->u.Status = STATUS_NOT_IMPLEMENTED;
    io->Information = 0;
2480

2481 2482 2483
    switch( info_class )
    {
    case FileFsVolumeInformation:
2484
        if (!once++) FIXME( "%p: volume info not supported\n", handle );
2485 2486 2487 2488 2489 2490 2491 2492 2493 2494
        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;
2495

2496 2497 2498 2499 2500 2501 2502 2503 2504
            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;
            }
2505 2506
            else
            {
2507
                ULONGLONG bsize;
2508 2509 2510 2511 2512 2513 2514 2515 2516
                /* 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;
                }
2517
                bsize = stfs.f_frsize;
2518 2519 2520 2521 2522 2523 2524
#else
                struct statfs stfs;
                if (fstatfs( fd, &stfs ) < 0)
                {
                    io->u.Status = FILE_GetNtStatus();
                    break;
                }
2525
                bsize = stfs.f_bsize;
2526
#endif
2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538
                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);
2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550
                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;

2551
            if ((io->u.Status = get_device_info( fd, info )) == STATUS_SUCCESS)
2552
                io->Information = sizeof(*info);
2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573
        }
        break;
    case FileFsAttributeInformation:
        FIXME( "%p: attribute info not supported\n", handle );
        break;
    case FileFsControlInformation:
        FIXME( "%p: control info not supported\n", handle );
        break;
    case FileFsFullSizeInformation:
        FIXME( "%p: full size info not supported\n", handle );
        break;
    case FileFsObjectIdInformation:
        FIXME( "%p: object id info not supported\n", handle );
        break;
    case FileFsMaximumInformation:
        FIXME( "%p: maximum info not supported\n", handle );
        break;
    default:
        io->u.Status = STATUS_INVALID_PARAMETER;
        break;
    }
2574
    if (needs_close) close( fd );
2575
    return io->u.Status;
2576
}
2577

2578

2579 2580 2581 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 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631
/******************************************************************
 *		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;
}


2632 2633
/******************************************************************
 *		NtFlushBuffersFile  (NTDLL.@)
Jon Griffiths's avatar
Jon Griffiths committed
2634 2635 2636 2637 2638 2639 2640 2641 2642 2643
 *
 * 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.
2644 2645 2646 2647
 */
NTSTATUS WINAPI NtFlushBuffersFile( HANDLE hFile, IO_STATUS_BLOCK* IoStatusBlock )
{
    NTSTATUS ret;
2648 2649
    HANDLE hEvent = NULL;

2650 2651
    SERVER_START_REQ( flush_file )
    {
2652
        req->handle = wine_server_obj_handle( hFile );
2653
        ret = wine_server_call( req );
2654
        hEvent = wine_server_ptr_handle( reply->event );
2655 2656
    }
    SERVER_END_REQ;
2657
    if (!ret && hEvent)
2658 2659 2660 2661
    {
        ret = NtWaitForSingleObject( hEvent, FALSE, NULL );
        NtClose( hEvent );
    }
2662 2663
    return ret;
}
2664 2665 2666 2667 2668 2669 2670

/******************************************************************
 *		NtLockFile       (NTDLL.@)
 *
 *
 */
NTSTATUS WINAPI NtLockFile( HANDLE hFile, HANDLE lock_granted_event,
Jon Griffiths's avatar
Jon Griffiths committed
2671 2672
                            PIO_APC_ROUTINE apc, void* apc_user,
                            PIO_STATUS_BLOCK io_status, PLARGE_INTEGER offset,
2673 2674 2675 2676 2677 2678
                            PLARGE_INTEGER count, ULONG* key, BOOLEAN dont_wait,
                            BOOLEAN exclusive )
{
    NTSTATUS    ret;
    HANDLE      handle;
    BOOLEAN     async;
2679
    static BOOLEAN     warn = TRUE;
2680 2681 2682 2683 2684 2685 2686

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

2687 2688 2689 2690 2691
    if (apc_user && warn)
    {
        FIXME("I/O completion on lock not implemented yet\n");
        warn = FALSE;
    }
2692

2693 2694 2695 2696
    for (;;)
    {
        SERVER_START_REQ( lock_file )
        {
2697
            req->handle      = wine_server_obj_handle( hFile );
2698 2699
            req->offset      = offset->QuadPart;
            req->count       = count->QuadPart;
2700 2701 2702
            req->shared      = !exclusive;
            req->wait        = !dont_wait;
            ret = wine_server_call( req );
2703
            handle = wine_server_ptr_handle( reply->handle );
2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730
            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;
2731
            NtDelayExecution( FALSE, &time );
2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747
        }
    }
}


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

2748
    TRACE( "%p %x%08x %x%08x\n",
2749
           hFile, offset->u.HighPart, offset->u.LowPart, count->u.HighPart, count->u.LowPart );
2750 2751 2752 2753 2754 2755 2756 2757 2758

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

    SERVER_START_REQ( unlock_file )
    {
2759
        req->handle = wine_server_obj_handle( hFile );
2760 2761
        req->offset = offset->QuadPart;
        req->count  = count->QuadPart;
2762 2763 2764 2765 2766
        status = wine_server_call( req );
    }
    SERVER_END_REQ;
    return status;
}
2767 2768 2769 2770 2771 2772

/******************************************************************
 *		NtCreateNamedPipeFile    (NTDLL.@)
 *
 *
 */
2773
NTSTATUS WINAPI NtCreateNamedPipeFile( PHANDLE handle, ULONG access,
2774
                                       POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK iosb,
2775 2776 2777 2778 2779
                                       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)
2780
{
2781 2782
    NTSTATUS    status;

2783
    TRACE("(%p %x %s %p %x %d %x %d %d %d %d %d %d %p)\n",
2784
          handle, access, debugstr_w(attr->ObjectName->Buffer), iosb, sharing, dispo,
2785 2786
          options, pipe_type, read_mode, completion_mode, max_inst, inbound_quota,
          outbound_quota, timeout);
2787

2788 2789
    /* assume we only get relative timeout */
    if (timeout->QuadPart > 0)
2790 2791 2792 2793
        FIXME("Wrong time %s\n", wine_dbgstr_longlong(timeout->QuadPart));

    SERVER_START_REQ( create_named_pipe )
    {
2794
        req->access  = access;
2795
        req->attributes = attr->Attributes;
2796
        req->rootdir = wine_server_obj_handle( attr->RootDirectory );
2797
        req->options = options;
2798
        req->sharing = sharing;
2799 2800 2801 2802 2803 2804 2805
        req->flags = 
            (pipe_type) ? NAMED_PIPE_MESSAGE_STREAM_WRITE : 0 |
            (read_mode) ? NAMED_PIPE_MESSAGE_STREAM_READ  : 0 |
            (completion_mode) ? NAMED_PIPE_NONBLOCKING_MODE  : 0;
        req->maxinstances = max_inst;
        req->outsize = outbound_quota;
        req->insize  = inbound_quota;
2806
        req->timeout = timeout->QuadPart;
2807 2808
        wine_server_add_data( req, attr->ObjectName->Buffer,
                              attr->ObjectName->Length );
2809
        status = wine_server_call( req );
2810
        if (!status) *handle = wine_server_ptr_handle( reply->handle );
2811 2812 2813
    }
    SERVER_END_REQ;
    return status;
2814
}
2815 2816 2817 2818 2819 2820 2821 2822

/******************************************************************
 *		NtDeleteFile    (NTDLL.@)
 *
 *
 */
NTSTATUS WINAPI NtDeleteFile( POBJECT_ATTRIBUTES ObjectAttributes )
{
2823 2824 2825 2826 2827
    NTSTATUS status;
    HANDLE hFile;
    IO_STATUS_BLOCK io;

    TRACE("%p\n", ObjectAttributes);
2828 2829
    status = NtCreateFile( &hFile, GENERIC_READ | GENERIC_WRITE | DELETE,
                           ObjectAttributes, &io, NULL, 0,
2830 2831 2832 2833
                           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;
2834 2835
}

2836 2837 2838 2839 2840 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
/******************************************************************
 *		NtCancelIoFileEx    (NTDLL.@)
 *
 *
 */
NTSTATUS WINAPI NtCancelIoFileEx( HANDLE hFile, PIO_STATUS_BLOCK iosb, PIO_STATUS_BLOCK io_status )
{
    LARGE_INTEGER timeout;

    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;
    if (io_status->u.Status)
        return io_status->u.Status;

    /* Let some APC be run, so that we can run the remaining APCs on hFile
     * either the cancelation of the pending one, but also the execution
     * of the queued APC, but not yet run. This is needed to ensure proper
     * clean-up of allocated data.
     */
    timeout.u.LowPart = timeout.u.HighPart = 0;
    NtDelayExecution( TRUE, &timeout );
    return io_status->u.Status;
}

2868 2869 2870 2871 2872
/******************************************************************
 *		NtCancelIoFile    (NTDLL.@)
 *
 *
 */
2873
NTSTATUS WINAPI NtCancelIoFile( HANDLE hFile, PIO_STATUS_BLOCK io_status )
2874
{
2875 2876 2877 2878 2879 2880
    LARGE_INTEGER timeout;

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

    SERVER_START_REQ( cancel_async )
    {
2881 2882 2883 2884
        req->handle      = wine_server_obj_handle( hFile );
        req->iosb        = 0;
        req->only_thread = TRUE;
        io_status->u.Status = wine_server_call( req );
2885 2886
    }
    SERVER_END_REQ;
2887 2888 2889
    if (io_status->u.Status)
        return io_status->u.Status;

2890 2891 2892 2893 2894 2895
    /* Let some APC be run, so that we can run the remaining APCs on hFile
     * either the cancelation of the pending one, but also the execution
     * of the queued APC, but not yet run. This is needed to ensure proper
     * clean-up of allocated data.
     */
    timeout.u.LowPart = timeout.u.HighPart = 0;
2896 2897
    NtDelayExecution( TRUE, &timeout );
    return io_status->u.Status;
2898
}
2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921

/******************************************************************************
 *  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)
{
2922
    LARGE_INTEGER timeout;
2923 2924
    NTSTATUS ret;

2925
    TRACE("%p %08x %p %p %08x %08x %08x %p\n",
2926 2927 2928
              pHandle, DesiredAccess, attr, IoStatusBlock,
              CreateOptions, MailslotQuota, MaxMessageSize, TimeOut);

2929
    if (!pHandle) return STATUS_ACCESS_VIOLATION;
2930 2931 2932
    if (!attr) return STATUS_INVALID_PARAMETER;
    if (!attr->ObjectName) return STATUS_OBJECT_PATH_SYNTAX_BAD;

2933 2934 2935 2936 2937 2938 2939 2940
    /*
     *  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
2941 2942
    SERVER_START_REQ( create_mailslot )
    {
2943
        req->access = DesiredAccess;
2944
        req->attributes = attr->Attributes;
2945
        req->rootdir = wine_server_obj_handle( attr->RootDirectory );
Mike McCormack's avatar
Mike McCormack committed
2946
        req->max_msgsize = MaxMessageSize;
2947
        req->read_timeout = timeout.QuadPart;
2948 2949
        wine_server_add_data( req, attr->ObjectName->Buffer,
                              attr->ObjectName->Length );
Mike McCormack's avatar
Mike McCormack committed
2950 2951
        ret = wine_server_call( req );
        if( ret == STATUS_SUCCESS )
2952
            *pHandle = wine_server_ptr_handle( reply->handle );
Mike McCormack's avatar
Mike McCormack committed
2953 2954 2955
    }
    SERVER_END_REQ;
 
2956 2957
    return ret;
}