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