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

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

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

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

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

83
WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
84

85 86 87 88 89
mode_t FILE_umask = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

283

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

494

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

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

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


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

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

568 569
    if (!io_status) return STATUS_ACCESS_VIOLATION;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802

/******************************************************************************
 *  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;

    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++;
        }
    }

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

 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 );
    }
    return status;
}


803 804 805
/***********************************************************************
 *             FILE_AsyncWriteService      (INTERNAL)
 */
806
static NTSTATUS FILE_AsyncWriteService(void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status, ULONG_PTR *total)
807
{
808
    async_fileio_write *fileio = user;
809
    int result, fd, needs_close;
810
    enum server_fd_type type;
811

812
    switch (status)
813
    {
814 815
    case STATUS_ALERTED:
        /* write some data (non-blocking) */
816
        if ((status = server_get_unix_fd( fileio->io.handle, FILE_WRITE_DATA, &fd,
817
                                          &needs_close, &type, NULL )))
818
            break;
819

820 821 822 823 824
        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 );

825
        if (needs_close) close( fd );
826

827 828
        if (result < 0)
        {
829 830
            if (errno == EAGAIN || errno == EINTR) status = STATUS_PENDING;
            else status = FILE_GetNtStatus();
831 832 833
        }
        else
        {
834 835
            fileio->already += result;
            status = (fileio->already < fileio->count) ? STATUS_PENDING : STATUS_SUCCESS;
836 837
        }
        break;
838 839 840 841

    case STATUS_TIMEOUT:
    case STATUS_IO_TIMEOUT:
        if (fileio->already) status = STATUS_SUCCESS;
842
        break;
843
    }
844 845 846
    if (status != STATUS_PENDING)
    {
        iosb->u.Status = status;
847
        iosb->Information = *total = fileio->already;
848
    }
849
    return status;
850 851 852 853 854 855
}

/******************************************************************************
 *  NtWriteFile					[NTDLL.@]
 *  ZwWriteFile					[NTDLL.@]
 *
Jon Griffiths's avatar
Jon Griffiths committed
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
 * 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.
873
 */
874 875 876 877 878
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
879
{
880 881
    int result, unix_handle, needs_close, timeout_init_done = 0;
    unsigned int options;
882
    struct io_timeouts timeouts;
883
    NTSTATUS status;
884
    ULONG total = 0;
885
    enum server_fd_type type;
886
    ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
887

888
    TRACE("(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p)!\n",
889 890
          hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);

891 892
    if (!io_status) return STATUS_ACCESS_VIOLATION;

893
    status = server_get_unix_fd( hFile, FILE_WRITE_DATA, &unix_handle,
894
                                 &needs_close, &type, &options );
895
    if (status) return status;
896

897
    if (type == FD_TYPE_FILE && offset && offset->QuadPart != (LONGLONG)-2 /* FILE_USE_FILE_POINTER_POSITION */ )
898
    {
899 900
        /* async I/O doesn't make sense on regular files */
        while ((result = pwrite( unix_handle, buffer, length, offset->QuadPart )) == -1)
901
        {
902
            if (errno != EINTR)
903
            {
904 905
                if (errno == EFAULT) status = STATUS_INVALID_USER_BUFFER;
                else status = FILE_GetNtStatus();
906 907
                goto done;
            }
908 909
        }

910 911
        if (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT))
            /* update file pointer position */
912 913 914 915 916 917 918 919 920
            lseek( unix_handle, offset->QuadPart + result, SEEK_SET );

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

    for (;;)
    {
921 922 923 924 925 926 927
        /* 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)
928 929 930
        {
            total += result;
            if (total == length)
931
            {
932
                status = STATUS_SUCCESS;
933 934 935 936 937
                goto done;
            }
        }
        else
        {
938 939
            if (errno == EINTR) continue;
            if (errno != EAGAIN)
940
            {
941 942 943 944 945 946
                if (errno == EFAULT)
                {
                    status = STATUS_INVALID_USER_BUFFER;
                    goto err;
                }
                status = FILE_GetNtStatus();
947 948 949
                goto done;
            }
        }
950

951
        if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
952
        {
953
            async_fileio_write *fileio;
954

955
            if (!(fileio = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(*fileio))))
956 957
            {
                status = STATUS_NO_MEMORY;
958
                goto err;
959
            }
960 961 962
            fileio->io.handle  = hFile;
            fileio->io.apc     = apc;
            fileio->io.apc_arg = apc_user;
963 964
            fileio->already = total;
            fileio->count = length;
965 966 967 968 969 970 971 972 973 974
            fileio->buffer = buffer;

            SERVER_START_REQ( register_async )
            {
                req->handle = hFile;
                req->type   = ASYNC_TYPE_WRITE;
                req->count  = length;
                req->async.callback = FILE_AsyncWriteService;
                req->async.iosb     = io_status;
                req->async.arg      = fileio;
975
                req->async.apc      = fileio_apc;
976
                req->async.event    = hEvent;
977
                req->async.cvalue   = cvalue;
978 979 980 981 982
                status = wine_server_call( req );
            }
            SERVER_END_REQ;

            if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
983
            goto err;
984
        }
985
        else  /* synchronous write, wait for the fd to become ready */
986
        {
987 988 989 990 991 992 993
            struct pollfd pfd;
            int ret, timeout;

            if (!timeout_init_done)
            {
                timeout_init_done = 1;
                if ((status = get_io_timeouts( hFile, type, length, FALSE, &timeouts )))
994
                    goto err;
995 996 997 998 999
                if (hEvent) NtResetEvent( hEvent, NULL );
            }
            timeout = get_next_io_timeout( &timeouts, total );

            pfd.fd = unix_handle;
1000
            pfd.events = POLLOUT;
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013

            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 */
1014
        }
1015 1016
    }

1017
done:
1018 1019 1020
    if (cvalue) NTDLL_AddCompletion( hFile, cvalue, status, total );

err:
1021
    if (needs_close) close( unix_handle );
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
    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 );
    }
