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