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