1036
    return status;
Juergen Schmied's avatar
Juergen Schmied committed
1037 1038
}

1039

1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
/******************************************************************************
 *  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;

    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++;
        }
    }

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

 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 );
    }
    return status;
}


1129 1130
struct async_ioctl
{
1131 1132 1133 1134 1135
    HANDLE          handle;   /* handle to the device */
    void           *buffer;   /* buffer for output */
    ULONG           size;     /* size of buffer */
    PIO_APC_ROUTINE apc;      /* user apc params */
    void           *apc_arg;
1136 1137
};

1138 1139 1140
/* callback for ioctl async I/O completion */
static NTSTATUS ioctl_completion( void *arg, IO_STATUS_BLOCK *io, NTSTATUS status )
{
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
    struct async_ioctl *async = arg;

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

1159 1160 1161 1162 1163 1164 1165 1166
/* 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 );
}

1167 1168 1169 1170
/* 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,
1171
                                   const void *in_buffer, ULONG in_size,
1172 1173
                                   PVOID out_buffer, ULONG out_size )
{
1174
    struct async_ioctl *async;
1175
    NTSTATUS status;
1176 1177
    HANDLE wait_handle;
    ULONG options;
1178
    ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;
1179

1180 1181
    if (!(async = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*async) )))
        return STATUS_NO_MEMORY;
1182 1183 1184 1185 1186
    async->handle  = handle;
    async->buffer  = out_buffer;
    async->size    = out_size;
    async->apc     = apc;
    async->apc_arg = apc_context;
1187

1188 1189 1190 1191 1192 1193
    SERVER_START_REQ( ioctl )
    {
        req->handle         = handle;
        req->code           = code;
        req->async.callback = ioctl_completion;
        req->async.iosb     = io;
1194
        req->async.arg      = async;
1195
        req->async.apc      = (apc || event) ? ioctl_apc : NULL;
1196
        req->async.event    = event;
1197
        req->async.cvalue   = cvalue;
1198 1199 1200 1201
        wine_server_add_data( req, in_buffer, in_size );
        wine_server_set_reply( req, out_buffer, out_size );
        if (!(status = wine_server_call( req )))
            io->Information = wine_server_reply_size( reply );
1202 1203
        wait_handle = reply->wait;
        options     = reply->options;
1204 1205 1206 1207 1208 1209 1210
    }
    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);

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

1213 1214 1215 1216 1217
    if (wait_handle)
    {
        NtWaitForSingleObject( wait_handle, (options & FILE_SYNCHRONOUS_IO_ALERT), NULL );
        status = io->u.Status;
        NtClose( wait_handle );
1218
        RtlFreeHeap( GetProcessHeap(), 0, async );
1219 1220
    }

1221 1222 1223 1224
    return status;
}


Juergen Schmied's avatar
Juergen Schmied committed
1225
/**************************************************************************
1226
 *		NtDeviceIoControlFile			[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
1227
 *		ZwDeviceIoControlFile			[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
1228 1229 1230 1231
 *
 * Perform an I/O control operation on an open file handle.
 *
 * PARAMS
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
 *  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
1242 1243 1244 1245
 *
 * RETURNS
 *  Success: 0. IoStatusBlock is updated.
 *  Failure: An NTSTATUS error code describing the error.
Juergen Schmied's avatar
Juergen Schmied committed
1246
 */
1247 1248 1249 1250 1251
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
1252
{
1253
    ULONG device = (code >> 16);
1254
    NTSTATUS status = STATUS_NOT_SUPPORTED;
1255

1256
    TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1257 1258 1259 1260
          handle, event, apc, apc_context, io, code,
          in_buffer, in_size, out_buffer, out_size);

    switch(device)
1261
    {
1262 1263 1264 1265 1266
    case FILE_DEVICE_DISK:
    case FILE_DEVICE_CD_ROM:
    case FILE_DEVICE_DVD:
    case FILE_DEVICE_CONTROLLER:
    case FILE_DEVICE_MASS_STORAGE:
1267 1268
        status = CDROM_DeviceIoControl(handle, event, apc, apc_context, io, code,
                                       in_buffer, in_size, out_buffer, out_size);
1269 1270
        break;
    case FILE_DEVICE_SERIAL_PORT:
1271 1272
        status = COMM_DeviceIoControl(handle, event, apc, apc_context, io, code,
                                      in_buffer, in_size, out_buffer, out_size);
1273
        break;
1274
    case FILE_DEVICE_TAPE:
1275 1276
        status = TAPE_DeviceIoControl(handle, event, apc, apc_context, io, code,
                                      in_buffer, in_size, out_buffer, out_size);
1277
        break;
1278 1279
    }

1280
    if (status == STATUS_NOT_SUPPORTED || status == STATUS_BAD_DEVICE_TYPE)
1281 1282
        status = server_ioctl_file( handle, event, apc, apc_context, io, code,
                                    in_buffer, in_size, out_buffer, out_size );
1283

1284 1285
    if (status != STATUS_PENDING) io->u.Status = status;
    return status;
Juergen Schmied's avatar
Juergen Schmied committed
1286 1287
}

1288 1289 1290 1291 1292 1293 1294 1295

/**************************************************************************
 *              NtFsControlFile                 [NTDLL.@]
 *              ZwFsControlFile                 [NTDLL.@]
 *
 * Perform a file system control operation on an open file handle.
 *
 * PARAMS
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
 *  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
1306 1307 1308 1309
 *
 * RETURNS
 *  Success: 0. IoStatusBlock is updated.
 *  Failure: An NTSTATUS error code describing the error.
Juergen Schmied's avatar
Juergen Schmied committed
1310
 */
1311 1312 1313
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
1314
{
1315 1316
    NTSTATUS status;

1317
    TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1318 1319
          handle, event, apc, apc_context, io, code,
          in_buffer, in_size, out_buffer, out_size);
