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