advapi32/ntdll: MakeRelativeSD should preserve NULL pointers (with testcase).
[wine] / dlls / ntdll / file.c
1 /*
2  * Copyright 1999, 2000 Juergen Schmied
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * 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 #include "config.h"
20 #include "wine/port.h"
21
22 #include <stdlib.h>
23 #include <string.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <assert.h>
27 #ifdef HAVE_UNISTD_H
28 # include <unistd.h>
29 #endif
30 #ifdef HAVE_SYS_ERRNO_H
31 #include <sys/errno.h>
32 #endif
33 #ifdef HAVE_LINUX_MAJOR_H
34 # include <linux/major.h>
35 #endif
36 #ifdef HAVE_SYS_STATVFS_H
37 # include <sys/statvfs.h>
38 #endif
39 #ifdef HAVE_SYS_PARAM_H
40 # include <sys/param.h>
41 #endif
42 #ifdef HAVE_SYS_TIME_H
43 # include <sys/time.h>
44 #endif
45 #ifdef HAVE_SYS_IOCTL_H
46 #include <sys/ioctl.h>
47 #endif
48 #ifdef HAVE_POLL_H
49 #include <poll.h>
50 #endif
51 #ifdef HAVE_SYS_POLL_H
52 #include <sys/poll.h>
53 #endif
54 #ifdef HAVE_SYS_SOCKET_H
55 #include <sys/socket.h>
56 #endif
57 #ifdef HAVE_UTIME_H
58 # include <utime.h>
59 #endif
60 #ifdef HAVE_SYS_VFS_H
61 # include <sys/vfs.h>
62 #endif
63 #ifdef HAVE_SYS_MOUNT_H
64 # include <sys/mount.h>
65 #endif
66 #ifdef HAVE_SYS_STATFS_H
67 # include <sys/statfs.h>
68 #endif
69
70 #define NONAMELESSUNION
71 #define NONAMELESSSTRUCT
72 #include "ntstatus.h"
73 #define WIN32_NO_STATUS
74 #include "wine/unicode.h"
75 #include "wine/debug.h"
76 #include "thread.h"
77 #include "wine/server.h"
78 #include "ntdll_misc.h"
79
80 #include "winternl.h"
81 #include "winioctl.h"
82 #include "ddk/ntddser.h"
83
84 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
85
86 mode_t FILE_umask = 0;
87
88 #define SECSPERDAY         86400
89 #define SECS_1601_TO_1970  ((369 * 365 + 89) * (ULONGLONG)SECSPERDAY)
90
91 /**************************************************************************
92  *                 NtOpenFile                           [NTDLL.@]
93  *                 ZwOpenFile                           [NTDLL.@]
94  *
95  * Open a file.
96  *
97  * PARAMS
98  *  handle    [O] Variable that receives the file handle on return
99  *  access    [I] Access desired by the caller to the file
100  *  attr      [I] Structure describing the file to be opened
101  *  io        [O] Receives details about the result of the operation
102  *  sharing   [I] Type of shared access the caller requires
103  *  options   [I] Options for the file open
104  *
105  * RETURNS
106  *  Success: 0. FileHandle and IoStatusBlock are updated.
107  *  Failure: An NTSTATUS error code describing the error.
108  */
109 NTSTATUS WINAPI NtOpenFile( PHANDLE handle, ACCESS_MASK access,
110                             POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK io,
111                             ULONG sharing, ULONG options )
112 {
113     return NtCreateFile( handle, access, attr, io, NULL, 0,
114                          sharing, FILE_OPEN, options, NULL, 0 );
115 }
116
117 /**************************************************************************
118  *              NtCreateFile                            [NTDLL.@]
119  *              ZwCreateFile                            [NTDLL.@]
120  *
121  * Either create a new file or directory, or open an existing file, device,
122  * directory or volume.
123  *
124  * PARAMS
125  *      handle       [O] Points to a variable which receives the file handle on return
126  *      access       [I] Desired access to the file
127  *      attr         [I] Structure describing the file
128  *      io           [O] Receives information about the operation on return
129  *      alloc_size   [I] Initial size of the file in bytes
130  *      attributes   [I] Attributes to create the file with
131  *      sharing      [I] Type of shared access the caller would like to the file
132  *      disposition  [I] Specifies what to do, depending on whether the file already exists
133  *      options      [I] Options for creating a new file
134  *      ea_buffer    [I] Pointer to an extended attributes buffer
135  *      ea_length    [I] Length of ea_buffer
136  *
137  * RETURNS
138  *  Success: 0. handle and io are updated.
139  *  Failure: An NTSTATUS error code describing the error.
140  */
141 NTSTATUS WINAPI NtCreateFile( PHANDLE handle, ACCESS_MASK access, POBJECT_ATTRIBUTES attr,
142                               PIO_STATUS_BLOCK io, PLARGE_INTEGER alloc_size,
143                               ULONG attributes, ULONG sharing, ULONG disposition,
144                               ULONG options, PVOID ea_buffer, ULONG ea_length )
145 {
146     ANSI_STRING unix_name;
147     int created = FALSE;
148
149     TRACE("handle=%p access=%08x name=%s objattr=%08x root=%p sec=%p io=%p alloc_size=%p\n"
150           "attr=%08x sharing=%08x disp=%d options=%08x ea=%p.0x%08x\n",
151           handle, access, debugstr_us(attr->ObjectName), attr->Attributes,
152           attr->RootDirectory, attr->SecurityDescriptor, io, alloc_size,
153           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     if (attr->RootDirectory)
160     {
161         FIXME( "RootDirectory %p not supported\n", attr->RootDirectory );
162         return STATUS_OBJECT_NAME_NOT_FOUND;
163     }
164
165     io->u.Status = wine_nt_to_unix_file_name( attr->ObjectName, &unix_name, disposition,
166                                               !(attr->Attributes & OBJ_CASE_INSENSITIVE) );
167
168     if (io->u.Status == STATUS_BAD_DEVICE_TYPE)
169     {
170         SERVER_START_REQ( open_file_object )
171         {
172             req->access     = access;
173             req->attributes = attr->Attributes;
174             req->rootdir    = attr->RootDirectory;
175             req->sharing    = sharing;
176             req->options    = options;
177             wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
178             io->u.Status = wine_server_call( req );
179             *handle = reply->handle;
180         }
181         SERVER_END_REQ;
182         return io->u.Status;
183     }
184
185     if (io->u.Status == STATUS_NO_SUCH_FILE &&
186         disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
187     {
188         created = TRUE;
189         io->u.Status = STATUS_SUCCESS;
190     }
191
192     if (io->u.Status == STATUS_SUCCESS)
193     {
194         SERVER_START_REQ( create_file )
195         {
196             req->access     = access;
197             req->attributes = attr->Attributes;
198             req->sharing    = sharing;
199             req->create     = disposition;
200             req->options    = options;
201             req->attrs      = attributes;
202             wine_server_add_data( req, unix_name.Buffer, unix_name.Length );
203             io->u.Status = wine_server_call( req );
204             *handle = reply->handle;
205         }
206         SERVER_END_REQ;
207         RtlFreeAnsiString( &unix_name );
208     }
209     else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), io->u.Status );
210
211     if (io->u.Status == STATUS_SUCCESS)
212     {
213         if (created) io->Information = FILE_CREATED;
214         else switch(disposition)
215         {
216         case FILE_SUPERSEDE:
217             io->Information = FILE_SUPERSEDED;
218             break;
219         case FILE_CREATE:
220             io->Information = FILE_CREATED;
221             break;
222         case FILE_OPEN:
223         case FILE_OPEN_IF:
224             io->Information = FILE_OPENED;
225             break;
226         case FILE_OVERWRITE:
227         case FILE_OVERWRITE_IF:
228             io->Information = FILE_OVERWRITTEN;
229             break;
230         }
231     }
232
233     return io->u.Status;
234 }
235
236 /***********************************************************************
237  *                  Asynchronous file I/O                              *
238  */
239
240 struct async_fileio
241 {
242     HANDLE              handle;
243     PIO_APC_ROUTINE     apc;
244     void               *apc_arg;
245 };
246
247 typedef struct
248 {
249     struct async_fileio io;
250     char*               buffer;
251     unsigned int        already;
252     unsigned int        count;
253     BOOL                avail_mode;
254 } async_fileio_read;
255
256 typedef struct
257 {
258     struct async_fileio io;
259     const char         *buffer;
260     unsigned int        already;
261     unsigned int        count;
262 } async_fileio_write;
263
264
265 /* callback for file I/O user APC */
266 static void WINAPI fileio_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
267 {
268     struct async_fileio *async = arg;
269     if (async->apc) async->apc( async->apc_arg, io, reserved );
270     RtlFreeHeap( GetProcessHeap(), 0, async );
271 }
272
273 /***********************************************************************
274  *           FILE_GetNtStatus(void)
275  *
276  * Retrieve the Nt Status code from errno.
277  * Try to be consistent with FILE_SetDosError().
278  */
279 NTSTATUS FILE_GetNtStatus(void)
280 {
281     int err = errno;
282
283     TRACE( "errno = %d\n", errno );
284     switch (err)
285     {
286     case EAGAIN:    return STATUS_SHARING_VIOLATION;
287     case EBADF:     return STATUS_INVALID_HANDLE;
288     case EBUSY:     return STATUS_DEVICE_BUSY;
289     case ENOSPC:    return STATUS_DISK_FULL;
290     case EPERM:
291     case EROFS:
292     case EACCES:    return STATUS_ACCESS_DENIED;
293     case ENOTDIR:   return STATUS_OBJECT_PATH_NOT_FOUND;
294     case ENOENT:    return STATUS_OBJECT_NAME_NOT_FOUND;
295     case EISDIR:    return STATUS_FILE_IS_A_DIRECTORY;
296     case EMFILE:
297     case ENFILE:    return STATUS_TOO_MANY_OPENED_FILES;
298     case EINVAL:    return STATUS_INVALID_PARAMETER;
299     case ENOTEMPTY: return STATUS_DIRECTORY_NOT_EMPTY;
300     case EPIPE:     return STATUS_PIPE_DISCONNECTED;
301     case EIO:       return STATUS_DEVICE_NOT_READY;
302 #ifdef ENOMEDIUM
303     case ENOMEDIUM: return STATUS_NO_MEDIA_IN_DEVICE;
304 #endif
305     case ENXIO:     return STATUS_NO_SUCH_DEVICE;
306     case ENOTTY:
307     case EOPNOTSUPP:return STATUS_NOT_SUPPORTED;
308     case ECONNRESET:return STATUS_PIPE_DISCONNECTED;
309     case EFAULT:    return STATUS_ACCESS_VIOLATION;
310     case ESPIPE:    return STATUS_ILLEGAL_FUNCTION;
311     case ENOEXEC:   /* ?? */
312     case EEXIST:    /* ?? */
313     default:
314         FIXME( "Converting errno %d to STATUS_UNSUCCESSFUL\n", err );
315         return STATUS_UNSUCCESSFUL;
316     }
317 }
318
319 /***********************************************************************
320  *             FILE_AsyncReadService      (INTERNAL)
321  */
322 static NTSTATUS FILE_AsyncReadService(void *user, PIO_STATUS_BLOCK iosb, NTSTATUS status)
323 {
324     async_fileio_read *fileio = user;
325     int fd, needs_close, result;
326
327     switch (status)
328     {
329     case STATUS_ALERTED: /* got some new data */
330         /* check to see if the data is ready (non-blocking) */
331         if ((status = server_get_unix_fd( fileio->io.handle, FILE_READ_DATA, &fd,
332                                           &needs_close, NULL, NULL )))
333             break;
334
335         result = read(fd, &fileio->buffer[fileio->already], fileio->count - fileio->already);
336         if (needs_close) close( fd );
337
338         if (result < 0)
339         {
340             if (errno == EAGAIN || errno == EINTR)
341                 status = STATUS_PENDING;
342             else /* check to see if the transfer is complete */
343                 status = FILE_GetNtStatus();
344         }
345         else if (result == 0)
346         {
347             status = fileio->already ? STATUS_SUCCESS : STATUS_PIPE_BROKEN;
348         }
349         else
350         {
351             fileio->already += result;
352             if (fileio->already >= fileio->count || fileio->avail_mode)
353                 status = STATUS_SUCCESS;
354             else
355             {
356                 /* if we only have to read the available data, and none is available,
357                  * simply cancel the request. If data was available, it has been read
358                  * while in by previous call (NtDelayExecution)
359                  */
360                 status = (fileio->avail_mode) ? STATUS_SUCCESS : STATUS_PENDING;
361             }
362         }
363         break;
364
365     case STATUS_TIMEOUT:
366     case STATUS_IO_TIMEOUT:
367         if (fileio->already) status = STATUS_SUCCESS;
368         break;
369     }
370     if (status != STATUS_PENDING)
371     {
372         iosb->u.Status = status;
373         iosb->Information = fileio->already;
374     }
375     return status;
376 }
377
378 struct io_timeouts
379 {
380     int interval;   /* max interval between two bytes */
381     int total;      /* total timeout for the whole operation */
382     int end_time;   /* absolute time of end of operation */
383 };
384
385 /* retrieve the I/O timeouts to use for a given handle */
386 static NTSTATUS get_io_timeouts( HANDLE handle, enum server_fd_type type, ULONG count, BOOL is_read,
387                                  struct io_timeouts *timeouts )
388 {
389     NTSTATUS status = STATUS_SUCCESS;
390
391     timeouts->interval = timeouts->total = -1;
392
393     switch(type)
394     {
395     case FD_TYPE_SERIAL:
396         {
397             /* GetCommTimeouts */
398             SERIAL_TIMEOUTS st;
399             IO_STATUS_BLOCK io;
400
401             status = NtDeviceIoControlFile( handle, NULL, NULL, NULL, &io,
402                                             IOCTL_SERIAL_GET_TIMEOUTS, NULL, 0, &st, sizeof(st) );
403             if (status) break;
404
405             if (is_read)
406             {
407                 if (st.ReadIntervalTimeout)
408                     timeouts->interval = st.ReadIntervalTimeout;
409
410                 if (st.ReadTotalTimeoutMultiplier || st.ReadTotalTimeoutConstant)
411                 {
412                     timeouts->total = st.ReadTotalTimeoutConstant;
413                     if (st.ReadTotalTimeoutMultiplier != MAXDWORD)
414                         timeouts->total += count * st.ReadTotalTimeoutMultiplier;
415                 }
416                 else if (st.ReadIntervalTimeout == MAXDWORD)
417                     timeouts->interval = 0;
418             }
419             else  /* write */
420             {
421                 if (st.WriteTotalTimeoutMultiplier || st.WriteTotalTimeoutConstant)
422                 {
423                     timeouts->total = st.WriteTotalTimeoutConstant;
424                     if (st.WriteTotalTimeoutMultiplier != MAXDWORD)
425                         timeouts->total += count * st.WriteTotalTimeoutMultiplier;
426                 }
427             }
428         }
429         break;
430     case FD_TYPE_MAILSLOT:
431         if (is_read)
432         {
433             timeouts->interval = 0;  /* return as soon as we got something */
434             SERVER_START_REQ( set_mailslot_info )
435             {
436                 req->handle = handle;
437                 req->flags = 0;
438                 if (!(status = wine_server_call( req )) &&
439                     reply->read_timeout != TIMEOUT_INFINITE)
440                     timeouts->total = reply->read_timeout / -10000;
441             }
442             SERVER_END_REQ;
443         }
444         break;
445     case FD_TYPE_SOCKET:
446     case FD_TYPE_PIPE:
447     case FD_TYPE_CHAR:
448         if (is_read) timeouts->interval = 0;  /* return as soon as we got something */
449         break;
450     default:
451         break;
452     }
453     if (timeouts->total != -1) timeouts->end_time = NtGetTickCount() + timeouts->total;
454     return STATUS_SUCCESS;
455 }
456
457
458 /* retrieve the timeout for the next wait, in milliseconds */
459 static inline int get_next_io_timeout( const struct io_timeouts *timeouts, ULONG already )
460 {
461     int ret = -1;
462
463     if (timeouts->total != -1)
464     {
465         ret = timeouts->end_time - NtGetTickCount();
466         if (ret < 0) ret = 0;
467     }
468     if (already && timeouts->interval != -1)
469     {
470         if (ret == -1 || ret > timeouts->interval) ret = timeouts->interval;
471     }
472     return ret;
473 }
474
475
476 /* retrieve the avail_mode flag for async reads */
477 static NTSTATUS get_io_avail_mode( HANDLE handle, enum server_fd_type type, BOOL *avail_mode )
478 {
479     NTSTATUS status = STATUS_SUCCESS;
480
481     switch(type)
482     {
483     case FD_TYPE_SERIAL:
484         {
485             /* GetCommTimeouts */
486             SERIAL_TIMEOUTS st;
487             IO_STATUS_BLOCK io;
488
489             status = NtDeviceIoControlFile( handle, NULL, NULL, NULL, &io,
490                                             IOCTL_SERIAL_GET_TIMEOUTS, NULL, 0, &st, sizeof(st) );
491             if (status) break;
492             *avail_mode = (!st.ReadTotalTimeoutMultiplier &&
493                            !st.ReadTotalTimeoutConstant &&
494                            st.ReadIntervalTimeout == MAXDWORD);
495         }
496         break;
497     case FD_TYPE_MAILSLOT:
498     case FD_TYPE_SOCKET:
499     case FD_TYPE_PIPE:
500     case FD_TYPE_CHAR:
501         *avail_mode = TRUE;
502         break;
503     default:
504         *avail_mode = FALSE;
505         break;
506     }
507     return status;
508 }
509
510
511 /******************************************************************************
512  *  NtReadFile                                  [NTDLL.@]
513  *  ZwReadFile                                  [NTDLL.@]
514  *
515  * Read from an open file handle.
516  *
517  * PARAMS
518  *  FileHandle    [I] Handle returned from ZwOpenFile() or ZwCreateFile()
519  *  Event         [I] Event to signal upon completion (or NULL)
520  *  ApcRoutine    [I] Callback to call upon completion (or NULL)
521  *  ApcContext    [I] Context for ApcRoutine (or NULL)
522  *  IoStatusBlock [O] Receives information about the operation on return
523  *  Buffer        [O] Destination for the data read
524  *  Length        [I] Size of Buffer
525  *  ByteOffset    [O] Destination for the new file pointer position (or NULL)
526  *  Key           [O] Function unknown (may be NULL)
527  *
528  * RETURNS
529  *  Success: 0. IoStatusBlock is updated, and the Information member contains
530  *           The number of bytes read.
531  *  Failure: An NTSTATUS error code describing the error.
532  */
533 NTSTATUS WINAPI NtReadFile(HANDLE hFile, HANDLE hEvent,
534                            PIO_APC_ROUTINE apc, void* apc_user,
535                            PIO_STATUS_BLOCK io_status, void* buffer, ULONG length,
536                            PLARGE_INTEGER offset, PULONG key)
537 {
538     int result, unix_handle, needs_close, timeout_init_done = 0;
539     unsigned int options;
540     struct io_timeouts timeouts;
541     NTSTATUS status;
542     ULONG total = 0;
543     enum server_fd_type type;
544
545     TRACE("(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
546           hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);
547
548     if (!io_status) return STATUS_ACCESS_VIOLATION;
549
550     status = server_get_unix_fd( hFile, FILE_READ_DATA, &unix_handle,
551                                  &needs_close, &type, &options );
552     if (status) return status;
553
554     if (type == FD_TYPE_FILE && offset && offset->QuadPart != (LONGLONG)-2 /* FILE_USE_FILE_POINTER_POSITION */ )
555     {
556         /* async I/O doesn't make sense on regular files */
557         while ((result = pread( unix_handle, buffer, length, offset->QuadPart )) == -1)
558         {
559             if (errno != EINTR)
560             {
561                 status = FILE_GetNtStatus();
562                 goto done;
563             }
564         }
565         if (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT))
566             /* update file pointer position */
567             lseek( unix_handle, offset->QuadPart + result, SEEK_SET );
568
569         total = result;
570         status = total ? STATUS_SUCCESS : STATUS_END_OF_FILE;
571         goto done;
572     }
573
574     for (;;)
575     {
576         if ((result = read( unix_handle, (char *)buffer + total, length - total )) >= 0)
577         {
578             total += result;
579             if (!result || total == length)
580             {
581                 if (total)
582                     status = STATUS_SUCCESS;
583                 else
584                     status = (type == FD_TYPE_FILE || type == FD_TYPE_CHAR) ? STATUS_END_OF_FILE : STATUS_PIPE_BROKEN;
585                 goto done;
586             }
587         }
588         else
589         {
590             if (errno == EINTR) continue;
591             if (errno != EAGAIN)
592             {
593                 status = FILE_GetNtStatus();
594                 goto done;
595             }
596         }
597
598         if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
599         {
600             async_fileio_read *fileio;
601             BOOL avail_mode;
602
603             if ((status = get_io_avail_mode( hFile, type, &avail_mode )))
604                 goto done;
605             if (total && avail_mode)
606             {
607                 status = STATUS_SUCCESS;
608                 goto done;
609             }
610
611             if (!(fileio = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(*fileio))))
612             {
613                 status = STATUS_NO_MEMORY;
614                 goto done;
615             }
616             fileio->io.handle  = hFile;
617             fileio->io.apc     = apc;
618             fileio->io.apc_arg = apc_user;
619             fileio->already = total;
620             fileio->count = length;
621             fileio->buffer = buffer;
622             fileio->avail_mode = avail_mode;
623
624             SERVER_START_REQ( register_async )
625             {
626                 req->handle = hFile;
627                 req->type   = ASYNC_TYPE_READ;
628                 req->count  = length;
629                 req->async.callback = FILE_AsyncReadService;
630                 req->async.iosb     = io_status;
631                 req->async.arg      = fileio;
632                 req->async.apc      = fileio_apc;
633                 req->async.event    = hEvent;
634                 status = wine_server_call( req );
635             }
636             SERVER_END_REQ;
637
638             if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
639             goto done;
640         }
641         else  /* synchronous read, wait for the fd to become ready */
642         {
643             struct pollfd pfd;
644             int ret, timeout;
645
646             if (!timeout_init_done)
647             {
648                 timeout_init_done = 1;
649                 if ((status = get_io_timeouts( hFile, type, length, TRUE, &timeouts )))
650                     goto done;
651                 if (hEvent) NtResetEvent( hEvent, NULL );
652             }
653             timeout = get_next_io_timeout( &timeouts, total );
654
655             pfd.fd = unix_handle;
656             pfd.events = POLLIN;
657
658             if (!timeout || !(ret = poll( &pfd, 1, timeout )))
659             {
660                 if (total)  /* return with what we got so far */
661                     status = STATUS_SUCCESS;
662                 else
663                     status = (type == FD_TYPE_MAILSLOT) ? STATUS_IO_TIMEOUT : STATUS_TIMEOUT;
664                 goto done;
665             }
666             if (ret == -1 && errno != EINTR)
667             {
668                 status = FILE_GetNtStatus();
669                 goto done;
670             }
671             /* will now restart the read */
672         }
673     }
674
675 done:
676     if (needs_close) close( unix_handle );
677     if (status == STATUS_SUCCESS)
678     {
679         io_status->u.Status = status;
680         io_status->Information = total;
681         TRACE("= SUCCESS (%u)\n", total);
682         if (hEvent) NtSetEvent( hEvent, NULL );
683         if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
684                                    (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
685     }
686     else
687     {
688         TRACE("= 0x%08x\n", status);
689         if (status != STATUS_PENDING && hEvent) NtResetEvent( hEvent, NULL );
690     }
691     return status;
692 }
693
694 /***********************************************************************
695  *             FILE_AsyncWriteService      (INTERNAL)
696  */
697 static NTSTATUS FILE_AsyncWriteService(void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status)
698 {
699     async_fileio_write *fileio = user;
700     int result, fd, needs_close;
701     enum server_fd_type type;
702
703     switch (status)
704     {
705     case STATUS_ALERTED:
706         /* write some data (non-blocking) */
707         if ((status = server_get_unix_fd( fileio->io.handle, FILE_WRITE_DATA, &fd,
708                                           &needs_close, &type, NULL )))
709             break;
710
711         if (!fileio->count && (type == FD_TYPE_MAILSLOT || type == FD_TYPE_PIPE || type == FD_TYPE_SOCKET))
712             result = send( fd, fileio->buffer, 0, 0 );
713         else
714             result = write( fd, &fileio->buffer[fileio->already], fileio->count - fileio->already );
715
716         if (needs_close) close( fd );
717
718         if (result < 0)
719         {
720             if (errno == EAGAIN || errno == EINTR) status = STATUS_PENDING;
721             else status = FILE_GetNtStatus();
722         }
723         else
724         {
725             fileio->already += result;
726             status = (fileio->already < fileio->count) ? STATUS_PENDING : STATUS_SUCCESS;
727         }
728         break;
729
730     case STATUS_TIMEOUT:
731     case STATUS_IO_TIMEOUT:
732         if (fileio->already) status = STATUS_SUCCESS;
733         break;
734     }
735     if (status != STATUS_PENDING)
736     {
737         iosb->u.Status = status;
738         iosb->Information = fileio->already;
739     }
740     return status;
741 }
742
743 /******************************************************************************
744  *  NtWriteFile                                 [NTDLL.@]
745  *  ZwWriteFile                                 [NTDLL.@]
746  *
747  * Write to an open file handle.
748  *
749  * PARAMS
750  *  FileHandle    [I] Handle returned from ZwOpenFile() or ZwCreateFile()
751  *  Event         [I] Event to signal upon completion (or NULL)
752  *  ApcRoutine    [I] Callback to call upon completion (or NULL)
753  *  ApcContext    [I] Context for ApcRoutine (or NULL)
754  *  IoStatusBlock [O] Receives information about the operation on return
755  *  Buffer        [I] Source for the data to write
756  *  Length        [I] Size of Buffer
757  *  ByteOffset    [O] Destination for the new file pointer position (or NULL)
758  *  Key           [O] Function unknown (may be NULL)
759  *
760  * RETURNS
761  *  Success: 0. IoStatusBlock is updated, and the Information member contains
762  *           The number of bytes written.
763  *  Failure: An NTSTATUS error code describing the error.
764  */
765 NTSTATUS WINAPI NtWriteFile(HANDLE hFile, HANDLE hEvent,
766                             PIO_APC_ROUTINE apc, void* apc_user,
767                             PIO_STATUS_BLOCK io_status, 
768                             const void* buffer, ULONG length,
769                             PLARGE_INTEGER offset, PULONG key)
770 {
771     int result, unix_handle, needs_close, timeout_init_done = 0;
772     unsigned int options;
773     struct io_timeouts timeouts;
774     NTSTATUS status;
775     ULONG total = 0;
776     enum server_fd_type type;
777
778     TRACE("(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p)!\n",
779           hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);
780
781     if (!io_status) return STATUS_ACCESS_VIOLATION;
782
783     status = server_get_unix_fd( hFile, FILE_WRITE_DATA, &unix_handle,
784                                  &needs_close, &type, &options );
785     if (status) return status;
786
787     if (type == FD_TYPE_FILE && offset && offset->QuadPart != (LONGLONG)-2 /* FILE_USE_FILE_POINTER_POSITION */ )
788     {
789         /* async I/O doesn't make sense on regular files */
790         while ((result = pwrite( unix_handle, buffer, length, offset->QuadPart )) == -1)
791         {
792             if (errno != EINTR)
793             {
794                 if (errno == EFAULT) status = STATUS_INVALID_USER_BUFFER;
795                 else status = FILE_GetNtStatus();
796                 goto done;
797             }
798         }
799
800         if (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT))
801             /* update file pointer position */
802             lseek( unix_handle, offset->QuadPart + result, SEEK_SET );
803
804         total = result;
805         status = STATUS_SUCCESS;
806         goto done;
807     }
808
809     for (;;)
810     {
811         /* zero-length writes on sockets may not work with plain write(2) */
812         if (!length && (type == FD_TYPE_MAILSLOT || type == FD_TYPE_PIPE || type == FD_TYPE_SOCKET))
813             result = send( unix_handle, buffer, 0, 0 );
814         else
815             result = write( unix_handle, (const char *)buffer + total, length - total );
816
817         if (result >= 0)
818         {
819             total += result;
820             if (total == length)
821             {
822                 status = STATUS_SUCCESS;
823                 goto done;
824             }
825         }
826         else
827         {
828             if (errno == EINTR) continue;
829             if (errno != EAGAIN)
830             {
831                 if (errno == EFAULT) status = STATUS_INVALID_USER_BUFFER;
832                 else status = FILE_GetNtStatus();
833                 goto done;
834             }
835         }
836
837         if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
838         {
839             async_fileio_write *fileio;
840
841             if (!(fileio = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(*fileio))))
842             {
843                 status = STATUS_NO_MEMORY;
844                 goto done;
845             }
846             fileio->io.handle  = hFile;
847             fileio->io.apc     = apc;
848             fileio->io.apc_arg = apc_user;
849             fileio->already = total;
850             fileio->count = length;
851             fileio->buffer = buffer;
852
853             SERVER_START_REQ( register_async )
854             {
855                 req->handle = hFile;
856                 req->type   = ASYNC_TYPE_WRITE;
857                 req->count  = length;
858                 req->async.callback = FILE_AsyncWriteService;
859                 req->async.iosb     = io_status;
860                 req->async.arg      = fileio;
861                 req->async.apc      = fileio_apc;
862                 req->async.event    = hEvent;
863                 status = wine_server_call( req );
864             }
865             SERVER_END_REQ;
866
867             if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
868             goto done;
869         }
870         else  /* synchronous write, wait for the fd to become ready */
871         {
872             struct pollfd pfd;
873             int ret, timeout;
874
875             if (!timeout_init_done)
876             {
877                 timeout_init_done = 1;
878                 if ((status = get_io_timeouts( hFile, type, length, FALSE, &timeouts )))
879                     goto done;
880                 if (hEvent) NtResetEvent( hEvent, NULL );
881             }
882             timeout = get_next_io_timeout( &timeouts, total );
883
884             pfd.fd = unix_handle;
885             pfd.events = POLLOUT;
886
887             if (!timeout || !(ret = poll( &pfd, 1, timeout )))
888             {
889                 /* return with what we got so far */
890                 status = total ? STATUS_SUCCESS : STATUS_TIMEOUT;
891                 goto done;
892             }
893             if (ret == -1 && errno != EINTR)
894             {
895                 status = FILE_GetNtStatus();
896                 goto done;
897             }
898             /* will now restart the write */
899         }
900     }
901
902 done:
903     if (needs_close) close( unix_handle );
904     if (status == STATUS_SUCCESS)
905     {
906         io_status->u.Status = status;
907         io_status->Information = total;
908         TRACE("= SUCCESS (%u)\n", total);
909         if (hEvent) NtSetEvent( hEvent, NULL );
910         if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
911                                    (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
912     }
913     else
914     {
915         TRACE("= 0x%08x\n", status);
916         if (status != STATUS_PENDING && hEvent) NtResetEvent( hEvent, NULL );
917     }
918     return status;
919 }
920
921
922 struct async_ioctl
923 {
924     HANDLE          handle;   /* handle to the device */
925     void           *buffer;   /* buffer for output */
926     ULONG           size;     /* size of buffer */
927     PIO_APC_ROUTINE apc;      /* user apc params */
928     void           *apc_arg;
929 };
930
931 /* callback for ioctl async I/O completion */
932 static NTSTATUS ioctl_completion( void *arg, IO_STATUS_BLOCK *io, NTSTATUS status )
933 {
934     struct async_ioctl *async = arg;
935
936     if (status == STATUS_ALERTED)
937     {
938         SERVER_START_REQ( get_ioctl_result )
939         {
940             req->handle   = async->handle;
941             req->user_arg = async;
942             wine_server_set_reply( req, async->buffer, async->size );
943             if (!(status = wine_server_call( req )))
944                 io->Information = wine_server_reply_size( reply );
945         }
946         SERVER_END_REQ;
947     }
948     if (status != STATUS_PENDING) io->u.Status = status;
949     return status;
950 }
951
952 /* callback for ioctl user APC */
953 static void WINAPI ioctl_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
954 {
955     struct async_ioctl *async = arg;
956     if (async->apc) async->apc( async->apc_arg, io, reserved );
957     RtlFreeHeap( GetProcessHeap(), 0, async );
958 }
959
960 /* do a ioctl call through the server */
961 static NTSTATUS server_ioctl_file( HANDLE handle, HANDLE event,
962                                    PIO_APC_ROUTINE apc, PVOID apc_context,
963                                    IO_STATUS_BLOCK *io, ULONG code,
964                                    const void *in_buffer, ULONG in_size,
965                                    PVOID out_buffer, ULONG out_size )
966 {
967     struct async_ioctl *async;
968     NTSTATUS status;
969     HANDLE wait_handle;
970     ULONG options;
971
972     if (!(async = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*async) )))
973         return STATUS_NO_MEMORY;
974     async->handle  = handle;
975     async->buffer  = out_buffer;
976     async->size    = out_size;
977     async->apc     = apc;
978     async->apc_arg = apc_context;
979
980     SERVER_START_REQ( ioctl )
981     {
982         req->handle         = handle;
983         req->code           = code;
984         req->async.callback = ioctl_completion;
985         req->async.iosb     = io;
986         req->async.arg      = async;
987         req->async.apc      = (apc || event) ? ioctl_apc : NULL;
988         req->async.event    = event;
989         wine_server_add_data( req, in_buffer, in_size );
990         wine_server_set_reply( req, out_buffer, out_size );
991         if (!(status = wine_server_call( req )))
992             io->Information = wine_server_reply_size( reply );
993         wait_handle = reply->wait;
994         options     = reply->options;
995     }
996     SERVER_END_REQ;
997
998     if (status == STATUS_NOT_SUPPORTED)
999         FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
1000               code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
1001
1002     if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, async );
1003
1004     if (wait_handle)
1005     {
1006         NtWaitForSingleObject( wait_handle, (options & FILE_SYNCHRONOUS_IO_ALERT), NULL );
1007         status = io->u.Status;
1008         NtClose( wait_handle );
1009         RtlFreeHeap( GetProcessHeap(), 0, async );
1010     }
1011
1012     return status;
1013 }
1014
1015
1016 /**************************************************************************
1017  *              NtDeviceIoControlFile                   [NTDLL.@]
1018  *              ZwDeviceIoControlFile                   [NTDLL.@]
1019  *
1020  * Perform an I/O control operation on an open file handle.
1021  *
1022  * PARAMS
1023  *  handle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1024  *  event          [I] Event to signal upon completion (or NULL)
1025  *  apc            [I] Callback to call upon completion (or NULL)
1026  *  apc_context    [I] Context for ApcRoutine (or NULL)
1027  *  io             [O] Receives information about the operation on return
1028  *  code           [I] Control code for the operation to perform
1029  *  in_buffer      [I] Source for any input data required (or NULL)
1030  *  in_size        [I] Size of InputBuffer
1031  *  out_buffer     [O] Source for any output data returned (or NULL)
1032  *  out_size       [I] Size of OutputBuffer
1033  *
1034  * RETURNS
1035  *  Success: 0. IoStatusBlock is updated.
1036  *  Failure: An NTSTATUS error code describing the error.
1037  */
1038 NTSTATUS WINAPI NtDeviceIoControlFile(HANDLE handle, HANDLE event,
1039                                       PIO_APC_ROUTINE apc, PVOID apc_context,
1040                                       PIO_STATUS_BLOCK io, ULONG code,
1041                                       PVOID in_buffer, ULONG in_size,
1042                                       PVOID out_buffer, ULONG out_size)
1043 {
1044     ULONG device = (code >> 16);
1045     NTSTATUS status;
1046
1047     TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1048           handle, event, apc, apc_context, io, code,
1049           in_buffer, in_size, out_buffer, out_size);
1050
1051     switch(device)
1052     {
1053     case FILE_DEVICE_DISK:
1054     case FILE_DEVICE_CD_ROM:
1055     case FILE_DEVICE_DVD:
1056     case FILE_DEVICE_CONTROLLER:
1057     case FILE_DEVICE_MASS_STORAGE:
1058         status = CDROM_DeviceIoControl(handle, event, apc, apc_context, io, code,
1059                                        in_buffer, in_size, out_buffer, out_size);
1060         break;
1061     case FILE_DEVICE_SERIAL_PORT:
1062         status = COMM_DeviceIoControl(handle, event, apc, apc_context, io, code,
1063                                       in_buffer, in_size, out_buffer, out_size);
1064         break;
1065     case FILE_DEVICE_TAPE:
1066         status = TAPE_DeviceIoControl(handle, event, apc, apc_context, io, code,
1067                                       in_buffer, in_size, out_buffer, out_size);
1068         break;
1069     default:
1070         status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1071                                     in_buffer, in_size, out_buffer, out_size );
1072         break;
1073     }
1074     if (status != STATUS_PENDING) io->u.Status = status;
1075     return status;
1076 }
1077
1078
1079 /**************************************************************************
1080  *              NtFsControlFile                 [NTDLL.@]
1081  *              ZwFsControlFile                 [NTDLL.@]
1082  *
1083  * Perform a file system control operation on an open file handle.
1084  *
1085  * PARAMS
1086  *  handle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1087  *  event          [I] Event to signal upon completion (or NULL)
1088  *  apc            [I] Callback to call upon completion (or NULL)
1089  *  apc_context    [I] Context for ApcRoutine (or NULL)
1090  *  io             [O] Receives information about the operation on return
1091  *  code           [I] Control code for the operation to perform
1092  *  in_buffer      [I] Source for any input data required (or NULL)
1093  *  in_size        [I] Size of InputBuffer
1094  *  out_buffer     [O] Source for any output data returned (or NULL)
1095  *  out_size       [I] Size of OutputBuffer
1096  *
1097  * RETURNS
1098  *  Success: 0. IoStatusBlock is updated.
1099  *  Failure: An NTSTATUS error code describing the error.
1100  */
1101 NTSTATUS WINAPI NtFsControlFile(HANDLE handle, HANDLE event, PIO_APC_ROUTINE apc,
1102                                 PVOID apc_context, PIO_STATUS_BLOCK io, ULONG code,
1103                                 PVOID in_buffer, ULONG in_size, PVOID out_buffer, ULONG out_size)
1104 {
1105     NTSTATUS status;
1106
1107     TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1108           handle, event, apc, apc_context, io, code,
1109           in_buffer, in_size, out_buffer, out_size);
1110
1111     if (!io) return STATUS_INVALID_PARAMETER;
1112
1113     switch(code)
1114     {
1115     case FSCTL_DISMOUNT_VOLUME:
1116         status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1117                                     in_buffer, in_size, out_buffer, out_size );
1118         if (!status) status = DIR_unmount_device( handle );
1119         break;
1120
1121     case FSCTL_PIPE_PEEK:
1122         {
1123             FILE_PIPE_PEEK_BUFFER *buffer = out_buffer;
1124             int avail = 0, fd, needs_close;
1125
1126             if (out_size < FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data ))
1127             {
1128                 status = STATUS_INFO_LENGTH_MISMATCH;
1129                 break;
1130             }
1131
1132             if ((status = server_get_unix_fd( handle, FILE_READ_DATA, &fd, &needs_close, NULL, NULL )))
1133                 break;
1134
1135 #ifdef FIONREAD
1136             if (ioctl( fd, FIONREAD, &avail ) != 0)
1137             {
1138                 TRACE("FIONREAD failed reason: %s\n",strerror(errno));
1139                 if (needs_close) close( fd );
1140                 status = FILE_GetNtStatus();
1141                 break;
1142             }
1143 #endif
1144             if (!avail)  /* check for closed pipe */
1145             {
1146                 struct pollfd pollfd;
1147                 int ret;
1148
1149                 pollfd.fd = fd;
1150                 pollfd.events = POLLIN;
1151                 pollfd.revents = 0;
1152                 ret = poll( &pollfd, 1, 0 );
1153                 if (ret == -1 || (ret == 1 && (pollfd.revents & (POLLHUP|POLLERR))))
1154                 {
1155                     if (needs_close) close( fd );
1156                     status = STATUS_PIPE_BROKEN;
1157                     break;
1158                 }
1159             }
1160             buffer->NamedPipeState    = 0;  /* FIXME */
1161             buffer->ReadDataAvailable = avail;
1162             buffer->NumberOfMessages  = 0;  /* FIXME */
1163             buffer->MessageLength     = 0;  /* FIXME */
1164             io->Information = FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data );
1165             status = STATUS_SUCCESS;
1166             if (avail)
1167             {
1168                 ULONG data_size = out_size - FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data );
1169                 if (data_size)
1170                 {
1171                     int res = recv( fd, buffer->Data, data_size, MSG_PEEK );
1172                     if (res >= 0) io->Information += res;
1173                 }
1174             }
1175             if (needs_close) close( fd );
1176         }
1177         break;
1178
1179     case FSCTL_PIPE_DISCONNECT:
1180         status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1181                                     in_buffer, in_size, out_buffer, out_size );
1182         if (!status)
1183         {
1184             int fd = server_remove_fd_from_cache( handle );
1185             if (fd != -1) close( fd );
1186         }
1187         break;
1188
1189     case FSCTL_PIPE_IMPERSONATE:
1190         FIXME("FSCTL_PIPE_IMPERSONATE: impersonating self\n");
1191         status = RtlImpersonateSelf( SecurityImpersonation );
1192         break;
1193
1194     case FSCTL_LOCK_VOLUME:
1195     case FSCTL_UNLOCK_VOLUME:
1196         FIXME("stub! return success - Unsupported fsctl %x (device=%x access=%x func=%x method=%x)\n",
1197               code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
1198         status = STATUS_SUCCESS;
1199         break;
1200
1201     case FSCTL_PIPE_LISTEN:
1202     case FSCTL_PIPE_WAIT:
1203     default:
1204         status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1205                                     in_buffer, in_size, out_buffer, out_size );
1206         break;
1207     }
1208
1209     if (status != STATUS_PENDING) io->u.Status = status;
1210     return status;
1211 }
1212
1213 /******************************************************************************
1214  *  NtSetVolumeInformationFile          [NTDLL.@]
1215  *  ZwSetVolumeInformationFile          [NTDLL.@]
1216  *
1217  * Set volume information for an open file handle.
1218  *
1219  * PARAMS
1220  *  FileHandle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1221  *  IoStatusBlock      [O] Receives information about the operation on return
1222  *  FsInformation      [I] Source for volume information
1223  *  Length             [I] Size of FsInformation
1224  *  FsInformationClass [I] Type of volume information to set
1225  *
1226  * RETURNS
1227  *  Success: 0. IoStatusBlock is updated.
1228  *  Failure: An NTSTATUS error code describing the error.
1229  */
1230 NTSTATUS WINAPI NtSetVolumeInformationFile(
1231         IN HANDLE FileHandle,
1232         PIO_STATUS_BLOCK IoStatusBlock,
1233         PVOID FsInformation,
1234         ULONG Length,
1235         FS_INFORMATION_CLASS FsInformationClass)
1236 {
1237         FIXME("(%p,%p,%p,0x%08x,0x%08x) stub\n",
1238         FileHandle,IoStatusBlock,FsInformation,Length,FsInformationClass);
1239         return 0;
1240 }
1241
1242 /******************************************************************************
1243  *  NtQueryInformationFile              [NTDLL.@]
1244  *  ZwQueryInformationFile              [NTDLL.@]
1245  *
1246  * Get information about an open file handle.
1247  *
1248  * PARAMS
1249  *  hFile    [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1250  *  io       [O] Receives information about the operation on return
1251  *  ptr      [O] Destination for file information
1252  *  len      [I] Size of FileInformation
1253  *  class    [I] Type of file information to get
1254  *
1255  * RETURNS
1256  *  Success: 0. IoStatusBlock and FileInformation are updated.
1257  *  Failure: An NTSTATUS error code describing the error.
1258  */
1259 NTSTATUS WINAPI NtQueryInformationFile( HANDLE hFile, PIO_STATUS_BLOCK io,
1260                                         PVOID ptr, LONG len, FILE_INFORMATION_CLASS class )
1261 {
1262     static const size_t info_sizes[] =
1263     {
1264         0,
1265         sizeof(FILE_DIRECTORY_INFORMATION),            /* FileDirectoryInformation */
1266         sizeof(FILE_FULL_DIRECTORY_INFORMATION),       /* FileFullDirectoryInformation */
1267         sizeof(FILE_BOTH_DIRECTORY_INFORMATION),       /* FileBothDirectoryInformation */
1268         sizeof(FILE_BASIC_INFORMATION),                /* FileBasicInformation */
1269         sizeof(FILE_STANDARD_INFORMATION),             /* FileStandardInformation */
1270         sizeof(FILE_INTERNAL_INFORMATION),             /* FileInternalInformation */
1271         sizeof(FILE_EA_INFORMATION),                   /* FileEaInformation */
1272         sizeof(FILE_ACCESS_INFORMATION),               /* FileAccessInformation */
1273         sizeof(FILE_NAME_INFORMATION)-sizeof(WCHAR),   /* FileNameInformation */
1274         sizeof(FILE_RENAME_INFORMATION)-sizeof(WCHAR), /* FileRenameInformation */
1275         0,                                             /* FileLinkInformation */
1276         sizeof(FILE_NAMES_INFORMATION)-sizeof(WCHAR),  /* FileNamesInformation */
1277         sizeof(FILE_DISPOSITION_INFORMATION),          /* FileDispositionInformation */
1278         sizeof(FILE_POSITION_INFORMATION),             /* FilePositionInformation */
1279         sizeof(FILE_FULL_EA_INFORMATION),              /* FileFullEaInformation */
1280         sizeof(FILE_MODE_INFORMATION),                 /* FileModeInformation */
1281         sizeof(FILE_ALIGNMENT_INFORMATION),            /* FileAlignmentInformation */
1282         sizeof(FILE_ALL_INFORMATION)-sizeof(WCHAR),    /* FileAllInformation */
1283         sizeof(FILE_ALLOCATION_INFORMATION),           /* FileAllocationInformation */
1284         sizeof(FILE_END_OF_FILE_INFORMATION),          /* FileEndOfFileInformation */
1285         0,                                             /* FileAlternateNameInformation */
1286         sizeof(FILE_STREAM_INFORMATION)-sizeof(WCHAR), /* FileStreamInformation */
1287         0,                                             /* FilePipeInformation */
1288         sizeof(FILE_PIPE_LOCAL_INFORMATION),           /* FilePipeLocalInformation */
1289         0,                                             /* FilePipeRemoteInformation */
1290         sizeof(FILE_MAILSLOT_QUERY_INFORMATION),       /* FileMailslotQueryInformation */
1291         0,                                             /* FileMailslotSetInformation */
1292         0,                                             /* FileCompressionInformation */
1293         0,                                             /* FileObjectIdInformation */
1294         0,                                             /* FileCompletionInformation */
1295         0,                                             /* FileMoveClusterInformation */
1296         0,                                             /* FileQuotaInformation */
1297         0,                                             /* FileReparsePointInformation */
1298         0,                                             /* FileNetworkOpenInformation */
1299         0,                                             /* FileAttributeTagInformation */
1300         0                                              /* FileTrackingInformation */
1301     };
1302
1303     struct stat st;
1304     int fd, needs_close = FALSE;
1305
1306     TRACE("(%p,%p,%p,0x%08x,0x%08x)\n", hFile, io, ptr, len, class);
1307
1308     io->Information = 0;
1309
1310     if (class <= 0 || class >= FileMaximumInformation)
1311         return io->u.Status = STATUS_INVALID_INFO_CLASS;
1312     if (!info_sizes[class])
1313     {
1314         FIXME("Unsupported class (%d)\n", class);
1315         return io->u.Status = STATUS_NOT_IMPLEMENTED;
1316     }
1317     if (len < info_sizes[class])
1318         return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
1319
1320     if (class != FilePipeLocalInformation)
1321     {
1322         if ((io->u.Status = server_get_unix_fd( hFile, 0, &fd, &needs_close, NULL, NULL )))
1323             return io->u.Status;
1324     }
1325
1326     switch (class)
1327     {
1328     case FileBasicInformation:
1329         {
1330             FILE_BASIC_INFORMATION *info = ptr;
1331
1332             if (fstat( fd, &st ) == -1)
1333                 io->u.Status = FILE_GetNtStatus();
1334             else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
1335                 io->u.Status = STATUS_INVALID_INFO_CLASS;
1336             else
1337             {
1338                 if (S_ISDIR(st.st_mode)) info->FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
1339                 else info->FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1340                 if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1341                     info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
1342                 RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime);
1343                 RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime);
1344                 RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime);
1345                 RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime);
1346             }
1347         }
1348         break;
1349     case FileStandardInformation:
1350         {
1351             FILE_STANDARD_INFORMATION *info = ptr;
1352
1353             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1354             else
1355             {
1356                 if ((info->Directory = S_ISDIR(st.st_mode)))
1357                 {
1358                     info->AllocationSize.QuadPart = 0;
1359                     info->EndOfFile.QuadPart      = 0;
1360                     info->NumberOfLinks           = 1;
1361                     info->DeletePending           = FALSE;
1362                 }
1363                 else
1364                 {
1365                     info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
1366                     info->EndOfFile.QuadPart      = st.st_size;
1367                     info->NumberOfLinks           = st.st_nlink;
1368                     info->DeletePending           = FALSE; /* FIXME */
1369                 }
1370             }
1371         }
1372         break;
1373     case FilePositionInformation:
1374         {
1375             FILE_POSITION_INFORMATION *info = ptr;
1376             off_t res = lseek( fd, 0, SEEK_CUR );
1377             if (res == (off_t)-1) io->u.Status = FILE_GetNtStatus();
1378             else info->CurrentByteOffset.QuadPart = res;
1379         }
1380         break;
1381     case FileInternalInformation:
1382         {
1383             FILE_INTERNAL_INFORMATION *info = ptr;
1384
1385             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1386             else info->IndexNumber.QuadPart = st.st_ino;
1387         }
1388         break;
1389     case FileEaInformation:
1390         {
1391             FILE_EA_INFORMATION *info = ptr;
1392             info->EaSize = 0;
1393         }
1394         break;
1395     case FileEndOfFileInformation:
1396         {
1397             FILE_END_OF_FILE_INFORMATION *info = ptr;
1398
1399             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1400             else info->EndOfFile.QuadPart = S_ISDIR(st.st_mode) ? 0 : st.st_size;
1401         }
1402         break;
1403     case FileAllInformation:
1404         {
1405             FILE_ALL_INFORMATION *info = ptr;
1406
1407             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1408             else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
1409                 io->u.Status = STATUS_INVALID_INFO_CLASS;
1410             else
1411             {
1412                 if ((info->StandardInformation.Directory = S_ISDIR(st.st_mode)))
1413                 {
1414                     info->BasicInformation.FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
1415                     info->StandardInformation.AllocationSize.QuadPart = 0;
1416                     info->StandardInformation.EndOfFile.QuadPart      = 0;
1417                     info->StandardInformation.NumberOfLinks           = 1;
1418                     info->StandardInformation.DeletePending           = FALSE;
1419                 }
1420                 else
1421                 {
1422                     info->BasicInformation.FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1423                     info->StandardInformation.AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
1424                     info->StandardInformation.EndOfFile.QuadPart      = st.st_size;
1425                     info->StandardInformation.NumberOfLinks           = st.st_nlink;
1426                     info->StandardInformation.DeletePending           = FALSE; /* FIXME */
1427                 }
1428                 if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1429                     info->BasicInformation.FileAttributes |= FILE_ATTRIBUTE_READONLY;
1430                 RtlSecondsSince1970ToTime( st.st_mtime, &info->BasicInformation.CreationTime);
1431                 RtlSecondsSince1970ToTime( st.st_mtime, &info->BasicInformation.LastWriteTime);
1432                 RtlSecondsSince1970ToTime( st.st_ctime, &info->BasicInformation.ChangeTime);
1433                 RtlSecondsSince1970ToTime( st.st_atime, &info->BasicInformation.LastAccessTime);
1434                 info->InternalInformation.IndexNumber.QuadPart = st.st_ino;
1435                 info->EaInformation.EaSize = 0;
1436                 info->AccessInformation.AccessFlags = 0;  /* FIXME */
1437                 info->PositionInformation.CurrentByteOffset.QuadPart = lseek( fd, 0, SEEK_CUR );
1438                 info->ModeInformation.Mode = 0;  /* FIXME */
1439                 info->AlignmentInformation.AlignmentRequirement = 1;  /* FIXME */
1440                 info->NameInformation.FileNameLength = 0;
1441                 io->Information = sizeof(*info) - sizeof(WCHAR);
1442             }
1443         }
1444         break;
1445     case FileMailslotQueryInformation:
1446         {
1447             FILE_MAILSLOT_QUERY_INFORMATION *info = ptr;
1448
1449             SERVER_START_REQ( set_mailslot_info )
1450             {
1451                 req->handle = hFile;
1452                 req->flags = 0;
1453                 io->u.Status = wine_server_call( req );
1454                 if( io->u.Status == STATUS_SUCCESS )
1455                 {
1456                     info->MaximumMessageSize = reply->max_msgsize;
1457                     info->MailslotQuota = 0;
1458                     info->NextMessageSize = 0;
1459                     info->MessagesAvailable = 0;
1460                     info->ReadTimeout.QuadPart = reply->read_timeout;
1461                 }
1462             }
1463             SERVER_END_REQ;
1464             if (!io->u.Status)
1465             {
1466                 char *tmpbuf;
1467                 ULONG size = info->MaximumMessageSize ? info->MaximumMessageSize : 0x10000;
1468                 if (size > 0x10000) size = 0x10000;
1469                 if ((tmpbuf = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1470                 {
1471                     int fd, needs_close;
1472                     if (!server_get_unix_fd( hFile, FILE_READ_DATA, &fd, &needs_close, NULL, NULL ))
1473                     {
1474                         int res = recv( fd, tmpbuf, size, MSG_PEEK );
1475                         info->MessagesAvailable = (res > 0);
1476                         info->NextMessageSize = (res >= 0) ? res : MAILSLOT_NO_MESSAGE;
1477                         if (needs_close) close( fd );
1478                     }
1479                     RtlFreeHeap( GetProcessHeap(), 0, tmpbuf );
1480                 }
1481             }
1482         }
1483         break;
1484     case FilePipeLocalInformation:
1485         {
1486             FILE_PIPE_LOCAL_INFORMATION* pli = ptr;
1487
1488             SERVER_START_REQ( get_named_pipe_info )
1489             {
1490                 req->handle = hFile;
1491                 if (!(io->u.Status = wine_server_call( req )))
1492                 {
1493                     pli->NamedPipeType = (reply->flags & NAMED_PIPE_MESSAGE_STREAM_WRITE) ? 
1494                         FILE_PIPE_TYPE_MESSAGE : FILE_PIPE_TYPE_BYTE;
1495                     pli->NamedPipeConfiguration = 0; /* FIXME */
1496                     pli->MaximumInstances = reply->maxinstances;
1497                     pli->CurrentInstances = reply->instances;
1498                     pli->InboundQuota = reply->insize;
1499                     pli->ReadDataAvailable = 0; /* FIXME */
1500                     pli->OutboundQuota = reply->outsize;
1501                     pli->WriteQuotaAvailable = 0; /* FIXME */
1502                     pli->NamedPipeState = 0; /* FIXME */
1503                     pli->NamedPipeEnd = (reply->flags & NAMED_PIPE_SERVER_END) ?
1504                         FILE_PIPE_SERVER_END : FILE_PIPE_CLIENT_END;
1505                 }
1506             }
1507             SERVER_END_REQ;
1508         }
1509         break;
1510     default:
1511         FIXME("Unsupported class (%d)\n", class);
1512         io->u.Status = STATUS_NOT_IMPLEMENTED;
1513         break;
1514     }
1515     if (needs_close) close( fd );
1516     if (io->u.Status == STATUS_SUCCESS && !io->Information) io->Information = info_sizes[class];
1517     return io->u.Status;
1518 }
1519
1520 /******************************************************************************
1521  *  NtSetInformationFile                [NTDLL.@]
1522  *  ZwSetInformationFile                [NTDLL.@]
1523  *
1524  * Set information about an open file handle.
1525  *
1526  * PARAMS
1527  *  handle  [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1528  *  io      [O] Receives information about the operation on return
1529  *  ptr     [I] Source for file information
1530  *  len     [I] Size of FileInformation
1531  *  class   [I] Type of file information to set
1532  *
1533  * RETURNS
1534  *  Success: 0. io is updated.
1535  *  Failure: An NTSTATUS error code describing the error.
1536  */
1537 NTSTATUS WINAPI NtSetInformationFile(HANDLE handle, PIO_STATUS_BLOCK io,
1538                                      PVOID ptr, ULONG len, FILE_INFORMATION_CLASS class)
1539 {
1540     int fd, needs_close;
1541
1542     TRACE("(%p,%p,%p,0x%08x,0x%08x)\n", handle, io, ptr, len, class);
1543
1544     if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
1545         return io->u.Status;
1546
1547     io->u.Status = STATUS_SUCCESS;
1548     switch (class)
1549     {
1550     case FileBasicInformation:
1551         if (len >= sizeof(FILE_BASIC_INFORMATION))
1552         {
1553             struct stat st;
1554             const FILE_BASIC_INFORMATION *info = ptr;
1555
1556             if (info->LastAccessTime.QuadPart || info->LastWriteTime.QuadPart)
1557             {
1558                 ULONGLONG sec, nsec;
1559                 struct timeval tv[2];
1560
1561                 if (!info->LastAccessTime.QuadPart || !info->LastWriteTime.QuadPart)
1562                 {
1563
1564                     tv[0].tv_sec = tv[0].tv_usec = 0;
1565                     tv[1].tv_sec = tv[1].tv_usec = 0;
1566                     if (!fstat( fd, &st ))
1567                     {
1568                         tv[0].tv_sec = st.st_atime;
1569                         tv[1].tv_sec = st.st_mtime;
1570                     }
1571                 }
1572                 if (info->LastAccessTime.QuadPart)
1573                 {
1574                     sec = RtlLargeIntegerDivide( info->LastAccessTime.QuadPart, 10000000, &nsec );
1575                     tv[0].tv_sec = sec - SECS_1601_TO_1970;
1576                     tv[0].tv_usec = (UINT)nsec / 10;
1577                 }
1578                 if (info->LastWriteTime.QuadPart)
1579                 {
1580                     sec = RtlLargeIntegerDivide( info->LastWriteTime.QuadPart, 10000000, &nsec );
1581                     tv[1].tv_sec = sec - SECS_1601_TO_1970;
1582                     tv[1].tv_usec = (UINT)nsec / 10;
1583                 }
1584                 if (futimes( fd, tv ) == -1) io->u.Status = FILE_GetNtStatus();
1585             }
1586
1587             if (io->u.Status == STATUS_SUCCESS && info->FileAttributes)
1588             {
1589                 if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1590                 else
1591                 {
1592                     if (info->FileAttributes & FILE_ATTRIBUTE_READONLY)
1593                     {
1594                         if (S_ISDIR( st.st_mode))
1595                             WARN("FILE_ATTRIBUTE_READONLY ignored for directory.\n");
1596                         else
1597                             st.st_mode &= ~0222; /* clear write permission bits */
1598                     }
1599                     else
1600                     {
1601                         /* add write permission only where we already have read permission */
1602                         st.st_mode |= (0600 | ((st.st_mode & 044) >> 1)) & (~FILE_umask);
1603                     }
1604                     if (fchmod( fd, st.st_mode ) == -1) io->u.Status = FILE_GetNtStatus();
1605                 }
1606             }
1607         }
1608         else io->u.Status = STATUS_INVALID_PARAMETER_3;
1609         break;
1610
1611     case FilePositionInformation:
1612         if (len >= sizeof(FILE_POSITION_INFORMATION))
1613         {
1614             const FILE_POSITION_INFORMATION *info = ptr;
1615
1616             if (lseek( fd, info->CurrentByteOffset.QuadPart, SEEK_SET ) == (off_t)-1)
1617                 io->u.Status = FILE_GetNtStatus();
1618         }
1619         else io->u.Status = STATUS_INVALID_PARAMETER_3;
1620         break;
1621
1622     case FileEndOfFileInformation:
1623         if (len >= sizeof(FILE_END_OF_FILE_INFORMATION))
1624         {
1625             struct stat st;
1626             const FILE_END_OF_FILE_INFORMATION *info = ptr;
1627
1628             /* first try normal truncate */
1629             if (ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
1630
1631             /* now check for the need to extend the file */
1632             if (fstat( fd, &st ) != -1 && (off_t)info->EndOfFile.QuadPart > st.st_size)
1633             {
1634                 static const char zero;
1635
1636                 /* extend the file one byte beyond the requested size and then truncate it */
1637                 /* this should work around ftruncate implementations that can't extend files */
1638                 if (pwrite( fd, &zero, 1, (off_t)info->EndOfFile.QuadPart ) != -1 &&
1639                     ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
1640             }
1641             io->u.Status = FILE_GetNtStatus();
1642         }
1643         else io->u.Status = STATUS_INVALID_PARAMETER_3;
1644         break;
1645
1646     case FileMailslotSetInformation:
1647         {
1648             FILE_MAILSLOT_SET_INFORMATION *info = ptr;
1649
1650             SERVER_START_REQ( set_mailslot_info )
1651             {
1652                 req->handle = handle;
1653                 req->flags = MAILSLOT_SET_READ_TIMEOUT;
1654                 req->read_timeout = info->ReadTimeout.QuadPart;
1655                 io->u.Status = wine_server_call( req );
1656             }
1657             SERVER_END_REQ;
1658         }
1659         break;
1660
1661     default:
1662         FIXME("Unsupported class (%d)\n", class);
1663         io->u.Status = STATUS_NOT_IMPLEMENTED;
1664         break;
1665     }
1666     if (needs_close) close( fd );
1667     io->Information = 0;
1668     return io->u.Status;
1669 }
1670
1671
1672 /******************************************************************************
1673  *              NtQueryFullAttributesFile   (NTDLL.@)
1674  */
1675 NTSTATUS WINAPI NtQueryFullAttributesFile( const OBJECT_ATTRIBUTES *attr,
1676                                            FILE_NETWORK_OPEN_INFORMATION *info )
1677 {
1678     ANSI_STRING unix_name;
1679     NTSTATUS status;
1680
1681     if (!(status = wine_nt_to_unix_file_name( attr->ObjectName, &unix_name, FILE_OPEN,
1682                                               !(attr->Attributes & OBJ_CASE_INSENSITIVE) )))
1683     {
1684         struct stat st;
1685
1686         if (stat( unix_name.Buffer, &st ) == -1)
1687             status = FILE_GetNtStatus();
1688         else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
1689             status = STATUS_INVALID_INFO_CLASS;
1690         else
1691         {
1692             if (S_ISDIR(st.st_mode))
1693             {
1694                 info->FileAttributes          = FILE_ATTRIBUTE_DIRECTORY;
1695                 info->AllocationSize.QuadPart = 0;
1696                 info->EndOfFile.QuadPart      = 0;
1697             }
1698             else
1699             {
1700                 info->FileAttributes          = FILE_ATTRIBUTE_ARCHIVE;
1701                 info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
1702                 info->EndOfFile.QuadPart      = st.st_size;
1703             }
1704             if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1705                 info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
1706             RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
1707             RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
1708             RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
1709             RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
1710             if (DIR_is_hidden_file( attr->ObjectName ))
1711                 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
1712         }
1713         RtlFreeAnsiString( &unix_name );
1714     }
1715     else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), status );
1716     return status;
1717 }
1718
1719
1720 /******************************************************************************
1721  *              NtQueryAttributesFile   (NTDLL.@)
1722  *              ZwQueryAttributesFile   (NTDLL.@)
1723  */
1724 NTSTATUS WINAPI NtQueryAttributesFile( const OBJECT_ATTRIBUTES *attr, FILE_BASIC_INFORMATION *info )
1725 {
1726     FILE_NETWORK_OPEN_INFORMATION full_info;
1727     NTSTATUS status;
1728
1729     if (!(status = NtQueryFullAttributesFile( attr, &full_info )))
1730     {
1731         info->CreationTime.QuadPart   = full_info.CreationTime.QuadPart;
1732         info->LastAccessTime.QuadPart = full_info.LastAccessTime.QuadPart;
1733         info->LastWriteTime.QuadPart  = full_info.LastWriteTime.QuadPart;
1734         info->ChangeTime.QuadPart     = full_info.ChangeTime.QuadPart;
1735         info->FileAttributes          = full_info.FileAttributes;
1736     }
1737     return status;
1738 }
1739
1740
1741 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__APPLE__)
1742 /* helper for FILE_GetDeviceInfo to hide some platform differences in fstatfs */
1743 static inline void get_device_info_fstatfs( FILE_FS_DEVICE_INFORMATION *info, const char *fstypename,
1744                                             unsigned int flags )
1745 {
1746     if (!strcmp("cd9660", fstypename) || !strcmp("udf", fstypename))
1747     {
1748         info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
1749         /* Don't assume read-only, let the mount options set it below */
1750         info->Characteristics |= FILE_REMOVABLE_MEDIA;
1751     }
1752     else if (!strcmp("nfs", fstypename) || !strcmp("nwfs", fstypename) ||
1753              !strcmp("smbfs", fstypename) || !strcmp("afpfs", fstypename))
1754     {
1755         info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
1756         info->Characteristics |= FILE_REMOTE_DEVICE;
1757     }
1758     else if (!strcmp("procfs", fstypename))
1759         info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
1760     else
1761         info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1762
1763     if (flags & MNT_RDONLY)
1764         info->Characteristics |= FILE_READ_ONLY_DEVICE;
1765
1766     if (!(flags & MNT_LOCAL))
1767     {
1768         info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
1769         info->Characteristics |= FILE_REMOTE_DEVICE;
1770     }
1771 }
1772 #endif
1773
1774 /******************************************************************************
1775  *              get_device_info
1776  *
1777  * Implementation of the FileFsDeviceInformation query for NtQueryVolumeInformationFile.
1778  */
1779 static NTSTATUS get_device_info( int fd, FILE_FS_DEVICE_INFORMATION *info )
1780 {
1781     struct stat st;
1782
1783     info->Characteristics = 0;
1784     if (fstat( fd, &st ) < 0) return FILE_GetNtStatus();
1785     if (S_ISCHR( st.st_mode ))
1786     {
1787         info->DeviceType = FILE_DEVICE_UNKNOWN;
1788 #ifdef linux
1789         switch(major(st.st_rdev))
1790         {
1791         case MEM_MAJOR:
1792             info->DeviceType = FILE_DEVICE_NULL;
1793             break;
1794         case TTY_MAJOR:
1795             info->DeviceType = FILE_DEVICE_SERIAL_PORT;
1796             break;
1797         case LP_MAJOR:
1798             info->DeviceType = FILE_DEVICE_PARALLEL_PORT;
1799             break;
1800         case SCSI_TAPE_MAJOR:
1801             info->DeviceType = FILE_DEVICE_TAPE;
1802             break;
1803         }
1804 #endif
1805     }
1806     else if (S_ISBLK( st.st_mode ))
1807     {
1808         info->DeviceType = FILE_DEVICE_DISK;
1809     }
1810     else if (S_ISFIFO( st.st_mode ) || S_ISSOCK( st.st_mode ))
1811     {
1812         info->DeviceType = FILE_DEVICE_NAMED_PIPE;
1813     }
1814     else  /* regular file or directory */
1815     {
1816 #if defined(linux) && defined(HAVE_FSTATFS)
1817         struct statfs stfs;
1818
1819         /* check for floppy disk */
1820         if (major(st.st_dev) == FLOPPY_MAJOR)
1821             info->Characteristics |= FILE_REMOVABLE_MEDIA;
1822
1823         if (fstatfs( fd, &stfs ) < 0) stfs.f_type = 0;
1824         switch (stfs.f_type)
1825         {
1826         case 0x9660:      /* iso9660 */
1827         case 0x9fa1:      /* supermount */
1828         case 0x15013346:  /* udf */
1829             info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
1830             info->Characteristics |= FILE_REMOVABLE_MEDIA|FILE_READ_ONLY_DEVICE;
1831             break;
1832         case 0x6969:  /* nfs */
1833         case 0x517B:  /* smbfs */
1834         case 0x564c:  /* ncpfs */
1835             info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
1836             info->Characteristics |= FILE_REMOTE_DEVICE;
1837             break;
1838         case 0x01021994:  /* tmpfs */
1839         case 0x28cd3d45:  /* cramfs */
1840         case 0x1373:      /* devfs */
1841         case 0x9fa0:      /* procfs */
1842             info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
1843             break;
1844         default:
1845             info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1846             break;
1847         }
1848 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__APPLE__)
1849         struct statfs stfs;
1850
1851         if (fstatfs( fd, &stfs ) < 0)
1852             info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1853         else
1854             get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flags );
1855 #elif defined(__NetBSD__)
1856         struct statvfs stfs;
1857
1858         if (fstatvfs( fd, &stfs) < 0)
1859             info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1860         else
1861             get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flag );
1862 #elif defined(sun)
1863         /* Use dkio to work out device types */
1864         {
1865 # include <sys/dkio.h>
1866 # include <sys/vtoc.h>
1867             struct dk_cinfo dkinf;
1868             int retval = ioctl(fd, DKIOCINFO, &dkinf);
1869             if(retval==-1){
1870                 WARN("Unable to get disk device type information - assuming a disk like device\n");
1871                 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1872             }
1873             switch (dkinf.dki_ctype)
1874             {
1875             case DKC_CDROM:
1876                 info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
1877                 info->Characteristics |= FILE_REMOVABLE_MEDIA|FILE_READ_ONLY_DEVICE;
1878                 break;
1879             case DKC_NCRFLOPPY:
1880             case DKC_SMSFLOPPY:
1881             case DKC_INTEL82072:
1882             case DKC_INTEL82077:
1883                 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1884                 info->Characteristics |= FILE_REMOVABLE_MEDIA;
1885                 break;
1886             case DKC_MD:
1887                 info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
1888                 break;
1889             default:
1890                 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1891             }
1892         }
1893 #else
1894         static int warned;
1895         if (!warned++) FIXME( "device info not properly supported on this platform\n" );
1896         info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1897 #endif
1898         info->Characteristics |= FILE_DEVICE_IS_MOUNTED;
1899     }
1900     return STATUS_SUCCESS;
1901 }
1902
1903
1904 /******************************************************************************
1905  *  NtQueryVolumeInformationFile                [NTDLL.@]
1906  *  ZwQueryVolumeInformationFile                [NTDLL.@]
1907  *
1908  * Get volume information for an open file handle.
1909  *
1910  * PARAMS
1911  *  handle      [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1912  *  io          [O] Receives information about the operation on return
1913  *  buffer      [O] Destination for volume information
1914  *  length      [I] Size of FsInformation
1915  *  info_class  [I] Type of volume information to set
1916  *
1917  * RETURNS
1918  *  Success: 0. io and buffer are updated.
1919  *  Failure: An NTSTATUS error code describing the error.
1920  */
1921 NTSTATUS WINAPI NtQueryVolumeInformationFile( HANDLE handle, PIO_STATUS_BLOCK io,
1922                                               PVOID buffer, ULONG length,
1923                                               FS_INFORMATION_CLASS info_class )
1924 {
1925     int fd, needs_close;
1926     struct stat st;
1927
1928     if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
1929         return io->u.Status;
1930
1931     io->u.Status = STATUS_NOT_IMPLEMENTED;
1932     io->Information = 0;
1933
1934     switch( info_class )
1935     {
1936     case FileFsVolumeInformation:
1937         FIXME( "%p: volume info not supported\n", handle );
1938         break;
1939     case FileFsLabelInformation:
1940         FIXME( "%p: label info not supported\n", handle );
1941         break;
1942     case FileFsSizeInformation:
1943         if (length < sizeof(FILE_FS_SIZE_INFORMATION))
1944             io->u.Status = STATUS_BUFFER_TOO_SMALL;
1945         else
1946         {
1947             FILE_FS_SIZE_INFORMATION *info = buffer;
1948
1949             if (fstat( fd, &st ) < 0)
1950             {
1951                 io->u.Status = FILE_GetNtStatus();
1952                 break;
1953             }
1954             if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
1955             {
1956                 io->u.Status = STATUS_INVALID_DEVICE_REQUEST;
1957             }
1958             else
1959             {
1960                 /* Linux's fstatvfs is buggy */
1961 #if !defined(linux) || !defined(HAVE_FSTATFS)
1962                 struct statvfs stfs;
1963
1964                 if (fstatvfs( fd, &stfs ) < 0)
1965                 {
1966                     io->u.Status = FILE_GetNtStatus();
1967                     break;
1968                 }
1969                 info->BytesPerSector = stfs.f_frsize;
1970 #else
1971                 struct statfs stfs;
1972                 if (fstatfs( fd, &stfs ) < 0)
1973                 {
1974                     io->u.Status = FILE_GetNtStatus();
1975                     break;
1976                 }
1977                 info->BytesPerSector = stfs.f_bsize;
1978 #endif
1979                 info->TotalAllocationUnits.QuadPart = stfs.f_blocks;
1980                 info->AvailableAllocationUnits.QuadPart = stfs.f_bavail;
1981                 info->SectorsPerAllocationUnit = 1;
1982                 io->Information = sizeof(*info);
1983                 io->u.Status = STATUS_SUCCESS;
1984             }
1985         }
1986         break;
1987     case FileFsDeviceInformation:
1988         if (length < sizeof(FILE_FS_DEVICE_INFORMATION))
1989             io->u.Status = STATUS_BUFFER_TOO_SMALL;
1990         else
1991         {
1992             FILE_FS_DEVICE_INFORMATION *info = buffer;
1993
1994             if ((io->u.Status = get_device_info( fd, info )) == STATUS_SUCCESS)
1995                 io->Information = sizeof(*info);
1996         }
1997         break;
1998     case FileFsAttributeInformation:
1999         FIXME( "%p: attribute info not supported\n", handle );
2000         break;
2001     case FileFsControlInformation:
2002         FIXME( "%p: control info not supported\n", handle );
2003         break;
2004     case FileFsFullSizeInformation:
2005         FIXME( "%p: full size info not supported\n", handle );
2006         break;
2007     case FileFsObjectIdInformation:
2008         FIXME( "%p: object id info not supported\n", handle );
2009         break;
2010     case FileFsMaximumInformation:
2011         FIXME( "%p: maximum info not supported\n", handle );
2012         break;
2013     default:
2014         io->u.Status = STATUS_INVALID_PARAMETER;
2015         break;
2016     }
2017     if (needs_close) close( fd );
2018     return io->u.Status;
2019 }
2020
2021
2022 /******************************************************************
2023  *              NtFlushBuffersFile  (NTDLL.@)
2024  *
2025  * Flush any buffered data on an open file handle.
2026  *
2027  * PARAMS
2028  *  FileHandle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
2029  *  IoStatusBlock      [O] Receives information about the operation on return
2030  *
2031  * RETURNS
2032  *  Success: 0. IoStatusBlock is updated.
2033  *  Failure: An NTSTATUS error code describing the error.
2034  */
2035 NTSTATUS WINAPI NtFlushBuffersFile( HANDLE hFile, IO_STATUS_BLOCK* IoStatusBlock )
2036 {
2037     NTSTATUS ret;
2038     HANDLE hEvent = NULL;
2039
2040     SERVER_START_REQ( flush_file )
2041     {
2042         req->handle = hFile;
2043         ret = wine_server_call( req );
2044         hEvent = reply->event;
2045     }
2046     SERVER_END_REQ;
2047     if (!ret && hEvent)
2048     {
2049         ret = NtWaitForSingleObject( hEvent, FALSE, NULL );
2050         NtClose( hEvent );
2051     }
2052     return ret;
2053 }
2054
2055 /******************************************************************
2056  *              NtLockFile       (NTDLL.@)
2057  *
2058  *
2059  */
2060 NTSTATUS WINAPI NtLockFile( HANDLE hFile, HANDLE lock_granted_event,
2061                             PIO_APC_ROUTINE apc, void* apc_user,
2062                             PIO_STATUS_BLOCK io_status, PLARGE_INTEGER offset,
2063                             PLARGE_INTEGER count, ULONG* key, BOOLEAN dont_wait,
2064                             BOOLEAN exclusive )
2065 {
2066     NTSTATUS    ret;
2067     HANDLE      handle;
2068     BOOLEAN     async;
2069
2070     if (apc || io_status || key)
2071     {
2072         FIXME("Unimplemented yet parameter\n");
2073         return STATUS_NOT_IMPLEMENTED;
2074     }
2075
2076     for (;;)
2077     {
2078         SERVER_START_REQ( lock_file )
2079         {
2080             req->handle      = hFile;
2081             req->offset_low  = offset->u.LowPart;
2082             req->offset_high = offset->u.HighPart;
2083             req->count_low   = count->u.LowPart;
2084             req->count_high  = count->u.HighPart;
2085             req->shared      = !exclusive;
2086             req->wait        = !dont_wait;
2087             ret = wine_server_call( req );
2088             handle = reply->handle;
2089             async  = reply->overlapped;
2090         }
2091         SERVER_END_REQ;
2092         if (ret != STATUS_PENDING)
2093         {
2094             if (!ret && lock_granted_event) NtSetEvent(lock_granted_event, NULL);
2095             return ret;
2096         }
2097
2098         if (async)
2099         {
2100             FIXME( "Async I/O lock wait not implemented, might deadlock\n" );
2101             if (handle) NtClose( handle );
2102             return STATUS_PENDING;
2103         }
2104         if (handle)
2105         {
2106             NtWaitForSingleObject( handle, FALSE, NULL );
2107             NtClose( handle );
2108         }
2109         else
2110         {
2111             LARGE_INTEGER time;
2112     
2113             /* Unix lock conflict, sleep a bit and retry */
2114             time.QuadPart = 100 * (ULONGLONG)10000;
2115             time.QuadPart = -time.QuadPart;
2116             NtDelayExecution( FALSE, &time );
2117         }
2118     }
2119 }
2120
2121
2122 /******************************************************************
2123  *              NtUnlockFile    (NTDLL.@)
2124  *
2125  *
2126  */
2127 NTSTATUS WINAPI NtUnlockFile( HANDLE hFile, PIO_STATUS_BLOCK io_status,
2128                               PLARGE_INTEGER offset, PLARGE_INTEGER count,
2129                               PULONG key )
2130 {
2131     NTSTATUS status;
2132
2133     TRACE( "%p %x%08x %x%08x\n",
2134            hFile, offset->u.HighPart, offset->u.LowPart, count->u.HighPart, count->u.LowPart );
2135
2136     if (io_status || key)
2137     {
2138         FIXME("Unimplemented yet parameter\n");
2139         return STATUS_NOT_IMPLEMENTED;
2140     }
2141
2142     SERVER_START_REQ( unlock_file )
2143     {
2144         req->handle      = hFile;
2145         req->offset_low  = offset->u.LowPart;
2146         req->offset_high = offset->u.HighPart;
2147         req->count_low   = count->u.LowPart;
2148         req->count_high  = count->u.HighPart;
2149         status = wine_server_call( req );
2150     }
2151     SERVER_END_REQ;
2152     return status;
2153 }
2154
2155 /******************************************************************
2156  *              NtCreateNamedPipeFile    (NTDLL.@)
2157  *
2158  *
2159  */
2160 NTSTATUS WINAPI NtCreateNamedPipeFile( PHANDLE handle, ULONG access,
2161                                        POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK iosb,
2162                                        ULONG sharing, ULONG dispo, ULONG options,
2163                                        ULONG pipe_type, ULONG read_mode, 
2164                                        ULONG completion_mode, ULONG max_inst,
2165                                        ULONG inbound_quota, ULONG outbound_quota,
2166                                        PLARGE_INTEGER timeout)
2167 {
2168     NTSTATUS    status;
2169
2170     TRACE("(%p %x %s %p %x %d %x %d %d %d %d %d %d %p)\n",
2171           handle, access, debugstr_w(attr->ObjectName->Buffer), iosb, sharing, dispo,
2172           options, pipe_type, read_mode, completion_mode, max_inst, inbound_quota,
2173           outbound_quota, timeout);
2174
2175     /* assume we only get relative timeout */
2176     if (timeout->QuadPart > 0)
2177         FIXME("Wrong time %s\n", wine_dbgstr_longlong(timeout->QuadPart));
2178
2179     SERVER_START_REQ( create_named_pipe )
2180     {
2181         req->access  = access;
2182         req->attributes = attr->Attributes;
2183         req->rootdir = attr->RootDirectory;
2184         req->options = options;
2185         req->flags = 
2186             (pipe_type) ? NAMED_PIPE_MESSAGE_STREAM_WRITE : 0 |
2187             (read_mode) ? NAMED_PIPE_MESSAGE_STREAM_READ  : 0 |
2188             (completion_mode) ? NAMED_PIPE_NONBLOCKING_MODE  : 0;
2189         req->maxinstances = max_inst;
2190         req->outsize = outbound_quota;
2191         req->insize  = inbound_quota;
2192         req->timeout = timeout->QuadPart;
2193         wine_server_add_data( req, attr->ObjectName->Buffer,
2194                               attr->ObjectName->Length );
2195         status = wine_server_call( req );
2196         if (!status) *handle = reply->handle;
2197     }
2198     SERVER_END_REQ;
2199     return status;
2200 }
2201
2202 /******************************************************************
2203  *              NtDeleteFile    (NTDLL.@)
2204  *
2205  *
2206  */
2207 NTSTATUS WINAPI NtDeleteFile( POBJECT_ATTRIBUTES ObjectAttributes )
2208 {
2209     NTSTATUS status;
2210     HANDLE hFile;
2211     IO_STATUS_BLOCK io;
2212
2213     TRACE("%p\n", ObjectAttributes);
2214     status = NtCreateFile( &hFile, GENERIC_READ | GENERIC_WRITE | DELETE,
2215                            ObjectAttributes, &io, NULL, 0,
2216                            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 
2217                            FILE_OPEN, FILE_DELETE_ON_CLOSE, NULL, 0 );
2218     if (status == STATUS_SUCCESS) status = NtClose(hFile);
2219     return status;
2220 }
2221
2222 /******************************************************************
2223  *              NtCancelIoFile    (NTDLL.@)
2224  *
2225  *
2226  */
2227 NTSTATUS WINAPI NtCancelIoFile( HANDLE hFile, PIO_STATUS_BLOCK io_status )
2228 {
2229     LARGE_INTEGER timeout;
2230
2231     TRACE("%p %p\n", hFile, io_status );
2232
2233     SERVER_START_REQ( cancel_async )
2234     {
2235         req->handle = hFile;
2236         wine_server_call( req );
2237     }
2238     SERVER_END_REQ;
2239     /* Let some APC be run, so that we can run the remaining APCs on hFile
2240      * either the cancelation of the pending one, but also the execution
2241      * of the queued APC, but not yet run. This is needed to ensure proper
2242      * clean-up of allocated data.
2243      */
2244     timeout.u.LowPart = timeout.u.HighPart = 0;
2245     return io_status->u.Status = NtDelayExecution( TRUE, &timeout );
2246 }
2247
2248 /******************************************************************************
2249  *  NtCreateMailslotFile        [NTDLL.@]
2250  *  ZwCreateMailslotFile        [NTDLL.@]
2251  *
2252  * PARAMS
2253  *  pHandle          [O] pointer to receive the handle created
2254  *  DesiredAccess    [I] access mode (read, write, etc)
2255  *  ObjectAttributes [I] fully qualified NT path of the mailslot
2256  *  IoStatusBlock    [O] receives completion status and other info
2257  *  CreateOptions    [I]
2258  *  MailslotQuota    [I]
2259  *  MaxMessageSize   [I]
2260  *  TimeOut          [I]
2261  *
2262  * RETURNS
2263  *  An NT status code
2264  */
2265 NTSTATUS WINAPI NtCreateMailslotFile(PHANDLE pHandle, ULONG DesiredAccess,
2266      POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK IoStatusBlock,
2267      ULONG CreateOptions, ULONG MailslotQuota, ULONG MaxMessageSize,
2268      PLARGE_INTEGER TimeOut)
2269 {
2270     LARGE_INTEGER timeout;
2271     NTSTATUS ret;
2272
2273     TRACE("%p %08x %p %p %08x %08x %08x %p\n",
2274               pHandle, DesiredAccess, attr, IoStatusBlock,
2275               CreateOptions, MailslotQuota, MaxMessageSize, TimeOut);
2276
2277     if (!pHandle) return STATUS_ACCESS_VIOLATION;
2278     if (!attr) return STATUS_INVALID_PARAMETER;
2279     if (!attr->ObjectName) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2280
2281     /*
2282      *  For a NULL TimeOut pointer set the default timeout value
2283      */
2284     if  (!TimeOut)
2285         timeout.QuadPart = -1;
2286     else
2287         timeout.QuadPart = TimeOut->QuadPart;
2288
2289     SERVER_START_REQ( create_mailslot )
2290     {
2291         req->access = DesiredAccess;
2292         req->attributes = attr->Attributes;
2293         req->rootdir = attr->RootDirectory;
2294         req->max_msgsize = MaxMessageSize;
2295         req->read_timeout = timeout.QuadPart;
2296         wine_server_add_data( req, attr->ObjectName->Buffer,
2297                               attr->ObjectName->Length );
2298         ret = wine_server_call( req );
2299         if( ret == STATUS_SUCCESS )
2300             *pHandle = reply->handle;
2301     }
2302     SERVER_END_REQ;
2303  
2304     return ret;
2305 }