1320

1321
    if (!io) return STATUS_INVALID_PARAMETER;
1322

1323
    switch(code)
1324
    {
1325
    case FSCTL_DISMOUNT_VOLUME:
1326 1327 1328
        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 );
1329
        break;
1330

1331 1332 1333
    case FSCTL_PIPE_PEEK:
        {
            FILE_PIPE_PEEK_BUFFER *buffer = out_buffer;
1334
            int avail = 0, fd, needs_close;
1335 1336 1337

            if (out_size < FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data ))
            {
1338
                status = STATUS_INFO_LENGTH_MISMATCH;
1339 1340 1341
                break;
            }

1342
            if ((status = server_get_unix_fd( handle, FILE_READ_DATA, &fd, &needs_close, NULL, NULL )))
1343 1344 1345 1346 1347 1348
                break;

#ifdef FIONREAD
            if (ioctl( fd, FIONREAD, &avail ) != 0)
            {
                TRACE("FIONREAD failed reason: %s\n",strerror(errno));
1349
                if (needs_close) close( fd );
1350
                status = FILE_GetNtStatus();
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
                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))))
                {
1365
                    if (needs_close) close( fd );
1366
                    status = STATUS_PIPE_BROKEN;
1367 1368 1369 1370 1371 1372 1373 1374
                    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 );
1375
            status = STATUS_SUCCESS;
1376 1377 1378 1379 1380 1381 1382 1383 1384
            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;
                }
            }
1385
            if (needs_close) close( fd );
1386 1387 1388
        }
        break;

1389
    case FSCTL_PIPE_DISCONNECT:
1390 1391 1392
        status = server_ioctl_file( handle, event, apc, apc_context, io, code,
                                    in_buffer, in_size, out_buffer, out_size );
        if (!status)
1393
        {
1394 1395
            int fd = server_remove_fd_from_cache( handle );
            if (fd != -1) close( fd );
1396 1397 1398
        }
        break;

1399
    case FSCTL_PIPE_IMPERSONATE:
1400
        FIXME("FSCTL_PIPE_IMPERSONATE: impersonating self\n");
1401 1402 1403
        status = RtlImpersonateSelf( SecurityImpersonation );
        break;

1404 1405
    case FSCTL_LOCK_VOLUME:
    case FSCTL_UNLOCK_VOLUME:
1406
        FIXME("stub! return success - Unsupported fsctl %x (device=%x access=%x func=%x method=%x)\n",
1407
              code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
1408
        status = STATUS_SUCCESS;
1409 1410
        break;

1411
    case FSCTL_PIPE_LISTEN:
1412
    case FSCTL_PIPE_WAIT:
1413
    default:
1414 1415
        status = server_ioctl_file( handle, event, apc, apc_context, io, code,
                                    in_buffer, in_size, out_buffer, out_size );
1416
        break;
1417
    }
1418 1419 1420

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

/******************************************************************************
1424
 *  NtSetVolumeInformationFile		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
1425
 *  ZwSetVolumeInformationFile		[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
 *
 * 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
1439 1440 1441
 */
NTSTATUS WINAPI NtSetVolumeInformationFile(
	IN HANDLE FileHandle,
1442 1443 1444
	PIO_STATUS_BLOCK IoStatusBlock,
	PVOID FsInformation,
        ULONG Length,
1445
	FS_INFORMATION_CLASS FsInformationClass)
Juergen Schmied's avatar
Juergen Schmied committed
1446
{
1447
	FIXME("(%p,%p,%p,0x%08x,0x%08x) stub\n",
1448
	FileHandle,IoStatusBlock,FsInformation,Length,FsInformationClass);
Juergen Schmied's avatar
Juergen Schmied committed
1449 1450 1451 1452
	return 0;
}

/******************************************************************************
1453
 *  NtQueryInformationFile		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
1454
 *  ZwQueryInformationFile		[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
1455 1456 1457 1458
 *
 * Get information about an open file handle.
 *
 * PARAMS
1459 1460 1461 1462 1463
 *  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
1464 1465 1466 1467
 *
 * RETURNS
 *  Success: 0. IoStatusBlock and FileInformation are updated.
 *  Failure: An NTSTATUS error code describing the error.
Juergen Schmied's avatar
Juergen Schmied committed
1468
 */
1469 1470
NTSTATUS WINAPI NtQueryInformationFile( HANDLE hFile, PIO_STATUS_BLOCK io,
                                        PVOID ptr, LONG len, FILE_INFORMATION_CLASS class )
