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