push 149f0a5527ac85057a8ef03858d34d91c36f97e8
[wine/hacks.git] / dlls / ntdll / directory.c
blob82953c2145f780bb9b4a94b13ecbf829aacb68dc
1 /*
2 * NTDLL directory functions
4 * Copyright 1993 Erik Bos
5 * Copyright 2003 Eric Pouech
6 * Copyright 1996, 2004 Alexandre Julliard
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include "config.h"
24 #include "wine/port.h"
26 #include <assert.h>
27 #include <sys/types.h>
28 #ifdef HAVE_DIRENT_H
29 # include <dirent.h>
30 #endif
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <stdarg.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <limits.h>
38 #ifdef HAVE_MNTENT_H
39 #include <mntent.h>
40 #endif
41 #ifdef HAVE_SYS_STAT_H
42 # include <sys/stat.h>
43 #endif
44 #ifdef HAVE_SYS_IOCTL_H
45 #include <sys/ioctl.h>
46 #endif
47 #ifdef HAVE_LINUX_IOCTL_H
48 #include <linux/ioctl.h>
49 #endif
50 #ifdef HAVE_LINUX_MAJOR_H
51 # include <linux/major.h>
52 #endif
53 #ifdef HAVE_SYS_PARAM_H
54 #include <sys/param.h>
55 #endif
56 #ifdef HAVE_SYS_MOUNT_H
57 #include <sys/mount.h>
58 #endif
59 #include <time.h>
60 #ifdef HAVE_UNISTD_H
61 # include <unistd.h>
62 #endif
64 #define NONAMELESSUNION
65 #define NONAMELESSSTRUCT
66 #include "ntstatus.h"
67 #define WIN32_NO_STATUS
68 #include "windef.h"
69 #include "winnt.h"
70 #include "winternl.h"
71 #include "ntdll_misc.h"
72 #include "wine/unicode.h"
73 #include "wine/server.h"
74 #include "wine/library.h"
75 #include "wine/debug.h"
77 WINE_DEFAULT_DEBUG_CHANNEL(file);
79 /* just in case... */
80 #undef VFAT_IOCTL_READDIR_BOTH
81 #undef USE_GETDENTS
83 #ifdef linux
85 /* We want the real kernel dirent structure, not the libc one */
86 typedef struct
88 long d_ino;
89 long d_off;
90 unsigned short d_reclen;
91 char d_name[256];
92 } KERNEL_DIRENT;
94 /* Define the VFAT ioctl to get both short and long file names */
95 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
97 #ifndef O_DIRECTORY
98 # define O_DIRECTORY 0200000 /* must be directory */
99 #endif
101 #ifdef __i386__
103 typedef struct
105 ULONG64 d_ino;
106 LONG64 d_off;
107 unsigned short d_reclen;
108 unsigned char d_type;
109 char d_name[256];
110 } KERNEL_DIRENT64;
112 static inline int getdents64( int fd, char *de, unsigned int size )
114 int ret;
115 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
116 : "=a" (ret)
117 : "0" (220 /*NR_getdents64*/), "r" (fd), "c" (de), "d" (size)
118 : "memory" );
119 if (ret < 0)
121 errno = -ret;
122 ret = -1;
124 return ret;
126 #define USE_GETDENTS
128 #endif /* i386 */
130 #endif /* linux */
132 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
133 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
135 #define INVALID_NT_CHARS '*','?','<','>','|','"'
136 #define INVALID_DOS_CHARS INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
138 #define MAX_DIR_ENTRY_LEN 255 /* max length of a directory entry in chars */
140 #define MAX_IGNORED_FILES 4
142 struct file_identity
144 dev_t dev;
145 ino_t ino;
148 static struct file_identity ignored_files[MAX_IGNORED_FILES];
149 static int ignored_files_count;
151 union file_directory_info
153 ULONG next;
154 FILE_DIRECTORY_INFORMATION dir;
155 FILE_BOTH_DIRECTORY_INFORMATION both;
156 FILE_FULL_DIRECTORY_INFORMATION full;
157 FILE_ID_BOTH_DIRECTORY_INFORMATION id_both;
158 FILE_ID_FULL_DIRECTORY_INFORMATION id_full;
161 static int show_dot_files = -1;
163 /* at some point we may want to allow Winelib apps to set this */
164 static const int is_case_sensitive = FALSE;
166 UNICODE_STRING windows_dir = { 0, 0, NULL }; /* windows directory */
167 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
169 static struct file_identity curdir;
170 static struct file_identity windir;
172 static RTL_CRITICAL_SECTION dir_section;
173 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
175 0, 0, &dir_section,
176 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
177 0, 0, { (DWORD_PTR)(__FILE__ ": dir_section") }
179 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
182 /* check if a given Unicode char is OK in a DOS short name */
183 static inline BOOL is_invalid_dos_char( WCHAR ch )
185 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
186 if (ch > 0x7f) return TRUE;
187 return strchrW( invalid_chars, ch ) != NULL;
190 /* check if the device can be a mounted volume */
191 static inline int is_valid_mounted_device( const struct stat *st )
193 #if defined(linux) || defined(__sun__)
194 return S_ISBLK( st->st_mode );
195 #else
196 /* disks are char devices on *BSD */
197 return S_ISCHR( st->st_mode );
198 #endif
201 static inline void ignore_file( const char *name )
203 struct stat st;
204 assert( ignored_files_count < MAX_IGNORED_FILES );
205 if (!stat( name, &st ))
207 ignored_files[ignored_files_count].dev = st.st_dev;
208 ignored_files[ignored_files_count].ino = st.st_ino;
209 ignored_files_count++;
213 static inline BOOL is_same_file( const struct file_identity *file, const struct stat *st )
215 return st->st_dev == file->dev && st->st_ino == file->ino;
218 static inline BOOL is_ignored_file( const struct stat *st )
220 unsigned int i;
222 for (i = 0; i < ignored_files_count; i++)
223 if (is_same_file( &ignored_files[i], st )) return TRUE;
224 return FALSE;
227 static inline unsigned int dir_info_size( FILE_INFORMATION_CLASS class, unsigned int len )
229 switch (class)
231 case FileDirectoryInformation:
232 return (FIELD_OFFSET( FILE_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
233 case FileBothDirectoryInformation:
234 return (FIELD_OFFSET( FILE_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
235 case FileFullDirectoryInformation:
236 return (FIELD_OFFSET( FILE_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
237 case FileIdBothDirectoryInformation:
238 return (FIELD_OFFSET( FILE_ID_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
239 case FileIdFullDirectoryInformation:
240 return (FIELD_OFFSET( FILE_ID_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
241 default:
242 assert(0);
246 static inline unsigned int max_dir_info_size( FILE_INFORMATION_CLASS class )
248 return dir_info_size( class, MAX_DIR_ENTRY_LEN );
252 /***********************************************************************
253 * get_default_com_device
255 * Return the default device to use for serial ports.
257 static char *get_default_com_device( int num )
259 char *ret = NULL;
261 if (!num || num > 9) return ret;
262 #ifdef linux
263 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
264 if (ret)
266 strcpy( ret, "/dev/ttyS0" );
267 ret[strlen(ret) - 1] = '0' + num - 1;
269 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
270 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuad0") );
271 if (ret)
273 strcpy( ret, "/dev/cuad0" );
274 ret[strlen(ret) - 1] = '0' + num - 1;
276 #else
277 FIXME( "no known default for device com%d\n", num );
278 #endif
279 return ret;
283 /***********************************************************************
284 * get_default_lpt_device
286 * Return the default device to use for parallel ports.
288 static char *get_default_lpt_device( int num )
290 char *ret = NULL;
292 if (!num || num > 9) return ret;
293 #ifdef linux
294 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
295 if (ret)
297 strcpy( ret, "/dev/lp0" );
298 ret[strlen(ret) - 1] = '0' + num - 1;
300 #else
301 FIXME( "no known default for device lpt%d\n", num );
302 #endif
303 return ret;
307 /***********************************************************************
308 * DIR_get_drives_info
310 * Retrieve device/inode number for all the drives. Helper for find_drive_root.
312 unsigned int DIR_get_drives_info( struct drive_info info[MAX_DOS_DRIVES] )
314 static struct drive_info cache[MAX_DOS_DRIVES];
315 static time_t last_update;
316 static unsigned int nb_drives;
317 unsigned int ret;
318 time_t now = time(NULL);
320 RtlEnterCriticalSection( &dir_section );
321 if (now != last_update)
323 const char *config_dir = wine_get_config_dir();
324 char *buffer, *p;
325 struct stat st;
326 unsigned int i;
328 if ((buffer = RtlAllocateHeap( GetProcessHeap(), 0,
329 strlen(config_dir) + sizeof("/dosdevices/a:") )))
331 strcpy( buffer, config_dir );
332 strcat( buffer, "/dosdevices/a:" );
333 p = buffer + strlen(buffer) - 2;
335 for (i = nb_drives = 0; i < MAX_DOS_DRIVES; i++)
337 *p = 'a' + i;
338 if (!stat( buffer, &st ))
340 cache[i].dev = st.st_dev;
341 cache[i].ino = st.st_ino;
342 nb_drives++;
344 else
346 cache[i].dev = 0;
347 cache[i].ino = 0;
350 RtlFreeHeap( GetProcessHeap(), 0, buffer );
352 last_update = now;
354 memcpy( info, cache, sizeof(cache) );
355 ret = nb_drives;
356 RtlLeaveCriticalSection( &dir_section );
357 return ret;
361 /***********************************************************************
362 * parse_mount_entries
364 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
367 #ifdef sun
368 #include <sys/vfstab.h>
369 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
371 struct vfstab entry;
372 struct stat st;
373 char *device;
375 while (! getvfsent( f, &entry ))
377 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
378 if (!strcmp( entry.vfs_fstype, "nfs" ) ||
379 !strcmp( entry.vfs_fstype, "smbfs" ) ||
380 !strcmp( entry.vfs_fstype, "ncpfs" )) continue;
382 if (stat( entry.vfs_mountp, &st ) == -1) continue;
383 if (st.st_dev != dev || st.st_ino != ino) continue;
384 if (!strcmp( entry.vfs_fstype, "fd" ))
386 if ((device = strstr( entry.vfs_mntopts, "dev=" )))
388 char *p = strchr( device + 4, ',' );
389 if (p) *p = 0;
390 return device + 4;
393 else
394 return entry.vfs_special;
396 return NULL;
398 #endif
400 #ifdef linux
401 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
403 struct mntent *entry;
404 struct stat st;
405 char *device;
407 while ((entry = getmntent( f )))
409 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
410 if (!strcmp( entry->mnt_type, "nfs" ) ||
411 !strcmp( entry->mnt_type, "smbfs" ) ||
412 !strcmp( entry->mnt_type, "ncpfs" )) continue;
414 if (stat( entry->mnt_dir, &st ) == -1) continue;
415 if (st.st_dev != dev || st.st_ino != ino) continue;
416 if (!strcmp( entry->mnt_type, "supermount" ))
418 if ((device = strstr( entry->mnt_opts, "dev=" )))
420 char *p = strchr( device + 4, ',' );
421 if (p) *p = 0;
422 return device + 4;
425 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
427 /* if device is a regular file check for a loop mount */
428 if ((device = strstr( entry->mnt_opts, "loop=" )))
430 char *p = strchr( device + 5, ',' );
431 if (p) *p = 0;
432 return device + 5;
435 else
436 return entry->mnt_fsname;
438 return NULL;
440 #endif
442 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
443 #include <fstab.h>
444 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
446 struct fstab *entry;
447 struct stat st;
449 while ((entry = getfsent()))
451 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
452 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
453 !strcmp( entry->fs_vfstype, "smbfs" ) ||
454 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
456 if (stat( entry->fs_file, &st ) == -1) continue;
457 if (st.st_dev != dev || st.st_ino != ino) continue;
458 return entry->fs_spec;
460 return NULL;
462 #endif
464 #ifdef sun
465 #include <sys/mnttab.h>
466 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
468 struct mnttab entry;
469 struct stat st;
470 char *device;
473 while (( ! getmntent( f, &entry) ))
475 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
476 if (!strcmp( entry.mnt_fstype, "nfs" ) ||
477 !strcmp( entry.mnt_fstype, "smbfs" ) ||
478 !strcmp( entry.mnt_fstype, "ncpfs" )) continue;
480 if (stat( entry.mnt_mountp, &st ) == -1) continue;
481 if (st.st_dev != dev || st.st_ino != ino) continue;
482 if (!strcmp( entry.mnt_fstype, "fd" ))
484 if ((device = strstr( entry.mnt_mntopts, "dev=" )))
486 char *p = strchr( device + 4, ',' );
487 if (p) *p = 0;
488 return device + 4;
491 else
492 return entry.mnt_special;
494 return NULL;
496 #endif
498 /***********************************************************************
499 * get_default_drive_device
501 * Return the default device to use for a given drive mount point.
503 static char *get_default_drive_device( const char *root )
505 char *ret = NULL;
507 #ifdef linux
508 FILE *f;
509 char *device = NULL;
510 int fd, res = -1;
511 struct stat st;
513 /* try to open it first to force it to get mounted */
514 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
516 res = fstat( fd, &st );
517 close( fd );
519 /* now try normal stat just in case */
520 if (res == -1) res = stat( root, &st );
521 if (res == -1) return NULL;
523 RtlEnterCriticalSection( &dir_section );
525 if ((f = fopen( "/etc/mtab", "r" )))
527 device = parse_mount_entries( f, st.st_dev, st.st_ino );
528 endmntent( f );
530 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
531 if (!device && (f = fopen( "/etc/fstab", "r" )))
533 device = parse_mount_entries( f, st.st_dev, st.st_ino );
534 endmntent( f );
536 if (device)
538 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
539 if (ret) strcpy( ret, device );
541 RtlLeaveCriticalSection( &dir_section );
543 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ )
544 char *device = NULL;
545 int fd, res = -1;
546 struct stat st;
548 /* try to open it first to force it to get mounted */
549 if ((fd = open( root, O_RDONLY )) != -1)
551 res = fstat( fd, &st );
552 close( fd );
554 /* now try normal stat just in case */
555 if (res == -1) res = stat( root, &st );
556 if (res == -1) return NULL;
558 RtlEnterCriticalSection( &dir_section );
560 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
561 * pass NULL. Leave the argument in for symmetry.
563 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
564 if (device)
566 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
567 if (ret) strcpy( ret, device );
569 RtlLeaveCriticalSection( &dir_section );
571 #elif defined( sun )
572 FILE *f;
573 char *device = NULL;
574 int fd, res = -1;
575 struct stat st;
577 /* try to open it first to force it to get mounted */
578 if ((fd = open( root, O_RDONLY )) != -1)
580 res = fstat( fd, &st );
581 close( fd );
583 /* now try normal stat just in case */
584 if (res == -1) res = stat( root, &st );
585 if (res == -1) return NULL;
587 RtlEnterCriticalSection( &dir_section );
589 if ((f = fopen( "/etc/mnttab", "r" )))
591 device = parse_mount_entries( f, st.st_dev, st.st_ino);
592 fclose( f );
594 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
595 if (!device && (f = fopen( "/etc/vfstab", "r" )))
597 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
598 fclose( f );
600 if (device)
602 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
603 if (ret) strcpy( ret, device );
605 RtlLeaveCriticalSection( &dir_section );
607 #elif defined(__APPLE__)
608 struct statfs *mntStat;
609 struct stat st;
610 int i;
611 int mntSize;
612 dev_t dev;
613 ino_t ino;
614 static const char path_bsd_device[] = "/dev/disk";
615 int res;
617 res = stat( root, &st );
618 if (res == -1) return NULL;
620 dev = st.st_dev;
621 ino = st.st_ino;
623 RtlEnterCriticalSection( &dir_section );
625 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
627 for (i = 0; i < mntSize && !ret; i++)
629 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
630 if (st.st_dev != dev || st.st_ino != ino) continue;
632 /* FIXME add support for mounted network drive */
633 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
635 /* set return value to the corresponding raw BSD node */
636 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
637 if (ret)
639 strcpy(ret, "/dev/r");
640 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
644 RtlLeaveCriticalSection( &dir_section );
645 #else
646 static int warned;
647 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
648 #endif
649 return ret;
653 /***********************************************************************
654 * get_device_mount_point
656 * Return the current mount point for a device.
658 static char *get_device_mount_point( dev_t dev )
660 char *ret = NULL;
662 #ifdef linux
663 FILE *f;
665 RtlEnterCriticalSection( &dir_section );
667 if ((f = fopen( "/etc/mtab", "r" )))
669 struct mntent *entry;
670 struct stat st;
671 char *p, *device;
673 while ((entry = getmntent( f )))
675 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
676 if (!strcmp( entry->mnt_type, "nfs" ) ||
677 !strcmp( entry->mnt_type, "smbfs" ) ||
678 !strcmp( entry->mnt_type, "ncpfs" )) continue;
680 if (!strcmp( entry->mnt_type, "supermount" ))
682 if ((device = strstr( entry->mnt_opts, "dev=" )))
684 device += 4;
685 if ((p = strchr( device, ',' ))) *p = 0;
688 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
690 /* if device is a regular file check for a loop mount */
691 if ((device = strstr( entry->mnt_opts, "loop=" )))
693 device += 5;
694 if ((p = strchr( device, ',' ))) *p = 0;
697 else device = entry->mnt_fsname;
699 if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
701 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
702 if (ret) strcpy( ret, entry->mnt_dir );
703 break;
706 endmntent( f );
708 RtlLeaveCriticalSection( &dir_section );
709 #elif defined(__APPLE__)
710 struct statfs *entry;
711 struct stat st;
712 int i, size;
714 RtlEnterCriticalSection( &dir_section );
716 size = getmntinfo( &entry, MNT_NOWAIT );
717 for (i = 0; i < size; i++)
719 if (stat( entry[i].f_mntfromname, &st ) == -1) continue;
720 if (S_ISBLK(st.st_mode) && st.st_rdev == dev)
722 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry[i].f_mntfromname) + 1 );
723 if (ret) strcpy( ret, entry[i].f_mntfromname );
724 break;
727 RtlLeaveCriticalSection( &dir_section );
728 #else
729 static int warned;
730 if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
731 #endif
732 return ret;
736 /***********************************************************************
737 * init_options
739 * Initialize the show_dot_files options.
741 static void init_options(void)
743 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
744 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
745 char tmp[80];
746 HANDLE root, hkey;
747 DWORD dummy;
748 OBJECT_ATTRIBUTES attr;
749 UNICODE_STRING nameW;
751 show_dot_files = 0;
753 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
754 attr.Length = sizeof(attr);
755 attr.RootDirectory = root;
756 attr.ObjectName = &nameW;
757 attr.Attributes = 0;
758 attr.SecurityDescriptor = NULL;
759 attr.SecurityQualityOfService = NULL;
760 RtlInitUnicodeString( &nameW, WineW );
762 /* @@ Wine registry key: HKCU\Software\Wine */
763 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
765 RtlInitUnicodeString( &nameW, ShowDotFilesW );
766 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
768 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
769 show_dot_files = IS_OPTION_TRUE( str[0] );
771 NtClose( hkey );
773 NtClose( root );
775 /* a couple of directories that we don't want to return in directory searches */
776 ignore_file( wine_get_config_dir() );
777 ignore_file( "/dev" );
778 ignore_file( "/proc" );
779 #ifdef linux
780 ignore_file( "/sys" );
781 #endif
785 /***********************************************************************
786 * DIR_is_hidden_file
788 * Check if the specified file should be hidden based on its name and the show dot files option.
790 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
792 WCHAR *p, *end;
794 if (show_dot_files == -1) init_options();
795 if (show_dot_files) return FALSE;
797 end = p = name->Buffer + name->Length/sizeof(WCHAR);
798 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
799 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
800 if (p == end || *p != '.') return FALSE;
801 /* make sure it isn't '.' or '..' */
802 if (p + 1 == end) return FALSE;
803 if (p[1] == '.' && p + 2 == end) return FALSE;
804 return TRUE;
808 /***********************************************************************
809 * hash_short_file_name
811 * Transform a Unix file name into a hashed DOS name. If the name is a valid
812 * DOS name, it is converted to upper-case; otherwise it is replaced by a
813 * hashed version that fits in 8.3 format.
814 * 'buffer' must be at least 12 characters long.
815 * Returns length of short name in bytes; short name is NOT null-terminated.
817 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
819 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
821 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
822 LPWSTR dst;
823 unsigned short hash;
824 int i;
826 /* Compute the hash code of the file name */
827 /* If you know something about hash functions, feel free to */
828 /* insert a better algorithm here... */
829 if (!is_case_sensitive)
831 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
832 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
833 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
835 else
837 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
838 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
839 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
842 /* Find last dot for start of the extension */
843 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
845 /* Copy first 4 chars, replacing invalid chars with '_' */
846 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
848 if (p == end || p == ext) break;
849 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
851 /* Pad to 5 chars with '~' */
852 while (i-- >= 0) *dst++ = '~';
854 /* Insert hash code converted to 3 ASCII chars */
855 *dst++ = hash_chars[(hash >> 10) & 0x1f];
856 *dst++ = hash_chars[(hash >> 5) & 0x1f];
857 *dst++ = hash_chars[hash & 0x1f];
859 /* Copy the first 3 chars of the extension (if any) */
860 if (ext)
862 *dst++ = '.';
863 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
864 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
866 return dst - buffer;
870 /***********************************************************************
871 * match_filename
873 * Check a long file name against a mask.
875 * Tests (done in W95 DOS shell - case insensitive):
876 * *.txt test1.test.txt *
877 * *st1* test1.txt *
878 * *.t??????.t* test1.ta.tornado.txt *
879 * *tornado* test1.ta.tornado.txt *
880 * t*t test1.ta.tornado.txt *
881 * ?est* test1.txt *
882 * ?est??? test1.txt -
883 * *test1.txt* test1.txt *
884 * h?l?o*t.dat hellothisisatest.dat *
886 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
888 int mismatch;
889 const WCHAR *name = name_str->Buffer;
890 const WCHAR *mask = mask_str->Buffer;
891 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
892 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
893 const WCHAR *lastjoker = NULL;
894 const WCHAR *next_to_retry = NULL;
896 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
898 while (name < name_end && mask < mask_end)
900 switch(*mask)
902 case '*':
903 mask++;
904 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
905 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
906 lastjoker = mask;
908 /* skip to the next match after the joker(s) */
909 if (is_case_sensitive)
910 while (name < name_end && (*name != *mask)) name++;
911 else
912 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
913 next_to_retry = name;
914 break;
915 case '?':
916 mask++;
917 name++;
918 break;
919 default:
920 if (is_case_sensitive) mismatch = (*mask != *name);
921 else mismatch = (toupperW(*mask) != toupperW(*name));
923 if (!mismatch)
925 mask++;
926 name++;
927 if (mask == mask_end)
929 if (name == name_end) return TRUE;
930 if (lastjoker) mask = lastjoker;
933 else /* mismatch ! */
935 if (lastjoker) /* we had an '*', so we can try unlimitedly */
937 mask = lastjoker;
939 /* this scan sequence was a mismatch, so restart
940 * 1 char after the first char we checked last time */
941 next_to_retry++;
942 name = next_to_retry;
944 else return FALSE; /* bad luck */
946 break;
949 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
950 mask++; /* Ignore trailing '.' or '*' in mask */
951 return (name == name_end && mask == mask_end);
955 /***********************************************************************
956 * append_entry
958 * helper for NtQueryDirectoryFile
960 static union file_directory_info *append_entry( void *info_ptr, IO_STATUS_BLOCK *io, ULONG max_length,
961 const char *long_name, const char *short_name,
962 const UNICODE_STRING *mask, FILE_INFORMATION_CLASS class )
964 union file_directory_info *info;
965 int i, long_len, short_len, total_len;
966 struct stat st;
967 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
968 WCHAR short_nameW[12];
969 WCHAR *filename;
970 UNICODE_STRING str;
971 ULONG attributes = 0;
973 io->u.Status = STATUS_SUCCESS;
974 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
975 if (long_len == -1) return NULL;
977 str.Buffer = long_nameW;
978 str.Length = long_len * sizeof(WCHAR);
979 str.MaximumLength = sizeof(long_nameW);
981 if (short_name)
983 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
984 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
985 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
987 else /* generate a short name if necessary */
989 BOOLEAN spaces;
991 short_len = 0;
992 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
993 short_len = hash_short_file_name( &str, short_nameW );
996 TRACE( "long %s short %s mask %s\n",
997 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
999 if (mask && !match_filename( &str, mask ))
1001 if (!short_len) return NULL; /* no short name to match */
1002 str.Buffer = short_nameW;
1003 str.Length = short_len * sizeof(WCHAR);
1004 str.MaximumLength = sizeof(short_nameW);
1005 if (!match_filename( &str, mask )) return NULL;
1008 if (lstat( long_name, &st ) == -1) return NULL;
1009 if (S_ISLNK( st.st_mode ))
1011 if (stat( long_name, &st ) == -1) return NULL;
1012 if (S_ISDIR( st.st_mode )) attributes |= FILE_ATTRIBUTE_REPARSE_POINT;
1014 if (is_ignored_file( &st ))
1016 TRACE( "ignoring file %s\n", long_name );
1017 return NULL;
1019 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
1020 attributes |= FILE_ATTRIBUTE_HIDDEN;
1022 total_len = dir_info_size( class, long_len );
1023 if (io->Information + total_len > max_length)
1025 total_len = max_length - io->Information;
1026 io->u.Status = STATUS_BUFFER_OVERFLOW;
1028 info = (union file_directory_info *)((char *)info_ptr + io->Information);
1029 if (st.st_dev != curdir.dev) st.st_ino = 0; /* ignore inode if on a different device */
1030 /* all the structures start with a FileDirectoryInformation layout */
1031 fill_stat_info( &st, info, class );
1032 info->dir.NextEntryOffset = total_len;
1033 info->dir.FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
1034 info->dir.FileAttributes |= attributes;
1036 switch (class)
1038 case FileDirectoryInformation:
1039 info->dir.FileNameLength = long_len * sizeof(WCHAR);
1040 filename = info->dir.FileName;
1041 break;
1043 case FileFullDirectoryInformation:
1044 info->full.EaSize = 0; /* FIXME */
1045 info->full.FileNameLength = long_len * sizeof(WCHAR);
1046 filename = info->full.FileName;
1047 break;
1049 case FileIdFullDirectoryInformation:
1050 info->id_full.EaSize = 0; /* FIXME */
1051 info->id_full.FileNameLength = long_len * sizeof(WCHAR);
1052 filename = info->id_full.FileName;
1053 break;
1055 case FileBothDirectoryInformation:
1056 info->both.EaSize = 0; /* FIXME */
1057 info->both.ShortNameLength = short_len * sizeof(WCHAR);
1058 for (i = 0; i < short_len; i++) info->both.ShortName[i] = toupperW(short_nameW[i]);
1059 info->both.FileNameLength = long_len * sizeof(WCHAR);
1060 filename = info->both.FileName;
1061 break;
1063 case FileIdBothDirectoryInformation:
1064 info->id_both.EaSize = 0; /* FIXME */
1065 info->id_both.ShortNameLength = short_len * sizeof(WCHAR);
1066 for (i = 0; i < short_len; i++) info->id_both.ShortName[i] = toupperW(short_nameW[i]);
1067 info->id_both.FileNameLength = long_len * sizeof(WCHAR);
1068 filename = info->id_both.FileName;
1069 break;
1071 default:
1072 assert(0);
1074 memcpy( filename, long_nameW, total_len - ((char *)filename - (char *)info) );
1075 io->Information += total_len;
1076 return info;
1080 #ifdef VFAT_IOCTL_READDIR_BOTH
1082 /***********************************************************************
1083 * start_vfat_ioctl
1085 * Wrapper for the VFAT ioctl to work around various kernel bugs.
1086 * dir_section must be held by caller.
1088 static KERNEL_DIRENT *start_vfat_ioctl( int fd )
1090 static KERNEL_DIRENT *de;
1091 int res;
1093 if (!de)
1095 const size_t page_size = getpagesize();
1096 SIZE_T size = 2 * sizeof(*de) + page_size;
1097 void *addr = NULL;
1099 if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_RESERVE, PAGE_READWRITE ))
1100 return NULL;
1101 /* commit only the size needed for the dir entries */
1102 /* this leaves an extra unaccessible page, which should make the kernel */
1103 /* fail with -EFAULT before it stomps all over our memory */
1104 de = addr;
1105 size = 2 * sizeof(*de);
1106 NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_COMMIT, PAGE_READWRITE );
1109 /* set d_reclen to 65535 to work around an AFS kernel bug */
1110 de[0].d_reclen = 65535;
1111 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
1112 if (res == -1)
1114 if (errno != ENOENT) return NULL; /* VFAT ioctl probably not supported */
1115 de[0].d_reclen = 0; /* eof */
1117 else if (!res && de[0].d_reclen == 65535) return NULL; /* AFS bug */
1119 return de;
1123 /***********************************************************************
1124 * read_directory_vfat
1126 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
1128 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1129 BOOLEAN single_entry, const UNICODE_STRING *mask,
1130 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1133 size_t len;
1134 KERNEL_DIRENT *de;
1135 union file_directory_info *info, *last_info = NULL;
1137 io->u.Status = STATUS_SUCCESS;
1139 if (restart_scan) lseek( fd, 0, SEEK_SET );
1141 if (length < max_dir_info_size(class)) /* we may have to return a partial entry here */
1143 off_t old_pos = lseek( fd, 0, SEEK_CUR );
1145 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1147 while (de[0].d_reclen)
1149 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1150 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1151 de[0].d_name[len] = 0;
1152 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1153 de[1].d_name[len] = 0;
1155 if (de[1].d_name[0])
1156 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1157 else
1158 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1159 if (info)
1161 last_info = info;
1162 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1163 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1164 break;
1166 old_pos = lseek( fd, 0, SEEK_CUR );
1167 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1170 else /* we'll only return full entries, no need to worry about overflow */
1172 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1174 while (de[0].d_reclen)
1176 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1177 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1178 de[0].d_name[len] = 0;
1179 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1180 de[1].d_name[len] = 0;
1182 if (de[1].d_name[0])
1183 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1184 else
1185 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1186 if (info)
1188 last_info = info;
1189 if (single_entry) break;
1190 /* check if we still have enough space for the largest possible entry */
1191 if (io->Information + max_dir_info_size(class) > length) break;
1193 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1197 if (last_info) last_info->next = 0;
1198 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1199 return 0;
1201 #endif /* VFAT_IOCTL_READDIR_BOTH */
1204 /***********************************************************************
1205 * read_directory_getdents
1207 * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
1209 #ifdef USE_GETDENTS
1210 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1211 BOOLEAN single_entry, const UNICODE_STRING *mask,
1212 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1214 off_t old_pos = 0;
1215 size_t size = length;
1216 int res, fake_dot_dot = 1;
1217 char *data, local_buffer[8192];
1218 KERNEL_DIRENT64 *de;
1219 union file_directory_info *info, *last_info = NULL;
1221 if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1223 size = sizeof(local_buffer);
1224 data = local_buffer;
1227 if (restart_scan) lseek( fd, 0, SEEK_SET );
1228 else if (length < max_dir_info_size(class)) /* we may have to return a partial entry here */
1230 old_pos = lseek( fd, 0, SEEK_CUR );
1231 if (old_pos == -1 && errno == ENOENT)
1233 io->u.Status = STATUS_NO_MORE_FILES;
1234 res = 0;
1235 goto done;
1239 io->u.Status = STATUS_SUCCESS;
1241 res = getdents64( fd, data, size );
1242 if (res == -1)
1244 if (errno != ENOSYS)
1246 io->u.Status = FILE_GetNtStatus();
1247 res = 0;
1249 goto done;
1252 de = (KERNEL_DIRENT64 *)data;
1254 if (restart_scan)
1256 /* check if we got . and .. from getdents */
1257 if (res > 0)
1259 if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1261 KERNEL_DIRENT64 *next_de = (KERNEL_DIRENT64 *)(data + de->d_reclen);
1262 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1265 /* make sure we have enough room for both entries */
1266 if (fake_dot_dot)
1268 const ULONG min_info_size = dir_info_size( class, 1 ) + dir_info_size( class, 2 );
1269 if (length < min_info_size || single_entry)
1271 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1272 fake_dot_dot = 0;
1276 if (fake_dot_dot)
1278 if ((info = append_entry( buffer, io, length, ".", NULL, mask, class )))
1279 last_info = info;
1280 if ((info = append_entry( buffer, io, length, "..", NULL, mask, class )))
1281 last_info = info;
1283 /* check if we still have enough space for the largest possible entry */
1284 if (last_info && io->Information + max_dir_info_size(class) > length)
1286 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1287 res = 0;
1292 while (res > 0)
1294 res -= de->d_reclen;
1295 if (de->d_ino &&
1296 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1297 (info = append_entry( buffer, io, length, de->d_name, NULL, mask, class )))
1299 last_info = info;
1300 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1302 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1303 break;
1305 /* check if we still have enough space for the largest possible entry */
1306 if (single_entry || io->Information + max_dir_info_size(class) > length)
1308 if (res > 0) lseek( fd, de->d_off, SEEK_SET ); /* set pos to next entry */
1309 break;
1312 old_pos = de->d_off;
1313 /* move on to the next entry */
1314 if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1315 else
1317 res = getdents64( fd, data, size );
1318 de = (KERNEL_DIRENT64 *)data;
1322 if (last_info) last_info->next = 0;
1323 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1324 res = 0;
1325 done:
1326 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1327 return res;
1330 #elif defined HAVE_GETDIRENTRIES
1332 #if _DARWIN_FEATURE_64_BIT_INODE
1334 /* Darwin doesn't provide a version of getdirentries with support for 64-bit
1335 * inodes. When 64-bit inodes are enabled, the getdirentries symbol is mapped
1336 * to _getdirentries_is_not_available_when_64_bit_inodes_are_in_effect so that
1337 * we get link errors if we try to use it. We still need getdirentries, but we
1338 * don't need it to support 64-bit inodes. So, we use the legacy getdirentries
1339 * with 32-bit inodes. We have to be careful to use a corresponding dirent
1340 * structure, too.
1342 int darwin_legacy_getdirentries(int, char *, int, long *) __asm("_getdirentries");
1343 #define getdirentries darwin_legacy_getdirentries
1345 struct darwin_legacy_dirent {
1346 __uint32_t d_ino;
1347 __uint16_t d_reclen;
1348 __uint8_t d_type;
1349 __uint8_t d_namlen;
1350 char d_name[__DARWIN_MAXNAMLEN + 1];
1352 #define dirent darwin_legacy_dirent
1354 #endif
1356 /***********************************************************************
1357 * wine_getdirentries
1359 * Wrapper for the BSD getdirentries system call to fix a bug in the
1360 * Mac OS X version. For some file systems (at least Apple Filing
1361 * Protocol a.k.a. AFP), getdirentries resets the file position to 0
1362 * when it's about to return 0 (no more entries). So, a subsequent
1363 * getdirentries call starts over at the beginning again, causing an
1364 * infinite loop.
1366 static inline int wine_getdirentries(int fd, char *buf, int nbytes, long *basep)
1368 int res = getdirentries(fd, buf, nbytes, basep);
1369 #ifdef __APPLE__
1370 if (res == 0)
1371 lseek(fd, *basep, SEEK_SET);
1372 #endif
1373 return res;
1376 /***********************************************************************
1377 * read_directory_getdirentries
1379 * Read a directory using the BSD getdirentries system call; helper for NtQueryDirectoryFile.
1381 static int read_directory_getdirentries( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1382 BOOLEAN single_entry, const UNICODE_STRING *mask,
1383 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1385 long restart_pos;
1386 ULONG_PTR restart_info_pos = 0;
1387 size_t size, initial_size = length;
1388 int res, fake_dot_dot = 1;
1389 char *data, local_buffer[8192];
1390 struct dirent *de;
1391 union file_directory_info *info, *last_info = NULL, *restart_last_info = NULL;
1393 size = initial_size;
1394 data = local_buffer;
1395 if (size > sizeof(local_buffer) && !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1397 io->u.Status = STATUS_NO_MEMORY;
1398 return io->u.Status;
1401 if (restart_scan) lseek( fd, 0, SEEK_SET );
1403 io->u.Status = STATUS_SUCCESS;
1405 /* FIXME: should make sure size is larger than filesystem block size */
1406 res = wine_getdirentries( fd, data, size, &restart_pos );
1407 if (res == -1)
1409 io->u.Status = FILE_GetNtStatus();
1410 res = 0;
1411 goto done;
1414 de = (struct dirent *)data;
1416 if (restart_scan)
1418 /* check if we got . and .. from getdirentries */
1419 if (res > 0)
1421 if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1423 struct dirent *next_de = (struct dirent *)(data + de->d_reclen);
1424 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1427 /* make sure we have enough room for both entries */
1428 if (fake_dot_dot)
1430 const ULONG min_info_size = dir_info_size( class, 1 ) + dir_info_size( class, 2 );
1431 if (length < min_info_size || single_entry)
1433 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1434 fake_dot_dot = 0;
1438 if (fake_dot_dot)
1440 if ((info = append_entry( buffer, io, length, ".", NULL, mask, class )))
1441 last_info = info;
1442 if ((info = append_entry( buffer, io, length, "..", NULL, mask, class )))
1443 last_info = info;
1445 restart_last_info = last_info;
1446 restart_info_pos = io->Information;
1448 /* check if we still have enough space for the largest possible entry */
1449 if (last_info && io->Information + max_dir_info_size(class) > length)
1451 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1452 res = 0;
1457 while (res > 0)
1459 res -= de->d_reclen;
1460 if (de->d_fileno &&
1461 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1462 ((info = append_entry( buffer, io, length, de->d_name, NULL, mask, class ))))
1464 last_info = info;
1465 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1467 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1468 if (restart_info_pos) /* if we have a complete read already, return it */
1470 io->u.Status = STATUS_SUCCESS;
1471 io->Information = restart_info_pos;
1472 last_info = restart_last_info;
1473 break;
1475 /* otherwise restart from the start with a smaller size */
1476 size = (char *)de - data;
1477 if (!size) break;
1478 io->Information = 0;
1479 last_info = NULL;
1480 goto restart;
1482 /* if we have to return but the buffer contains more data, restart with a smaller size */
1483 if (res > 0 && (single_entry || io->Information + max_dir_info_size(class) > length))
1485 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1486 size = (char *)de - data;
1487 io->Information = restart_info_pos;
1488 last_info = restart_last_info;
1489 goto restart;
1492 /* move on to the next entry */
1493 if (res > 0)
1495 de = (struct dirent *)((char *)de + de->d_reclen);
1496 continue;
1498 if (size < initial_size) break; /* already restarted once, give up now */
1499 size = min( size, length - io->Information );
1500 /* if size is too small don't bother to continue */
1501 if (size < max_dir_info_size(class) && last_info) break;
1502 restart_last_info = last_info;
1503 restart_info_pos = io->Information;
1504 restart:
1505 res = wine_getdirentries( fd, data, size, &restart_pos );
1506 de = (struct dirent *)data;
1509 if (last_info) last_info->next = 0;
1510 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1511 res = 0;
1512 done:
1513 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1514 return res;
1517 #if _DARWIN_FEATURE_64_BIT_INODE
1518 #undef getdirentries
1519 #undef dirent
1520 #endif
1522 #endif /* HAVE_GETDIRENTRIES */
1525 /***********************************************************************
1526 * read_directory_readdir
1528 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1530 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1531 BOOLEAN single_entry, const UNICODE_STRING *mask,
1532 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1534 DIR *dir;
1535 off_t i, old_pos = 0;
1536 struct dirent *de;
1537 union file_directory_info *info, *last_info = NULL;
1539 if (!(dir = opendir( "." )))
1541 io->u.Status = FILE_GetNtStatus();
1542 return;
1545 if (!restart_scan)
1547 old_pos = lseek( fd, 0, SEEK_CUR );
1548 /* skip the right number of entries */
1549 for (i = 0; i < old_pos - 2; i++)
1551 if (!readdir( dir ))
1553 closedir( dir );
1554 io->u.Status = STATUS_NO_MORE_FILES;
1555 return;
1559 io->u.Status = STATUS_SUCCESS;
1561 for (;;)
1563 if (old_pos == 0)
1564 info = append_entry( buffer, io, length, ".", NULL, mask, class );
1565 else if (old_pos == 1)
1566 info = append_entry( buffer, io, length, "..", NULL, mask, class );
1567 else if ((de = readdir( dir )))
1569 if (strcmp( de->d_name, "." ) && strcmp( de->d_name, ".." ))
1570 info = append_entry( buffer, io, length, de->d_name, NULL, mask, class );
1571 else
1572 info = NULL;
1574 else
1575 break;
1576 old_pos++;
1577 if (info)
1579 last_info = info;
1580 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1582 old_pos--; /* restore pos to previous entry */
1583 break;
1585 if (single_entry) break;
1586 /* check if we still have enough space for the largest possible entry */
1587 if (io->Information + max_dir_info_size(class) > length) break;
1591 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
1592 closedir( dir );
1594 if (last_info) last_info->next = 0;
1595 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1598 /***********************************************************************
1599 * read_directory_stat
1601 * Read a single file from a directory by determining whether the file
1602 * identified by mask exists using stat.
1604 static int read_directory_stat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1605 BOOLEAN single_entry, const UNICODE_STRING *mask,
1606 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1608 int unix_len, ret, used_default;
1609 char *unix_name;
1610 struct stat st;
1612 TRACE("trying optimisation for file %s\n", debugstr_us( mask ));
1614 unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
1615 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
1617 io->u.Status = STATUS_NO_MEMORY;
1618 return 0;
1620 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
1621 NULL, &used_default );
1622 if (ret > 0 && !used_default)
1624 unix_name[ret] = 0;
1625 if (restart_scan)
1627 lseek( fd, 0, SEEK_SET );
1629 else if (lseek( fd, 0, SEEK_CUR ) != 0)
1631 io->u.Status = STATUS_NO_MORE_FILES;
1632 ret = 0;
1633 goto done;
1636 ret = stat( unix_name, &st );
1637 if (!ret)
1639 union file_directory_info *info = append_entry( buffer, io, length, unix_name, NULL, NULL, class );
1640 if (info)
1642 info->next = 0;
1643 if (io->u.Status != STATUS_BUFFER_OVERFLOW) lseek( fd, 1, SEEK_CUR );
1645 else io->u.Status = STATUS_NO_MORE_FILES;
1648 else ret = -1;
1650 done:
1651 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1653 TRACE("returning %d\n", ret);
1655 return ret;
1659 static inline WCHAR *mempbrkW( const WCHAR *ptr, const WCHAR *accept, size_t n )
1661 const WCHAR *end;
1662 for (end = ptr + n; ptr < end; ptr++) if (strchrW( accept, *ptr )) return (WCHAR *)ptr;
1663 return NULL;
1666 /******************************************************************************
1667 * NtQueryDirectoryFile [NTDLL.@]
1668 * ZwQueryDirectoryFile [NTDLL.@]
1670 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
1671 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
1672 PIO_STATUS_BLOCK io,
1673 PVOID buffer, ULONG length,
1674 FILE_INFORMATION_CLASS info_class,
1675 BOOLEAN single_entry,
1676 PUNICODE_STRING mask,
1677 BOOLEAN restart_scan )
1679 int cwd, fd, needs_close;
1680 static const WCHAR wszWildcards[] = { '*','?',0 };
1682 TRACE("(%p %p %p %p %p %p 0x%08x 0x%08x 0x%08x %s 0x%08x\n",
1683 handle, event, apc_routine, apc_context, io, buffer,
1684 length, info_class, single_entry, debugstr_us(mask),
1685 restart_scan);
1687 if (event || apc_routine)
1689 FIXME( "Unsupported yet option\n" );
1690 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1692 switch (info_class)
1694 case FileDirectoryInformation:
1695 case FileBothDirectoryInformation:
1696 case FileFullDirectoryInformation:
1697 case FileIdBothDirectoryInformation:
1698 case FileIdFullDirectoryInformation:
1699 if (length < dir_info_size( info_class, 1 )) return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
1700 break;
1701 default:
1702 FIXME( "Unsupported file info class %d\n", info_class );
1703 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1706 if ((io->u.Status = server_get_unix_fd( handle, FILE_LIST_DIRECTORY, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
1707 return io->u.Status;
1709 io->Information = 0;
1711 RtlEnterCriticalSection( &dir_section );
1713 if (show_dot_files == -1) init_options();
1715 cwd = open( ".", O_RDONLY );
1716 if (fchdir( fd ) != -1)
1718 struct stat st;
1719 fstat( fd, &st );
1720 curdir.dev = st.st_dev;
1721 curdir.ino = st.st_ino;
1722 #ifdef VFAT_IOCTL_READDIR_BOTH
1723 if ((read_directory_vfat( fd, io, buffer, length, single_entry,
1724 mask, restart_scan, info_class )) != -1) goto done;
1725 #endif
1726 if (mask && !mempbrkW( mask->Buffer, wszWildcards, mask->Length / sizeof(WCHAR) ) &&
1727 read_directory_stat( fd, io, buffer, length, single_entry,
1728 mask, restart_scan, info_class ) != -1) goto done;
1729 #ifdef USE_GETDENTS
1730 if ((read_directory_getdents( fd, io, buffer, length, single_entry,
1731 mask, restart_scan, info_class )) != -1) goto done;
1732 #elif defined HAVE_GETDIRENTRIES
1733 if ((read_directory_getdirentries( fd, io, buffer, length, single_entry,
1734 mask, restart_scan, info_class )) != -1) goto done;
1735 #endif
1736 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan, info_class );
1738 done:
1739 if (cwd == -1 || fchdir( cwd ) == -1) chdir( "/" );
1741 else io->u.Status = FILE_GetNtStatus();
1743 RtlLeaveCriticalSection( &dir_section );
1745 if (needs_close) close( fd );
1746 if (cwd != -1) close( cwd );
1747 TRACE( "=> %x (%ld)\n", io->u.Status, io->Information );
1748 return io->u.Status;
1752 /***********************************************************************
1753 * find_file_in_dir
1755 * Find a file in a directory the hard way, by doing a case-insensitive search.
1756 * The file found is appended to unix_name at pos.
1757 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
1759 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
1760 int check_case, int *is_win_dir )
1762 WCHAR buffer[MAX_DIR_ENTRY_LEN];
1763 UNICODE_STRING str;
1764 BOOLEAN spaces;
1765 DIR *dir;
1766 struct dirent *de;
1767 struct stat st;
1768 int ret, used_default, is_name_8_dot_3;
1770 /* try a shortcut for this directory */
1772 unix_name[pos++] = '/';
1773 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
1774 NULL, &used_default );
1775 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
1776 /* so it cannot match the file we are looking for */
1777 if (ret >= 0 && !used_default)
1779 unix_name[pos + ret] = 0;
1780 if (!stat( unix_name, &st ))
1782 if (is_win_dir) *is_win_dir = is_same_file( &windir, &st );
1783 return STATUS_SUCCESS;
1786 if (check_case) goto not_found; /* we want an exact match */
1788 if (pos > 1) unix_name[pos - 1] = 0;
1789 else unix_name[1] = 0; /* keep the initial slash */
1791 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
1793 str.Buffer = (WCHAR *)name;
1794 str.Length = length * sizeof(WCHAR);
1795 str.MaximumLength = str.Length;
1796 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
1798 /* now look for it through the directory */
1800 #ifdef VFAT_IOCTL_READDIR_BOTH
1801 if (is_name_8_dot_3)
1803 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
1804 if (fd != -1)
1806 KERNEL_DIRENT *de;
1808 RtlEnterCriticalSection( &dir_section );
1809 if ((de = start_vfat_ioctl( fd )))
1811 unix_name[pos - 1] = '/';
1812 while (de[0].d_reclen)
1814 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1815 size_t len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1816 de[0].d_name[len] = 0;
1817 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1818 de[1].d_name[len] = 0;
1820 if (de[1].d_name[0])
1822 ret = ntdll_umbstowcs( 0, de[1].d_name, strlen(de[1].d_name),
1823 buffer, MAX_DIR_ENTRY_LEN );
1824 if (ret == length && !memicmpW( buffer, name, length))
1826 strcpy( unix_name + pos, de[1].d_name );
1827 RtlLeaveCriticalSection( &dir_section );
1828 close( fd );
1829 goto success;
1832 ret = ntdll_umbstowcs( 0, de[0].d_name, strlen(de[0].d_name),
1833 buffer, MAX_DIR_ENTRY_LEN );
1834 if (ret == length && !memicmpW( buffer, name, length))
1836 strcpy( unix_name + pos,
1837 de[1].d_name[0] ? de[1].d_name : de[0].d_name );
1838 RtlLeaveCriticalSection( &dir_section );
1839 close( fd );
1840 goto success;
1842 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1)
1844 RtlLeaveCriticalSection( &dir_section );
1845 close( fd );
1846 goto not_found;
1850 RtlLeaveCriticalSection( &dir_section );
1851 close( fd );
1853 /* fall through to normal handling */
1855 #endif /* VFAT_IOCTL_READDIR_BOTH */
1857 if (!(dir = opendir( unix_name )))
1859 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
1860 else return FILE_GetNtStatus();
1862 unix_name[pos - 1] = '/';
1863 str.Buffer = buffer;
1864 str.MaximumLength = sizeof(buffer);
1865 while ((de = readdir( dir )))
1867 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
1868 if (ret == length && !memicmpW( buffer, name, length ))
1870 strcpy( unix_name + pos, de->d_name );
1871 closedir( dir );
1872 goto success;
1875 if (!is_name_8_dot_3) continue;
1877 str.Length = ret * sizeof(WCHAR);
1878 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1880 WCHAR short_nameW[12];
1881 ret = hash_short_file_name( &str, short_nameW );
1882 if (ret == length && !memicmpW( short_nameW, name, length ))
1884 strcpy( unix_name + pos, de->d_name );
1885 closedir( dir );
1886 goto success;
1890 closedir( dir );
1891 goto not_found; /* avoid warning */
1893 not_found:
1894 unix_name[pos - 1] = 0;
1895 return STATUS_OBJECT_PATH_NOT_FOUND;
1897 success:
1898 if (is_win_dir && !stat( unix_name, &st )) *is_win_dir = is_same_file( &windir, &st );
1899 return STATUS_SUCCESS;
1903 #ifndef _WIN64
1905 static const WCHAR catrootW[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t',0};
1906 static const WCHAR catroot2W[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t','2',0};
1907 static const WCHAR driversstoreW[] = {'s','y','s','t','e','m','3','2','\\','d','r','i','v','e','r','s','s','t','o','r','e',0};
1908 static const WCHAR driversetcW[] = {'s','y','s','t','e','m','3','2','\\','d','r','i','v','e','r','s','\\','e','t','c',0};
1909 static const WCHAR logfilesW[] = {'s','y','s','t','e','m','3','2','\\','l','o','g','f','i','l','e','s',0};
1910 static const WCHAR spoolW[] = {'s','y','s','t','e','m','3','2','\\','s','p','o','o','l',0};
1911 static const WCHAR system32W[] = {'s','y','s','t','e','m','3','2',0};
1912 static const WCHAR syswow64W[] = {'s','y','s','w','o','w','6','4',0};
1913 static const WCHAR sysnativeW[] = {'s','y','s','n','a','t','i','v','e',0};
1914 static const WCHAR regeditW[] = {'r','e','g','e','d','i','t','.','e','x','e',0};
1915 static const WCHAR wow_regeditW[] = {'s','y','s','w','o','w','6','4','\\','r','e','g','e','d','i','t','.','e','x','e',0};
1917 static struct
1919 const WCHAR *source;
1920 const WCHAR *dos_target;
1921 const char *unix_target;
1922 } redirects[] =
1924 { catrootW, NULL, NULL },
1925 { catroot2W, NULL, NULL },
1926 { driversstoreW, NULL, NULL },
1927 { driversetcW, NULL, NULL },
1928 { logfilesW, NULL, NULL },
1929 { spoolW, NULL, NULL },
1930 { system32W, syswow64W, NULL },
1931 { sysnativeW, system32W, NULL },
1932 { regeditW, wow_regeditW, NULL }
1935 static unsigned int nb_redirects;
1938 /***********************************************************************
1939 * get_redirect_target
1941 * Find the target unix name for a redirected dir.
1943 static const char *get_redirect_target( const char *windows_dir, const WCHAR *name )
1945 int used_default, len, pos, win_len = strlen( windows_dir );
1946 char *unix_name, *unix_target = NULL;
1947 NTSTATUS status;
1949 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, win_len + MAX_DIR_ENTRY_LEN + 2 )))
1950 return NULL;
1951 memcpy( unix_name, windows_dir, win_len );
1952 pos = win_len;
1954 while (*name)
1956 const WCHAR *end, *next;
1958 for (end = name; *end; end++) if (IS_SEPARATOR(*end)) break;
1959 for (next = end; *next; next++) if (!IS_SEPARATOR(*next)) break;
1961 status = find_file_in_dir( unix_name, pos, name, end - name, FALSE, NULL );
1962 if (status == STATUS_OBJECT_PATH_NOT_FOUND && !*next) /* not finding last element is ok */
1964 len = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
1965 MAX_DIR_ENTRY_LEN - (pos - win_len), NULL, &used_default );
1966 if (len > 0 && !used_default)
1968 unix_name[pos] = '/';
1969 pos += len + 1;
1970 unix_name[pos] = 0;
1971 break;
1974 if (status) goto done;
1975 pos += strlen( unix_name + pos );
1976 name = next;
1979 if ((unix_target = RtlAllocateHeap( GetProcessHeap(), 0, pos - win_len )))
1980 memcpy( unix_target, unix_name + win_len + 1, pos - win_len );
1982 done:
1983 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1984 return unix_target;
1988 /***********************************************************************
1989 * init_redirects
1991 static void init_redirects(void)
1993 UNICODE_STRING nt_name;
1994 ANSI_STRING unix_name;
1995 NTSTATUS status;
1996 struct stat st;
1997 unsigned int i;
1999 if (!RtlDosPathNameToNtPathName_U( windows_dir.Buffer, &nt_name, NULL, NULL ))
2001 ERR( "can't convert %s\n", debugstr_us(&windows_dir) );
2002 return;
2004 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
2005 RtlFreeUnicodeString( &nt_name );
2006 if (status)
2008 ERR( "cannot open %s (%x)\n", debugstr_us(&windows_dir), status );
2009 return;
2011 if (!stat( unix_name.Buffer, &st ))
2013 windir.dev = st.st_dev;
2014 windir.ino = st.st_ino;
2015 nb_redirects = sizeof(redirects) / sizeof(redirects[0]);
2016 for (i = 0; i < nb_redirects; i++)
2018 if (!redirects[i].dos_target) continue;
2019 redirects[i].unix_target = get_redirect_target( unix_name.Buffer, redirects[i].dos_target );
2020 TRACE( "%s -> %s\n", debugstr_w(redirects[i].source), redirects[i].unix_target );
2023 RtlFreeAnsiString( &unix_name );
2028 /***********************************************************************
2029 * match_redirect
2031 * Check if path matches a redirect name. If yes, return matched length.
2033 static int match_redirect( const WCHAR *path, int len, const WCHAR *redir, int check_case )
2035 int i = 0;
2037 while (i < len && *redir)
2039 if (IS_SEPARATOR(path[i]))
2041 if (*redir++ != '\\') return 0;
2042 while (i < len && IS_SEPARATOR(path[i])) i++;
2043 continue; /* move on to next path component */
2045 else if (check_case)
2047 if (path[i] != *redir) return 0;
2049 else
2051 if (tolowerW(path[i]) != tolowerW(*redir)) return 0;
2053 i++;
2054 redir++;
2056 if (*redir) return 0;
2057 if (i < len && !IS_SEPARATOR(path[i])) return 0;
2058 while (i < len && IS_SEPARATOR(path[i])) i++;
2059 return i;
2063 /***********************************************************************
2064 * get_redirect_path
2066 * Retrieve the Unix path corresponding to a redirected path if any.
2068 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, int check_case )
2070 unsigned int i;
2071 int len;
2073 for (i = 0; i < nb_redirects; i++)
2075 if ((len = match_redirect( name, length, redirects[i].source, check_case )))
2077 if (!redirects[i].unix_target) break;
2078 unix_name[pos++] = '/';
2079 strcpy( unix_name + pos, redirects[i].unix_target );
2080 return len;
2083 return 0;
2086 #else /* _WIN64 */
2088 /* there are no redirects on 64-bit */
2090 static const unsigned int nb_redirects = 0;
2092 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, int check_case )
2094 return 0;
2097 #endif
2099 /***********************************************************************
2100 * DIR_init_windows_dir
2102 void DIR_init_windows_dir( const WCHAR *win, const WCHAR *sys )
2104 /* FIXME: should probably store paths as NT file names */
2106 RtlCreateUnicodeString( &windows_dir, win );
2107 RtlCreateUnicodeString( &system_dir, sys );
2109 #ifndef _WIN64
2110 if (is_wow64) init_redirects();
2111 #endif
2115 /******************************************************************************
2116 * get_dos_device
2118 * Get the Unix path of a DOS device.
2120 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
2122 const char *config_dir = wine_get_config_dir();
2123 struct stat st;
2124 char *unix_name, *new_name, *dev;
2125 unsigned int i;
2126 int unix_len;
2128 /* make sure the device name is ASCII */
2129 for (i = 0; i < name_len; i++)
2130 if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
2132 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
2134 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2135 return STATUS_NO_MEMORY;
2137 strcpy( unix_name, config_dir );
2138 strcat( unix_name, "/dosdevices/" );
2139 dev = unix_name + strlen(unix_name);
2141 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
2142 dev[i] = 0;
2144 /* special case for drive devices */
2145 if (name_len == 2 && dev[1] == ':')
2147 dev[i++] = ':';
2148 dev[i] = 0;
2151 for (;;)
2153 if (!stat( unix_name, &st ))
2155 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
2156 unix_name_ret->Buffer = unix_name;
2157 unix_name_ret->Length = strlen(unix_name);
2158 unix_name_ret->MaximumLength = unix_len;
2159 return STATUS_SUCCESS;
2161 if (!dev) break;
2163 /* now try some defaults for it */
2164 if (!strcmp( dev, "aux" ))
2166 strcpy( dev, "com1" );
2167 continue;
2169 if (!strcmp( dev, "prn" ))
2171 strcpy( dev, "lpt1" );
2172 continue;
2174 if (!strcmp( dev, "nul" ))
2176 strcpy( unix_name, "/dev/null" );
2177 dev = NULL; /* last try */
2178 continue;
2181 new_name = NULL;
2182 if (dev[1] == ':' && dev[2] == ':') /* drive device */
2184 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
2185 new_name = get_default_drive_device( unix_name );
2187 else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( atoi(dev + 3 ));
2188 else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( atoi(dev + 3 ));
2190 if (!new_name) break;
2192 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2193 unix_name = new_name;
2194 unix_len = strlen(unix_name) + 1;
2195 dev = NULL; /* last try */
2197 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2198 return STATUS_BAD_DEVICE_TYPE;
2202 /* return the length of the DOS namespace prefix if any */
2203 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
2205 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
2206 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
2208 if (name->Length > sizeof(nt_prefixW) &&
2209 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
2210 return sizeof(nt_prefixW) / sizeof(WCHAR);
2212 if (name->Length > sizeof(dosdev_prefixW) &&
2213 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
2214 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
2216 return 0;
2220 /******************************************************************************
2221 * file_id_to_unix_file_name
2223 * Lookup a file from its file id instead of its name.
2225 NTSTATUS file_id_to_unix_file_name( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name_ret )
2227 enum server_fd_type type;
2228 int old_cwd, root_fd, needs_close;
2229 char *unix_name;
2230 int unix_len;
2231 NTSTATUS status;
2232 ULONGLONG file_id;
2233 struct stat st, root_st;
2234 DIR *dir;
2235 struct dirent *de;
2237 if (attr->ObjectName->Length != sizeof(ULONGLONG)) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2238 if (!attr->RootDirectory) return STATUS_INVALID_PARAMETER;
2239 memcpy( &file_id, attr->ObjectName->Buffer, sizeof(file_id) );
2241 unix_len = MAX_DIR_ENTRY_LEN + 1;
2242 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2243 return STATUS_NO_MEMORY;
2244 unix_name[0] = 0;
2246 if (!(status = server_get_unix_fd( attr->RootDirectory, FILE_READ_DATA, &root_fd,
2247 &needs_close, &type, NULL )))
2249 if (type != FD_TYPE_DIR)
2251 if (needs_close) close( root_fd );
2252 status = STATUS_OBJECT_TYPE_MISMATCH;
2254 else
2256 fstat( root_fd, &root_st );
2257 RtlEnterCriticalSection( &dir_section );
2258 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2260 if (!(dir = opendir( "." ))) status = FILE_GetNtStatus();
2261 else
2263 while ((de = readdir( dir )))
2265 if (stat( de->d_name, &st ) == -1) continue;
2266 if (st.st_dev == root_st.st_dev && st.st_ino == file_id)
2268 strcpy( unix_name, de->d_name );
2269 break;
2272 closedir( dir );
2273 if (!unix_name[0]) status = STATUS_OBJECT_NAME_NOT_FOUND;
2275 if (fchdir( old_cwd ) == -1) chdir( "/" );
2277 else status = FILE_GetNtStatus();
2278 RtlLeaveCriticalSection( &dir_section );
2279 if (old_cwd != -1) close( old_cwd );
2280 if (needs_close) close( root_fd );
2284 if (status == STATUS_SUCCESS)
2286 TRACE( "%s -> %s\n", wine_dbgstr_longlong(file_id), debugstr_a(unix_name) );
2287 unix_name_ret->Buffer = unix_name;
2288 unix_name_ret->Length = strlen(unix_name);
2289 unix_name_ret->MaximumLength = unix_len;
2291 else
2293 TRACE( "%s not found in %s\n", wine_dbgstr_longlong(file_id), unix_name );
2294 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2296 return status;
2300 /******************************************************************************
2301 * lookup_unix_name
2303 * Helper for nt_to_unix_file_name
2305 static NTSTATUS lookup_unix_name( const WCHAR *name, int name_len, char **buffer, int unix_len, int pos,
2306 UINT disposition, BOOLEAN check_case )
2308 NTSTATUS status;
2309 int ret, used_default, len;
2310 struct stat st;
2311 char *unix_name = *buffer;
2312 const BOOL redirect = nb_redirects && ntdll_get_thread_data()->wow64_redir;
2314 /* try a shortcut first */
2316 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
2317 NULL, &used_default );
2319 while (name_len && IS_SEPARATOR(*name))
2321 name++;
2322 name_len--;
2325 if (ret >= 0 && !used_default) /* if we used the default char the name didn't convert properly */
2327 char *p;
2328 unix_name[pos + ret] = 0;
2329 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
2330 if (!redirect || (!strstr( unix_name, "/windows/") && strncmp( unix_name, "windows/", 8 )))
2332 if (!stat( unix_name, &st ))
2334 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
2335 if (disposition == FILE_CREATE)
2336 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
2337 return STATUS_SUCCESS;
2342 if (!name_len) /* empty name -> drive root doesn't exist */
2343 return STATUS_OBJECT_PATH_NOT_FOUND;
2344 if (check_case && !redirect && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
2345 return STATUS_OBJECT_NAME_NOT_FOUND;
2347 /* now do it component by component */
2349 while (name_len)
2351 const WCHAR *end, *next;
2352 int is_win_dir = 0;
2354 end = name;
2355 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
2356 next = end;
2357 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
2358 name_len -= next - name;
2360 /* grow the buffer if needed */
2362 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
2364 char *new_name;
2365 unix_len += 2 * MAX_DIR_ENTRY_LEN;
2366 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
2367 return STATUS_NO_MEMORY;
2368 unix_name = *buffer = new_name;
2371 status = find_file_in_dir( unix_name, pos, name, end - name,
2372 check_case, redirect ? &is_win_dir : NULL );
2374 /* if this is the last element, not finding it is not necessarily fatal */
2375 if (!name_len)
2377 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
2379 status = STATUS_OBJECT_NAME_NOT_FOUND;
2380 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
2382 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2383 MAX_DIR_ENTRY_LEN, NULL, &used_default );
2384 if (ret > 0 && !used_default)
2386 unix_name[pos] = '/';
2387 unix_name[pos + 1 + ret] = 0;
2388 status = STATUS_NO_SUCH_FILE;
2389 break;
2393 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
2395 status = STATUS_OBJECT_NAME_COLLISION;
2399 if (status != STATUS_SUCCESS) break;
2401 pos += strlen( unix_name + pos );
2402 name = next;
2404 if (is_win_dir && (len = get_redirect_path( unix_name, pos, name, name_len, check_case )))
2406 name += len;
2407 name_len -= len;
2408 pos += strlen( unix_name + pos );
2409 TRACE( "redirecting -> %s + %s\n", debugstr_a(unix_name), debugstr_w(name) );
2413 return status;
2417 /******************************************************************************
2418 * nt_to_unix_file_name_attr
2420 NTSTATUS nt_to_unix_file_name_attr( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name_ret,
2421 UINT disposition )
2423 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2424 enum server_fd_type type;
2425 int old_cwd, root_fd, needs_close;
2426 const WCHAR *name, *p;
2427 char *unix_name;
2428 int name_len, unix_len;
2429 NTSTATUS status;
2430 BOOLEAN check_case = !(attr->Attributes & OBJ_CASE_INSENSITIVE);
2432 if (!attr->RootDirectory) /* without root dir fall back to normal lookup */
2433 return wine_nt_to_unix_file_name( attr->ObjectName, unix_name_ret, disposition, check_case );
2435 name = attr->ObjectName->Buffer;
2436 name_len = attr->ObjectName->Length / sizeof(WCHAR);
2438 if (name_len && IS_SEPARATOR(name[0])) return STATUS_INVALID_PARAMETER;
2440 /* check for invalid characters */
2441 for (p = name; p < name + name_len; p++)
2442 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2444 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
2445 unix_len += MAX_DIR_ENTRY_LEN + 3;
2446 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2447 return STATUS_NO_MEMORY;
2448 unix_name[0] = '.';
2450 if (!(status = server_get_unix_fd( attr->RootDirectory, FILE_READ_DATA, &root_fd,
2451 &needs_close, &type, NULL )))
2453 if (type != FD_TYPE_DIR)
2455 if (needs_close) close( root_fd );
2456 status = STATUS_BAD_DEVICE_TYPE;
2458 else
2460 RtlEnterCriticalSection( &dir_section );
2461 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2463 status = lookup_unix_name( name, name_len, &unix_name, unix_len, 1,
2464 disposition, check_case );
2465 if (fchdir( old_cwd ) == -1) chdir( "/" );
2467 else status = FILE_GetNtStatus();
2468 RtlLeaveCriticalSection( &dir_section );
2469 if (old_cwd != -1) close( old_cwd );
2470 if (needs_close) close( root_fd );
2473 else if (status == STATUS_OBJECT_TYPE_MISMATCH) status = STATUS_BAD_DEVICE_TYPE;
2475 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
2477 TRACE( "%s -> %s\n", debugstr_us(attr->ObjectName), debugstr_a(unix_name) );
2478 unix_name_ret->Buffer = unix_name;
2479 unix_name_ret->Length = strlen(unix_name);
2480 unix_name_ret->MaximumLength = unix_len;
2482 else
2484 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
2485 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2487 return status;
2491 /******************************************************************************
2492 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
2494 * Convert a file name from NT namespace to Unix namespace.
2496 * If disposition is not FILE_OPEN or FILE_OVERWRITE, the last path
2497 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
2498 * returned, but the unix name is still filled in properly.
2500 NTSTATUS CDECL wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
2501 UINT disposition, BOOLEAN check_case )
2503 static const WCHAR unixW[] = {'u','n','i','x'};
2504 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2506 NTSTATUS status = STATUS_SUCCESS;
2507 const char *config_dir = wine_get_config_dir();
2508 const WCHAR *name, *p;
2509 struct stat st;
2510 char *unix_name;
2511 int pos, ret, name_len, unix_len, prefix_len, used_default;
2512 WCHAR prefix[MAX_DIR_ENTRY_LEN];
2513 BOOLEAN is_unix = FALSE;
2515 name = nameW->Buffer;
2516 name_len = nameW->Length / sizeof(WCHAR);
2518 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2520 if (!(pos = get_dos_prefix_len( nameW )))
2521 return STATUS_BAD_DEVICE_TYPE; /* no DOS prefix, assume NT native name */
2523 name += pos;
2524 name_len -= pos;
2526 /* check for sub-directory */
2527 for (pos = 0; pos < name_len; pos++)
2529 if (IS_SEPARATOR(name[pos])) break;
2530 if (name[pos] < 32 || strchrW( invalid_charsW, name[pos] ))
2531 return STATUS_OBJECT_NAME_INVALID;
2533 if (pos > MAX_DIR_ENTRY_LEN)
2534 return STATUS_OBJECT_NAME_INVALID;
2536 if (pos == name_len) /* no subdir, plain DOS device */
2537 return get_dos_device( name, name_len, unix_name_ret );
2539 for (prefix_len = 0; prefix_len < pos; prefix_len++)
2540 prefix[prefix_len] = tolowerW(name[prefix_len]);
2542 name += prefix_len;
2543 name_len -= prefix_len;
2545 /* check for invalid characters (all chars except 0 are valid for unix) */
2546 is_unix = (prefix_len == 4 && !memcmp( prefix, unixW, sizeof(unixW) ));
2547 if (is_unix)
2549 for (p = name; p < name + name_len; p++)
2550 if (!*p) return STATUS_OBJECT_NAME_INVALID;
2551 check_case = TRUE;
2553 else
2555 for (p = name; p < name + name_len; p++)
2556 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2559 unix_len = ntdll_wcstoumbs( 0, prefix, prefix_len, NULL, 0, NULL, NULL );
2560 unix_len += ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
2561 unix_len += MAX_DIR_ENTRY_LEN + 3;
2562 unix_len += strlen(config_dir) + sizeof("/dosdevices/");
2563 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2564 return STATUS_NO_MEMORY;
2565 strcpy( unix_name, config_dir );
2566 strcat( unix_name, "/dosdevices/" );
2567 pos = strlen(unix_name);
2569 ret = ntdll_wcstoumbs( 0, prefix, prefix_len, unix_name + pos, unix_len - pos - 1,
2570 NULL, &used_default );
2571 if (!ret || used_default)
2573 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2574 return STATUS_OBJECT_NAME_INVALID;
2576 pos += ret;
2578 /* check if prefix exists (except for DOS drives to avoid extra stat calls) */
2580 if (prefix_len != 2 || prefix[1] != ':')
2582 unix_name[pos] = 0;
2583 if (lstat( unix_name, &st ) == -1 && errno == ENOENT)
2585 if (!is_unix)
2587 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2588 return STATUS_BAD_DEVICE_TYPE;
2590 pos = 0; /* fall back to unix root */
2594 status = lookup_unix_name( name, name_len, &unix_name, unix_len, pos, disposition, check_case );
2595 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
2597 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
2598 unix_name_ret->Buffer = unix_name;
2599 unix_name_ret->Length = strlen(unix_name);
2600 unix_name_ret->MaximumLength = unix_len;
2602 else
2604 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
2605 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2607 return status;
2611 /******************************************************************
2612 * RtlWow64EnableFsRedirection (NTDLL.@)
2614 NTSTATUS WINAPI RtlWow64EnableFsRedirection( BOOLEAN enable )
2616 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
2617 ntdll_get_thread_data()->wow64_redir = enable;
2618 return STATUS_SUCCESS;
2622 /******************************************************************
2623 * RtlWow64EnableFsRedirectionEx (NTDLL.@)
2625 NTSTATUS WINAPI RtlWow64EnableFsRedirectionEx( ULONG disable, ULONG *old_value )
2627 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
2628 *old_value = !ntdll_get_thread_data()->wow64_redir;
2629 ntdll_get_thread_data()->wow64_redir = !disable;
2630 return STATUS_SUCCESS;
2634 /******************************************************************
2635 * RtlDoesFileExists_U (NTDLL.@)
2637 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
2639 UNICODE_STRING nt_name;
2640 FILE_BASIC_INFORMATION basic_info;
2641 OBJECT_ATTRIBUTES attr;
2642 BOOLEAN ret;
2644 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
2646 attr.Length = sizeof(attr);
2647 attr.RootDirectory = 0;
2648 attr.ObjectName = &nt_name;
2649 attr.Attributes = OBJ_CASE_INSENSITIVE;
2650 attr.SecurityDescriptor = NULL;
2651 attr.SecurityQualityOfService = NULL;
2653 ret = NtQueryAttributesFile(&attr, &basic_info) == STATUS_SUCCESS;
2655 RtlFreeUnicodeString( &nt_name );
2656 return ret;
2660 /***********************************************************************
2661 * DIR_unmount_device
2663 * Unmount the specified device.
2665 NTSTATUS DIR_unmount_device( HANDLE handle )
2667 NTSTATUS status;
2668 int unix_fd, needs_close;
2670 if (!(status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )))
2672 struct stat st;
2673 char *mount_point = NULL;
2675 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2676 status = STATUS_INVALID_PARAMETER;
2677 else
2679 if ((mount_point = get_device_mount_point( st.st_rdev )))
2681 #ifdef __APPLE__
2682 static const char umount[] = "diskutil unmount >/dev/null 2>&1 ";
2683 #else
2684 static const char umount[] = "umount >/dev/null 2>&1 ";
2685 #endif
2686 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
2687 if (cmd)
2689 strcpy( cmd, umount );
2690 strcat( cmd, mount_point );
2691 system( cmd );
2692 RtlFreeHeap( GetProcessHeap(), 0, cmd );
2693 #ifdef linux
2694 /* umount will fail to release the loop device since we still have
2695 a handle to it, so we release it here */
2696 if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
2697 #endif
2699 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
2702 if (needs_close) close( unix_fd );
2704 return status;
2708 /******************************************************************************
2709 * DIR_get_unix_cwd
2711 * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
2712 * Returned value must be freed by caller.
2714 NTSTATUS DIR_get_unix_cwd( char **cwd )
2716 int old_cwd, unix_fd, needs_close;
2717 CURDIR *curdir;
2718 HANDLE handle;
2719 NTSTATUS status;
2721 RtlAcquirePebLock();
2723 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
2724 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
2725 else
2726 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
2728 if (!(handle = curdir->Handle))
2730 UNICODE_STRING dirW;
2731 OBJECT_ATTRIBUTES attr;
2732 IO_STATUS_BLOCK io;
2734 if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
2736 status = STATUS_OBJECT_NAME_INVALID;
2737 goto done;
2739 attr.Length = sizeof(attr);
2740 attr.RootDirectory = 0;
2741 attr.Attributes = OBJ_CASE_INSENSITIVE;
2742 attr.ObjectName = &dirW;
2743 attr.SecurityDescriptor = NULL;
2744 attr.SecurityQualityOfService = NULL;
2746 status = NtOpenFile( &handle, 0, &attr, &io, 0,
2747 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
2748 RtlFreeUnicodeString( &dirW );
2749 if (status != STATUS_SUCCESS) goto done;
2752 if ((status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )) == STATUS_SUCCESS)
2754 RtlEnterCriticalSection( &dir_section );
2756 if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
2758 unsigned int size = 512;
2760 for (;;)
2762 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2764 status = STATUS_NO_MEMORY;
2765 break;
2767 if (getcwd( *cwd, size )) break;
2768 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
2769 if (errno != ERANGE)
2771 status = STATUS_OBJECT_PATH_INVALID;
2772 break;
2774 size *= 2;
2776 if (fchdir( old_cwd ) == -1) chdir( "/" );
2778 else status = FILE_GetNtStatus();
2780 RtlLeaveCriticalSection( &dir_section );
2781 if (old_cwd != -1) close( old_cwd );
2782 if (needs_close) close( unix_fd );
2784 if (!curdir->Handle) NtClose( handle );
2786 done:
2787 RtlReleasePebLock();
2788 return status;
2791 struct read_changes_info
2793 HANDLE FileHandle;
2794 PVOID Buffer;
2795 ULONG BufferSize;
2796 PIO_APC_ROUTINE apc;
2797 void *apc_arg;
2800 /* callback for ioctl user APC */
2801 static void WINAPI read_changes_user_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
2803 struct read_changes_info *info = arg;
2804 if (info->apc) info->apc( info->apc_arg, io, reserved );
2805 RtlFreeHeap( GetProcessHeap(), 0, info );
2808 static NTSTATUS read_changes_apc( void *user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
2810 struct read_changes_info *info = user;
2811 char path[PATH_MAX];
2812 NTSTATUS ret = STATUS_SUCCESS;
2813 int len, action, i;
2815 SERVER_START_REQ( read_change )
2817 req->handle = wine_server_obj_handle( info->FileHandle );
2818 wine_server_set_reply( req, path, PATH_MAX );
2819 ret = wine_server_call( req );
2820 action = reply->action;
2821 len = wine_server_reply_size( reply );
2823 SERVER_END_REQ;
2825 if (ret == STATUS_SUCCESS && info->Buffer &&
2826 (info->BufferSize > (sizeof (FILE_NOTIFY_INFORMATION) + len*sizeof(WCHAR))))
2828 PFILE_NOTIFY_INFORMATION pfni;
2830 pfni = info->Buffer;
2832 /* convert to an NT style path */
2833 for (i=0; i<len; i++)
2834 if (path[i] == '/')
2835 path[i] = '\\';
2837 len = ntdll_umbstowcs( 0, path, len, pfni->FileName,
2838 info->BufferSize - sizeof (*pfni) );
2840 pfni->NextEntryOffset = 0;
2841 pfni->Action = action;
2842 pfni->FileNameLength = len * sizeof (WCHAR);
2843 pfni->FileName[len] = 0;
2844 len = sizeof (*pfni) - sizeof (DWORD) + pfni->FileNameLength;
2846 else
2848 ret = STATUS_NOTIFY_ENUM_DIR;
2849 len = 0;
2852 iosb->u.Status = ret;
2853 iosb->Information = len;
2854 *apc = read_changes_user_apc;
2855 return ret;
2858 #define FILE_NOTIFY_ALL ( \
2859 FILE_NOTIFY_CHANGE_FILE_NAME | \
2860 FILE_NOTIFY_CHANGE_DIR_NAME | \
2861 FILE_NOTIFY_CHANGE_ATTRIBUTES | \
2862 FILE_NOTIFY_CHANGE_SIZE | \
2863 FILE_NOTIFY_CHANGE_LAST_WRITE | \
2864 FILE_NOTIFY_CHANGE_LAST_ACCESS | \
2865 FILE_NOTIFY_CHANGE_CREATION | \
2866 FILE_NOTIFY_CHANGE_SECURITY )
2868 /******************************************************************************
2869 * NtNotifyChangeDirectoryFile [NTDLL.@]
2871 NTSTATUS WINAPI
2872 NtNotifyChangeDirectoryFile( HANDLE FileHandle, HANDLE Event,
2873 PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext,
2874 PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer,
2875 ULONG BufferSize, ULONG CompletionFilter, BOOLEAN WatchTree )
2877 struct read_changes_info *info;
2878 NTSTATUS status;
2879 ULONG_PTR cvalue = ApcRoutine ? 0 : (ULONG_PTR)ApcContext;
2881 TRACE("%p %p %p %p %p %p %u %u %d\n",
2882 FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock,
2883 Buffer, BufferSize, CompletionFilter, WatchTree );
2885 if (!IoStatusBlock)
2886 return STATUS_ACCESS_VIOLATION;
2888 if (CompletionFilter == 0 || (CompletionFilter & ~FILE_NOTIFY_ALL))
2889 return STATUS_INVALID_PARAMETER;
2891 info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof *info );
2892 if (!info)
2893 return STATUS_NO_MEMORY;
2895 info->FileHandle = FileHandle;
2896 info->Buffer = Buffer;
2897 info->BufferSize = BufferSize;
2898 info->apc = ApcRoutine;
2899 info->apc_arg = ApcContext;
2901 SERVER_START_REQ( read_directory_changes )
2903 req->filter = CompletionFilter;
2904 req->want_data = (Buffer != NULL);
2905 req->subtree = WatchTree;
2906 req->async.handle = wine_server_obj_handle( FileHandle );
2907 req->async.callback = wine_server_client_ptr( read_changes_apc );
2908 req->async.iosb = wine_server_client_ptr( IoStatusBlock );
2909 req->async.arg = wine_server_client_ptr( info );
2910 req->async.event = wine_server_obj_handle( Event );
2911 req->async.cvalue = cvalue;
2912 status = wine_server_call( req );
2914 SERVER_END_REQ;
2916 if (status != STATUS_PENDING)
2917 RtlFreeHeap( GetProcessHeap(), 0, info );
2919 return status;