Juergen Schmied's avatar
Juergen Schmied committed
1471
{
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
    static const size_t info_sizes[] =
    {
        0,
        sizeof(FILE_DIRECTORY_INFORMATION),            /* FileDirectoryInformation */
        sizeof(FILE_FULL_DIRECTORY_INFORMATION),       /* FileFullDirectoryInformation */
        sizeof(FILE_BOTH_DIRECTORY_INFORMATION),       /* FileBothDirectoryInformation */
        sizeof(FILE_BASIC_INFORMATION),                /* FileBasicInformation */
        sizeof(FILE_STANDARD_INFORMATION),             /* FileStandardInformation */
        sizeof(FILE_INTERNAL_INFORMATION),             /* FileInternalInformation */
        sizeof(FILE_EA_INFORMATION),                   /* FileEaInformation */
        sizeof(FILE_ACCESS_INFORMATION),               /* FileAccessInformation */
        sizeof(FILE_NAME_INFORMATION)-sizeof(WCHAR),   /* FileNameInformation */
        sizeof(FILE_RENAME_INFORMATION)-sizeof(WCHAR), /* FileRenameInformation */
        0,                                             /* FileLinkInformation */
        sizeof(FILE_NAMES_INFORMATION)-sizeof(WCHAR),  /* FileNamesInformation */
        sizeof(FILE_DISPOSITION_INFORMATION),          /* FileDispositionInformation */
        sizeof(FILE_POSITION_INFORMATION),             /* FilePositionInformation */
        sizeof(FILE_FULL_EA_INFORMATION),              /* FileFullEaInformation */
        sizeof(FILE_MODE_INFORMATION),                 /* FileModeInformation */
        sizeof(FILE_ALIGNMENT_INFORMATION),            /* FileAlignmentInformation */
        sizeof(FILE_ALL_INFORMATION)-sizeof(WCHAR),    /* FileAllInformation */
        sizeof(FILE_ALLOCATION_INFORMATION),           /* FileAllocationInformation */
        sizeof(FILE_END_OF_FILE_INFORMATION),          /* FileEndOfFileInformation */
        0,                                             /* FileAlternateNameInformation */
        sizeof(FILE_STREAM_INFORMATION)-sizeof(WCHAR), /* FileStreamInformation */
        0,                                             /* FilePipeInformation */
1498
        sizeof(FILE_PIPE_LOCAL_INFORMATION),           /* FilePipeLocalInformation */
1499
        0,                                             /* FilePipeRemoteInformation */
1500
        sizeof(FILE_MAILSLOT_QUERY_INFORMATION),       /* FileMailslotQueryInformation */
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
        0,                                             /* FileMailslotSetInformation */
        0,                                             /* FileCompressionInformation */
        0,                                             /* FileObjectIdInformation */
        0,                                             /* FileCompletionInformation */
        0,                                             /* FileMoveClusterInformation */
        0,                                             /* FileQuotaInformation */
        0,                                             /* FileReparsePointInformation */
        0,                                             /* FileNetworkOpenInformation */
        0,                                             /* FileAttributeTagInformation */
        0                                              /* FileTrackingInformation */
    };

    struct stat st;
1514
    int fd, needs_close = FALSE;
1515

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

1518
    io->Information = 0;
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529

    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;

1530 1531
    if (class != FilePipeLocalInformation)
    {
1532
        if ((io->u.Status = server_get_unix_fd( hFile, 0, &fd, &needs_close, NULL, NULL )))
1533
            return io->u.Status;
1534
    }
1535 1536 1537 1538 1539

    switch (class)
    {
    case FileBasicInformation:
        {
1540
            FILE_BASIC_INFORMATION *info = ptr;
1541

1542 1543 1544 1545
            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;
1546
            else
1547
            {
1548 1549
                if (S_ISDIR(st.st_mode)) info->FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
                else info->FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1550 1551
                if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
                    info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
1552 1553 1554 1555
                RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime);
                RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime);
                RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime);
                RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime);
1556 1557 1558 1559 1560
            }
        }
        break;
    case FileStandardInformation:
        {
1561
            FILE_STANDARD_INFORMATION *info = ptr;
1562

1563
            if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1564
            else
1565
            {
1566 1567 1568 1569 1570 1571 1572
                if ((info->Directory = S_ISDIR(st.st_mode)))
                {
                    info->AllocationSize.QuadPart = 0;
                    info->EndOfFile.QuadPart      = 0;
                    info->NumberOfLinks           = 1;
                    info->DeletePending           = FALSE;
                }
1573
                else
1574
                {
1575 1576 1577 1578
                    info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
                    info->EndOfFile.QuadPart      = st.st_size;
                    info->NumberOfLinks           = st.st_nlink;
                    info->DeletePending           = FALSE; /* FIXME */
1579 1580 1581 1582 1583 1584
                }
            }
        }
        break;
    case FilePositionInformation:
        {
1585
            FILE_POSITION_INFORMATION *info = ptr;
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
            off_t res = lseek( fd, 0, SEEK_CUR );
            if (res == (off_t)-1) io->u.Status = FILE_GetNtStatus();
            else info->CurrentByteOffset.QuadPart = res;
        }
        break;
    case FileInternalInformation:
        {
            FILE_INTERNAL_INFORMATION *info = ptr;

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

1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
            if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
            else info->EndOfFile.QuadPart = S_ISDIR(st.st_mode) ? 0 : st.st_size;
        }
        break;
    case FileAllInformation:
        {
            FILE_ALL_INFORMATION *info = ptr;

            if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
            else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
                io->u.Status = STATUS_INVALID_INFO_CLASS;
1620
            else
1621
            {
1622 1623 1624 1625 1626 1627 1628 1629
                if ((info->StandardInformation.Directory = S_ISDIR(st.st_mode)))
                {
                    info->BasicInformation.FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
                    info->StandardInformation.AllocationSize.QuadPart = 0;
                    info->StandardInformation.EndOfFile.QuadPart      = 0;
                    info->StandardInformation.NumberOfLinks           = 1;
                    info->StandardInformation.DeletePending           = FALSE;
                }
1630
                else
1631
                {
1632 1633 1634 1635 1636
                    info->BasicInformation.FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
                    info->StandardInformation.AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
                    info->StandardInformation.EndOfFile.QuadPart      = st.st_size;
                    info->StandardInformation.NumberOfLinks           = st.st_nlink;
                    info->StandardInformation.DeletePending           = FALSE; /* FIXME */
1637
                }
1638
                if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
                    info->BasicInformation.FileAttributes |= FILE_ATTRIBUTE_READONLY;
                RtlSecondsSince1970ToTime( st.st_mtime, &info->BasicInformation.CreationTime);
                RtlSecondsSince1970ToTime( st.st_mtime, &info->BasicInformation.LastWriteTime);
                RtlSecondsSince1970ToTime( st.st_ctime, &info->BasicInformation.ChangeTime);
                RtlSecondsSince1970ToTime( st.st_atime, &info->BasicInformation.LastAccessTime);
                info->InternalInformation.IndexNumber.QuadPart = st.st_ino;
                info->EaInformation.EaSize = 0;
                info->AccessInformation.AccessFlags = 0;  /* FIXME */
                info->PositionInformation.CurrentByteOffset.QuadPart = lseek( fd, 0, SEEK_CUR );
                info->ModeInformation.Mode = 0;  /* FIXME */
                info->AlignmentInformation.AlignmentRequirement = 1;  /* FIXME */
                info->NameInformation.FileNameLength = 0;
                io->Information = sizeof(*info) - sizeof(WCHAR);
1652 1653 1654
            }
        }
        break;
