crypt32: Test CryptStringToBinary with weird Base64.
[wine.git] / dlls / ntdll / file.c
blobfd7f3dd955ae0654cb7e5dbfccb6f9b0f627c0f2
1 /*
2 * Copyright 1999, 2000 Juergen Schmied
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.
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.
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
19 #include "config.h"
20 #include "wine/port.h"
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_LINUX_MAJOR_H
31 # include <linux/major.h>
32 #endif
33 #ifdef HAVE_SYS_STATVFS_H
34 # include <sys/statvfs.h>
35 #endif
36 #ifdef HAVE_SYS_PARAM_H
37 # include <sys/param.h>
38 #endif
39 #ifdef HAVE_SYS_SYSCALL_H
40 # include <sys/syscall.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_SYS_FILIO_H
49 # include <sys/filio.h>
50 #endif
51 #ifdef HAVE_POLL_H
52 #include <poll.h>
53 #endif
54 #ifdef HAVE_SYS_POLL_H
55 #include <sys/poll.h>
56 #endif
57 #ifdef HAVE_SYS_SOCKET_H
58 #include <sys/socket.h>
59 #endif
60 #ifdef MAJOR_IN_MKDEV
61 # include <sys/mkdev.h>
62 #elif defined(MAJOR_IN_SYSMACROS)
63 # include <sys/sysmacros.h>
64 #endif
65 #ifdef HAVE_UTIME_H
66 # include <utime.h>
67 #endif
68 #ifdef HAVE_SYS_VFS_H
69 /* Work around a conflict with Solaris' system list defined in sys/list.h. */
70 #define list SYSLIST
71 #define list_next SYSLIST_NEXT
72 #define list_prev SYSLIST_PREV
73 #define list_head SYSLIST_HEAD
74 #define list_tail SYSLIST_TAIL
75 #define list_move_tail SYSLIST_MOVE_TAIL
76 #define list_remove SYSLIST_REMOVE
77 # include <sys/vfs.h>
78 #undef list
79 #undef list_next
80 #undef list_prev
81 #undef list_head
82 #undef list_tail
83 #undef list_move_tail
84 #undef list_remove
85 #endif
86 #ifdef HAVE_SYS_MOUNT_H
87 # include <sys/mount.h>
88 #endif
89 #ifdef HAVE_SYS_STATFS_H
90 # include <sys/statfs.h>
91 #endif
92 #ifdef HAVE_TERMIOS_H
93 #include <termios.h>
94 #endif
95 #ifdef HAVE_VALGRIND_MEMCHECK_H
96 # include <valgrind/memcheck.h>
97 #endif
99 #include "ntstatus.h"
100 #define WIN32_NO_STATUS
101 #define NONAMELESSUNION
102 #include "wine/unicode.h"
103 #include "wine/debug.h"
104 #include "wine/server.h"
105 #include "ntdll_misc.h"
107 #include "winternl.h"
108 #include "winioctl.h"
109 #include "ddk/ntddk.h"
110 #include "ddk/ntddser.h"
112 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
113 WINE_DECLARE_DEBUG_CHANNEL(winediag);
115 mode_t FILE_umask = 0;
117 #define SECSPERDAY 86400
118 #define SECS_1601_TO_1970 ((369 * 365 + 89) * (ULONGLONG)SECSPERDAY)
120 #define FILE_WRITE_TO_END_OF_FILE ((LONGLONG)-1)
121 #define FILE_USE_FILE_POINTER_POSITION ((LONGLONG)-2)
123 static const WCHAR ntfsW[] = {'N','T','F','S'};
125 /* fetch the attributes of a file */
126 static inline ULONG get_file_attributes( const struct stat *st )
128 ULONG attr;
130 if (S_ISDIR(st->st_mode))
131 attr = FILE_ATTRIBUTE_DIRECTORY;
132 else
133 attr = FILE_ATTRIBUTE_ARCHIVE;
134 if (!(st->st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
135 attr |= FILE_ATTRIBUTE_READONLY;
136 return attr;
139 /* get the stat info and file attributes for a file (by file descriptor) */
140 int fd_get_file_info( int fd, struct stat *st, ULONG *attr )
142 int ret;
144 *attr = 0;
145 ret = fstat( fd, st );
146 if (ret == -1) return ret;
147 *attr |= get_file_attributes( st );
148 return ret;
151 /* get the stat info and file attributes for a file (by name) */
152 int get_file_info( const char *path, struct stat *st, ULONG *attr )
154 int ret;
156 *attr = 0;
157 ret = lstat( path, st );
158 if (ret == -1) return ret;
159 if (S_ISLNK( st->st_mode ))
161 ret = stat( path, st );
162 if (ret == -1) return ret;
163 /* is a symbolic link and a directory, consider these "reparse points" */
164 if (S_ISDIR( st->st_mode )) *attr |= FILE_ATTRIBUTE_REPARSE_POINT;
166 *attr |= get_file_attributes( st );
167 return ret;
170 /**************************************************************************
171 * FILE_CreateFile (internal)
172 * Open a file.
174 * Parameter set fully identical with NtCreateFile
176 static NTSTATUS FILE_CreateFile( PHANDLE handle, ACCESS_MASK access, POBJECT_ATTRIBUTES attr,
177 PIO_STATUS_BLOCK io, PLARGE_INTEGER alloc_size,
178 ULONG attributes, ULONG sharing, ULONG disposition,
179 ULONG options, PVOID ea_buffer, ULONG ea_length )
181 ANSI_STRING unix_name;
182 BOOL created = FALSE;
184 TRACE("handle=%p access=%08x name=%s objattr=%08x root=%p sec=%p io=%p alloc_size=%p "
185 "attr=%08x sharing=%08x disp=%d options=%08x ea=%p.0x%08x\n",
186 handle, access, debugstr_us(attr->ObjectName), attr->Attributes,
187 attr->RootDirectory, attr->SecurityDescriptor, io, alloc_size,
188 attributes, sharing, disposition, options, ea_buffer, ea_length );
190 if (!attr || !attr->ObjectName) return STATUS_INVALID_PARAMETER;
192 if (alloc_size) FIXME( "alloc_size not supported\n" );
194 if (options & FILE_OPEN_BY_FILE_ID)
195 io->u.Status = file_id_to_unix_file_name( attr, &unix_name );
196 else
197 io->u.Status = nt_to_unix_file_name_attr( attr, &unix_name, disposition );
199 if (io->u.Status == STATUS_BAD_DEVICE_TYPE)
201 SERVER_START_REQ( open_file_object )
203 req->access = access;
204 req->attributes = attr->Attributes;
205 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
206 req->sharing = sharing;
207 req->options = options;
208 wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
209 io->u.Status = wine_server_call( req );
210 *handle = wine_server_ptr_handle( reply->handle );
212 SERVER_END_REQ;
213 if (io->u.Status == STATUS_SUCCESS) io->Information = FILE_OPENED;
214 return io->u.Status;
217 if (io->u.Status == STATUS_NO_SUCH_FILE &&
218 disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
220 created = TRUE;
221 io->u.Status = STATUS_SUCCESS;
224 if (io->u.Status == STATUS_SUCCESS)
226 static UNICODE_STRING empty_string;
227 OBJECT_ATTRIBUTES unix_attr = *attr;
228 data_size_t len;
229 struct object_attributes *objattr;
231 unix_attr.ObjectName = &empty_string; /* we send the unix name instead */
232 if ((io->u.Status = alloc_object_attributes( &unix_attr, &objattr, &len )))
234 RtlFreeAnsiString( &unix_name );
235 return io->u.Status;
238 SERVER_START_REQ( create_file )
240 req->access = access;
241 req->sharing = sharing;
242 req->create = disposition;
243 req->options = options;
244 req->attrs = attributes;
245 wine_server_add_data( req, objattr, len );
246 wine_server_add_data( req, unix_name.Buffer, unix_name.Length );
247 io->u.Status = wine_server_call( req );
248 *handle = wine_server_ptr_handle( reply->handle );
250 SERVER_END_REQ;
251 RtlFreeHeap( GetProcessHeap(), 0, objattr );
252 RtlFreeAnsiString( &unix_name );
254 else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), io->u.Status );
256 if (io->u.Status == STATUS_SUCCESS)
258 if (created) io->Information = FILE_CREATED;
259 else switch(disposition)
261 case FILE_SUPERSEDE:
262 io->Information = FILE_SUPERSEDED;
263 break;
264 case FILE_CREATE:
265 io->Information = FILE_CREATED;
266 break;
267 case FILE_OPEN:
268 case FILE_OPEN_IF:
269 io->Information = FILE_OPENED;
270 break;
271 case FILE_OVERWRITE:
272 case FILE_OVERWRITE_IF:
273 io->Information = FILE_OVERWRITTEN;
274 break;
277 else if (io->u.Status == STATUS_TOO_MANY_OPENED_FILES)
279 static int once;
280 if (!once++) ERR_(winediag)( "Too many open files, ulimit -n probably needs to be increased\n" );
283 return io->u.Status;
286 /**************************************************************************
287 * NtOpenFile [NTDLL.@]
288 * ZwOpenFile [NTDLL.@]
290 * Open a file.
292 * PARAMS
293 * handle [O] Variable that receives the file handle on return
294 * access [I] Access desired by the caller to the file
295 * attr [I] Structure describing the file to be opened
296 * io [O] Receives details about the result of the operation
297 * sharing [I] Type of shared access the caller requires
298 * options [I] Options for the file open
300 * RETURNS
301 * Success: 0. FileHandle and IoStatusBlock are updated.
302 * Failure: An NTSTATUS error code describing the error.
304 NTSTATUS WINAPI NtOpenFile( PHANDLE handle, ACCESS_MASK access,
305 POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK io,
306 ULONG sharing, ULONG options )
308 return FILE_CreateFile( handle, access, attr, io, NULL, 0,
309 sharing, FILE_OPEN, options, NULL, 0 );
312 /**************************************************************************
313 * NtCreateFile [NTDLL.@]
314 * ZwCreateFile [NTDLL.@]
316 * Either create a new file or directory, or open an existing file, device,
317 * directory or volume.
319 * PARAMS
320 * handle [O] Points to a variable which receives the file handle on return
321 * access [I] Desired access to the file
322 * attr [I] Structure describing the file
323 * io [O] Receives information about the operation on return
324 * alloc_size [I] Initial size of the file in bytes
325 * attributes [I] Attributes to create the file with
326 * sharing [I] Type of shared access the caller would like to the file
327 * disposition [I] Specifies what to do, depending on whether the file already exists
328 * options [I] Options for creating a new file
329 * ea_buffer [I] Pointer to an extended attributes buffer
330 * ea_length [I] Length of ea_buffer
332 * RETURNS
333 * Success: 0. handle and io are updated.
334 * Failure: An NTSTATUS error code describing the error.
336 NTSTATUS WINAPI NtCreateFile( PHANDLE handle, ACCESS_MASK access, POBJECT_ATTRIBUTES attr,
337 PIO_STATUS_BLOCK io, PLARGE_INTEGER alloc_size,
338 ULONG attributes, ULONG sharing, ULONG disposition,
339 ULONG options, PVOID ea_buffer, ULONG ea_length )
341 return FILE_CreateFile( handle, access, attr, io, alloc_size, attributes,
342 sharing, disposition, options, ea_buffer, ea_length );
345 /***********************************************************************
346 * Asynchronous file I/O *
349 struct async_fileio
351 struct async_fileio *next;
352 HANDLE handle;
353 PIO_APC_ROUTINE apc;
354 void *apc_arg;
357 struct async_fileio_read
359 struct async_fileio io;
360 char* buffer;
361 unsigned int already;
362 unsigned int count;
363 BOOL avail_mode;
366 struct async_fileio_write
368 struct async_fileio io;
369 const char *buffer;
370 unsigned int already;
371 unsigned int count;
374 struct async_irp
376 struct async_fileio io;
377 HANDLE event; /* async event */
378 void *buffer; /* buffer for output */
379 ULONG size; /* size of buffer */
382 static struct async_fileio *fileio_freelist;
384 static void release_fileio( struct async_fileio *io )
386 for (;;)
388 struct async_fileio *next = fileio_freelist;
389 io->next = next;
390 if (interlocked_cmpxchg_ptr( (void **)&fileio_freelist, io, next ) == next) return;
394 static struct async_fileio *alloc_fileio( DWORD size, HANDLE handle, PIO_APC_ROUTINE apc, void *arg )
396 /* first free remaining previous fileinfos */
398 struct async_fileio *io = interlocked_xchg_ptr( (void **)&fileio_freelist, NULL );
400 while (io)
402 struct async_fileio *next = io->next;
403 RtlFreeHeap( GetProcessHeap(), 0, io );
404 io = next;
407 if ((io = RtlAllocateHeap( GetProcessHeap(), 0, size )))
409 io->handle = handle;
410 io->apc = apc;
411 io->apc_arg = arg;
413 return io;
416 /* callback for irp async I/O completion */
417 static NTSTATUS irp_completion( void *user, IO_STATUS_BLOCK *io, NTSTATUS status, void **apc, void **arg )
419 struct async_irp *async = user;
420 ULONG information = 0;
422 if (status == STATUS_ALERTED)
424 SERVER_START_REQ( get_async_result )
426 req->user_arg = wine_server_client_ptr( async );
427 wine_server_set_reply( req, async->buffer, async->size );
428 status = wine_server_call( req );
429 information = reply->size;
431 SERVER_END_REQ;
433 if (status != STATUS_PENDING)
435 io->u.Status = status;
436 io->Information = information;
437 *apc = async->io.apc;
438 *arg = async->io.apc_arg;
439 release_fileio( &async->io );
441 return status;
444 /***********************************************************************
445 * FILE_GetNtStatus(void)
447 * Retrieve the Nt Status code from errno.
448 * Try to be consistent with FILE_SetDosError().
450 NTSTATUS FILE_GetNtStatus(void)
452 int err = errno;
454 TRACE( "errno = %d\n", errno );
455 switch (err)
457 case EAGAIN: return STATUS_SHARING_VIOLATION;
458 case EBADF: return STATUS_INVALID_HANDLE;
459 case EBUSY: return STATUS_DEVICE_BUSY;
460 case ENOSPC: return STATUS_DISK_FULL;
461 case EPERM:
462 case EROFS:
463 case EACCES: return STATUS_ACCESS_DENIED;
464 case ENOTDIR: return STATUS_OBJECT_PATH_NOT_FOUND;
465 case ENOENT: return STATUS_OBJECT_NAME_NOT_FOUND;
466 case EISDIR: return STATUS_FILE_IS_A_DIRECTORY;
467 case EMFILE:
468 case ENFILE: return STATUS_TOO_MANY_OPENED_FILES;
469 case EINVAL: return STATUS_INVALID_PARAMETER;
470 case ENOTEMPTY: return STATUS_DIRECTORY_NOT_EMPTY;
471 case EPIPE: return STATUS_PIPE_DISCONNECTED;
472 case EIO: return STATUS_DEVICE_NOT_READY;
473 #ifdef ENOMEDIUM
474 case ENOMEDIUM: return STATUS_NO_MEDIA_IN_DEVICE;
475 #endif
476 case ENXIO: return STATUS_NO_SUCH_DEVICE;
477 case ENOTTY:
478 case EOPNOTSUPP:return STATUS_NOT_SUPPORTED;
479 case ECONNRESET:return STATUS_PIPE_DISCONNECTED;
480 case EFAULT: return STATUS_ACCESS_VIOLATION;
481 case ESPIPE: return STATUS_ILLEGAL_FUNCTION;
482 #ifdef ETIME /* Missing on FreeBSD */
483 case ETIME: return STATUS_IO_TIMEOUT;
484 #endif
485 case ENOEXEC: /* ?? */
486 case EEXIST: /* ?? */
487 default:
488 FIXME( "Converting errno %d to STATUS_UNSUCCESSFUL\n", err );
489 return STATUS_UNSUCCESSFUL;
493 /***********************************************************************
494 * FILE_AsyncReadService (INTERNAL)
496 static NTSTATUS FILE_AsyncReadService( void *user, IO_STATUS_BLOCK *iosb,
497 NTSTATUS status, void **apc, void **arg )
499 struct async_fileio_read *fileio = user;
500 int fd, needs_close, result;
502 switch (status)
504 case STATUS_ALERTED: /* got some new data */
505 /* check to see if the data is ready (non-blocking) */
506 if ((status = server_get_unix_fd( fileio->io.handle, FILE_READ_DATA, &fd,
507 &needs_close, NULL, NULL )))
508 break;
510 result = read(fd, &fileio->buffer[fileio->already], fileio->count - fileio->already);
511 if (needs_close) close( fd );
513 if (result < 0)
515 if (errno == EAGAIN || errno == EINTR)
516 status = STATUS_PENDING;
517 else /* check to see if the transfer is complete */
518 status = FILE_GetNtStatus();
520 else if (result == 0)
522 status = fileio->already ? STATUS_SUCCESS : STATUS_PIPE_BROKEN;
524 else
526 fileio->already += result;
527 if (fileio->already >= fileio->count || fileio->avail_mode)
528 status = STATUS_SUCCESS;
529 else
530 status = STATUS_PENDING;
532 break;
534 case STATUS_TIMEOUT:
535 case STATUS_IO_TIMEOUT:
536 if (fileio->already) status = STATUS_SUCCESS;
537 break;
539 if (status != STATUS_PENDING)
541 iosb->u.Status = status;
542 iosb->Information = fileio->already;
543 *apc = fileio->io.apc;
544 *arg = fileio->io.apc_arg;
545 release_fileio( &fileio->io );
547 return status;
550 /* do a read call through the server */
551 static NTSTATUS server_read_file( HANDLE handle, HANDLE event, PIO_APC_ROUTINE apc, void *apc_context,
552 IO_STATUS_BLOCK *io, void *buffer, ULONG size,
553 LARGE_INTEGER *offset, ULONG *key )
555 struct async_irp *async;
556 NTSTATUS status;
557 HANDLE wait_handle;
558 ULONG options;
559 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;
561 if (!(async = (struct async_irp *)alloc_fileio( sizeof(*async), handle, apc, apc_context )))
562 return STATUS_NO_MEMORY;
564 async->event = event;
565 async->buffer = buffer;
566 async->size = size;
568 SERVER_START_REQ( read )
570 req->blocking = !apc && !event && !cvalue;
571 req->async.handle = wine_server_obj_handle( handle );
572 req->async.callback = wine_server_client_ptr( irp_completion );
573 req->async.iosb = wine_server_client_ptr( io );
574 req->async.arg = wine_server_client_ptr( async );
575 req->async.event = wine_server_obj_handle( event );
576 req->async.cvalue = cvalue;
577 req->pos = offset ? offset->QuadPart : 0;
578 wine_server_set_reply( req, buffer, size );
579 status = wine_server_call( req );
580 wait_handle = wine_server_ptr_handle( reply->wait );
581 options = reply->options;
583 SERVER_END_REQ;
585 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, async );
587 if (wait_handle)
589 NtWaitForSingleObject( wait_handle, (options & FILE_SYNCHRONOUS_IO_ALERT), NULL );
590 status = io->u.Status;
591 NtClose( wait_handle );
594 return status;
597 /* do a write call through the server */
598 static NTSTATUS server_write_file( HANDLE handle, HANDLE event, PIO_APC_ROUTINE apc, void *apc_context,
599 IO_STATUS_BLOCK *io, const void *buffer, ULONG size,
600 LARGE_INTEGER *offset, ULONG *key )
602 struct async_irp *async;
603 NTSTATUS status;
604 HANDLE wait_handle;
605 ULONG options;
606 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;
608 if (!(async = (struct async_irp *)alloc_fileio( sizeof(*async), handle, apc, apc_context )))
609 return STATUS_NO_MEMORY;
611 async->event = event;
612 async->buffer = NULL;
613 async->size = 0;
615 SERVER_START_REQ( write )
617 req->blocking = !apc && !event && !cvalue;
618 req->async.handle = wine_server_obj_handle( handle );
619 req->async.callback = wine_server_client_ptr( irp_completion );
620 req->async.iosb = wine_server_client_ptr( io );
621 req->async.arg = wine_server_client_ptr( async );
622 req->async.event = wine_server_obj_handle( event );
623 req->async.cvalue = cvalue;
624 req->pos = offset ? offset->QuadPart : 0;
625 wine_server_add_data( req, buffer, size );
626 status = wine_server_call( req );
627 wait_handle = wine_server_ptr_handle( reply->wait );
628 options = reply->options;
630 SERVER_END_REQ;
632 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, async );
634 if (wait_handle)
636 NtWaitForSingleObject( wait_handle, (options & FILE_SYNCHRONOUS_IO_ALERT), NULL );
637 status = io->u.Status;
638 NtClose( wait_handle );
641 return status;
644 struct io_timeouts
646 int interval; /* max interval between two bytes */
647 int total; /* total timeout for the whole operation */
648 int end_time; /* absolute time of end of operation */
651 /* retrieve the I/O timeouts to use for a given handle */
652 static NTSTATUS get_io_timeouts( HANDLE handle, enum server_fd_type type, ULONG count, BOOL is_read,
653 struct io_timeouts *timeouts )
655 NTSTATUS status = STATUS_SUCCESS;
657 timeouts->interval = timeouts->total = -1;
659 switch(type)
661 case FD_TYPE_SERIAL:
663 /* GetCommTimeouts */
664 SERIAL_TIMEOUTS st;
665 IO_STATUS_BLOCK io;
667 status = NtDeviceIoControlFile( handle, NULL, NULL, NULL, &io,
668 IOCTL_SERIAL_GET_TIMEOUTS, NULL, 0, &st, sizeof(st) );
669 if (status) break;
671 if (is_read)
673 if (st.ReadIntervalTimeout)
674 timeouts->interval = st.ReadIntervalTimeout;
676 if (st.ReadTotalTimeoutMultiplier || st.ReadTotalTimeoutConstant)
678 timeouts->total = st.ReadTotalTimeoutConstant;
679 if (st.ReadTotalTimeoutMultiplier != MAXDWORD)
680 timeouts->total += count * st.ReadTotalTimeoutMultiplier;
682 else if (st.ReadIntervalTimeout == MAXDWORD)
683 timeouts->interval = timeouts->total = 0;
685 else /* write */
687 if (st.WriteTotalTimeoutMultiplier || st.WriteTotalTimeoutConstant)
689 timeouts->total = st.WriteTotalTimeoutConstant;
690 if (st.WriteTotalTimeoutMultiplier != MAXDWORD)
691 timeouts->total += count * st.WriteTotalTimeoutMultiplier;
695 break;
696 case FD_TYPE_MAILSLOT:
697 if (is_read)
699 timeouts->interval = 0; /* return as soon as we got something */
700 SERVER_START_REQ( set_mailslot_info )
702 req->handle = wine_server_obj_handle( handle );
703 req->flags = 0;
704 if (!(status = wine_server_call( req )) &&
705 reply->read_timeout != TIMEOUT_INFINITE)
706 timeouts->total = reply->read_timeout / -10000;
708 SERVER_END_REQ;
710 break;
711 case FD_TYPE_SOCKET:
712 case FD_TYPE_PIPE:
713 case FD_TYPE_CHAR:
714 if (is_read) timeouts->interval = 0; /* return as soon as we got something */
715 break;
716 default:
717 break;
719 if (timeouts->total != -1) timeouts->end_time = NtGetTickCount() + timeouts->total;
720 return STATUS_SUCCESS;
724 /* retrieve the timeout for the next wait, in milliseconds */
725 static inline int get_next_io_timeout( const struct io_timeouts *timeouts, ULONG already )
727 int ret = -1;
729 if (timeouts->total != -1)
731 ret = timeouts->end_time - NtGetTickCount();
732 if (ret < 0) ret = 0;
734 if (already && timeouts->interval != -1)
736 if (ret == -1 || ret > timeouts->interval) ret = timeouts->interval;
738 return ret;
742 /* retrieve the avail_mode flag for async reads */
743 static NTSTATUS get_io_avail_mode( HANDLE handle, enum server_fd_type type, BOOL *avail_mode )
745 NTSTATUS status = STATUS_SUCCESS;
747 switch(type)
749 case FD_TYPE_SERIAL:
751 /* GetCommTimeouts */
752 SERIAL_TIMEOUTS st;
753 IO_STATUS_BLOCK io;
755 status = NtDeviceIoControlFile( handle, NULL, NULL, NULL, &io,
756 IOCTL_SERIAL_GET_TIMEOUTS, NULL, 0, &st, sizeof(st) );
757 if (status) break;
758 *avail_mode = (!st.ReadTotalTimeoutMultiplier &&
759 !st.ReadTotalTimeoutConstant &&
760 st.ReadIntervalTimeout == MAXDWORD);
762 break;
763 case FD_TYPE_MAILSLOT:
764 case FD_TYPE_SOCKET:
765 case FD_TYPE_PIPE:
766 case FD_TYPE_CHAR:
767 *avail_mode = TRUE;
768 break;
769 default:
770 *avail_mode = FALSE;
771 break;
773 return status;
776 /* register an async I/O for a file read; helper for NtReadFile */
777 static NTSTATUS register_async_file_read( HANDLE handle, HANDLE event,
778 PIO_APC_ROUTINE apc, void *apc_user,
779 IO_STATUS_BLOCK *iosb, void *buffer,
780 ULONG already, ULONG length, BOOL avail_mode )
782 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
783 struct async_fileio_read *fileio;
784 NTSTATUS status;
786 if (!(fileio = (struct async_fileio_read *)alloc_fileio( sizeof(*fileio), handle, apc, apc_user )))
787 return STATUS_NO_MEMORY;
789 fileio->already = already;
790 fileio->count = length;
791 fileio->buffer = buffer;
792 fileio->avail_mode = avail_mode;
794 SERVER_START_REQ( register_async )
796 req->type = ASYNC_TYPE_READ;
797 req->count = length;
798 req->async.handle = wine_server_obj_handle( handle );
799 req->async.event = wine_server_obj_handle( event );
800 req->async.callback = wine_server_client_ptr( FILE_AsyncReadService );
801 req->async.iosb = wine_server_client_ptr( iosb );
802 req->async.arg = wine_server_client_ptr( fileio );
803 req->async.cvalue = cvalue;
804 status = wine_server_call( req );
806 SERVER_END_REQ;
808 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
809 return status;
813 /******************************************************************************
814 * NtReadFile [NTDLL.@]
815 * ZwReadFile [NTDLL.@]
817 * Read from an open file handle.
819 * PARAMS
820 * FileHandle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
821 * Event [I] Event to signal upon completion (or NULL)
822 * ApcRoutine [I] Callback to call upon completion (or NULL)
823 * ApcContext [I] Context for ApcRoutine (or NULL)
824 * IoStatusBlock [O] Receives information about the operation on return
825 * Buffer [O] Destination for the data read
826 * Length [I] Size of Buffer
827 * ByteOffset [O] Destination for the new file pointer position (or NULL)
828 * Key [O] Function unknown (may be NULL)
830 * RETURNS
831 * Success: 0. IoStatusBlock is updated, and the Information member contains
832 * The number of bytes read.
833 * Failure: An NTSTATUS error code describing the error.
835 NTSTATUS WINAPI NtReadFile(HANDLE hFile, HANDLE hEvent,
836 PIO_APC_ROUTINE apc, void* apc_user,
837 PIO_STATUS_BLOCK io_status, void* buffer, ULONG length,
838 PLARGE_INTEGER offset, PULONG key)
840 int result, unix_handle, needs_close;
841 unsigned int options;
842 struct io_timeouts timeouts;
843 NTSTATUS status;
844 ULONG total = 0;
845 enum server_fd_type type;
846 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
847 BOOL send_completion = FALSE, async_read, timeout_init_done = FALSE;
849 TRACE("(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
850 hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);
852 if (!io_status) return STATUS_ACCESS_VIOLATION;
854 status = server_get_unix_fd( hFile, FILE_READ_DATA, &unix_handle,
855 &needs_close, &type, &options );
856 if (status && status != STATUS_BAD_DEVICE_TYPE) return status;
858 if (!virtual_check_buffer_for_write( buffer, length )) return STATUS_ACCESS_VIOLATION;
860 if (status == STATUS_BAD_DEVICE_TYPE)
861 return server_read_file( hFile, hEvent, apc, apc_user, io_status, buffer, length, offset, key );
863 async_read = !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
865 if (type == FD_TYPE_FILE)
867 if (async_read && (!offset || offset->QuadPart < 0))
869 status = STATUS_INVALID_PARAMETER;
870 goto done;
873 if (offset && offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
875 /* async I/O doesn't make sense on regular files */
876 while ((result = pread( unix_handle, buffer, length, offset->QuadPart )) == -1)
878 if (errno != EINTR)
880 status = FILE_GetNtStatus();
881 goto done;
884 if (!async_read)
885 /* update file pointer position */
886 lseek( unix_handle, offset->QuadPart + result, SEEK_SET );
888 total = result;
889 status = (total || !length) ? STATUS_SUCCESS : STATUS_END_OF_FILE;
890 goto done;
893 else if (type == FD_TYPE_SERIAL || type == FD_TYPE_DEVICE)
895 if (async_read && (!offset || offset->QuadPart < 0))
897 status = STATUS_INVALID_PARAMETER;
898 goto done;
902 if (type == FD_TYPE_SERIAL && async_read && length)
904 /* an asynchronous serial port read with a read interval timeout needs to
905 skip the synchronous read to make sure that the server starts the read
906 interval timer after the first read */
907 if ((status = get_io_timeouts( hFile, type, length, TRUE, &timeouts ))) goto err;
908 if (timeouts.interval)
910 status = register_async_file_read( hFile, hEvent, apc, apc_user, io_status,
911 buffer, total, length, FALSE );
912 goto err;
916 for (;;)
918 if ((result = read( unix_handle, (char *)buffer + total, length - total )) >= 0)
920 total += result;
921 if (!result || total == length)
923 if (total)
925 status = STATUS_SUCCESS;
926 goto done;
928 switch (type)
930 case FD_TYPE_FILE:
931 case FD_TYPE_CHAR:
932 case FD_TYPE_DEVICE:
933 status = length ? STATUS_END_OF_FILE : STATUS_SUCCESS;
934 goto done;
935 case FD_TYPE_SERIAL:
936 if (!length)
938 status = STATUS_SUCCESS;
939 goto done;
941 break;
942 default:
943 status = STATUS_PIPE_BROKEN;
944 goto done;
947 else if (type == FD_TYPE_FILE) continue; /* no async I/O on regular files */
949 else if (errno != EAGAIN)
951 if (errno == EINTR) continue;
952 if (!total) status = FILE_GetNtStatus();
953 goto done;
956 if (async_read)
958 BOOL avail_mode;
960 if ((status = get_io_avail_mode( hFile, type, &avail_mode )))
961 goto err;
962 if (total && avail_mode)
964 status = STATUS_SUCCESS;
965 goto done;
967 status = register_async_file_read( hFile, hEvent, apc, apc_user, io_status,
968 buffer, total, length, avail_mode );
969 goto err;
971 else /* synchronous read, wait for the fd to become ready */
973 struct pollfd pfd;
974 int ret, timeout;
976 if (!timeout_init_done)
978 timeout_init_done = TRUE;
979 if ((status = get_io_timeouts( hFile, type, length, TRUE, &timeouts )))
980 goto err;
981 if (hEvent) NtResetEvent( hEvent, NULL );
983 timeout = get_next_io_timeout( &timeouts, total );
985 pfd.fd = unix_handle;
986 pfd.events = POLLIN;
988 if (!timeout || !(ret = poll( &pfd, 1, timeout )))
990 if (total) /* return with what we got so far */
991 status = STATUS_SUCCESS;
992 else
993 status = (type == FD_TYPE_MAILSLOT) ? STATUS_IO_TIMEOUT : STATUS_TIMEOUT;
994 goto done;
996 if (ret == -1 && errno != EINTR)
998 status = FILE_GetNtStatus();
999 goto done;
1001 /* will now restart the read */
1005 done:
1006 send_completion = cvalue != 0;
1008 err:
1009 if (needs_close) close( unix_handle );
1010 if (status == STATUS_SUCCESS || (status == STATUS_END_OF_FILE && !async_read))
1012 io_status->u.Status = status;
1013 io_status->Information = total;
1014 TRACE("= SUCCESS (%u)\n", total);
1015 if (hEvent) NtSetEvent( hEvent, NULL );
1016 if (apc && !status) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
1017 (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
1019 else
1021 TRACE("= 0x%08x\n", status);
1022 if (status != STATUS_PENDING && hEvent) NtResetEvent( hEvent, NULL );
1025 if (send_completion) NTDLL_AddCompletion( hFile, cvalue, status, total );
1027 return status;
1031 /******************************************************************************
1032 * NtReadFileScatter [NTDLL.@]
1033 * ZwReadFileScatter [NTDLL.@]
1035 NTSTATUS WINAPI NtReadFileScatter( HANDLE file, HANDLE event, PIO_APC_ROUTINE apc, void *apc_user,
1036 PIO_STATUS_BLOCK io_status, FILE_SEGMENT_ELEMENT *segments,
1037 ULONG length, PLARGE_INTEGER offset, PULONG key )
1039 int result, unix_handle, needs_close;
1040 unsigned int options;
1041 NTSTATUS status;
1042 ULONG pos = 0, total = 0;
1043 enum server_fd_type type;
1044 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
1045 BOOL send_completion = FALSE;
1047 TRACE( "(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
1048 file, event, apc, apc_user, io_status, segments, length, offset, key);
1050 if (length % page_size) return STATUS_INVALID_PARAMETER;
1051 if (!io_status) return STATUS_ACCESS_VIOLATION;
1053 status = server_get_unix_fd( file, FILE_READ_DATA, &unix_handle,
1054 &needs_close, &type, &options );
1055 if (status) return status;
1057 if ((type != FD_TYPE_FILE) ||
1058 (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) ||
1059 !(options & FILE_NO_INTERMEDIATE_BUFFERING))
1061 status = STATUS_INVALID_PARAMETER;
1062 goto error;
1065 while (length)
1067 if (offset && offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
1068 result = pread( unix_handle, (char *)segments->Buffer + pos,
1069 page_size - pos, offset->QuadPart + total );
1070 else
1071 result = read( unix_handle, (char *)segments->Buffer + pos, page_size - pos );
1073 if (result == -1)
1075 if (errno == EINTR) continue;
1076 status = FILE_GetNtStatus();
1077 break;
1079 if (!result)
1081 status = STATUS_END_OF_FILE;
1082 break;
1084 total += result;
1085 length -= result;
1086 if ((pos += result) == page_size)
1088 pos = 0;
1089 segments++;
1093 send_completion = cvalue != 0;
1095 error:
1096 if (needs_close) close( unix_handle );
1097 if (status == STATUS_SUCCESS)
1099 io_status->u.Status = status;
1100 io_status->Information = total;
1101 TRACE("= SUCCESS (%u)\n", total);
1102 if (event) NtSetEvent( event, NULL );
1103 if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
1104 (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
1106 else
1108 TRACE("= 0x%08x\n", status);
1109 if (status != STATUS_PENDING && event) NtResetEvent( event, NULL );
1112 if (send_completion) NTDLL_AddCompletion( file, cvalue, status, total );
1114 return status;
1118 /***********************************************************************
1119 * FILE_AsyncWriteService (INTERNAL)
1121 static NTSTATUS FILE_AsyncWriteService( void *user, IO_STATUS_BLOCK *iosb,
1122 NTSTATUS status, void **apc, void **arg )
1124 struct async_fileio_write *fileio = user;
1125 int result, fd, needs_close;
1126 enum server_fd_type type;
1128 switch (status)
1130 case STATUS_ALERTED:
1131 /* write some data (non-blocking) */
1132 if ((status = server_get_unix_fd( fileio->io.handle, FILE_WRITE_DATA, &fd,
1133 &needs_close, &type, NULL )))
1134 break;
1136 if (!fileio->count && (type == FD_TYPE_MAILSLOT || type == FD_TYPE_PIPE || type == FD_TYPE_SOCKET))
1137 result = send( fd, fileio->buffer, 0, 0 );
1138 else
1139 result = write( fd, &fileio->buffer[fileio->already], fileio->count - fileio->already );
1141 if (needs_close) close( fd );
1143 if (result < 0)
1145 if (errno == EAGAIN || errno == EINTR) status = STATUS_PENDING;
1146 else status = FILE_GetNtStatus();
1148 else
1150 fileio->already += result;
1151 status = (fileio->already < fileio->count) ? STATUS_PENDING : STATUS_SUCCESS;
1153 break;
1155 case STATUS_TIMEOUT:
1156 case STATUS_IO_TIMEOUT:
1157 if (fileio->already) status = STATUS_SUCCESS;
1158 break;
1160 if (status != STATUS_PENDING)
1162 iosb->u.Status = status;
1163 iosb->Information = fileio->already;
1164 *apc = fileio->io.apc;
1165 *arg = fileio->io.apc_arg;
1166 release_fileio( &fileio->io );
1168 return status;
1171 static NTSTATUS set_pending_write( HANDLE device )
1173 NTSTATUS status;
1175 SERVER_START_REQ( set_serial_info )
1177 req->handle = wine_server_obj_handle( device );
1178 req->flags = SERIALINFO_PENDING_WRITE;
1179 status = wine_server_call( req );
1181 SERVER_END_REQ;
1182 return status;
1185 /******************************************************************************
1186 * NtWriteFile [NTDLL.@]
1187 * ZwWriteFile [NTDLL.@]
1189 * Write to an open file handle.
1191 * PARAMS
1192 * FileHandle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1193 * Event [I] Event to signal upon completion (or NULL)
1194 * ApcRoutine [I] Callback to call upon completion (or NULL)
1195 * ApcContext [I] Context for ApcRoutine (or NULL)
1196 * IoStatusBlock [O] Receives information about the operation on return
1197 * Buffer [I] Source for the data to write
1198 * Length [I] Size of Buffer
1199 * ByteOffset [O] Destination for the new file pointer position (or NULL)
1200 * Key [O] Function unknown (may be NULL)
1202 * RETURNS
1203 * Success: 0. IoStatusBlock is updated, and the Information member contains
1204 * The number of bytes written.
1205 * Failure: An NTSTATUS error code describing the error.
1207 NTSTATUS WINAPI NtWriteFile(HANDLE hFile, HANDLE hEvent,
1208 PIO_APC_ROUTINE apc, void* apc_user,
1209 PIO_STATUS_BLOCK io_status,
1210 const void* buffer, ULONG length,
1211 PLARGE_INTEGER offset, PULONG key)
1213 int result, unix_handle, needs_close;
1214 unsigned int options;
1215 struct io_timeouts timeouts;
1216 NTSTATUS status;
1217 ULONG total = 0;
1218 enum server_fd_type type;
1219 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
1220 BOOL send_completion = FALSE, async_write, append_write = FALSE, timeout_init_done = FALSE;
1221 LARGE_INTEGER offset_eof;
1223 TRACE("(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p)!\n",
1224 hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);
1226 if (!io_status) return STATUS_ACCESS_VIOLATION;
1228 status = server_get_unix_fd( hFile, FILE_WRITE_DATA, &unix_handle,
1229 &needs_close, &type, &options );
1230 if (status == STATUS_ACCESS_DENIED)
1232 status = server_get_unix_fd( hFile, FILE_APPEND_DATA, &unix_handle,
1233 &needs_close, &type, &options );
1234 append_write = TRUE;
1236 if (status && status != STATUS_BAD_DEVICE_TYPE) return status;
1238 if (!virtual_check_buffer_for_read( buffer, length ))
1240 status = STATUS_INVALID_USER_BUFFER;
1241 goto done;
1244 if (status == STATUS_BAD_DEVICE_TYPE)
1245 return server_write_file( hFile, hEvent, apc, apc_user, io_status, buffer, length, offset, key );
1247 async_write = !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
1249 if (type == FD_TYPE_FILE)
1251 if (async_write &&
1252 (!offset || (offset->QuadPart < 0 && offset->QuadPart != FILE_WRITE_TO_END_OF_FILE)))
1254 status = STATUS_INVALID_PARAMETER;
1255 goto done;
1258 if (append_write)
1260 offset_eof.QuadPart = FILE_WRITE_TO_END_OF_FILE;
1261 offset = &offset_eof;
1264 if (offset && offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
1266 off_t off = offset->QuadPart;
1268 if (offset->QuadPart == FILE_WRITE_TO_END_OF_FILE)
1270 struct stat st;
1272 if (fstat( unix_handle, &st ) == -1)
1274 status = FILE_GetNtStatus();
1275 goto done;
1277 off = st.st_size;
1279 else if (offset->QuadPart < 0)
1281 status = STATUS_INVALID_PARAMETER;
1282 goto done;
1285 /* async I/O doesn't make sense on regular files */
1286 while ((result = pwrite( unix_handle, buffer, length, off )) == -1)
1288 if (errno != EINTR)
1290 if (errno == EFAULT) status = STATUS_INVALID_USER_BUFFER;
1291 else status = FILE_GetNtStatus();
1292 goto done;
1296 if (!async_write)
1297 /* update file pointer position */
1298 lseek( unix_handle, off + result, SEEK_SET );
1300 total = result;
1301 status = STATUS_SUCCESS;
1302 goto done;
1305 else if (type == FD_TYPE_SERIAL || type == FD_TYPE_DEVICE)
1307 if (async_write &&
1308 (!offset || (offset->QuadPart < 0 && offset->QuadPart != FILE_WRITE_TO_END_OF_FILE)))
1310 status = STATUS_INVALID_PARAMETER;
1311 goto done;
1315 for (;;)
1317 /* zero-length writes on sockets may not work with plain write(2) */
1318 if (!length && (type == FD_TYPE_MAILSLOT || type == FD_TYPE_PIPE || type == FD_TYPE_SOCKET))
1319 result = send( unix_handle, buffer, 0, 0 );
1320 else
1321 result = write( unix_handle, (const char *)buffer + total, length - total );
1323 if (result >= 0)
1325 total += result;
1326 if (total == length)
1328 status = STATUS_SUCCESS;
1329 goto done;
1331 if (type == FD_TYPE_FILE) continue; /* no async I/O on regular files */
1333 else if (errno != EAGAIN)
1335 if (errno == EINTR) continue;
1336 if (!total)
1338 if (errno == EFAULT) status = STATUS_INVALID_USER_BUFFER;
1339 else status = FILE_GetNtStatus();
1341 goto done;
1344 if (async_write)
1346 struct async_fileio_write *fileio;
1348 fileio = (struct async_fileio_write *)alloc_fileio( sizeof(*fileio), hFile, apc, apc_user );
1349 if (!fileio)
1351 status = STATUS_NO_MEMORY;
1352 goto err;
1354 fileio->already = total;
1355 fileio->count = length;
1356 fileio->buffer = buffer;
1358 SERVER_START_REQ( register_async )
1360 req->type = ASYNC_TYPE_WRITE;
1361 req->count = length;
1362 req->async.handle = wine_server_obj_handle( hFile );
1363 req->async.event = wine_server_obj_handle( hEvent );
1364 req->async.callback = wine_server_client_ptr( FILE_AsyncWriteService );
1365 req->async.iosb = wine_server_client_ptr( io_status );
1366 req->async.arg = wine_server_client_ptr( fileio );
1367 req->async.cvalue = cvalue;
1368 status = wine_server_call( req );
1370 SERVER_END_REQ;
1372 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
1373 goto err;
1375 else /* synchronous write, wait for the fd to become ready */
1377 struct pollfd pfd;
1378 int ret, timeout;
1380 if (!timeout_init_done)
1382 timeout_init_done = TRUE;
1383 if ((status = get_io_timeouts( hFile, type, length, FALSE, &timeouts )))
1384 goto err;
1385 if (hEvent) NtResetEvent( hEvent, NULL );
1387 timeout = get_next_io_timeout( &timeouts, total );
1389 pfd.fd = unix_handle;
1390 pfd.events = POLLOUT;
1392 if (!timeout || !(ret = poll( &pfd, 1, timeout )))
1394 /* return with what we got so far */
1395 status = total ? STATUS_SUCCESS : STATUS_TIMEOUT;
1396 goto done;
1398 if (ret == -1 && errno != EINTR)
1400 status = FILE_GetNtStatus();
1401 goto done;
1403 /* will now restart the write */
1407 done:
1408 send_completion = cvalue != 0;
1410 err:
1411 if (needs_close) close( unix_handle );
1413 if (type == FD_TYPE_SERIAL && (status == STATUS_SUCCESS || status == STATUS_PENDING))
1414 set_pending_write( hFile );
1416 if (status == STATUS_SUCCESS)
1418 io_status->u.Status = status;
1419 io_status->Information = total;
1420 TRACE("= SUCCESS (%u)\n", total);
1421 if (hEvent) NtSetEvent( hEvent, NULL );
1422 if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
1423 (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
1425 else
1427 TRACE("= 0x%08x\n", status);
1428 if (status != STATUS_PENDING && hEvent) NtResetEvent( hEvent, NULL );
1431 if (send_completion) NTDLL_AddCompletion( hFile, cvalue, status, total );
1433 return status;
1437 /******************************************************************************
1438 * NtWriteFileGather [NTDLL.@]
1439 * ZwWriteFileGather [NTDLL.@]
1441 NTSTATUS WINAPI NtWriteFileGather( HANDLE file, HANDLE event, PIO_APC_ROUTINE apc, void *apc_user,
1442 PIO_STATUS_BLOCK io_status, FILE_SEGMENT_ELEMENT *segments,
1443 ULONG length, PLARGE_INTEGER offset, PULONG key )
1445 int result, unix_handle, needs_close;
1446 unsigned int options;
1447 NTSTATUS status;
1448 ULONG pos = 0, total = 0;
1449 enum server_fd_type type;
1450 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
1451 BOOL send_completion = FALSE;
1453 TRACE( "(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
1454 file, event, apc, apc_user, io_status, segments, length, offset, key);
1456 if (length % page_size) return STATUS_INVALID_PARAMETER;
1457 if (!io_status) return STATUS_ACCESS_VIOLATION;
1459 status = server_get_unix_fd( file, FILE_WRITE_DATA, &unix_handle,
1460 &needs_close, &type, &options );
1461 if (status) return status;
1463 if ((type != FD_TYPE_FILE) ||
1464 (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) ||
1465 !(options & FILE_NO_INTERMEDIATE_BUFFERING))
1467 status = STATUS_INVALID_PARAMETER;
1468 goto error;
1471 while (length)
1473 if (offset && offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
1474 result = pwrite( unix_handle, (char *)segments->Buffer + pos,
1475 page_size - pos, offset->QuadPart + total );
1476 else
1477 result = write( unix_handle, (char *)segments->Buffer + pos, page_size - pos );
1479 if (result == -1)
1481 if (errno == EINTR) continue;
1482 if (errno == EFAULT)
1484 status = STATUS_INVALID_USER_BUFFER;
1485 goto error;
1487 status = FILE_GetNtStatus();
1488 break;
1490 if (!result)
1492 status = STATUS_DISK_FULL;
1493 break;
1495 total += result;
1496 length -= result;
1497 if ((pos += result) == page_size)
1499 pos = 0;
1500 segments++;
1504 send_completion = cvalue != 0;
1506 error:
1507 if (needs_close) close( unix_handle );
1508 if (status == STATUS_SUCCESS)
1510 io_status->u.Status = status;
1511 io_status->Information = total;
1512 TRACE("= SUCCESS (%u)\n", total);
1513 if (event) NtSetEvent( event, NULL );
1514 if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
1515 (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
1517 else
1519 TRACE("= 0x%08x\n", status);
1520 if (status != STATUS_PENDING && event) NtResetEvent( event, NULL );
1523 if (send_completion) NTDLL_AddCompletion( file, cvalue, status, total );
1525 return status;
1529 /* do an ioctl call through the server */
1530 static NTSTATUS server_ioctl_file( HANDLE handle, HANDLE event,
1531 PIO_APC_ROUTINE apc, PVOID apc_context,
1532 IO_STATUS_BLOCK *io, ULONG code,
1533 const void *in_buffer, ULONG in_size,
1534 PVOID out_buffer, ULONG out_size )
1536 struct async_irp *async;
1537 NTSTATUS status;
1538 HANDLE wait_handle;
1539 ULONG options;
1540 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;
1542 if (!(async = (struct async_irp *)alloc_fileio( sizeof(*async), handle, apc, apc_context )))
1543 return STATUS_NO_MEMORY;
1544 async->event = event;
1545 async->buffer = out_buffer;
1546 async->size = out_size;
1548 SERVER_START_REQ( ioctl )
1550 req->code = code;
1551 req->blocking = !apc && !event && !cvalue;
1552 req->async.handle = wine_server_obj_handle( handle );
1553 req->async.callback = wine_server_client_ptr( irp_completion );
1554 req->async.iosb = wine_server_client_ptr( io );
1555 req->async.arg = wine_server_client_ptr( async );
1556 req->async.event = wine_server_obj_handle( event );
1557 req->async.cvalue = cvalue;
1558 wine_server_add_data( req, in_buffer, in_size );
1559 if ((code & 3) != METHOD_BUFFERED)
1560 wine_server_add_data( req, out_buffer, out_size );
1561 wine_server_set_reply( req, out_buffer, out_size );
1562 status = wine_server_call( req );
1563 wait_handle = wine_server_ptr_handle( reply->wait );
1564 options = reply->options;
1565 if (status != STATUS_PENDING) io->Information = wine_server_reply_size( reply );
1567 SERVER_END_REQ;
1569 if (status == STATUS_NOT_SUPPORTED)
1570 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
1571 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
1573 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, async );
1575 if (wait_handle)
1577 NtWaitForSingleObject( wait_handle, (options & FILE_SYNCHRONOUS_IO_ALERT), NULL );
1578 status = io->u.Status;
1579 NtClose( wait_handle );
1582 return status;
1585 /* Tell Valgrind to ignore any holes in structs we will be passing to the
1586 * server */
1587 static void ignore_server_ioctl_struct_holes (ULONG code, const void *in_buffer,
1588 ULONG in_size)
1590 #ifdef VALGRIND_MAKE_MEM_DEFINED
1591 # define IGNORE_STRUCT_HOLE(buf, size, t, f1, f2) \
1592 do { \
1593 if (FIELD_OFFSET(t, f1) + sizeof(((t *)0)->f1) < FIELD_OFFSET(t, f2)) \
1594 if ((size) >= FIELD_OFFSET(t, f2)) \
1595 VALGRIND_MAKE_MEM_DEFINED( \
1596 (const char *)(buf) + FIELD_OFFSET(t, f1) + sizeof(((t *)0)->f1), \
1597 FIELD_OFFSET(t, f2) - FIELD_OFFSET(t, f1) + sizeof(((t *)0)->f1)); \
1598 } while (0)
1600 switch (code)
1602 case FSCTL_PIPE_WAIT:
1603 IGNORE_STRUCT_HOLE(in_buffer, in_size, FILE_PIPE_WAIT_FOR_BUFFER, TimeoutSpecified, Name);
1604 break;
1606 #endif
1610 /**************************************************************************
1611 * NtDeviceIoControlFile [NTDLL.@]
1612 * ZwDeviceIoControlFile [NTDLL.@]
1614 * Perform an I/O control operation on an open file handle.
1616 * PARAMS
1617 * handle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1618 * event [I] Event to signal upon completion (or NULL)
1619 * apc [I] Callback to call upon completion (or NULL)
1620 * apc_context [I] Context for ApcRoutine (or NULL)
1621 * io [O] Receives information about the operation on return
1622 * code [I] Control code for the operation to perform
1623 * in_buffer [I] Source for any input data required (or NULL)
1624 * in_size [I] Size of InputBuffer
1625 * out_buffer [O] Source for any output data returned (or NULL)
1626 * out_size [I] Size of OutputBuffer
1628 * RETURNS
1629 * Success: 0. IoStatusBlock is updated.
1630 * Failure: An NTSTATUS error code describing the error.
1632 NTSTATUS WINAPI NtDeviceIoControlFile(HANDLE handle, HANDLE event,
1633 PIO_APC_ROUTINE apc, PVOID apc_context,
1634 PIO_STATUS_BLOCK io, ULONG code,
1635 PVOID in_buffer, ULONG in_size,
1636 PVOID out_buffer, ULONG out_size)
1638 ULONG device = (code >> 16);
1639 NTSTATUS status = STATUS_NOT_SUPPORTED;
1641 TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1642 handle, event, apc, apc_context, io, code,
1643 in_buffer, in_size, out_buffer, out_size);
1645 switch(device)
1647 case FILE_DEVICE_DISK:
1648 case FILE_DEVICE_CD_ROM:
1649 case FILE_DEVICE_DVD:
1650 case FILE_DEVICE_CONTROLLER:
1651 case FILE_DEVICE_MASS_STORAGE:
1652 status = CDROM_DeviceIoControl(handle, event, apc, apc_context, io, code,
1653 in_buffer, in_size, out_buffer, out_size);
1654 break;
1655 case FILE_DEVICE_SERIAL_PORT:
1656 status = COMM_DeviceIoControl(handle, event, apc, apc_context, io, code,
1657 in_buffer, in_size, out_buffer, out_size);
1658 break;
1659 case FILE_DEVICE_TAPE:
1660 status = TAPE_DeviceIoControl(handle, event, apc, apc_context, io, code,
1661 in_buffer, in_size, out_buffer, out_size);
1662 break;
1665 if (status == STATUS_NOT_SUPPORTED || status == STATUS_BAD_DEVICE_TYPE)
1666 status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1667 in_buffer, in_size, out_buffer, out_size );
1669 if (status != STATUS_PENDING) io->u.Status = status;
1670 return status;
1674 /**************************************************************************
1675 * NtFsControlFile [NTDLL.@]
1676 * ZwFsControlFile [NTDLL.@]
1678 * Perform a file system control operation on an open file handle.
1680 * PARAMS
1681 * handle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1682 * event [I] Event to signal upon completion (or NULL)
1683 * apc [I] Callback to call upon completion (or NULL)
1684 * apc_context [I] Context for ApcRoutine (or NULL)
1685 * io [O] Receives information about the operation on return
1686 * code [I] Control code for the operation to perform
1687 * in_buffer [I] Source for any input data required (or NULL)
1688 * in_size [I] Size of InputBuffer
1689 * out_buffer [O] Source for any output data returned (or NULL)
1690 * out_size [I] Size of OutputBuffer
1692 * RETURNS
1693 * Success: 0. IoStatusBlock is updated.
1694 * Failure: An NTSTATUS error code describing the error.
1696 NTSTATUS WINAPI NtFsControlFile(HANDLE handle, HANDLE event, PIO_APC_ROUTINE apc,
1697 PVOID apc_context, PIO_STATUS_BLOCK io, ULONG code,
1698 PVOID in_buffer, ULONG in_size, PVOID out_buffer, ULONG out_size)
1700 NTSTATUS status;
1702 TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1703 handle, event, apc, apc_context, io, code,
1704 in_buffer, in_size, out_buffer, out_size);
1706 if (!io) return STATUS_INVALID_PARAMETER;
1708 ignore_server_ioctl_struct_holes( code, in_buffer, in_size );
1710 switch(code)
1712 case FSCTL_DISMOUNT_VOLUME:
1713 status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1714 in_buffer, in_size, out_buffer, out_size );
1715 if (!status) status = DIR_unmount_device( handle );
1716 break;
1718 case FSCTL_PIPE_PEEK:
1720 FILE_PIPE_PEEK_BUFFER *buffer = out_buffer;
1721 int avail = 0, fd, needs_close;
1723 if (out_size < FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data ))
1725 status = STATUS_INFO_LENGTH_MISMATCH;
1726 break;
1729 if ((status = server_get_unix_fd( handle, FILE_READ_DATA, &fd, &needs_close, NULL, NULL )))
1730 break;
1732 #ifdef FIONREAD
1733 if (ioctl( fd, FIONREAD, &avail ) != 0)
1735 TRACE("FIONREAD failed reason: %s\n",strerror(errno));
1736 if (needs_close) close( fd );
1737 status = FILE_GetNtStatus();
1738 break;
1740 #endif
1741 if (!avail) /* check for closed pipe */
1743 struct pollfd pollfd;
1744 int ret;
1746 pollfd.fd = fd;
1747 pollfd.events = POLLIN;
1748 pollfd.revents = 0;
1749 ret = poll( &pollfd, 1, 0 );
1750 if (ret == -1 || (ret == 1 && (pollfd.revents & (POLLHUP|POLLERR))))
1752 if (needs_close) close( fd );
1753 status = STATUS_PIPE_BROKEN;
1754 break;
1757 buffer->NamedPipeState = 0; /* FIXME */
1758 buffer->ReadDataAvailable = avail;
1759 buffer->NumberOfMessages = 0; /* FIXME */
1760 buffer->MessageLength = 0; /* FIXME */
1761 io->Information = FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data );
1762 status = STATUS_SUCCESS;
1763 if (avail)
1765 ULONG data_size = out_size - FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data );
1766 if (data_size)
1768 int res = recv( fd, buffer->Data, data_size, MSG_PEEK );
1769 if (res >= 0) io->Information += res;
1772 if (needs_close) close( fd );
1774 break;
1776 case FSCTL_PIPE_DISCONNECT:
1777 status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1778 in_buffer, in_size, out_buffer, out_size );
1779 if (!status)
1781 int fd = server_remove_fd_from_cache( handle );
1782 if (fd != -1) close( fd );
1784 break;
1786 case FSCTL_PIPE_LISTEN:
1787 status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1788 in_buffer, in_size, out_buffer, out_size );
1789 return status;
1791 case FSCTL_PIPE_IMPERSONATE:
1792 FIXME("FSCTL_PIPE_IMPERSONATE: impersonating self\n");
1793 status = RtlImpersonateSelf( SecurityImpersonation );
1794 break;
1796 case FSCTL_IS_VOLUME_MOUNTED:
1797 case FSCTL_LOCK_VOLUME:
1798 case FSCTL_UNLOCK_VOLUME:
1799 FIXME("stub! return success - Unsupported fsctl %x (device=%x access=%x func=%x method=%x)\n",
1800 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
1801 status = STATUS_SUCCESS;
1802 break;
1804 case FSCTL_GET_RETRIEVAL_POINTERS:
1806 RETRIEVAL_POINTERS_BUFFER *buffer = (RETRIEVAL_POINTERS_BUFFER *)out_buffer;
1808 FIXME("stub: FSCTL_GET_RETRIEVAL_POINTERS\n");
1810 if (out_size >= sizeof(RETRIEVAL_POINTERS_BUFFER))
1812 buffer->ExtentCount = 1;
1813 buffer->StartingVcn.QuadPart = 1;
1814 buffer->Extents[0].NextVcn.QuadPart = 0;
1815 buffer->Extents[0].Lcn.QuadPart = 0;
1816 io->Information = sizeof(RETRIEVAL_POINTERS_BUFFER);
1817 status = STATUS_SUCCESS;
1819 else
1821 io->Information = 0;
1822 status = STATUS_BUFFER_TOO_SMALL;
1824 break;
1826 case FSCTL_SET_SPARSE:
1827 TRACE("FSCTL_SET_SPARSE: Ignoring request\n");
1828 io->Information = 0;
1829 status = STATUS_SUCCESS;
1830 break;
1831 case FSCTL_PIPE_WAIT:
1832 default:
1833 status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1834 in_buffer, in_size, out_buffer, out_size );
1835 break;
1838 if (status != STATUS_PENDING) io->u.Status = status;
1839 return status;
1843 struct read_changes_fileio
1845 struct async_fileio io;
1846 void *buffer;
1847 ULONG buffer_size;
1848 ULONG data_size;
1849 char data[1];
1852 static NTSTATUS read_changes_apc( void *user, IO_STATUS_BLOCK *iosb,
1853 NTSTATUS status, void **apc, void **arg )
1855 struct read_changes_fileio *fileio = user;
1856 int size = 0;
1858 if (status == STATUS_ALERTED)
1860 SERVER_START_REQ( read_change )
1862 req->handle = wine_server_obj_handle( fileio->io.handle );
1863 wine_server_set_reply( req, fileio->data, fileio->data_size );
1864 status = wine_server_call( req );
1865 size = wine_server_reply_size( reply );
1867 SERVER_END_REQ;
1869 if (status == STATUS_SUCCESS && fileio->buffer)
1871 FILE_NOTIFY_INFORMATION *pfni = fileio->buffer;
1872 int i, left = fileio->buffer_size;
1873 DWORD *last_entry_offset = NULL;
1874 struct filesystem_event *event = (struct filesystem_event*)fileio->data;
1876 while (size && left >= sizeof(*pfni))
1878 /* convert to an NT style path */
1879 for (i = 0; i < event->len; i++)
1880 if (event->name[i] == '/') event->name[i] = '\\';
1882 pfni->Action = event->action;
1883 pfni->FileNameLength = ntdll_umbstowcs( 0, event->name, event->len, pfni->FileName,
1884 (left - offsetof(FILE_NOTIFY_INFORMATION, FileName)) / sizeof(WCHAR));
1885 last_entry_offset = &pfni->NextEntryOffset;
1887 if (pfni->FileNameLength == -1 || pfni->FileNameLength == -2) break;
1889 i = offsetof(FILE_NOTIFY_INFORMATION, FileName[pfni->FileNameLength]);
1890 pfni->FileNameLength *= sizeof(WCHAR);
1891 pfni->NextEntryOffset = i;
1892 pfni = (FILE_NOTIFY_INFORMATION*)((char*)pfni + i);
1893 left -= i;
1895 i = (offsetof(struct filesystem_event, name[event->len])
1896 + sizeof(int)-1) / sizeof(int) * sizeof(int);
1897 event = (struct filesystem_event*)((char*)event + i);
1898 size -= i;
1901 if (size)
1903 status = STATUS_NOTIFY_ENUM_DIR;
1904 size = 0;
1906 else
1908 if (last_entry_offset) *last_entry_offset = 0;
1909 size = fileio->buffer_size - left;
1912 else
1914 status = STATUS_NOTIFY_ENUM_DIR;
1915 size = 0;
1919 if (status != STATUS_PENDING)
1921 iosb->u.Status = status;
1922 iosb->Information = size;
1923 *apc = fileio->io.apc;
1924 *arg = fileio->io.apc_arg;
1925 release_fileio( &fileio->io );
1927 return status;
1930 #define FILE_NOTIFY_ALL ( \
1931 FILE_NOTIFY_CHANGE_FILE_NAME | \
1932 FILE_NOTIFY_CHANGE_DIR_NAME | \
1933 FILE_NOTIFY_CHANGE_ATTRIBUTES | \
1934 FILE_NOTIFY_CHANGE_SIZE | \
1935 FILE_NOTIFY_CHANGE_LAST_WRITE | \
1936 FILE_NOTIFY_CHANGE_LAST_ACCESS | \
1937 FILE_NOTIFY_CHANGE_CREATION | \
1938 FILE_NOTIFY_CHANGE_SECURITY )
1940 /******************************************************************************
1941 * NtNotifyChangeDirectoryFile [NTDLL.@]
1943 NTSTATUS WINAPI NtNotifyChangeDirectoryFile( HANDLE handle, HANDLE event, PIO_APC_ROUTINE apc,
1944 void *apc_context, PIO_STATUS_BLOCK iosb, void *buffer,
1945 ULONG buffer_size, ULONG filter, BOOLEAN subtree )
1947 struct read_changes_fileio *fileio;
1948 NTSTATUS status;
1949 ULONG size = max( 4096, buffer_size );
1950 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;
1952 TRACE( "%p %p %p %p %p %p %u %u %d\n",
1953 handle, event, apc, apc_context, iosb, buffer, buffer_size, filter, subtree );
1955 if (!iosb) return STATUS_ACCESS_VIOLATION;
1956 if (filter == 0 || (filter & ~FILE_NOTIFY_ALL)) return STATUS_INVALID_PARAMETER;
1958 fileio = (struct read_changes_fileio *)alloc_fileio( offsetof(struct read_changes_fileio, data[size]),
1959 handle, apc, apc_context );
1960 if (!fileio) return STATUS_NO_MEMORY;
1962 fileio->buffer = buffer;
1963 fileio->buffer_size = buffer_size;
1964 fileio->data_size = size;
1966 SERVER_START_REQ( read_directory_changes )
1968 req->filter = filter;
1969 req->want_data = (buffer != NULL);
1970 req->subtree = subtree;
1971 req->async.handle = wine_server_obj_handle( handle );
1972 req->async.callback = wine_server_client_ptr( read_changes_apc );
1973 req->async.iosb = wine_server_client_ptr( iosb );
1974 req->async.arg = wine_server_client_ptr( fileio );
1975 req->async.event = wine_server_obj_handle( event );
1976 req->async.cvalue = cvalue;
1977 status = wine_server_call( req );
1979 SERVER_END_REQ;
1981 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
1982 return status;
1985 /******************************************************************************
1986 * NtSetVolumeInformationFile [NTDLL.@]
1987 * ZwSetVolumeInformationFile [NTDLL.@]
1989 * Set volume information for an open file handle.
1991 * PARAMS
1992 * FileHandle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1993 * IoStatusBlock [O] Receives information about the operation on return
1994 * FsInformation [I] Source for volume information
1995 * Length [I] Size of FsInformation
1996 * FsInformationClass [I] Type of volume information to set
1998 * RETURNS
1999 * Success: 0. IoStatusBlock is updated.
2000 * Failure: An NTSTATUS error code describing the error.
2002 NTSTATUS WINAPI NtSetVolumeInformationFile(
2003 IN HANDLE FileHandle,
2004 PIO_STATUS_BLOCK IoStatusBlock,
2005 PVOID FsInformation,
2006 ULONG Length,
2007 FS_INFORMATION_CLASS FsInformationClass)
2009 FIXME("(%p,%p,%p,0x%08x,0x%08x) stub\n",
2010 FileHandle,IoStatusBlock,FsInformation,Length,FsInformationClass);
2011 return 0;
2014 #if defined(__ANDROID__) && !defined(HAVE_FUTIMENS)
2015 static int futimens( int fd, const struct timespec spec[2] )
2017 return syscall( __NR_utimensat, fd, NULL, spec, 0 );
2019 #define HAVE_FUTIMENS
2020 #endif /* __ANDROID__ */
2022 #ifndef UTIME_OMIT
2023 #define UTIME_OMIT ((1 << 30) - 2)
2024 #endif
2026 static NTSTATUS set_file_times( int fd, const LARGE_INTEGER *mtime, const LARGE_INTEGER *atime )
2028 NTSTATUS status = STATUS_SUCCESS;
2030 #ifdef HAVE_FUTIMENS
2031 struct timespec tv[2];
2033 tv[0].tv_sec = tv[1].tv_sec = 0;
2034 tv[0].tv_nsec = tv[1].tv_nsec = UTIME_OMIT;
2035 if (atime->QuadPart)
2037 tv[0].tv_sec = atime->QuadPart / 10000000 - SECS_1601_TO_1970;
2038 tv[0].tv_nsec = (atime->QuadPart % 10000000) * 100;
2040 if (mtime->QuadPart)
2042 tv[1].tv_sec = mtime->QuadPart / 10000000 - SECS_1601_TO_1970;
2043 tv[1].tv_nsec = (mtime->QuadPart % 10000000) * 100;
2045 if (futimens( fd, tv ) == -1) status = FILE_GetNtStatus();
2047 #elif defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT)
2048 struct timeval tv[2];
2049 struct stat st;
2051 if (!atime->QuadPart || !mtime->QuadPart)
2054 tv[0].tv_sec = tv[0].tv_usec = 0;
2055 tv[1].tv_sec = tv[1].tv_usec = 0;
2056 if (!fstat( fd, &st ))
2058 tv[0].tv_sec = st.st_atime;
2059 tv[1].tv_sec = st.st_mtime;
2060 #ifdef HAVE_STRUCT_STAT_ST_ATIM
2061 tv[0].tv_usec = st.st_atim.tv_nsec / 1000;
2062 #elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC)
2063 tv[0].tv_usec = st.st_atimespec.tv_nsec / 1000;
2064 #endif
2065 #ifdef HAVE_STRUCT_STAT_ST_MTIM
2066 tv[1].tv_usec = st.st_mtim.tv_nsec / 1000;
2067 #elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC)
2068 tv[1].tv_usec = st.st_mtimespec.tv_nsec / 1000;
2069 #endif
2072 if (atime->QuadPart)
2074 tv[0].tv_sec = atime->QuadPart / 10000000 - SECS_1601_TO_1970;
2075 tv[0].tv_usec = (atime->QuadPart % 10000000) / 10;
2077 if (mtime->QuadPart)
2079 tv[1].tv_sec = mtime->QuadPart / 10000000 - SECS_1601_TO_1970;
2080 tv[1].tv_usec = (mtime->QuadPart % 10000000) / 10;
2082 #ifdef HAVE_FUTIMES
2083 if (futimes( fd, tv ) == -1) status = FILE_GetNtStatus();
2084 #elif defined(HAVE_FUTIMESAT)
2085 if (futimesat( fd, NULL, tv ) == -1) status = FILE_GetNtStatus();
2086 #endif
2088 #else /* HAVE_FUTIMES || HAVE_FUTIMESAT */
2089 FIXME( "setting file times not supported\n" );
2090 status = STATUS_NOT_IMPLEMENTED;
2091 #endif
2092 return status;
2095 static inline void get_file_times( const struct stat *st, LARGE_INTEGER *mtime, LARGE_INTEGER *ctime,
2096 LARGE_INTEGER *atime, LARGE_INTEGER *creation )
2098 RtlSecondsSince1970ToTime( st->st_mtime, mtime );
2099 RtlSecondsSince1970ToTime( st->st_ctime, ctime );
2100 RtlSecondsSince1970ToTime( st->st_atime, atime );
2101 #ifdef HAVE_STRUCT_STAT_ST_MTIM
2102 mtime->QuadPart += st->st_mtim.tv_nsec / 100;
2103 #elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC)
2104 mtime->QuadPart += st->st_mtimespec.tv_nsec / 100;
2105 #endif
2106 #ifdef HAVE_STRUCT_STAT_ST_CTIM
2107 ctime->QuadPart += st->st_ctim.tv_nsec / 100;
2108 #elif defined(HAVE_STRUCT_STAT_ST_CTIMESPEC)
2109 ctime->QuadPart += st->st_ctimespec.tv_nsec / 100;
2110 #endif
2111 #ifdef HAVE_STRUCT_STAT_ST_ATIM
2112 atime->QuadPart += st->st_atim.tv_nsec / 100;
2113 #elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC)
2114 atime->QuadPart += st->st_atimespec.tv_nsec / 100;
2115 #endif
2116 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
2117 RtlSecondsSince1970ToTime( st->st_birthtime, creation );
2118 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIM
2119 creation->QuadPart += st->st_birthtim.tv_nsec / 100;
2120 #elif defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC)
2121 creation->QuadPart += st->st_birthtimespec.tv_nsec / 100;
2122 #endif
2123 #elif defined(HAVE_STRUCT_STAT___ST_BIRTHTIME)
2124 RtlSecondsSince1970ToTime( st->__st_birthtime, creation );
2125 #ifdef HAVE_STRUCT_STAT___ST_BIRTHTIM
2126 creation->QuadPart += st->__st_birthtim.tv_nsec / 100;
2127 #endif
2128 #else
2129 *creation = *mtime;
2130 #endif
2133 /* fill in the file information that depends on the stat and attribute info */
2134 NTSTATUS fill_file_info( const struct stat *st, ULONG attr, void *ptr,
2135 FILE_INFORMATION_CLASS class )
2137 switch (class)
2139 case FileBasicInformation:
2141 FILE_BASIC_INFORMATION *info = ptr;
2143 get_file_times( st, &info->LastWriteTime, &info->ChangeTime,
2144 &info->LastAccessTime, &info->CreationTime );
2145 info->FileAttributes = attr;
2147 break;
2148 case FileStandardInformation:
2150 FILE_STANDARD_INFORMATION *info = ptr;
2152 if ((info->Directory = S_ISDIR(st->st_mode)))
2154 info->AllocationSize.QuadPart = 0;
2155 info->EndOfFile.QuadPart = 0;
2156 info->NumberOfLinks = 1;
2158 else
2160 info->AllocationSize.QuadPart = (ULONGLONG)st->st_blocks * 512;
2161 info->EndOfFile.QuadPart = st->st_size;
2162 info->NumberOfLinks = st->st_nlink;
2165 break;
2166 case FileInternalInformation:
2168 FILE_INTERNAL_INFORMATION *info = ptr;
2169 info->IndexNumber.QuadPart = st->st_ino;
2171 break;
2172 case FileEndOfFileInformation:
2174 FILE_END_OF_FILE_INFORMATION *info = ptr;
2175 info->EndOfFile.QuadPart = S_ISDIR(st->st_mode) ? 0 : st->st_size;
2177 break;
2178 case FileAllInformation:
2180 FILE_ALL_INFORMATION *info = ptr;
2181 fill_file_info( st, attr, &info->BasicInformation, FileBasicInformation );
2182 fill_file_info( st, attr, &info->StandardInformation, FileStandardInformation );
2183 fill_file_info( st, attr, &info->InternalInformation, FileInternalInformation );
2185 break;
2186 /* all directory structures start with the FileDirectoryInformation layout */
2187 case FileBothDirectoryInformation:
2188 case FileFullDirectoryInformation:
2189 case FileDirectoryInformation:
2191 FILE_DIRECTORY_INFORMATION *info = ptr;
2193 get_file_times( st, &info->LastWriteTime, &info->ChangeTime,
2194 &info->LastAccessTime, &info->CreationTime );
2195 if (S_ISDIR(st->st_mode))
2197 info->AllocationSize.QuadPart = 0;
2198 info->EndOfFile.QuadPart = 0;
2200 else
2202 info->AllocationSize.QuadPart = (ULONGLONG)st->st_blocks * 512;
2203 info->EndOfFile.QuadPart = st->st_size;
2205 info->FileAttributes = attr;
2207 break;
2208 case FileIdFullDirectoryInformation:
2210 FILE_ID_FULL_DIRECTORY_INFORMATION *info = ptr;
2211 info->FileId.QuadPart = st->st_ino;
2212 fill_file_info( st, attr, info, FileDirectoryInformation );
2214 break;
2215 case FileIdBothDirectoryInformation:
2217 FILE_ID_BOTH_DIRECTORY_INFORMATION *info = ptr;
2218 info->FileId.QuadPart = st->st_ino;
2219 fill_file_info( st, attr, info, FileDirectoryInformation );
2221 break;
2222 case FileIdGlobalTxDirectoryInformation:
2224 FILE_ID_GLOBAL_TX_DIR_INFORMATION *info = ptr;
2225 info->FileId.QuadPart = st->st_ino;
2226 fill_file_info( st, attr, info, FileDirectoryInformation );
2228 break;
2230 default:
2231 return STATUS_INVALID_INFO_CLASS;
2233 return STATUS_SUCCESS;
2236 NTSTATUS server_get_unix_name( HANDLE handle, ANSI_STRING *unix_name )
2238 data_size_t size = 1024;
2239 NTSTATUS ret;
2240 char *name;
2242 for (;;)
2244 name = RtlAllocateHeap( GetProcessHeap(), 0, size + 1 );
2245 if (!name) return STATUS_NO_MEMORY;
2246 unix_name->MaximumLength = size + 1;
2248 SERVER_START_REQ( get_handle_unix_name )
2250 req->handle = wine_server_obj_handle( handle );
2251 wine_server_set_reply( req, name, size );
2252 ret = wine_server_call( req );
2253 size = reply->name_len;
2255 SERVER_END_REQ;
2257 if (!ret)
2259 name[size] = 0;
2260 unix_name->Buffer = name;
2261 unix_name->Length = size;
2262 break;
2264 RtlFreeHeap( GetProcessHeap(), 0, name );
2265 if (ret != STATUS_BUFFER_OVERFLOW) break;
2267 return ret;
2270 static NTSTATUS fill_name_info( const ANSI_STRING *unix_name, FILE_NAME_INFORMATION *info, LONG *name_len )
2272 UNICODE_STRING nt_name;
2273 NTSTATUS status;
2275 if (!(status = wine_unix_to_nt_file_name( unix_name, &nt_name )))
2277 const WCHAR *ptr = nt_name.Buffer;
2278 const WCHAR *end = ptr + (nt_name.Length / sizeof(WCHAR));
2280 /* Skip the volume mount point. */
2281 while (ptr != end && *ptr == '\\') ++ptr;
2282 while (ptr != end && *ptr != '\\') ++ptr;
2283 while (ptr != end && *ptr == '\\') ++ptr;
2284 while (ptr != end && *ptr != '\\') ++ptr;
2286 info->FileNameLength = (end - ptr) * sizeof(WCHAR);
2287 if (*name_len < info->FileNameLength) status = STATUS_BUFFER_OVERFLOW;
2288 else *name_len = info->FileNameLength;
2290 memcpy( info->FileName, ptr, *name_len );
2291 RtlFreeUnicodeString( &nt_name );
2294 return status;
2297 /******************************************************************************
2298 * NtQueryInformationFile [NTDLL.@]
2299 * ZwQueryInformationFile [NTDLL.@]
2301 * Get information about an open file handle.
2303 * PARAMS
2304 * hFile [I] Handle returned from ZwOpenFile() or ZwCreateFile()
2305 * io [O] Receives information about the operation on return
2306 * ptr [O] Destination for file information
2307 * len [I] Size of FileInformation
2308 * class [I] Type of file information to get
2310 * RETURNS
2311 * Success: 0. IoStatusBlock and FileInformation are updated.
2312 * Failure: An NTSTATUS error code describing the error.
2314 NTSTATUS WINAPI NtQueryInformationFile( HANDLE hFile, PIO_STATUS_BLOCK io,
2315 PVOID ptr, LONG len, FILE_INFORMATION_CLASS class )
2317 static const size_t info_sizes[] =
2320 sizeof(FILE_DIRECTORY_INFORMATION), /* FileDirectoryInformation */
2321 sizeof(FILE_FULL_DIRECTORY_INFORMATION), /* FileFullDirectoryInformation */
2322 sizeof(FILE_BOTH_DIRECTORY_INFORMATION), /* FileBothDirectoryInformation */
2323 sizeof(FILE_BASIC_INFORMATION), /* FileBasicInformation */
2324 sizeof(FILE_STANDARD_INFORMATION), /* FileStandardInformation */
2325 sizeof(FILE_INTERNAL_INFORMATION), /* FileInternalInformation */
2326 sizeof(FILE_EA_INFORMATION), /* FileEaInformation */
2327 sizeof(FILE_ACCESS_INFORMATION), /* FileAccessInformation */
2328 sizeof(FILE_NAME_INFORMATION), /* FileNameInformation */
2329 sizeof(FILE_RENAME_INFORMATION)-sizeof(WCHAR), /* FileRenameInformation */
2330 0, /* FileLinkInformation */
2331 sizeof(FILE_NAMES_INFORMATION)-sizeof(WCHAR), /* FileNamesInformation */
2332 sizeof(FILE_DISPOSITION_INFORMATION), /* FileDispositionInformation */
2333 sizeof(FILE_POSITION_INFORMATION), /* FilePositionInformation */
2334 sizeof(FILE_FULL_EA_INFORMATION), /* FileFullEaInformation */
2335 sizeof(FILE_MODE_INFORMATION), /* FileModeInformation */
2336 sizeof(FILE_ALIGNMENT_INFORMATION), /* FileAlignmentInformation */
2337 sizeof(FILE_ALL_INFORMATION), /* FileAllInformation */
2338 sizeof(FILE_ALLOCATION_INFORMATION), /* FileAllocationInformation */
2339 sizeof(FILE_END_OF_FILE_INFORMATION), /* FileEndOfFileInformation */
2340 0, /* FileAlternateNameInformation */
2341 sizeof(FILE_STREAM_INFORMATION)-sizeof(WCHAR), /* FileStreamInformation */
2342 sizeof(FILE_PIPE_INFORMATION), /* FilePipeInformation */
2343 sizeof(FILE_PIPE_LOCAL_INFORMATION), /* FilePipeLocalInformation */
2344 0, /* FilePipeRemoteInformation */
2345 sizeof(FILE_MAILSLOT_QUERY_INFORMATION), /* FileMailslotQueryInformation */
2346 0, /* FileMailslotSetInformation */
2347 0, /* FileCompressionInformation */
2348 0, /* FileObjectIdInformation */
2349 0, /* FileCompletionInformation */
2350 0, /* FileMoveClusterInformation */
2351 0, /* FileQuotaInformation */
2352 0, /* FileReparsePointInformation */
2353 sizeof(FILE_NETWORK_OPEN_INFORMATION), /* FileNetworkOpenInformation */
2354 0, /* FileAttributeTagInformation */
2355 0, /* FileTrackingInformation */
2356 0, /* FileIdBothDirectoryInformation */
2357 0, /* FileIdFullDirectoryInformation */
2358 0, /* FileValidDataLengthInformation */
2359 0, /* FileShortNameInformation */
2360 0, /* FileIoCompletionNotificationInformation, */
2361 0, /* FileIoStatusBlockRangeInformation */
2362 0, /* FileIoPriorityHintInformation */
2363 0, /* FileSfioReserveInformation */
2364 0, /* FileSfioVolumeInformation */
2365 0, /* FileHardLinkInformation */
2366 0, /* FileProcessIdsUsingFileInformation */
2367 0, /* FileNormalizedNameInformation */
2368 0, /* FileNetworkPhysicalNameInformation */
2369 0, /* FileIdGlobalTxDirectoryInformation */
2370 0, /* FileIsRemoteDeviceInformation */
2371 0, /* FileAttributeCacheInformation */
2372 0, /* FileNumaNodeInformation */
2373 0, /* FileStandardLinkInformation */
2374 0, /* FileRemoteProtocolInformation */
2375 0, /* FileRenameInformationBypassAccessCheck */
2376 0, /* FileLinkInformationBypassAccessCheck */
2377 0, /* FileVolumeNameInformation */
2378 sizeof(FILE_ID_INFORMATION), /* FileIdInformation */
2379 0, /* FileIdExtdDirectoryInformation */
2380 0, /* FileReplaceCompletionInformation */
2381 0, /* FileHardLinkFullIdInformation */
2382 0, /* FileIdExtdBothDirectoryInformation */
2385 struct stat st;
2386 int fd, needs_close = FALSE;
2387 ULONG attr;
2389 TRACE("(%p,%p,%p,0x%08x,0x%08x)\n", hFile, io, ptr, len, class);
2391 io->Information = 0;
2393 if (class <= 0 || class >= FileMaximumInformation)
2394 return io->u.Status = STATUS_INVALID_INFO_CLASS;
2395 if (!info_sizes[class])
2397 FIXME("Unsupported class (%d)\n", class);
2398 return io->u.Status = STATUS_NOT_IMPLEMENTED;
2400 if (len < info_sizes[class])
2401 return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
2403 if (class != FilePipeInformation && class != FilePipeLocalInformation)
2405 if ((io->u.Status = server_get_unix_fd( hFile, 0, &fd, &needs_close, NULL, NULL )))
2406 return io->u.Status;
2409 switch (class)
2411 case FileBasicInformation:
2412 if (fd_get_file_info( fd, &st, &attr ) == -1)
2413 io->u.Status = FILE_GetNtStatus();
2414 else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
2415 io->u.Status = STATUS_INVALID_INFO_CLASS;
2416 else
2417 fill_file_info( &st, attr, ptr, class );
2418 break;
2419 case FileStandardInformation:
2421 FILE_STANDARD_INFORMATION *info = ptr;
2423 if (fd_get_file_info( fd, &st, &attr ) == -1) io->u.Status = FILE_GetNtStatus();
2424 else
2426 fill_file_info( &st, attr, info, class );
2427 info->DeletePending = FALSE; /* FIXME */
2430 break;
2431 case FilePositionInformation:
2433 FILE_POSITION_INFORMATION *info = ptr;
2434 off_t res = lseek( fd, 0, SEEK_CUR );
2435 if (res == (off_t)-1) io->u.Status = FILE_GetNtStatus();
2436 else info->CurrentByteOffset.QuadPart = res;
2438 break;
2439 case FileInternalInformation:
2440 if (fd_get_file_info( fd, &st, &attr ) == -1) io->u.Status = FILE_GetNtStatus();
2441 else fill_file_info( &st, attr, ptr, class );
2442 break;
2443 case FileEaInformation:
2445 FILE_EA_INFORMATION *info = ptr;
2446 info->EaSize = 0;
2448 break;
2449 case FileEndOfFileInformation:
2450 if (fd_get_file_info( fd, &st, &attr ) == -1) io->u.Status = FILE_GetNtStatus();
2451 else fill_file_info( &st, attr, ptr, class );
2452 break;
2453 case FileAllInformation:
2455 FILE_ALL_INFORMATION *info = ptr;
2456 ANSI_STRING unix_name;
2458 if (fd_get_file_info( fd, &st, &attr ) == -1) io->u.Status = FILE_GetNtStatus();
2459 else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
2460 io->u.Status = STATUS_INVALID_INFO_CLASS;
2461 else if (!(io->u.Status = server_get_unix_name( hFile, &unix_name )))
2463 LONG name_len = len - FIELD_OFFSET(FILE_ALL_INFORMATION, NameInformation.FileName);
2465 fill_file_info( &st, attr, info, FileAllInformation );
2466 info->StandardInformation.DeletePending = FALSE; /* FIXME */
2467 info->EaInformation.EaSize = 0;
2468 info->AccessInformation.AccessFlags = 0; /* FIXME */
2469 info->PositionInformation.CurrentByteOffset.QuadPart = lseek( fd, 0, SEEK_CUR );
2470 info->ModeInformation.Mode = 0; /* FIXME */
2471 info->AlignmentInformation.AlignmentRequirement = 1; /* FIXME */
2473 io->u.Status = fill_name_info( &unix_name, &info->NameInformation, &name_len );
2474 RtlFreeAnsiString( &unix_name );
2475 io->Information = FIELD_OFFSET(FILE_ALL_INFORMATION, NameInformation.FileName) + name_len;
2478 break;
2479 case FileMailslotQueryInformation:
2481 FILE_MAILSLOT_QUERY_INFORMATION *info = ptr;
2483 SERVER_START_REQ( set_mailslot_info )
2485 req->handle = wine_server_obj_handle( hFile );
2486 req->flags = 0;
2487 io->u.Status = wine_server_call( req );
2488 if( io->u.Status == STATUS_SUCCESS )
2490 info->MaximumMessageSize = reply->max_msgsize;
2491 info->MailslotQuota = 0;
2492 info->NextMessageSize = 0;
2493 info->MessagesAvailable = 0;
2494 info->ReadTimeout.QuadPart = reply->read_timeout;
2497 SERVER_END_REQ;
2498 if (!io->u.Status)
2500 char *tmpbuf;
2501 ULONG size = info->MaximumMessageSize ? info->MaximumMessageSize : 0x10000;
2502 if (size > 0x10000) size = 0x10000;
2503 if ((tmpbuf = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2505 if (!server_get_unix_fd( hFile, FILE_READ_DATA, &fd, &needs_close, NULL, NULL ))
2507 int res = recv( fd, tmpbuf, size, MSG_PEEK );
2508 info->MessagesAvailable = (res > 0);
2509 info->NextMessageSize = (res >= 0) ? res : MAILSLOT_NO_MESSAGE;
2510 if (needs_close) close( fd );
2512 RtlFreeHeap( GetProcessHeap(), 0, tmpbuf );
2516 break;
2517 case FilePipeInformation:
2519 FILE_PIPE_INFORMATION* pi = ptr;
2521 SERVER_START_REQ( get_named_pipe_info )
2523 req->handle = wine_server_obj_handle( hFile );
2524 if (!(io->u.Status = wine_server_call( req )))
2526 pi->ReadMode = (reply->flags & NAMED_PIPE_MESSAGE_STREAM_READ) ?
2527 FILE_PIPE_MESSAGE_MODE : FILE_PIPE_BYTE_STREAM_MODE;
2528 pi->CompletionMode = (reply->flags & NAMED_PIPE_NONBLOCKING_MODE) ?
2529 FILE_PIPE_COMPLETE_OPERATION : FILE_PIPE_QUEUE_OPERATION;
2532 SERVER_END_REQ;
2534 break;
2535 case FilePipeLocalInformation:
2537 FILE_PIPE_LOCAL_INFORMATION* pli = ptr;
2539 SERVER_START_REQ( get_named_pipe_info )
2541 req->handle = wine_server_obj_handle( hFile );
2542 if (!(io->u.Status = wine_server_call( req )))
2544 pli->NamedPipeType = (reply->flags & NAMED_PIPE_MESSAGE_STREAM_WRITE) ?
2545 FILE_PIPE_TYPE_MESSAGE : FILE_PIPE_TYPE_BYTE;
2546 switch (reply->sharing)
2548 case FILE_SHARE_READ:
2549 pli->NamedPipeConfiguration = FILE_PIPE_OUTBOUND;
2550 break;
2551 case FILE_SHARE_WRITE:
2552 pli->NamedPipeConfiguration = FILE_PIPE_INBOUND;
2553 break;
2554 case FILE_SHARE_READ | FILE_SHARE_WRITE:
2555 pli->NamedPipeConfiguration = FILE_PIPE_FULL_DUPLEX;
2556 break;
2558 pli->MaximumInstances = reply->maxinstances;
2559 pli->CurrentInstances = reply->instances;
2560 pli->InboundQuota = reply->insize;
2561 pli->ReadDataAvailable = 0; /* FIXME */
2562 pli->OutboundQuota = reply->outsize;
2563 pli->WriteQuotaAvailable = 0; /* FIXME */
2564 pli->NamedPipeState = 0; /* FIXME */
2565 pli->NamedPipeEnd = (reply->flags & NAMED_PIPE_SERVER_END) ?
2566 FILE_PIPE_SERVER_END : FILE_PIPE_CLIENT_END;
2569 SERVER_END_REQ;
2571 break;
2572 case FileNameInformation:
2574 FILE_NAME_INFORMATION *info = ptr;
2575 ANSI_STRING unix_name;
2577 if (!(io->u.Status = server_get_unix_name( hFile, &unix_name )))
2579 LONG name_len = len - FIELD_OFFSET(FILE_NAME_INFORMATION, FileName);
2580 io->u.Status = fill_name_info( &unix_name, info, &name_len );
2581 RtlFreeAnsiString( &unix_name );
2582 io->Information = FIELD_OFFSET(FILE_NAME_INFORMATION, FileName) + name_len;
2585 break;
2586 case FileNetworkOpenInformation:
2588 FILE_NETWORK_OPEN_INFORMATION *info = ptr;
2589 ANSI_STRING unix_name;
2591 if (!(io->u.Status = server_get_unix_name( hFile, &unix_name )))
2593 ULONG attributes;
2594 struct stat st;
2596 if (get_file_info( unix_name.Buffer, &st, &attributes ) == -1)
2597 io->u.Status = FILE_GetNtStatus();
2598 else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
2599 io->u.Status = STATUS_INVALID_INFO_CLASS;
2600 else
2602 FILE_BASIC_INFORMATION basic;
2603 FILE_STANDARD_INFORMATION std;
2605 fill_file_info( &st, attributes, &basic, FileBasicInformation );
2606 fill_file_info( &st, attributes, &std, FileStandardInformation );
2608 info->CreationTime = basic.CreationTime;
2609 info->LastAccessTime = basic.LastAccessTime;
2610 info->LastWriteTime = basic.LastWriteTime;
2611 info->ChangeTime = basic.ChangeTime;
2612 info->AllocationSize = std.AllocationSize;
2613 info->EndOfFile = std.EndOfFile;
2614 info->FileAttributes = basic.FileAttributes;
2616 RtlFreeAnsiString( &unix_name );
2619 break;
2620 case FileIdInformation:
2621 if (fd_get_file_info( fd, &st, &attr ) == -1) io->u.Status = FILE_GetNtStatus();
2622 else
2624 FILE_ID_INFORMATION *info = ptr;
2625 info->VolumeSerialNumber = 0; /* FIXME */
2626 memset( &info->FileId, 0, sizeof(info->FileId) );
2627 *(ULONGLONG *)&info->FileId = st.st_ino;
2629 break;
2630 default:
2631 FIXME("Unsupported class (%d)\n", class);
2632 io->u.Status = STATUS_NOT_IMPLEMENTED;
2633 break;
2635 if (needs_close) close( fd );
2636 if (io->u.Status == STATUS_SUCCESS && !io->Information) io->Information = info_sizes[class];
2637 return io->u.Status;
2640 /******************************************************************************
2641 * NtSetInformationFile [NTDLL.@]
2642 * ZwSetInformationFile [NTDLL.@]
2644 * Set information about an open file handle.
2646 * PARAMS
2647 * handle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
2648 * io [O] Receives information about the operation on return
2649 * ptr [I] Source for file information
2650 * len [I] Size of FileInformation
2651 * class [I] Type of file information to set
2653 * RETURNS
2654 * Success: 0. io is updated.
2655 * Failure: An NTSTATUS error code describing the error.
2657 NTSTATUS WINAPI NtSetInformationFile(HANDLE handle, PIO_STATUS_BLOCK io,
2658 PVOID ptr, ULONG len, FILE_INFORMATION_CLASS class)
2660 int fd, needs_close;
2662 TRACE("(%p,%p,%p,0x%08x,0x%08x)\n", handle, io, ptr, len, class);
2664 io->u.Status = STATUS_SUCCESS;
2665 switch (class)
2667 case FileBasicInformation:
2668 if (len >= sizeof(FILE_BASIC_INFORMATION))
2670 struct stat st;
2671 const FILE_BASIC_INFORMATION *info = ptr;
2673 if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
2674 return io->u.Status;
2676 if (info->LastAccessTime.QuadPart || info->LastWriteTime.QuadPart)
2677 io->u.Status = set_file_times( fd, &info->LastWriteTime, &info->LastAccessTime );
2679 if (io->u.Status == STATUS_SUCCESS && info->FileAttributes)
2681 if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
2682 else
2684 if (info->FileAttributes & FILE_ATTRIBUTE_READONLY)
2686 if (S_ISDIR( st.st_mode))
2687 WARN("FILE_ATTRIBUTE_READONLY ignored for directory.\n");
2688 else
2689 st.st_mode &= ~0222; /* clear write permission bits */
2691 else
2693 /* add write permission only where we already have read permission */
2694 st.st_mode |= (0600 | ((st.st_mode & 044) >> 1)) & (~FILE_umask);
2696 if (fchmod( fd, st.st_mode ) == -1) io->u.Status = FILE_GetNtStatus();
2700 if (needs_close) close( fd );
2702 else io->u.Status = STATUS_INVALID_PARAMETER_3;
2703 break;
2705 case FilePositionInformation:
2706 if (len >= sizeof(FILE_POSITION_INFORMATION))
2708 const FILE_POSITION_INFORMATION *info = ptr;
2710 if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
2711 return io->u.Status;
2713 if (lseek( fd, info->CurrentByteOffset.QuadPart, SEEK_SET ) == (off_t)-1)
2714 io->u.Status = FILE_GetNtStatus();
2716 if (needs_close) close( fd );
2718 else io->u.Status = STATUS_INVALID_PARAMETER_3;
2719 break;
2721 case FileEndOfFileInformation:
2722 if (len >= sizeof(FILE_END_OF_FILE_INFORMATION))
2724 struct stat st;
2725 const FILE_END_OF_FILE_INFORMATION *info = ptr;
2727 if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
2728 return io->u.Status;
2730 /* first try normal truncate */
2731 if (ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
2733 /* now check for the need to extend the file */
2734 if (fstat( fd, &st ) != -1 && (off_t)info->EndOfFile.QuadPart > st.st_size)
2736 static const char zero;
2738 /* extend the file one byte beyond the requested size and then truncate it */
2739 /* this should work around ftruncate implementations that can't extend files */
2740 if (pwrite( fd, &zero, 1, (off_t)info->EndOfFile.QuadPart ) != -1 &&
2741 ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
2743 io->u.Status = FILE_GetNtStatus();
2745 if (needs_close) close( fd );
2747 else io->u.Status = STATUS_INVALID_PARAMETER_3;
2748 break;
2750 case FilePipeInformation:
2751 if (len >= sizeof(FILE_PIPE_INFORMATION))
2753 FILE_PIPE_INFORMATION *info = ptr;
2755 if ((info->CompletionMode | info->ReadMode) & ~1)
2757 io->u.Status = STATUS_INVALID_PARAMETER;
2758 break;
2761 SERVER_START_REQ( set_named_pipe_info )
2763 req->handle = wine_server_obj_handle( handle );
2764 req->flags = (info->CompletionMode ? NAMED_PIPE_NONBLOCKING_MODE : 0) |
2765 (info->ReadMode ? NAMED_PIPE_MESSAGE_STREAM_READ : 0);
2766 io->u.Status = wine_server_call( req );
2768 SERVER_END_REQ;
2770 else io->u.Status = STATUS_INVALID_PARAMETER_3;
2771 break;
2773 case FileMailslotSetInformation:
2775 FILE_MAILSLOT_SET_INFORMATION *info = ptr;
2777 SERVER_START_REQ( set_mailslot_info )
2779 req->handle = wine_server_obj_handle( handle );
2780 req->flags = MAILSLOT_SET_READ_TIMEOUT;
2781 req->read_timeout = info->ReadTimeout.QuadPart;
2782 io->u.Status = wine_server_call( req );
2784 SERVER_END_REQ;
2786 break;
2788 case FileCompletionInformation:
2789 if (len >= sizeof(FILE_COMPLETION_INFORMATION))
2791 FILE_COMPLETION_INFORMATION *info = ptr;
2793 SERVER_START_REQ( set_completion_info )
2795 req->handle = wine_server_obj_handle( handle );
2796 req->chandle = wine_server_obj_handle( info->CompletionPort );
2797 req->ckey = info->CompletionKey;
2798 io->u.Status = wine_server_call( req );
2800 SERVER_END_REQ;
2801 } else
2802 io->u.Status = STATUS_INVALID_PARAMETER_3;
2803 break;
2805 case FileAllInformation:
2806 io->u.Status = STATUS_INVALID_INFO_CLASS;
2807 break;
2809 case FileValidDataLengthInformation:
2810 if (len >= sizeof(FILE_VALID_DATA_LENGTH_INFORMATION))
2812 struct stat st;
2813 const FILE_VALID_DATA_LENGTH_INFORMATION *info = ptr;
2815 if ((io->u.Status = server_get_unix_fd( handle, FILE_WRITE_DATA, &fd, &needs_close, NULL, NULL )))
2816 return io->u.Status;
2818 if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
2819 else if (info->ValidDataLength.QuadPart <= 0 || (off_t)info->ValidDataLength.QuadPart > st.st_size)
2820 io->u.Status = STATUS_INVALID_PARAMETER;
2821 else
2823 #ifdef HAVE_FALLOCATE
2824 if (fallocate( fd, 0, 0, (off_t)info->ValidDataLength.QuadPart ) == -1)
2826 NTSTATUS status = FILE_GetNtStatus();
2827 if (status == STATUS_NOT_SUPPORTED) WARN( "fallocate not supported on this filesystem\n" );
2828 else io->u.Status = status;
2830 #else
2831 FIXME( "setting valid data length not supported\n" );
2832 #endif
2834 if (needs_close) close( fd );
2836 else io->u.Status = STATUS_INVALID_PARAMETER_3;
2837 break;
2839 case FileDispositionInformation:
2840 if (len >= sizeof(FILE_DISPOSITION_INFORMATION))
2842 FILE_DISPOSITION_INFORMATION *info = ptr;
2844 SERVER_START_REQ( set_fd_disp_info )
2846 req->handle = wine_server_obj_handle( handle );
2847 req->unlink = info->DoDeleteFile;
2848 io->u.Status = wine_server_call( req );
2850 SERVER_END_REQ;
2851 } else
2852 io->u.Status = STATUS_INVALID_PARAMETER_3;
2853 break;
2855 case FileRenameInformation:
2856 if (len >= sizeof(FILE_RENAME_INFORMATION))
2858 FILE_RENAME_INFORMATION *info = ptr;
2859 UNICODE_STRING name_str;
2860 OBJECT_ATTRIBUTES attr;
2861 ANSI_STRING unix_name;
2863 name_str.Buffer = info->FileName;
2864 name_str.Length = info->FileNameLength;
2865 name_str.MaximumLength = info->FileNameLength + sizeof(WCHAR);
2867 attr.Length = sizeof(attr);
2868 attr.ObjectName = &name_str;
2869 attr.RootDirectory = info->RootDir;
2870 attr.Attributes = OBJ_CASE_INSENSITIVE;
2872 io->u.Status = nt_to_unix_file_name_attr( &attr, &unix_name, FILE_OPEN_IF );
2873 if (io->u.Status != STATUS_SUCCESS && io->u.Status != STATUS_NO_SUCH_FILE)
2874 break;
2876 if (!info->Replace && io->u.Status == STATUS_SUCCESS)
2878 RtlFreeAnsiString( &unix_name );
2879 io->u.Status = STATUS_OBJECT_NAME_COLLISION;
2880 break;
2883 SERVER_START_REQ( set_fd_name_info )
2885 req->handle = wine_server_obj_handle( handle );
2886 req->rootdir = wine_server_obj_handle( attr.RootDirectory );
2887 req->link = FALSE;
2888 wine_server_add_data( req, unix_name.Buffer, unix_name.Length );
2889 io->u.Status = wine_server_call( req );
2891 SERVER_END_REQ;
2893 RtlFreeAnsiString( &unix_name );
2895 else io->u.Status = STATUS_INVALID_PARAMETER_3;
2896 break;
2898 case FileLinkInformation:
2899 if (len >= sizeof(FILE_LINK_INFORMATION))
2901 FILE_LINK_INFORMATION *info = ptr;
2902 UNICODE_STRING name_str;
2903 OBJECT_ATTRIBUTES attr;
2904 ANSI_STRING unix_name;
2906 name_str.Buffer = info->FileName;
2907 name_str.Length = info->FileNameLength;
2908 name_str.MaximumLength = info->FileNameLength + sizeof(WCHAR);
2910 attr.Length = sizeof(attr);
2911 attr.ObjectName = &name_str;
2912 attr.RootDirectory = info->RootDirectory;
2913 attr.Attributes = OBJ_CASE_INSENSITIVE;
2915 io->u.Status = nt_to_unix_file_name_attr( &attr, &unix_name, FILE_OPEN_IF );
2916 if (io->u.Status != STATUS_SUCCESS && io->u.Status != STATUS_NO_SUCH_FILE)
2917 break;
2919 if (!info->ReplaceIfExists && io->u.Status == STATUS_SUCCESS)
2921 RtlFreeAnsiString( &unix_name );
2922 io->u.Status = STATUS_OBJECT_NAME_COLLISION;
2923 break;
2926 SERVER_START_REQ( set_fd_name_info )
2928 req->handle = wine_server_obj_handle( handle );
2929 req->rootdir = wine_server_obj_handle( attr.RootDirectory );
2930 req->link = TRUE;
2931 wine_server_add_data( req, unix_name.Buffer, unix_name.Length );
2932 io->u.Status = wine_server_call( req );
2934 SERVER_END_REQ;
2936 RtlFreeAnsiString( &unix_name );
2938 else io->u.Status = STATUS_INVALID_PARAMETER_3;
2939 break;
2941 default:
2942 FIXME("Unsupported class (%d)\n", class);
2943 io->u.Status = STATUS_NOT_IMPLEMENTED;
2944 break;
2946 io->Information = 0;
2947 return io->u.Status;
2951 /******************************************************************************
2952 * NtQueryFullAttributesFile (NTDLL.@)
2954 NTSTATUS WINAPI NtQueryFullAttributesFile( const OBJECT_ATTRIBUTES *attr,
2955 FILE_NETWORK_OPEN_INFORMATION *info )
2957 ANSI_STRING unix_name;
2958 NTSTATUS status;
2960 if (!(status = nt_to_unix_file_name_attr( attr, &unix_name, FILE_OPEN )))
2962 ULONG attributes;
2963 struct stat st;
2965 if (get_file_info( unix_name.Buffer, &st, &attributes ) == -1)
2966 status = FILE_GetNtStatus();
2967 else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
2968 status = STATUS_INVALID_INFO_CLASS;
2969 else
2971 FILE_BASIC_INFORMATION basic;
2972 FILE_STANDARD_INFORMATION std;
2974 fill_file_info( &st, attributes, &basic, FileBasicInformation );
2975 fill_file_info( &st, attributes, &std, FileStandardInformation );
2977 info->CreationTime = basic.CreationTime;
2978 info->LastAccessTime = basic.LastAccessTime;
2979 info->LastWriteTime = basic.LastWriteTime;
2980 info->ChangeTime = basic.ChangeTime;
2981 info->AllocationSize = std.AllocationSize;
2982 info->EndOfFile = std.EndOfFile;
2983 info->FileAttributes = basic.FileAttributes;
2984 if (DIR_is_hidden_file( attr->ObjectName ))
2985 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
2987 RtlFreeAnsiString( &unix_name );
2989 else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), status );
2990 return status;
2994 /******************************************************************************
2995 * NtQueryAttributesFile (NTDLL.@)
2996 * ZwQueryAttributesFile (NTDLL.@)
2998 NTSTATUS WINAPI NtQueryAttributesFile( const OBJECT_ATTRIBUTES *attr, FILE_BASIC_INFORMATION *info )
3000 ANSI_STRING unix_name;
3001 NTSTATUS status;
3003 if (!(status = nt_to_unix_file_name_attr( attr, &unix_name, FILE_OPEN )))
3005 ULONG attributes;
3006 struct stat st;
3008 if (get_file_info( unix_name.Buffer, &st, &attributes ) == -1)
3009 status = FILE_GetNtStatus();
3010 else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
3011 status = STATUS_INVALID_INFO_CLASS;
3012 else
3014 status = fill_file_info( &st, attributes, info, FileBasicInformation );
3015 if (DIR_is_hidden_file( attr->ObjectName ))
3016 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
3018 RtlFreeAnsiString( &unix_name );
3020 else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), status );
3021 return status;
3025 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
3026 /* helper for FILE_GetDeviceInfo to hide some platform differences in fstatfs */
3027 static inline void get_device_info_fstatfs( FILE_FS_DEVICE_INFORMATION *info, const char *fstypename,
3028 unsigned int flags )
3030 if (!strcmp("cd9660", fstypename) || !strcmp("udf", fstypename))
3032 info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
3033 /* Don't assume read-only, let the mount options set it below */
3034 info->Characteristics |= FILE_REMOVABLE_MEDIA;
3036 else if (!strcmp("nfs", fstypename) || !strcmp("nwfs", fstypename) ||
3037 !strcmp("smbfs", fstypename) || !strcmp("afpfs", fstypename))
3039 info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
3040 info->Characteristics |= FILE_REMOTE_DEVICE;
3042 else if (!strcmp("procfs", fstypename))
3043 info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
3044 else
3045 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
3047 if (flags & MNT_RDONLY)
3048 info->Characteristics |= FILE_READ_ONLY_DEVICE;
3050 if (!(flags & MNT_LOCAL))
3052 info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
3053 info->Characteristics |= FILE_REMOTE_DEVICE;
3056 #endif
3058 static inline BOOL is_device_placeholder( int fd )
3060 static const char wine_placeholder[] = "Wine device placeholder";
3061 char buffer[sizeof(wine_placeholder)-1];
3063 if (pread( fd, buffer, sizeof(wine_placeholder) - 1, 0 ) != sizeof(wine_placeholder) - 1)
3064 return FALSE;
3065 return !memcmp( buffer, wine_placeholder, sizeof(wine_placeholder) - 1 );
3068 /******************************************************************************
3069 * get_device_info
3071 * Implementation of the FileFsDeviceInformation query for NtQueryVolumeInformationFile.
3073 static NTSTATUS get_device_info( int fd, FILE_FS_DEVICE_INFORMATION *info )
3075 struct stat st;
3077 info->Characteristics = 0;
3078 if (fstat( fd, &st ) < 0) return FILE_GetNtStatus();
3079 if (S_ISCHR( st.st_mode ))
3081 info->DeviceType = FILE_DEVICE_UNKNOWN;
3082 #ifdef linux
3083 switch(major(st.st_rdev))
3085 case MEM_MAJOR:
3086 info->DeviceType = FILE_DEVICE_NULL;
3087 break;
3088 case TTY_MAJOR:
3089 info->DeviceType = FILE_DEVICE_SERIAL_PORT;
3090 break;
3091 case LP_MAJOR:
3092 info->DeviceType = FILE_DEVICE_PARALLEL_PORT;
3093 break;
3094 case SCSI_TAPE_MAJOR:
3095 info->DeviceType = FILE_DEVICE_TAPE;
3096 break;
3098 #endif
3100 else if (S_ISBLK( st.st_mode ))
3102 info->DeviceType = FILE_DEVICE_DISK;
3104 else if (S_ISFIFO( st.st_mode ) || S_ISSOCK( st.st_mode ))
3106 info->DeviceType = FILE_DEVICE_NAMED_PIPE;
3108 else if (is_device_placeholder( fd ))
3110 info->DeviceType = FILE_DEVICE_DISK;
3112 else /* regular file or directory */
3114 #if defined(linux) && defined(HAVE_FSTATFS)
3115 struct statfs stfs;
3117 /* check for floppy disk */
3118 if (major(st.st_dev) == FLOPPY_MAJOR)
3119 info->Characteristics |= FILE_REMOVABLE_MEDIA;
3121 if (fstatfs( fd, &stfs ) < 0) stfs.f_type = 0;
3122 switch (stfs.f_type)
3124 case 0x9660: /* iso9660 */
3125 case 0x9fa1: /* supermount */
3126 case 0x15013346: /* udf */
3127 info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
3128 info->Characteristics |= FILE_REMOVABLE_MEDIA|FILE_READ_ONLY_DEVICE;
3129 break;
3130 case 0x6969: /* nfs */
3131 case 0x517B: /* smbfs */
3132 case 0x564c: /* ncpfs */
3133 info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
3134 info->Characteristics |= FILE_REMOTE_DEVICE;
3135 break;
3136 case 0x01021994: /* tmpfs */
3137 case 0x28cd3d45: /* cramfs */
3138 case 0x1373: /* devfs */
3139 case 0x9fa0: /* procfs */
3140 info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
3141 break;
3142 default:
3143 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
3144 break;
3146 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
3147 struct statfs stfs;
3149 if (fstatfs( fd, &stfs ) < 0)
3150 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
3151 else
3152 get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flags );
3153 #elif defined(__NetBSD__)
3154 struct statvfs stfs;
3156 if (fstatvfs( fd, &stfs) < 0)
3157 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
3158 else
3159 get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flag );
3160 #elif defined(sun)
3161 /* Use dkio to work out device types */
3163 # include <sys/dkio.h>
3164 # include <sys/vtoc.h>
3165 struct dk_cinfo dkinf;
3166 int retval = ioctl(fd, DKIOCINFO, &dkinf);
3167 if(retval==-1){
3168 WARN("Unable to get disk device type information - assuming a disk like device\n");
3169 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
3171 switch (dkinf.dki_ctype)
3173 case DKC_CDROM:
3174 info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
3175 info->Characteristics |= FILE_REMOVABLE_MEDIA|FILE_READ_ONLY_DEVICE;
3176 break;
3177 case DKC_NCRFLOPPY:
3178 case DKC_SMSFLOPPY:
3179 case DKC_INTEL82072:
3180 case DKC_INTEL82077:
3181 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
3182 info->Characteristics |= FILE_REMOVABLE_MEDIA;
3183 break;
3184 case DKC_MD:
3185 info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
3186 break;
3187 default:
3188 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
3191 #else
3192 static int warned;
3193 if (!warned++) FIXME( "device info not properly supported on this platform\n" );
3194 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
3195 #endif
3196 info->Characteristics |= FILE_DEVICE_IS_MOUNTED;
3198 return STATUS_SUCCESS;
3202 /******************************************************************************
3203 * NtQueryVolumeInformationFile [NTDLL.@]
3204 * ZwQueryVolumeInformationFile [NTDLL.@]
3206 * Get volume information for an open file handle.
3208 * PARAMS
3209 * handle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
3210 * io [O] Receives information about the operation on return
3211 * buffer [O] Destination for volume information
3212 * length [I] Size of FsInformation
3213 * info_class [I] Type of volume information to set
3215 * RETURNS
3216 * Success: 0. io and buffer are updated.
3217 * Failure: An NTSTATUS error code describing the error.
3219 NTSTATUS WINAPI NtQueryVolumeInformationFile( HANDLE handle, PIO_STATUS_BLOCK io,
3220 PVOID buffer, ULONG length,
3221 FS_INFORMATION_CLASS info_class )
3223 int fd, needs_close;
3224 struct stat st;
3225 static int once;
3227 if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
3228 return io->u.Status;
3230 io->u.Status = STATUS_NOT_IMPLEMENTED;
3231 io->Information = 0;
3233 switch( info_class )
3235 case FileFsVolumeInformation:
3236 if (!once++) FIXME( "%p: volume info not supported\n", handle );
3237 break;
3238 case FileFsLabelInformation:
3239 FIXME( "%p: label info not supported\n", handle );
3240 break;
3241 case FileFsSizeInformation:
3242 if (length < sizeof(FILE_FS_SIZE_INFORMATION))
3243 io->u.Status = STATUS_BUFFER_TOO_SMALL;
3244 else
3246 FILE_FS_SIZE_INFORMATION *info = buffer;
3248 if (fstat( fd, &st ) < 0)
3250 io->u.Status = FILE_GetNtStatus();
3251 break;
3253 if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
3255 io->u.Status = STATUS_INVALID_DEVICE_REQUEST;
3257 else
3259 ULONGLONG bsize;
3260 /* Linux's fstatvfs is buggy */
3261 #if !defined(linux) || !defined(HAVE_FSTATFS)
3262 struct statvfs stfs;
3264 if (fstatvfs( fd, &stfs ) < 0)
3266 io->u.Status = FILE_GetNtStatus();
3267 break;
3269 bsize = stfs.f_frsize;
3270 #else
3271 struct statfs stfs;
3272 if (fstatfs( fd, &stfs ) < 0)
3274 io->u.Status = FILE_GetNtStatus();
3275 break;
3277 bsize = stfs.f_bsize;
3278 #endif
3279 if (bsize == 2048) /* assume CD-ROM */
3281 info->BytesPerSector = 2048;
3282 info->SectorsPerAllocationUnit = 1;
3284 else
3286 info->BytesPerSector = 512;
3287 info->SectorsPerAllocationUnit = 8;
3289 info->TotalAllocationUnits.QuadPart = bsize * stfs.f_blocks / (info->BytesPerSector * info->SectorsPerAllocationUnit);
3290 info->AvailableAllocationUnits.QuadPart = bsize * stfs.f_bavail / (info->BytesPerSector * info->SectorsPerAllocationUnit);
3291 io->Information = sizeof(*info);
3292 io->u.Status = STATUS_SUCCESS;
3295 break;
3296 case FileFsDeviceInformation:
3297 if (length < sizeof(FILE_FS_DEVICE_INFORMATION))
3298 io->u.Status = STATUS_BUFFER_TOO_SMALL;
3299 else
3301 FILE_FS_DEVICE_INFORMATION *info = buffer;
3303 if ((io->u.Status = get_device_info( fd, info )) == STATUS_SUCCESS)
3304 io->Information = sizeof(*info);
3306 break;
3307 case FileFsAttributeInformation:
3308 if (length < offsetof( FILE_FS_ATTRIBUTE_INFORMATION, FileSystemName[sizeof(ntfsW)/sizeof(WCHAR)] ))
3309 io->u.Status = STATUS_BUFFER_TOO_SMALL;
3310 else
3312 FILE_FS_ATTRIBUTE_INFORMATION *info = buffer;
3314 FIXME( "%p: faking attribute info\n", handle );
3315 info->FileSystemAttribute = FILE_SUPPORTS_ENCRYPTION | FILE_FILE_COMPRESSION |
3316 FILE_PERSISTENT_ACLS | FILE_UNICODE_ON_DISK |
3317 FILE_CASE_PRESERVED_NAMES | FILE_CASE_SENSITIVE_SEARCH;
3318 info->MaximumComponentNameLength = MAXIMUM_FILENAME_LENGTH - 1;
3319 info->FileSystemNameLength = sizeof(ntfsW);
3320 memcpy(info->FileSystemName, ntfsW, sizeof(ntfsW));
3322 io->Information = sizeof(*info);
3323 io->u.Status = STATUS_SUCCESS;
3325 break;
3326 case FileFsControlInformation:
3327 FIXME( "%p: control info not supported\n", handle );
3328 break;
3329 case FileFsFullSizeInformation:
3330 FIXME( "%p: full size info not supported\n", handle );
3331 break;
3332 case FileFsObjectIdInformation:
3333 FIXME( "%p: object id info not supported\n", handle );
3334 break;
3335 case FileFsMaximumInformation:
3336 FIXME( "%p: maximum info not supported\n", handle );
3337 break;
3338 default:
3339 io->u.Status = STATUS_INVALID_PARAMETER;
3340 break;
3342 if (needs_close) close( fd );
3343 return io->u.Status;
3347 /******************************************************************
3348 * NtQueryEaFile (NTDLL.@)
3350 * Read extended attributes from NTFS files.
3352 * PARAMS
3353 * hFile [I] File handle, must be opened with FILE_READ_EA access
3354 * iosb [O] Receives information about the operation on return
3355 * buffer [O] Output buffer
3356 * length [I] Length of output buffer
3357 * single_entry [I] Only read and return one entry
3358 * ea_list [I] Optional list with names of EAs to return
3359 * ea_list_len [I] Length of ea_list in bytes
3360 * ea_index [I] Optional pointer to 1-based index of attribute to return
3361 * restart [I] restart EA scan
3363 * RETURNS
3364 * Success: 0. Atrributes read into buffer
3365 * Failure: An NTSTATUS error code describing the error.
3367 NTSTATUS WINAPI NtQueryEaFile( HANDLE hFile, PIO_STATUS_BLOCK iosb, PVOID buffer, ULONG length,
3368 BOOLEAN single_entry, PVOID ea_list, ULONG ea_list_len,
3369 PULONG ea_index, BOOLEAN restart )
3371 FIXME("(%p,%p,%p,%d,%d,%p,%d,%p,%d) stub\n",
3372 hFile, iosb, buffer, length, single_entry, ea_list,
3373 ea_list_len, ea_index, restart);
3374 return STATUS_ACCESS_DENIED;
3378 /******************************************************************
3379 * NtSetEaFile (NTDLL.@)
3381 * Update extended attributes for NTFS files.
3383 * PARAMS
3384 * hFile [I] File handle, must be opened with FILE_READ_EA access
3385 * iosb [O] Receives information about the operation on return
3386 * buffer [I] Buffer with EA information
3387 * length [I] Length of buffer
3389 * RETURNS
3390 * Success: 0. Attributes are updated
3391 * Failure: An NTSTATUS error code describing the error.
3393 NTSTATUS WINAPI NtSetEaFile( HANDLE hFile, PIO_STATUS_BLOCK iosb, PVOID buffer, ULONG length )
3395 FIXME("(%p,%p,%p,%d) stub\n", hFile, iosb, buffer, length);
3396 return STATUS_ACCESS_DENIED;
3400 /******************************************************************
3401 * NtFlushBuffersFile (NTDLL.@)
3403 * Flush any buffered data on an open file handle.
3405 * PARAMS
3406 * FileHandle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
3407 * IoStatusBlock [O] Receives information about the operation on return
3409 * RETURNS
3410 * Success: 0. IoStatusBlock is updated.
3411 * Failure: An NTSTATUS error code describing the error.
3413 NTSTATUS WINAPI NtFlushBuffersFile( HANDLE hFile, IO_STATUS_BLOCK* IoStatusBlock )
3415 NTSTATUS ret;
3416 HANDLE hEvent = NULL;
3417 enum server_fd_type type;
3418 int fd, needs_close;
3420 ret = server_get_unix_fd( hFile, FILE_WRITE_DATA, &fd, &needs_close, &type, NULL );
3422 if (!ret && type == FD_TYPE_SERIAL)
3424 ret = COMM_FlushBuffersFile( fd );
3426 else
3428 SERVER_START_REQ( flush )
3430 req->blocking = 1; /* always blocking */
3431 req->async.handle = wine_server_obj_handle( hFile );
3432 req->async.iosb = wine_server_client_ptr( IoStatusBlock );
3433 ret = wine_server_call( req );
3434 hEvent = wine_server_ptr_handle( reply->event );
3436 SERVER_END_REQ;
3438 if (hEvent)
3440 NtWaitForSingleObject( hEvent, FALSE, NULL );
3441 NtClose( hEvent );
3442 ret = STATUS_SUCCESS;
3446 if (needs_close) close( fd );
3447 return ret;
3450 /******************************************************************
3451 * NtLockFile (NTDLL.@)
3455 NTSTATUS WINAPI NtLockFile( HANDLE hFile, HANDLE lock_granted_event,
3456 PIO_APC_ROUTINE apc, void* apc_user,
3457 PIO_STATUS_BLOCK io_status, PLARGE_INTEGER offset,
3458 PLARGE_INTEGER count, ULONG* key, BOOLEAN dont_wait,
3459 BOOLEAN exclusive )
3461 NTSTATUS ret;
3462 HANDLE handle;
3463 BOOLEAN async;
3464 static BOOLEAN warn = TRUE;
3466 if (apc || io_status || key)
3468 FIXME("Unimplemented yet parameter\n");
3469 return STATUS_NOT_IMPLEMENTED;
3472 if (apc_user && warn)
3474 FIXME("I/O completion on lock not implemented yet\n");
3475 warn = FALSE;
3478 for (;;)
3480 SERVER_START_REQ( lock_file )
3482 req->handle = wine_server_obj_handle( hFile );
3483 req->offset = offset->QuadPart;
3484 req->count = count->QuadPart;
3485 req->shared = !exclusive;
3486 req->wait = !dont_wait;
3487 ret = wine_server_call( req );
3488 handle = wine_server_ptr_handle( reply->handle );
3489 async = reply->overlapped;
3491 SERVER_END_REQ;
3492 if (ret != STATUS_PENDING)
3494 if (!ret && lock_granted_event) NtSetEvent(lock_granted_event, NULL);
3495 return ret;
3498 if (async)
3500 FIXME( "Async I/O lock wait not implemented, might deadlock\n" );
3501 if (handle) NtClose( handle );
3502 return STATUS_PENDING;
3504 if (handle)
3506 NtWaitForSingleObject( handle, FALSE, NULL );
3507 NtClose( handle );
3509 else
3511 LARGE_INTEGER time;
3513 /* Unix lock conflict, sleep a bit and retry */
3514 time.QuadPart = 100 * (ULONGLONG)10000;
3515 time.QuadPart = -time.QuadPart;
3516 NtDelayExecution( FALSE, &time );
3522 /******************************************************************
3523 * NtUnlockFile (NTDLL.@)
3527 NTSTATUS WINAPI NtUnlockFile( HANDLE hFile, PIO_STATUS_BLOCK io_status,
3528 PLARGE_INTEGER offset, PLARGE_INTEGER count,
3529 PULONG key )
3531 NTSTATUS status;
3533 TRACE( "%p %x%08x %x%08x\n",
3534 hFile, offset->u.HighPart, offset->u.LowPart, count->u.HighPart, count->u.LowPart );
3536 if (io_status || key)
3538 FIXME("Unimplemented yet parameter\n");
3539 return STATUS_NOT_IMPLEMENTED;
3542 SERVER_START_REQ( unlock_file )
3544 req->handle = wine_server_obj_handle( hFile );
3545 req->offset = offset->QuadPart;
3546 req->count = count->QuadPart;
3547 status = wine_server_call( req );
3549 SERVER_END_REQ;
3550 return status;
3553 /******************************************************************
3554 * NtCreateNamedPipeFile (NTDLL.@)
3558 NTSTATUS WINAPI NtCreateNamedPipeFile( PHANDLE handle, ULONG access,
3559 POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK iosb,
3560 ULONG sharing, ULONG dispo, ULONG options,
3561 ULONG pipe_type, ULONG read_mode,
3562 ULONG completion_mode, ULONG max_inst,
3563 ULONG inbound_quota, ULONG outbound_quota,
3564 PLARGE_INTEGER timeout)
3566 NTSTATUS status;
3567 data_size_t len;
3568 struct object_attributes *objattr;
3570 TRACE("(%p %x %s %p %x %d %x %d %d %d %d %d %d %p)\n",
3571 handle, access, debugstr_w(attr->ObjectName->Buffer), iosb, sharing, dispo,
3572 options, pipe_type, read_mode, completion_mode, max_inst, inbound_quota,
3573 outbound_quota, timeout);
3575 if (!attr) return STATUS_INVALID_PARAMETER;
3577 /* assume we only get relative timeout */
3578 if (timeout->QuadPart > 0)
3579 FIXME("Wrong time %s\n", wine_dbgstr_longlong(timeout->QuadPart));
3581 if ((status = alloc_object_attributes( attr, &objattr, &len ))) return status;
3583 SERVER_START_REQ( create_named_pipe )
3585 req->access = access;
3586 req->options = options;
3587 req->sharing = sharing;
3588 req->flags =
3589 (pipe_type ? NAMED_PIPE_MESSAGE_STREAM_WRITE : 0) |
3590 (read_mode ? NAMED_PIPE_MESSAGE_STREAM_READ : 0) |
3591 (completion_mode ? NAMED_PIPE_NONBLOCKING_MODE : 0);
3592 req->maxinstances = max_inst;
3593 req->outsize = outbound_quota;
3594 req->insize = inbound_quota;
3595 req->timeout = timeout->QuadPart;
3596 wine_server_add_data( req, objattr, len );
3597 status = wine_server_call( req );
3598 if (!status) *handle = wine_server_ptr_handle( reply->handle );
3600 SERVER_END_REQ;
3602 RtlFreeHeap( GetProcessHeap(), 0, objattr );
3603 return status;
3606 /******************************************************************
3607 * NtDeleteFile (NTDLL.@)
3611 NTSTATUS WINAPI NtDeleteFile( POBJECT_ATTRIBUTES ObjectAttributes )
3613 NTSTATUS status;
3614 HANDLE hFile;
3615 IO_STATUS_BLOCK io;
3617 TRACE("%p\n", ObjectAttributes);
3618 status = NtCreateFile( &hFile, GENERIC_READ | GENERIC_WRITE | DELETE,
3619 ObjectAttributes, &io, NULL, 0,
3620 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
3621 FILE_OPEN, FILE_DELETE_ON_CLOSE, NULL, 0 );
3622 if (status == STATUS_SUCCESS) status = NtClose(hFile);
3623 return status;
3626 /******************************************************************
3627 * NtCancelIoFileEx (NTDLL.@)
3631 NTSTATUS WINAPI NtCancelIoFileEx( HANDLE hFile, PIO_STATUS_BLOCK iosb, PIO_STATUS_BLOCK io_status )
3633 TRACE("%p %p %p\n", hFile, iosb, io_status );
3635 SERVER_START_REQ( cancel_async )
3637 req->handle = wine_server_obj_handle( hFile );
3638 req->iosb = wine_server_client_ptr( iosb );
3639 req->only_thread = FALSE;
3640 io_status->u.Status = wine_server_call( req );
3642 SERVER_END_REQ;
3644 return io_status->u.Status;
3647 /******************************************************************
3648 * NtCancelIoFile (NTDLL.@)
3652 NTSTATUS WINAPI NtCancelIoFile( HANDLE hFile, PIO_STATUS_BLOCK io_status )
3654 TRACE("%p %p\n", hFile, io_status );
3656 SERVER_START_REQ( cancel_async )
3658 req->handle = wine_server_obj_handle( hFile );
3659 req->iosb = 0;
3660 req->only_thread = TRUE;
3661 io_status->u.Status = wine_server_call( req );
3663 SERVER_END_REQ;
3665 return io_status->u.Status;
3668 /******************************************************************************
3669 * NtCreateMailslotFile [NTDLL.@]
3670 * ZwCreateMailslotFile [NTDLL.@]
3672 * PARAMS
3673 * pHandle [O] pointer to receive the handle created
3674 * DesiredAccess [I] access mode (read, write, etc)
3675 * ObjectAttributes [I] fully qualified NT path of the mailslot
3676 * IoStatusBlock [O] receives completion status and other info
3677 * CreateOptions [I]
3678 * MailslotQuota [I]
3679 * MaxMessageSize [I]
3680 * TimeOut [I]
3682 * RETURNS
3683 * An NT status code
3685 NTSTATUS WINAPI NtCreateMailslotFile(PHANDLE pHandle, ULONG DesiredAccess,
3686 POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK IoStatusBlock,
3687 ULONG CreateOptions, ULONG MailslotQuota, ULONG MaxMessageSize,
3688 PLARGE_INTEGER TimeOut)
3690 LARGE_INTEGER timeout;
3691 NTSTATUS ret;
3692 data_size_t len;
3693 struct object_attributes *objattr;
3695 TRACE("%p %08x %p %p %08x %08x %08x %p\n",
3696 pHandle, DesiredAccess, attr, IoStatusBlock,
3697 CreateOptions, MailslotQuota, MaxMessageSize, TimeOut);
3699 if (!pHandle) return STATUS_ACCESS_VIOLATION;
3700 if (!attr) return STATUS_INVALID_PARAMETER;
3702 if ((ret = alloc_object_attributes( attr, &objattr, &len ))) return ret;
3705 * For a NULL TimeOut pointer set the default timeout value
3707 if (!TimeOut)
3708 timeout.QuadPart = -1;
3709 else
3710 timeout.QuadPart = TimeOut->QuadPart;
3712 SERVER_START_REQ( create_mailslot )
3714 req->access = DesiredAccess;
3715 req->max_msgsize = MaxMessageSize;
3716 req->read_timeout = timeout.QuadPart;
3717 wine_server_add_data( req, objattr, len );
3718 ret = wine_server_call( req );
3719 if( ret == STATUS_SUCCESS )
3720 *pHandle = wine_server_ptr_handle( reply->handle );
3722 SERVER_END_REQ;
3724 RtlFreeHeap( GetProcessHeap(), 0, objattr );
3725 return ret;