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