1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
    case FileMailslotQueryInformation:
        {
            FILE_MAILSLOT_QUERY_INFORMATION *info = ptr;

            SERVER_START_REQ( set_mailslot_info )
            {
                req->handle = hFile;
                req->flags = 0;
                io->u.Status = wine_server_call( req );
                if( io->u.Status == STATUS_SUCCESS )
                {
                    info->MaximumMessageSize = reply->max_msgsize;
                    info->MailslotQuota = 0;
1668 1669
                    info->NextMessageSize = 0;
                    info->MessagesAvailable = 0;
1670
                    info->ReadTimeout.QuadPart = reply->read_timeout;
1671 1672 1673
                }
            }
            SERVER_END_REQ;
1674 1675
            if (!io->u.Status)
            {
1676
                char *tmpbuf;
1677
                ULONG size = info->MaximumMessageSize ? info->MaximumMessageSize : 0x10000;
1678 1679
                if (size > 0x10000) size = 0x10000;
                if ((tmpbuf = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1680 1681
                {
                    int fd, needs_close;
1682
                    if (!server_get_unix_fd( hFile, FILE_READ_DATA, &fd, &needs_close, NULL, NULL ))
1683 1684 1685 1686 1687 1688 1689 1690 1691
                    {
                        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 );
                }
            }
1692 1693
        }
        break;
1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
    case FilePipeLocalInformation:
        {
            FILE_PIPE_LOCAL_INFORMATION* pli = ptr;

            SERVER_START_REQ( get_named_pipe_info )
            {
                req->handle = hFile;
                if (!(io->u.Status = wine_server_call( req )))
                {
                    pli->NamedPipeType = (reply->flags & NAMED_PIPE_MESSAGE_STREAM_WRITE) ? 
                        FILE_PIPE_TYPE_MESSAGE : FILE_PIPE_TYPE_BYTE;
                    pli->NamedPipeConfiguration = 0; /* FIXME */
                    pli->MaximumInstances = reply->maxinstances;
                    pli->CurrentInstances = reply->instances;
                    pli->InboundQuota = reply->insize;
                    pli->ReadDataAvailable = 0; /* FIXME */
                    pli->OutboundQuota = reply->outsize;
                    pli->WriteQuotaAvailable = 0; /* FIXME */
                    pli->NamedPipeState = 0; /* FIXME */
                    pli->NamedPipeEnd = (reply->flags & NAMED_PIPE_SERVER_END) ?
                        FILE_PIPE_SERVER_END : FILE_PIPE_CLIENT_END;
                }
            }
            SERVER_END_REQ;
        }
        break;
1720 1721
    default:
        FIXME("Unsupported class (%d)\n", class);
1722 1723
        io->u.Status = STATUS_NOT_IMPLEMENTED;
        break;
1724
    }
1725
    if (needs_close) close( fd );
1726
    if (io->u.Status == STATUS_SUCCESS && !io->Information) io->Information = info_sizes[class];
1727
    return io->u.Status;
Juergen Schmied's avatar
Juergen Schmied committed
1728 1729 1730
}

/******************************************************************************
1731
 *  NtSetInformationFile		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
1732
 *  ZwSetInformationFile		[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
1733 1734 1735 1736
 *
 * Set information about an open file handle.
 *
 * PARAMS
1737 1738 1739 1740 1741
 *  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
1742 1743
 *
 * RETURNS
1744
 *  Success: 0. io is updated.
Jon Griffiths's avatar
Jon Griffiths committed
1745
 *  Failure: An NTSTATUS error code describing the error.
Juergen Schmied's avatar
Juergen Schmied committed
1746
 */
1747 1748
NTSTATUS WINAPI NtSetInformationFile(HANDLE handle, PIO_STATUS_BLOCK io,
                                     PVOID ptr, ULONG len, FILE_INFORMATION_CLASS class)
Juergen Schmied's avatar
Juergen Schmied committed
1749
{
1750
    int fd, needs_close;
1751

1752
    TRACE("(%p,%p,%p,0x%08x,0x%08x)\n", handle, io, ptr, len, class);
1753 1754

    io->u.Status = STATUS_SUCCESS;
1755
    switch (class)
Jon Griffiths's avatar
Jon Griffiths committed
1756
    {
1757 1758
    case FileBasicInformation:
        if (len >= sizeof(FILE_BASIC_INFORMATION))
1759
        {
1760 1761
            struct stat st;
            const FILE_BASIC_INFORMATION *info = ptr;
1762

1763 1764 1765
            if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
                return io->u.Status;

1766
            if (info->LastAccessTime.QuadPart || info->LastWriteTime.QuadPart)
1767
            {
1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
                ULONGLONG sec, nsec;
                struct timeval tv[2];

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

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

1797 1798 1799 1800 1801 1802 1803
            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)
                    {
1804 1805 1806 1807
                        if (S_ISDIR( st.st_mode))
                            WARN("FILE_ATTRIBUTE_READONLY ignored for directory.\n");
                        else
                            st.st_mode &= ~0222; /* clear write permission bits */
1808 1809 1810 1811 1812 1813 1814 1815 1816
                    }
                    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();
                }
            }
1817 1818

            if (needs_close) close( fd );
1819 1820 1821 1822 1823 1824 1825 1826 1827
        }
        else io->u.Status = STATUS_INVALID_PARAMETER_3;
        break;

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

1828 1829 1830
            if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
                return io->u.Status;

1831 1832
            if (lseek( fd, info->CurrentByteOffset.QuadPart, SEEK_SET ) == (off_t)-1)
                io->u.Status = FILE_GetNtStatus();
1833 1834

            if (needs_close) close( fd );
