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