1835
        }
1836
        else io->u.Status = STATUS_INVALID_PARAMETER_3;
1837
        break;
1838

1839 1840 1841
    case FileEndOfFileInformation:
        if (len >= sizeof(FILE_END_OF_FILE_INFORMATION))
        {
1842
            struct stat st;
1843 1844
            const FILE_END_OF_FILE_INFORMATION *info = ptr;

1845 1846 1847
            if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
                return io->u.Status;

1848 1849 1850 1851 1852
            /* 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)
1853 1854 1855 1856 1857
            {
                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 */
1858 1859
                if (pwrite( fd, &zero, 1, (off_t)info->EndOfFile.QuadPart ) != -1 &&
                    ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
1860
            }
1861
            io->u.Status = FILE_GetNtStatus();
1862 1863

            if (needs_close) close( fd );
1864 1865 1866 1867
        }
        else io->u.Status = STATUS_INVALID_PARAMETER_3;
        break;

1868 1869 1870 1871 1872 1873 1874 1875
    case FileMailslotSetInformation:
        {
            FILE_MAILSLOT_SET_INFORMATION *info = ptr;

            SERVER_START_REQ( set_mailslot_info )
            {
                req->handle = handle;
                req->flags = MAILSLOT_SET_READ_TIMEOUT;
1876
                req->read_timeout = info->ReadTimeout.QuadPart;
1877 1878 1879 1880 1881 1882
                io->u.Status = wine_server_call( req );
            }
            SERVER_END_REQ;
        }
        break;

1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
    case FileCompletionInformation:
        if (len >= sizeof(FILE_COMPLETION_INFORMATION))
        {
            FILE_COMPLETION_INFORMATION *info = (FILE_COMPLETION_INFORMATION *)ptr;

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

1900 1901
    default:
        FIXME("Unsupported class (%d)\n", class);
1902 1903
        io->u.Status = STATUS_NOT_IMPLEMENTED;
        break;
1904
    }
1905 1906 1907 1908 1909 1910
    io->Information = 0;
    return io->u.Status;
}


/******************************************************************************
1911
 *              NtQueryFullAttributesFile   (NTDLL.@)
1912
 */
1913 1914
NTSTATUS WINAPI NtQueryFullAttributesFile( const OBJECT_ATTRIBUTES *attr,
                                           FILE_NETWORK_OPEN_INFORMATION *info )
1915 1916 1917 1918
{
    ANSI_STRING unix_name;
    NTSTATUS status;

1919 1920
    if (!(status = wine_nt_to_unix_file_name( attr->ObjectName, &unix_name, FILE_OPEN,
                                              !(attr->Attributes & OBJ_CASE_INSENSITIVE) )))
1921 1922 1923 1924 1925 1926 1927 1928 1929
    {
        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
        {
1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
            if (S_ISDIR(st.st_mode))
            {
                info->FileAttributes          = FILE_ATTRIBUTE_DIRECTORY;
                info->AllocationSize.QuadPart = 0;
                info->EndOfFile.QuadPart      = 0;
            }
            else
            {
                info->FileAttributes          = FILE_ATTRIBUTE_ARCHIVE;
                info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
                info->EndOfFile.QuadPart      = st.st_size;
            }
1942 1943
            if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
                info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
1944 1945 1946 1947 1948 1949 1950 1951 1952
            RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
            RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
            RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
            RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
            if (DIR_is_hidden_file( attr->ObjectName ))
                info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
        }
        RtlFreeAnsiString( &unix_name );
    }
1953
    else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), status );
1954
    return status;
Juergen Schmied's avatar
Juergen Schmied committed
1955 1956
}

1957

1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978
/******************************************************************************
 *              NtQueryAttributesFile   (NTDLL.@)
 *              ZwQueryAttributesFile   (NTDLL.@)
 */
NTSTATUS WINAPI NtQueryAttributesFile( const OBJECT_ATTRIBUTES *attr, FILE_BASIC_INFORMATION *info )
{
    FILE_NETWORK_OPEN_INFORMATION full_info;
    NTSTATUS status;

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


1979 1980
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__APPLE__)
/* helper for FILE_GetDeviceInfo to hide some platform differences in fstatfs */
1981
static inline void get_device_info_fstatfs( FILE_FS_DEVICE_INFORMATION *info, const char *fstypename,
1982
                                            unsigned int flags )
1983
{
1984
    if (!strcmp("cd9660", fstypename) || !strcmp("udf", fstypename))
1985 1986 1987 1988 1989
    {
        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;
    }
1990 1991
    else if (!strcmp("nfs", fstypename) || !strcmp("nwfs", fstypename) ||
             !strcmp("smbfs", fstypename) || !strcmp("afpfs", fstypename))
1992 1993 1994 1995
    {
        info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
        info->Characteristics |= FILE_REMOTE_DEVICE;
    }
1996
    else if (!strcmp("procfs", fstypename))
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
        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

2012 2013 2014 2015 2016 2017 2018 2019 2020 2021
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 );
}

2022
/******************************************************************************
2023
 *              get_device_info
2024 2025 2026
 *
 * Implementation of the FileFsDeviceInformation query for NtQueryVolumeInformationFile.
 */
2027
static NTSTATUS get_device_info( int fd, FILE_FS_DEVICE_INFORMATION *info )
2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
{
    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;
2048 2049 2050
        case SCSI_TAPE_MAJOR:
            info->DeviceType = FILE_DEVICE_TAPE;
            break;
2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
        }
#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;
    }
2062 2063 2064 2065
    else if (is_device_placeholder( fd ))
    {
        info->DeviceType = FILE_DEVICE_DISK;
    }
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078
    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 */
2079
        case 0x9fa1:      /* supermount */
2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099
        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;
        }
2100
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__APPLE__)
2101 2102 2103 2104 2105
        struct statfs stfs;

        if (fstatfs( fd, &stfs ) < 0)
            info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
        else
2106
            get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flags );
2107 2108 2109 2110
#elif defined(__NetBSD__)
        struct statvfs stfs;

        if (fstatvfs( fd, &stfs) < 0)
2111
            info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2112
        else
2113
            get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flag );
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
#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;
}


2156
/******************************************************************************
2157
 *  NtQueryVolumeInformationFile		[NTDLL.@]
Patrik Stridvall's avatar
Patrik Stridvall committed
2158
 *  ZwQueryVolumeInformationFile		[NTDLL.@]
Jon Griffiths's avatar
Jon Griffiths committed
2159 2160 2161 2162
 *
 * Get volume information for an open file handle.
 *
 * PARAMS
2163 2164 2165 2166 2167
 *  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
2168 2169
 *
 * RETURNS
2170
 *  Success: 0. io and buffer are updated.
Jon Griffiths's avatar
Jon Griffiths committed
2171
 *  Failure: An NTSTATUS error code describing the error.
2172
 */
2173 2174 2175
NTSTATUS WINAPI NtQueryVolumeInformationFile( HANDLE handle, PIO_STATUS_BLOCK io,
                                              PVOID buffer, ULONG length,
                                              FS_INFORMATION_CLASS info_class )
2176
{
2177
    int fd, needs_close;
2178
    struct stat st;
2179

2180
    if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
2181
        return io->u.Status;
2182

2183 2184
    io->u.Status = STATUS_NOT_IMPLEMENTED;
    io->Information = 0;
2185

2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199
    switch( info_class )
    {
    case FileFsVolumeInformation:
        FIXME( "%p: volume info not supported\n", handle );
        break;
    case FileFsLabelInformation:
        FIXME( "%p: label info not supported\n", handle );
        break;
    case FileFsSizeInformation:
        if (length < sizeof(FILE_FS_SIZE_INFORMATION))
            io->u.Status = STATUS_BUFFER_TOO_SMALL;
        else
        {
            FILE_FS_SIZE_INFORMATION *info = buffer;
2200

2201 2202 2203 2204 2205 2206 2207 2208 2209
            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;
            }
2210 2211
            else
            {
2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232
                /* Linux's fstatvfs is buggy */
#if !defined(linux) || !defined(HAVE_FSTATFS)
                struct statvfs stfs;

                if (fstatvfs( fd, &stfs ) < 0)
                {
                    io->u.Status = FILE_GetNtStatus();
                    break;
                }
                info->BytesPerSector = stfs.f_frsize;
#else
                struct statfs stfs;
                if (fstatfs( fd, &stfs ) < 0)
                {
                    io->u.Status = FILE_GetNtStatus();
                    break;
                }
                info->BytesPerSector = stfs.f_bsize;
#endif
                info->TotalAllocationUnits.QuadPart = stfs.f_blocks;
                info->AvailableAllocationUnits.QuadPart = stfs.f_bavail;
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245
                info->SectorsPerAllocationUnit = 1;
                io->Information = sizeof(*info);
                io->u.Status = STATUS_SUCCESS;
            }
        }
        break;
    case FileFsDeviceInformation:
        if (length < sizeof(FILE_FS_DEVICE_INFORMATION))
            io->u.Status = STATUS_BUFFER_TOO_SMALL;
        else
        {
            FILE_FS_DEVICE_INFORMATION *info = buffer;

2246
            if ((io->u.Status = get_device_info( fd, info )) == STATUS_SUCCESS)
2247
                io->Information = sizeof(*info);
2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268
        }
        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;
    }
2269
    if (needs_close) close( fd );
2270
    return io->u.Status;
2271
}
2272

2273

2274 2275
/******************************************************************
 *		NtFlushBuffersFile  (NTDLL.@)
Jon Griffiths's avatar
Jon Griffiths committed
2276 2277 2278 2279 2280 2281 2282 2283 2284 2285
 *
 * 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.
2286 2287 2288 2289
 */
NTSTATUS WINAPI NtFlushBuffersFile( HANDLE hFile, IO_STATUS_BLOCK* IoStatusBlock )
{
    NTSTATUS ret;
2290 2291
    HANDLE hEvent = NULL;

2292 2293 2294 2295
    SERVER_START_REQ( flush_file )
    {
        req->handle = hFile;
        ret = wine_server_call( req );
2296
        hEvent = reply->event;
2297 2298
    }
    SERVER_END_REQ;
2299
    if (!ret && hEvent)
2300 2301 2302 2303
    {
        ret = NtWaitForSingleObject( hEvent, FALSE, NULL );
        NtClose( hEvent );
    }
2304 2305
    return ret;
}
2306 2307 2308 2309 2310 2311 2312

/******************************************************************
 *		NtLockFile       (NTDLL.@)
 *
 *
 */
NTSTATUS WINAPI NtLockFile( HANDLE hFile, HANDLE lock_granted_event,
Jon Griffiths's avatar
Jon Griffiths committed
2313 2314
                            PIO_APC_ROUTINE apc, void* apc_user,
                            PIO_STATUS_BLOCK io_status, PLARGE_INTEGER offset,
2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
                            PLARGE_INTEGER count, ULONG* key, BOOLEAN dont_wait,
                            BOOLEAN exclusive )
{
    NTSTATUS    ret;
    HANDLE      handle;
    BOOLEAN     async;

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

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

2330 2331 2332 2333 2334
    for (;;)
    {
        SERVER_START_REQ( lock_file )
        {
            req->handle      = hFile;
2335 2336
            req->offset      = offset->QuadPart;
            req->count       = count->QuadPart;
2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367
            req->shared      = !exclusive;
            req->wait        = !dont_wait;
            ret = wine_server_call( req );
            handle = reply->handle;
            async  = reply->overlapped;
        }
        SERVER_END_REQ;
        if (ret != STATUS_PENDING)
        {
            if (!ret && lock_granted_event) NtSetEvent(lock_granted_event, NULL);
            return ret;
        }

        if (async)
        {
            FIXME( "Async I/O lock wait not implemented, might deadlock\n" );
            if (handle) NtClose( handle );
            return STATUS_PENDING;
        }
        if (handle)
        {
            NtWaitForSingleObject( handle, FALSE, NULL );
            NtClose( handle );
        }
        else
        {
            LARGE_INTEGER time;
    
            /* Unix lock conflict, sleep a bit and retry */
            time.QuadPart = 100 * (ULONGLONG)10000;
            time.QuadPart = -time.QuadPart;
2368
            NtDelayExecution( FALSE, &time );
2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384
        }
    }
}


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

2385
    TRACE( "%p %x%08x %x%08x\n",
2386
           hFile, offset->u.HighPart, offset->u.LowPart, count->u.HighPart, count->u.LowPart );
2387 2388 2389 2390 2391 2392 2393 2394 2395

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

    SERVER_START_REQ( unlock_file )
    {
2396 2397 2398
        req->handle = hFile;
        req->offset = offset->QuadPart;
        req->count  = count->QuadPart;
2399 2400 2401 2402 2403
        status = wine_server_call( req );
    }
    SERVER_END_REQ;
    return status;
}
2404 2405 2406 2407 2408 2409

/******************************************************************
 *		NtCreateNamedPipeFile    (NTDLL.@)
 *
 *
 */
2410
NTSTATUS WINAPI NtCreateNamedPipeFile( PHANDLE handle, ULONG access,
2411
                                       POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK iosb,
2412 2413 2414 2415 2416
                                       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)
2417
{
2418 2419
    NTSTATUS    status;

2420
    TRACE("(%p %x %s %p %x %d %x %d %d %d %d %d %d %p)\n",
2421
          handle, access, debugstr_w(attr->ObjectName->Buffer), iosb, sharing, dispo,
2422 2423
          options, pipe_type, read_mode, completion_mode, max_inst, inbound_quota,
          outbound_quota, timeout);
2424

2425 2426
    /* assume we only get relative timeout */
    if (timeout->QuadPart > 0)
2427 2428 2429 2430
        FIXME("Wrong time %s\n", wine_dbgstr_longlong(timeout->QuadPart));

    SERVER_START_REQ( create_named_pipe )
    {
2431
        req->access  = access;
2432 2433
        req->attributes = attr->Attributes;
        req->rootdir = attr->RootDirectory;
2434
        req->options = options;
2435 2436 2437 2438 2439 2440 2441
        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;
2442
        req->timeout = timeout->QuadPart;
2443 2444
        wine_server_add_data( req, attr->ObjectName->Buffer,
                              attr->ObjectName->Length );
2445 2446 2447 2448 2449
        status = wine_server_call( req );
        if (!status) *handle = reply->handle;
    }
    SERVER_END_REQ;
    return status;
2450
}
2451 2452 2453 2454 2455 2456 2457 2458

/******************************************************************
 *		NtDeleteFile    (NTDLL.@)
 *
 *
 */
NTSTATUS WINAPI NtDeleteFile( POBJECT_ATTRIBUTES ObjectAttributes )
{
2459 2460 2461 2462 2463
    NTSTATUS status;
    HANDLE hFile;
    IO_STATUS_BLOCK io;

    TRACE("%p\n", ObjectAttributes);
2464 2465
    status = NtCreateFile( &hFile, GENERIC_READ | GENERIC_WRITE | DELETE,
                           ObjectAttributes, &io, NULL, 0,
2466 2467 2468 2469
                           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;
2470 2471 2472 2473 2474 2475 2476
}

/******************************************************************
 *		NtCancelIoFile    (NTDLL.@)
 *
 *
 */
2477
NTSTATUS WINAPI NtCancelIoFile( HANDLE hFile, PIO_STATUS_BLOCK io_status )
2478
{
2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495
    LARGE_INTEGER timeout;

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

    SERVER_START_REQ( cancel_async )
    {
        req->handle = hFile;
        wine_server_call( req );
    }
    SERVER_END_REQ;
    /* Let some APC be run, so that we can run the remaining APCs on hFile
     * either the cancelation of the pending one, but also the execution
     * of the queued APC, but not yet run. This is needed to ensure proper
     * clean-up of allocated data.
     */
    timeout.u.LowPart = timeout.u.HighPart = 0;
    return io_status->u.Status = NtDelayExecution( TRUE, &timeout );
2496
}
2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519

/******************************************************************************
 *  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)
{
2520
    LARGE_INTEGER timeout;
2521 2522
    NTSTATUS ret;

2523
    TRACE("%p %08x %p %p %08x %08x %08x %p\n",
2524 2525 2526
              pHandle, DesiredAccess, attr, IoStatusBlock,
              CreateOptions, MailslotQuota, MaxMessageSize, TimeOut);

2527
    if (!pHandle) return STATUS_ACCESS_VIOLATION;
2528 2529 2530
    if (!attr) return STATUS_INVALID_PARAMETER;
    if (!attr->ObjectName) return STATUS_OBJECT_PATH_SYNTAX_BAD;

2531 2532 2533 2534 2535 2536 2537 2538
    /*
     *  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
2539 2540
    SERVER_START_REQ( create_mailslot )
    {
2541
        req->access = DesiredAccess;
2542 2543
        req->attributes = attr->Attributes;
        req->rootdir = attr->RootDirectory;
Mike McCormack's avatar
Mike McCormack committed
2544
        req->max_msgsize = MaxMessageSize;
2545
        req->read_timeout = timeout.QuadPart;
2546 2547
        wine_server_add_data( req, attr->ObjectName->Buffer,
                              attr->ObjectName->Length );
Mike McCormack's avatar
Mike McCormack committed
2548 2549 2550 2551 2552 2553
        ret = wine_server_call( req );
        if( ret == STATUS_SUCCESS )
            *pHandle = reply->handle;
    }
    SERVER_END_REQ;
 
2554 2555
    return ret;
}