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
24 #include "wine/port.h"
27 #include <sys/types.h>
41 #ifdef HAVE_SYS_STAT_H
42 # include <sys/stat.h>
44 #ifdef HAVE_SYS_IOCTL_H
45 #include <sys/ioctl.h>
47 #ifdef HAVE_LINUX_IOCTL_H
48 #include <linux/ioctl.h>
50 #ifdef HAVE_LINUX_MAJOR_H
51 # include <linux/major.h>
53 #ifdef HAVE_SYS_PARAM_H
54 #include <sys/param.h>
56 #ifdef HAVE_SYS_MOUNT_H
57 #include <sys/mount.h>
64 #define NONAMELESSUNION
65 #define NONAMELESSSTRUCT
67 #define WIN32_NO_STATUS
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);
80 #undef VFAT_IOCTL_READDIR_BOTH
85 /* We want the real kernel dirent structure, not the libc one */
90 unsigned short d_reclen;
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] )
98 # define O_DIRECTORY 0200000 /* must be directory */
107 unsigned short d_reclen;
108 unsigned char d_type;
112 static inline int getdents64( int fd, char *de, unsigned int size )
115 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
117 : "0" (220 /*NR_getdents64*/), "r" (fd), "c" (de), "d" (size)
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
148 static struct file_identity ignored_files[MAX_IGNORED_FILES];
149 static int ignored_files_count;
151 union file_directory_info
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 windir;
171 static RTL_CRITICAL_SECTION dir_section;
172 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
175 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
176 0, 0, { (DWORD_PTR)(__FILE__ ": dir_section") }
178 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
181 /* check if a given Unicode char is OK in a DOS short name */
182 static inline BOOL is_invalid_dos_char( WCHAR ch )
184 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
185 if (ch > 0x7f) return TRUE;
186 return strchrW( invalid_chars, ch ) != NULL;
189 /* check if the device can be a mounted volume */
190 static inline int is_valid_mounted_device( const struct stat *st )
192 #if defined(linux) || defined(__sun__)
193 return S_ISBLK( st->st_mode );
195 /* disks are char devices on *BSD */
196 return S_ISCHR( st->st_mode );
200 static inline void ignore_file( const char *name )
203 assert( ignored_files_count < MAX_IGNORED_FILES );
204 if (!stat( name, &st ))
206 ignored_files[ignored_files_count].dev = st.st_dev;
207 ignored_files[ignored_files_count].ino = st.st_ino;
208 ignored_files_count++;
212 static inline BOOL is_same_file( const struct file_identity *file, const struct stat *st )
214 return st->st_dev == file->dev && st->st_ino == file->ino;
217 static inline BOOL is_ignored_file( const struct stat *st )
221 for (i = 0; i < ignored_files_count; i++)
222 if (is_same_file( &ignored_files[i], st )) return TRUE;
226 static inline unsigned int dir_info_size( FILE_INFORMATION_CLASS class, unsigned int len )
230 case FileDirectoryInformation:
231 return (FIELD_OFFSET( FILE_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
232 case FileBothDirectoryInformation:
233 return (FIELD_OFFSET( FILE_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
234 case FileFullDirectoryInformation:
235 return (FIELD_OFFSET( FILE_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
236 case FileIdBothDirectoryInformation:
237 return (FIELD_OFFSET( FILE_ID_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
238 case FileIdFullDirectoryInformation:
239 return (FIELD_OFFSET( FILE_ID_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
245 static inline unsigned int max_dir_info_size( FILE_INFORMATION_CLASS class )
247 return dir_info_size( class, MAX_DIR_ENTRY_LEN );
251 /***********************************************************************
252 * get_default_com_device
254 * Return the default device to use for serial ports.
256 static char *get_default_com_device( int num )
260 if (!num || num > 9) return ret;
262 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
265 strcpy( ret, "/dev/ttyS0" );
266 ret[strlen(ret) - 1] = '0' + num - 1;
268 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
269 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuad0") );
272 strcpy( ret, "/dev/cuad0" );
273 ret[strlen(ret) - 1] = '0' + num - 1;
276 FIXME( "no known default for device com%d\n", num );
282 /***********************************************************************
283 * get_default_lpt_device
285 * Return the default device to use for parallel ports.
287 static char *get_default_lpt_device( int num )
291 if (!num || num > 9) return ret;
293 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
296 strcpy( ret, "/dev/lp0" );
297 ret[strlen(ret) - 1] = '0' + num - 1;
300 FIXME( "no known default for device lpt%d\n", num );
306 /***********************************************************************
307 * DIR_get_drives_info
309 * Retrieve device/inode number for all the drives. Helper for find_drive_root.
311 unsigned int DIR_get_drives_info( struct drive_info info[MAX_DOS_DRIVES] )
313 static struct drive_info cache[MAX_DOS_DRIVES];
314 static time_t last_update;
315 static unsigned int nb_drives;
317 time_t now = time(NULL);
319 RtlEnterCriticalSection( &dir_section );
320 if (now != last_update)
322 const char *config_dir = wine_get_config_dir();
327 if ((buffer = RtlAllocateHeap( GetProcessHeap(), 0,
328 strlen(config_dir) + sizeof("/dosdevices/a:") )))
330 strcpy( buffer, config_dir );
331 strcat( buffer, "/dosdevices/a:" );
332 p = buffer + strlen(buffer) - 2;
334 for (i = nb_drives = 0; i < MAX_DOS_DRIVES; i++)
337 if (!stat( buffer, &st ))
339 cache[i].dev = st.st_dev;
340 cache[i].ino = st.st_ino;
349 RtlFreeHeap( GetProcessHeap(), 0, buffer );
353 memcpy( info, cache, sizeof(cache) );
355 RtlLeaveCriticalSection( &dir_section );
360 /***********************************************************************
361 * parse_mount_entries
363 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
367 #include <sys/vfstab.h>
368 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
374 while (! getvfsent( f, &entry ))
376 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
377 if (!strcmp( entry.vfs_fstype, "nfs" ) ||
378 !strcmp( entry.vfs_fstype, "smbfs" ) ||
379 !strcmp( entry.vfs_fstype, "ncpfs" )) continue;
381 if (stat( entry.vfs_mountp, &st ) == -1) continue;
382 if (st.st_dev != dev || st.st_ino != ino) continue;
383 if (!strcmp( entry.vfs_fstype, "fd" ))
385 if ((device = strstr( entry.vfs_mntopts, "dev=" )))
387 char *p = strchr( device + 4, ',' );
393 return entry.vfs_special;
400 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
402 struct mntent *entry;
406 while ((entry = getmntent( f )))
408 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
409 if (!strcmp( entry->mnt_type, "nfs" ) ||
410 !strcmp( entry->mnt_type, "smbfs" ) ||
411 !strcmp( entry->mnt_type, "ncpfs" )) continue;
413 if (stat( entry->mnt_dir, &st ) == -1) continue;
414 if (st.st_dev != dev || st.st_ino != ino) continue;
415 if (!strcmp( entry->mnt_type, "supermount" ))
417 if ((device = strstr( entry->mnt_opts, "dev=" )))
419 char *p = strchr( device + 4, ',' );
424 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
426 /* if device is a regular file check for a loop mount */
427 if ((device = strstr( entry->mnt_opts, "loop=" )))
429 char *p = strchr( device + 5, ',' );
435 return entry->mnt_fsname;
441 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
443 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
448 while ((entry = getfsent()))
450 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
451 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
452 !strcmp( entry->fs_vfstype, "smbfs" ) ||
453 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
455 if (stat( entry->fs_file, &st ) == -1) continue;
456 if (st.st_dev != dev || st.st_ino != ino) continue;
457 return entry->fs_spec;
464 #include <sys/mnttab.h>
465 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
472 while (( ! getmntent( f, &entry) ))
474 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
475 if (!strcmp( entry.mnt_fstype, "nfs" ) ||
476 !strcmp( entry.mnt_fstype, "smbfs" ) ||
477 !strcmp( entry.mnt_fstype, "ncpfs" )) continue;
479 if (stat( entry.mnt_mountp, &st ) == -1) continue;
480 if (st.st_dev != dev || st.st_ino != ino) continue;
481 if (!strcmp( entry.mnt_fstype, "fd" ))
483 if ((device = strstr( entry.mnt_mntopts, "dev=" )))
485 char *p = strchr( device + 4, ',' );
491 return entry.mnt_special;
497 /***********************************************************************
498 * get_default_drive_device
500 * Return the default device to use for a given drive mount point.
502 static char *get_default_drive_device( const char *root )
512 /* try to open it first to force it to get mounted */
513 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
515 res = fstat( fd, &st );
518 /* now try normal stat just in case */
519 if (res == -1) res = stat( root, &st );
520 if (res == -1) return NULL;
522 RtlEnterCriticalSection( &dir_section );
524 if ((f = fopen( "/etc/mtab", "r" )))
526 device = parse_mount_entries( f, st.st_dev, st.st_ino );
529 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
530 if (!device && (f = fopen( "/etc/fstab", "r" )))
532 device = parse_mount_entries( f, st.st_dev, st.st_ino );
537 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
538 if (ret) strcpy( ret, device );
540 RtlLeaveCriticalSection( &dir_section );
542 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ )
547 /* try to open it first to force it to get mounted */
548 if ((fd = open( root, O_RDONLY )) != -1)
550 res = fstat( fd, &st );
553 /* now try normal stat just in case */
554 if (res == -1) res = stat( root, &st );
555 if (res == -1) return NULL;
557 RtlEnterCriticalSection( &dir_section );
559 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
560 * pass NULL. Leave the argument in for symmetry.
562 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
565 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
566 if (ret) strcpy( ret, device );
568 RtlLeaveCriticalSection( &dir_section );
576 /* try to open it first to force it to get mounted */
577 if ((fd = open( root, O_RDONLY )) != -1)
579 res = fstat( fd, &st );
582 /* now try normal stat just in case */
583 if (res == -1) res = stat( root, &st );
584 if (res == -1) return NULL;
586 RtlEnterCriticalSection( &dir_section );
588 if ((f = fopen( "/etc/mnttab", "r" )))
590 device = parse_mount_entries( f, st.st_dev, st.st_ino);
593 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
594 if (!device && (f = fopen( "/etc/vfstab", "r" )))
596 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
601 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
602 if (ret) strcpy( ret, device );
604 RtlLeaveCriticalSection( &dir_section );
606 #elif defined(__APPLE__)
607 struct statfs *mntStat;
613 static const char path_bsd_device[] = "/dev/disk";
616 res = stat( root, &st );
617 if (res == -1) return NULL;
622 RtlEnterCriticalSection( &dir_section );
624 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
626 for (i = 0; i < mntSize && !ret; i++)
628 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
629 if (st.st_dev != dev || st.st_ino != ino) continue;
631 /* FIXME add support for mounted network drive */
632 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
634 /* set return value to the corresponding raw BSD node */
635 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
638 strcpy(ret, "/dev/r");
639 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
643 RtlLeaveCriticalSection( &dir_section );
646 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
652 /***********************************************************************
653 * get_device_mount_point
655 * Return the current mount point for a device.
657 static char *get_device_mount_point( dev_t dev )
664 RtlEnterCriticalSection( &dir_section );
666 if ((f = fopen( "/etc/mtab", "r" )))
668 struct mntent *entry;
672 while ((entry = getmntent( f )))
674 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
675 if (!strcmp( entry->mnt_type, "nfs" ) ||
676 !strcmp( entry->mnt_type, "smbfs" ) ||
677 !strcmp( entry->mnt_type, "ncpfs" )) continue;
679 if (!strcmp( entry->mnt_type, "supermount" ))
681 if ((device = strstr( entry->mnt_opts, "dev=" )))
684 if ((p = strchr( device, ',' ))) *p = 0;
687 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
689 /* if device is a regular file check for a loop mount */
690 if ((device = strstr( entry->mnt_opts, "loop=" )))
693 if ((p = strchr( device, ',' ))) *p = 0;
696 else device = entry->mnt_fsname;
698 if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
700 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
701 if (ret) strcpy( ret, entry->mnt_dir );
707 RtlLeaveCriticalSection( &dir_section );
708 #elif defined(__APPLE__)
709 struct statfs *entry;
713 RtlEnterCriticalSection( &dir_section );
715 size = getmntinfo( &entry, MNT_NOWAIT );
716 for (i = 0; i < size; i++)
718 if (stat( entry[i].f_mntfromname, &st ) == -1) continue;
719 if (S_ISBLK(st.st_mode) && st.st_rdev == dev)
721 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry[i].f_mntfromname) + 1 );
722 if (ret) strcpy( ret, entry[i].f_mntfromname );
726 RtlLeaveCriticalSection( &dir_section );
729 if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
735 /***********************************************************************
738 * Initialize the show_dot_files options.
740 static void init_options(void)
742 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
743 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
747 OBJECT_ATTRIBUTES attr;
748 UNICODE_STRING nameW;
752 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
753 attr.Length = sizeof(attr);
754 attr.RootDirectory = root;
755 attr.ObjectName = &nameW;
757 attr.SecurityDescriptor = NULL;
758 attr.SecurityQualityOfService = NULL;
759 RtlInitUnicodeString( &nameW, WineW );
761 /* @@ Wine registry key: HKCU\Software\Wine */
762 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
764 RtlInitUnicodeString( &nameW, ShowDotFilesW );
765 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
767 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
768 show_dot_files = IS_OPTION_TRUE( str[0] );
774 /* a couple of directories that we don't want to return in directory searches */
775 ignore_file( wine_get_config_dir() );
776 ignore_file( "/dev" );
777 ignore_file( "/proc" );
779 ignore_file( "/sys" );
784 /***********************************************************************
787 * Check if the specified file should be hidden based on its name and the show dot files option.
789 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
793 if (show_dot_files == -1) init_options();
794 if (show_dot_files) return FALSE;
796 end = p = name->Buffer + name->Length/sizeof(WCHAR);
797 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
798 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
799 if (p == end || *p != '.') return FALSE;
800 /* make sure it isn't '.' or '..' */
801 if (p + 1 == end) return FALSE;
802 if (p[1] == '.' && p + 2 == end) return FALSE;
807 /***********************************************************************
808 * hash_short_file_name
810 * Transform a Unix file name into a hashed DOS name. If the name is a valid
811 * DOS name, it is converted to upper-case; otherwise it is replaced by a
812 * hashed version that fits in 8.3 format.
813 * 'buffer' must be at least 12 characters long.
814 * Returns length of short name in bytes; short name is NOT null-terminated.
816 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
818 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
820 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
825 /* Compute the hash code of the file name */
826 /* If you know something about hash functions, feel free to */
827 /* insert a better algorithm here... */
828 if (!is_case_sensitive)
830 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
831 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
832 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
836 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
837 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
838 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
841 /* Find last dot for start of the extension */
842 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
844 /* Copy first 4 chars, replacing invalid chars with '_' */
845 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
847 if (p == end || p == ext) break;
848 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
850 /* Pad to 5 chars with '~' */
851 while (i-- >= 0) *dst++ = '~';
853 /* Insert hash code converted to 3 ASCII chars */
854 *dst++ = hash_chars[(hash >> 10) & 0x1f];
855 *dst++ = hash_chars[(hash >> 5) & 0x1f];
856 *dst++ = hash_chars[hash & 0x1f];
858 /* Copy the first 3 chars of the extension (if any) */
862 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
863 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
869 /***********************************************************************
872 * Check a long file name against a mask.
874 * Tests (done in W95 DOS shell - case insensitive):
875 * *.txt test1.test.txt *
877 * *.t??????.t* test1.ta.tornado.txt *
878 * *tornado* test1.ta.tornado.txt *
879 * t*t test1.ta.tornado.txt *
881 * ?est??? test1.txt -
882 * *test1.txt* test1.txt *
883 * h?l?o*t.dat hellothisisatest.dat *
885 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
888 const WCHAR *name = name_str->Buffer;
889 const WCHAR *mask = mask_str->Buffer;
890 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
891 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
892 const WCHAR *lastjoker = NULL;
893 const WCHAR *next_to_retry = NULL;
895 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
897 while (name < name_end && mask < mask_end)
903 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
904 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
907 /* skip to the next match after the joker(s) */
908 if (is_case_sensitive)
909 while (name < name_end && (*name != *mask)) name++;
911 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
912 next_to_retry = name;
919 if (is_case_sensitive) mismatch = (*mask != *name);
920 else mismatch = (toupperW(*mask) != toupperW(*name));
926 if (mask == mask_end)
928 if (name == name_end) return TRUE;
929 if (lastjoker) mask = lastjoker;
932 else /* mismatch ! */
934 if (lastjoker) /* we had an '*', so we can try unlimitedly */
938 /* this scan sequence was a mismatch, so restart
939 * 1 char after the first char we checked last time */
941 name = next_to_retry;
943 else return FALSE; /* bad luck */
948 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
949 mask++; /* Ignore trailing '.' or '*' in mask */
950 return (name == name_end && mask == mask_end);
954 /***********************************************************************
957 * helper for NtQueryDirectoryFile
959 static union file_directory_info *append_entry( void *info_ptr, IO_STATUS_BLOCK *io, ULONG max_length,
960 const char *long_name, const char *short_name,
961 const UNICODE_STRING *mask, FILE_INFORMATION_CLASS class )
963 union file_directory_info *info;
964 int i, long_len, short_len, total_len;
966 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
967 WCHAR short_nameW[12];
970 ULONG attributes = 0;
972 io->u.Status = STATUS_SUCCESS;
973 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
974 if (long_len == -1) return NULL;
976 str.Buffer = long_nameW;
977 str.Length = long_len * sizeof(WCHAR);
978 str.MaximumLength = sizeof(long_nameW);
982 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
983 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
984 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
986 else /* generate a short name if necessary */
991 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
992 short_len = hash_short_file_name( &str, short_nameW );
995 TRACE( "long %s short %s mask %s\n",
996 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
998 if (mask && !match_filename( &str, mask ))
1000 if (!short_len) return NULL; /* no short name to match */
1001 str.Buffer = short_nameW;
1002 str.Length = short_len * sizeof(WCHAR);
1003 str.MaximumLength = sizeof(short_nameW);
1004 if (!match_filename( &str, mask )) return NULL;
1007 if (lstat( long_name, &st ) == -1) return NULL;
1008 if (S_ISLNK( st.st_mode ))
1010 if (stat( long_name, &st ) == -1) return NULL;
1011 if (S_ISDIR( st.st_mode )) attributes |= FILE_ATTRIBUTE_REPARSE_POINT;
1013 if (is_ignored_file( &st ))
1015 TRACE( "ignoring file %s\n", long_name );
1018 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
1019 attributes |= FILE_ATTRIBUTE_HIDDEN;
1021 total_len = dir_info_size( class, long_len );
1022 if (io->Information + total_len > max_length)
1024 total_len = max_length - io->Information;
1025 io->u.Status = STATUS_BUFFER_OVERFLOW;
1027 info = (union file_directory_info *)((char *)info_ptr + io->Information);
1028 /* all the structures start with a FileDirectoryInformation layout */
1029 fill_stat_info( &st, info, class );
1030 info->dir.NextEntryOffset = total_len;
1031 info->dir.FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
1032 info->dir.FileAttributes |= attributes;
1036 case FileDirectoryInformation:
1037 info->dir.FileNameLength = long_len * sizeof(WCHAR);
1038 filename = info->dir.FileName;
1041 case FileFullDirectoryInformation:
1042 info->full.EaSize = 0; /* FIXME */
1043 info->full.FileNameLength = long_len * sizeof(WCHAR);
1044 filename = info->full.FileName;
1047 case FileIdFullDirectoryInformation:
1048 info->id_full.EaSize = 0; /* FIXME */
1049 info->id_full.FileNameLength = long_len * sizeof(WCHAR);
1050 filename = info->id_full.FileName;
1053 case FileBothDirectoryInformation:
1054 info->both.EaSize = 0; /* FIXME */
1055 info->both.ShortNameLength = short_len * sizeof(WCHAR);
1056 for (i = 0; i < short_len; i++) info->both.ShortName[i] = toupperW(short_nameW[i]);
1057 info->both.FileNameLength = long_len * sizeof(WCHAR);
1058 filename = info->both.FileName;
1061 case FileIdBothDirectoryInformation:
1062 info->id_both.EaSize = 0; /* FIXME */
1063 info->id_both.ShortNameLength = short_len * sizeof(WCHAR);
1064 for (i = 0; i < short_len; i++) info->id_both.ShortName[i] = toupperW(short_nameW[i]);
1065 info->id_both.FileNameLength = long_len * sizeof(WCHAR);
1066 filename = info->id_both.FileName;
1072 memcpy( filename, long_nameW, total_len - ((char *)filename - (char *)info) );
1073 io->Information += total_len;
1078 #ifdef VFAT_IOCTL_READDIR_BOTH
1080 /***********************************************************************
1083 * Wrapper for the VFAT ioctl to work around various kernel bugs.
1084 * dir_section must be held by caller.
1086 static KERNEL_DIRENT *start_vfat_ioctl( int fd )
1088 static KERNEL_DIRENT *de;
1093 const size_t page_size = getpagesize();
1094 SIZE_T size = 2 * sizeof(*de) + page_size;
1097 if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_RESERVE, PAGE_READWRITE ))
1099 /* commit only the size needed for the dir entries */
1100 /* this leaves an extra unaccessible page, which should make the kernel */
1101 /* fail with -EFAULT before it stomps all over our memory */
1103 size = 2 * sizeof(*de);
1104 NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_COMMIT, PAGE_READWRITE );
1107 /* set d_reclen to 65535 to work around an AFS kernel bug */
1108 de[0].d_reclen = 65535;
1109 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
1112 if (errno != ENOENT) return NULL; /* VFAT ioctl probably not supported */
1113 de[0].d_reclen = 0; /* eof */
1115 else if (!res && de[0].d_reclen == 65535) return NULL; /* AFS bug */
1121 /***********************************************************************
1122 * read_directory_vfat
1124 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
1126 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1127 BOOLEAN single_entry, const UNICODE_STRING *mask,
1128 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1133 union file_directory_info *info, *last_info = NULL;
1135 io->u.Status = STATUS_SUCCESS;
1137 if (restart_scan) lseek( fd, 0, SEEK_SET );
1139 if (length < max_dir_info_size(class)) /* we may have to return a partial entry here */
1141 off_t old_pos = lseek( fd, 0, SEEK_CUR );
1143 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1145 while (de[0].d_reclen)
1147 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1148 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1149 de[0].d_name[len] = 0;
1150 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1151 de[1].d_name[len] = 0;
1153 if (de[1].d_name[0])
1154 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1156 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1160 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1161 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1164 old_pos = lseek( fd, 0, SEEK_CUR );
1165 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1168 else /* we'll only return full entries, no need to worry about overflow */
1170 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1172 while (de[0].d_reclen)
1174 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1175 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1176 de[0].d_name[len] = 0;
1177 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1178 de[1].d_name[len] = 0;
1180 if (de[1].d_name[0])
1181 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1183 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1187 if (single_entry) break;
1188 /* check if we still have enough space for the largest possible entry */
1189 if (io->Information + max_dir_info_size(class) > length) break;
1191 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1195 if (last_info) last_info->next = 0;
1196 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1199 #endif /* VFAT_IOCTL_READDIR_BOTH */
1202 /***********************************************************************
1203 * read_directory_getdents
1205 * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
1208 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1209 BOOLEAN single_entry, const UNICODE_STRING *mask,
1210 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1213 size_t size = length;
1214 int res, fake_dot_dot = 1;
1215 char *data, local_buffer[8192];
1216 KERNEL_DIRENT64 *de;
1217 union file_directory_info *info, *last_info = NULL;
1219 if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1221 size = sizeof(local_buffer);
1222 data = local_buffer;
1225 if (restart_scan) lseek( fd, 0, SEEK_SET );
1226 else if (length < max_dir_info_size(class)) /* we may have to return a partial entry here */
1228 old_pos = lseek( fd, 0, SEEK_CUR );
1229 if (old_pos == -1 && errno == ENOENT)
1231 io->u.Status = STATUS_NO_MORE_FILES;
1237 io->u.Status = STATUS_SUCCESS;
1239 res = getdents64( fd, data, size );
1242 if (errno != ENOSYS)
1244 io->u.Status = FILE_GetNtStatus();
1250 de = (KERNEL_DIRENT64 *)data;
1254 /* check if we got . and .. from getdents */
1257 if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1259 KERNEL_DIRENT64 *next_de = (KERNEL_DIRENT64 *)(data + de->d_reclen);
1260 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1263 /* make sure we have enough room for both entries */
1266 const ULONG min_info_size = dir_info_size( class, 1 ) + dir_info_size( class, 2 );
1267 if (length < min_info_size || single_entry)
1269 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1276 if ((info = append_entry( buffer, io, length, ".", NULL, mask, class )))
1278 if ((info = append_entry( buffer, io, length, "..", NULL, mask, class )))
1281 /* check if we still have enough space for the largest possible entry */
1282 if (last_info && io->Information + max_dir_info_size(class) > length)
1284 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1292 res -= de->d_reclen;
1294 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1295 (info = append_entry( buffer, io, length, de->d_name, NULL, mask, class )))
1298 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1300 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1303 /* check if we still have enough space for the largest possible entry */
1304 if (single_entry || io->Information + max_dir_info_size(class) > length)
1306 if (res > 0) lseek( fd, de->d_off, SEEK_SET ); /* set pos to next entry */
1310 old_pos = de->d_off;
1311 /* move on to the next entry */
1312 if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1315 res = getdents64( fd, data, size );
1316 de = (KERNEL_DIRENT64 *)data;
1320 if (last_info) last_info->next = 0;
1321 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1324 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1328 #elif defined HAVE_GETDIRENTRIES
1330 #if _DARWIN_FEATURE_64_BIT_INODE
1332 /* Darwin doesn't provide a version of getdirentries with support for 64-bit
1333 * inodes. When 64-bit inodes are enabled, the getdirentries symbol is mapped
1334 * to _getdirentries_is_not_available_when_64_bit_inodes_are_in_effect so that
1335 * we get link errors if we try to use it. We still need getdirentries, but we
1336 * don't need it to support 64-bit inodes. So, we use the legacy getdirentries
1337 * with 32-bit inodes. We have to be careful to use a corresponding dirent
1340 int darwin_legacy_getdirentries(int, char *, int, long *) __asm("_getdirentries");
1341 #define getdirentries darwin_legacy_getdirentries
1343 struct darwin_legacy_dirent {
1345 __uint16_t d_reclen;
1348 char d_name[__DARWIN_MAXNAMLEN + 1];
1350 #define dirent darwin_legacy_dirent
1354 /***********************************************************************
1355 * wine_getdirentries
1357 * Wrapper for the BSD getdirentries system call to fix a bug in the
1358 * Mac OS X version. For some file systems (at least Apple Filing
1359 * Protocol a.k.a. AFP), getdirentries resets the file position to 0
1360 * when it's about to return 0 (no more entries). So, a subsequent
1361 * getdirentries call starts over at the beginning again, causing an
1364 static inline int wine_getdirentries(int fd, char *buf, int nbytes, long *basep)
1366 int res = getdirentries(fd, buf, nbytes, basep);
1369 lseek(fd, *basep, SEEK_SET);
1374 /***********************************************************************
1375 * read_directory_getdirentries
1377 * Read a directory using the BSD getdirentries system call; helper for NtQueryDirectoryFile.
1379 static int read_directory_getdirentries( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1380 BOOLEAN single_entry, const UNICODE_STRING *mask,
1381 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1384 ULONG_PTR restart_info_pos = 0;
1385 size_t size, initial_size = length;
1386 int res, fake_dot_dot = 1;
1387 char *data, local_buffer[8192];
1389 union file_directory_info *info, *last_info = NULL, *restart_last_info = NULL;
1391 size = initial_size;
1392 data = local_buffer;
1393 if (size > sizeof(local_buffer) && !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1395 io->u.Status = STATUS_NO_MEMORY;
1396 return io->u.Status;
1399 if (restart_scan) lseek( fd, 0, SEEK_SET );
1401 io->u.Status = STATUS_SUCCESS;
1403 /* FIXME: should make sure size is larger than filesystem block size */
1404 res = wine_getdirentries( fd, data, size, &restart_pos );
1407 io->u.Status = FILE_GetNtStatus();
1412 de = (struct dirent *)data;
1416 /* check if we got . and .. from getdirentries */
1419 if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1421 struct dirent *next_de = (struct dirent *)(data + de->d_reclen);
1422 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1425 /* make sure we have enough room for both entries */
1428 const ULONG min_info_size = dir_info_size( class, 1 ) + dir_info_size( class, 2 );
1429 if (length < min_info_size || single_entry)
1431 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1438 if ((info = append_entry( buffer, io, length, ".", NULL, mask, class )))
1440 if ((info = append_entry( buffer, io, length, "..", NULL, mask, class )))
1443 restart_last_info = last_info;
1444 restart_info_pos = io->Information;
1446 /* check if we still have enough space for the largest possible entry */
1447 if (last_info && io->Information + max_dir_info_size(class) > length)
1449 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1457 res -= de->d_reclen;
1459 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1460 ((info = append_entry( buffer, io, length, de->d_name, NULL, mask, class ))))
1463 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1465 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1466 if (restart_info_pos) /* if we have a complete read already, return it */
1468 io->u.Status = STATUS_SUCCESS;
1469 io->Information = restart_info_pos;
1470 last_info = restart_last_info;
1473 /* otherwise restart from the start with a smaller size */
1474 size = (char *)de - data;
1476 io->Information = 0;
1480 /* if we have to return but the buffer contains more data, restart with a smaller size */
1481 if (res > 0 && (single_entry || io->Information + max_dir_info_size(class) > length))
1483 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1484 size = (char *)de - data;
1485 io->Information = restart_info_pos;
1486 last_info = restart_last_info;
1490 /* move on to the next entry */
1493 de = (struct dirent *)((char *)de + de->d_reclen);
1496 if (size < initial_size) break; /* already restarted once, give up now */
1497 size = min( size, length - io->Information );
1498 /* if size is too small don't bother to continue */
1499 if (size < max_dir_info_size(class) && last_info) break;
1500 restart_last_info = last_info;
1501 restart_info_pos = io->Information;
1503 res = wine_getdirentries( fd, data, size, &restart_pos );
1504 de = (struct dirent *)data;
1507 if (last_info) last_info->next = 0;
1508 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1511 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1515 #if _DARWIN_FEATURE_64_BIT_INODE
1516 #undef getdirentries
1520 #endif /* HAVE_GETDIRENTRIES */
1523 /***********************************************************************
1524 * read_directory_readdir
1526 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1528 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1529 BOOLEAN single_entry, const UNICODE_STRING *mask,
1530 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1533 off_t i, old_pos = 0;
1535 union file_directory_info *info, *last_info = NULL;
1537 if (!(dir = opendir( "." )))
1539 io->u.Status = FILE_GetNtStatus();
1545 old_pos = lseek( fd, 0, SEEK_CUR );
1546 /* skip the right number of entries */
1547 for (i = 0; i < old_pos - 2; i++)
1549 if (!readdir( dir ))
1552 io->u.Status = STATUS_NO_MORE_FILES;
1557 io->u.Status = STATUS_SUCCESS;
1562 info = append_entry( buffer, io, length, ".", NULL, mask, class );
1563 else if (old_pos == 1)
1564 info = append_entry( buffer, io, length, "..", NULL, mask, class );
1565 else if ((de = readdir( dir )))
1567 if (strcmp( de->d_name, "." ) && strcmp( de->d_name, ".." ))
1568 info = append_entry( buffer, io, length, de->d_name, NULL, mask, class );
1578 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1580 old_pos--; /* restore pos to previous entry */
1583 if (single_entry) break;
1584 /* check if we still have enough space for the largest possible entry */
1585 if (io->Information + max_dir_info_size(class) > length) break;
1589 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
1592 if (last_info) last_info->next = 0;
1593 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1596 /***********************************************************************
1597 * read_directory_stat
1599 * Read a single file from a directory by determining whether the file
1600 * identified by mask exists using stat.
1602 static int read_directory_stat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1603 BOOLEAN single_entry, const UNICODE_STRING *mask,
1604 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1606 int unix_len, ret, used_default;
1610 TRACE("trying optimisation for file %s\n", debugstr_us( mask ));
1612 unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
1613 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
1615 io->u.Status = STATUS_NO_MEMORY;
1618 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
1619 NULL, &used_default );
1620 if (ret > 0 && !used_default)
1625 lseek( fd, 0, SEEK_SET );
1627 else if (lseek( fd, 0, SEEK_CUR ) != 0)
1629 io->u.Status = STATUS_NO_MORE_FILES;
1634 ret = stat( unix_name, &st );
1637 union file_directory_info *info = append_entry( buffer, io, length, unix_name, NULL, NULL, class );
1641 if (io->u.Status != STATUS_BUFFER_OVERFLOW) lseek( fd, 1, SEEK_CUR );
1643 else io->u.Status = STATUS_NO_MORE_FILES;
1649 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1651 TRACE("returning %d\n", ret);
1657 static inline WCHAR *mempbrkW( const WCHAR *ptr, const WCHAR *accept, size_t n )
1660 for (end = ptr + n; ptr < end; ptr++) if (strchrW( accept, *ptr )) return (WCHAR *)ptr;
1664 /******************************************************************************
1665 * NtQueryDirectoryFile [NTDLL.@]
1666 * ZwQueryDirectoryFile [NTDLL.@]
1668 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
1669 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
1670 PIO_STATUS_BLOCK io,
1671 PVOID buffer, ULONG length,
1672 FILE_INFORMATION_CLASS info_class,
1673 BOOLEAN single_entry,
1674 PUNICODE_STRING mask,
1675 BOOLEAN restart_scan )
1677 int cwd, fd, needs_close;
1678 static const WCHAR wszWildcards[] = { '*','?',0 };
1680 TRACE("(%p %p %p %p %p %p 0x%08x 0x%08x 0x%08x %s 0x%08x\n",
1681 handle, event, apc_routine, apc_context, io, buffer,
1682 length, info_class, single_entry, debugstr_us(mask),
1685 if (event || apc_routine)
1687 FIXME( "Unsupported yet option\n" );
1688 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1692 case FileDirectoryInformation:
1693 case FileBothDirectoryInformation:
1694 case FileFullDirectoryInformation:
1695 case FileIdBothDirectoryInformation:
1696 case FileIdFullDirectoryInformation:
1697 if (length < dir_info_size( info_class, 1 )) return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
1700 FIXME( "Unsupported file info class %d\n", info_class );
1701 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1704 if ((io->u.Status = server_get_unix_fd( handle, FILE_LIST_DIRECTORY, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
1705 return io->u.Status;
1707 io->Information = 0;
1709 RtlEnterCriticalSection( &dir_section );
1711 if (show_dot_files == -1) init_options();
1713 cwd = open( ".", O_RDONLY );
1714 if (fchdir( fd ) != -1)
1716 #ifdef VFAT_IOCTL_READDIR_BOTH
1717 if ((read_directory_vfat( fd, io, buffer, length, single_entry,
1718 mask, restart_scan, info_class )) != -1) goto done;
1720 if (mask && !mempbrkW( mask->Buffer, wszWildcards, mask->Length / sizeof(WCHAR) ) &&
1721 read_directory_stat( fd, io, buffer, length, single_entry,
1722 mask, restart_scan, info_class ) != -1) goto done;
1724 if ((read_directory_getdents( fd, io, buffer, length, single_entry,
1725 mask, restart_scan, info_class )) != -1) goto done;
1726 #elif defined HAVE_GETDIRENTRIES
1727 if ((read_directory_getdirentries( fd, io, buffer, length, single_entry,
1728 mask, restart_scan, info_class )) != -1) goto done;
1730 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan, info_class );
1733 if (cwd == -1 || fchdir( cwd ) == -1) chdir( "/" );
1735 else io->u.Status = FILE_GetNtStatus();
1737 RtlLeaveCriticalSection( &dir_section );
1739 if (needs_close) close( fd );
1740 if (cwd != -1) close( cwd );
1741 TRACE( "=> %x (%ld)\n", io->u.Status, io->Information );
1742 return io->u.Status;
1746 /***********************************************************************
1749 * Find a file in a directory the hard way, by doing a case-insensitive search.
1750 * The file found is appended to unix_name at pos.
1751 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
1753 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
1754 int check_case, int *is_win_dir )
1756 WCHAR buffer[MAX_DIR_ENTRY_LEN];
1762 int ret, used_default, is_name_8_dot_3;
1764 /* try a shortcut for this directory */
1766 unix_name[pos++] = '/';
1767 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
1768 NULL, &used_default );
1769 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
1770 /* so it cannot match the file we are looking for */
1771 if (ret >= 0 && !used_default)
1773 unix_name[pos + ret] = 0;
1774 if (!stat( unix_name, &st ))
1776 if (is_win_dir) *is_win_dir = is_same_file( &windir, &st );
1777 return STATUS_SUCCESS;
1780 if (check_case) goto not_found; /* we want an exact match */
1782 if (pos > 1) unix_name[pos - 1] = 0;
1783 else unix_name[1] = 0; /* keep the initial slash */
1785 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
1787 str.Buffer = (WCHAR *)name;
1788 str.Length = length * sizeof(WCHAR);
1789 str.MaximumLength = str.Length;
1790 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
1792 /* now look for it through the directory */
1794 #ifdef VFAT_IOCTL_READDIR_BOTH
1795 if (is_name_8_dot_3)
1797 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
1802 RtlEnterCriticalSection( &dir_section );
1803 if ((de = start_vfat_ioctl( fd )))
1805 unix_name[pos - 1] = '/';
1806 while (de[0].d_reclen)
1808 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1809 size_t len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1810 de[0].d_name[len] = 0;
1811 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1812 de[1].d_name[len] = 0;
1814 if (de[1].d_name[0])
1816 ret = ntdll_umbstowcs( 0, de[1].d_name, strlen(de[1].d_name),
1817 buffer, MAX_DIR_ENTRY_LEN );
1818 if (ret == length && !memicmpW( buffer, name, length))
1820 strcpy( unix_name + pos, de[1].d_name );
1821 RtlLeaveCriticalSection( &dir_section );
1826 ret = ntdll_umbstowcs( 0, de[0].d_name, strlen(de[0].d_name),
1827 buffer, MAX_DIR_ENTRY_LEN );
1828 if (ret == length && !memicmpW( buffer, name, length))
1830 strcpy( unix_name + pos,
1831 de[1].d_name[0] ? de[1].d_name : de[0].d_name );
1832 RtlLeaveCriticalSection( &dir_section );
1836 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1)
1838 RtlLeaveCriticalSection( &dir_section );
1844 RtlLeaveCriticalSection( &dir_section );
1847 /* fall through to normal handling */
1849 #endif /* VFAT_IOCTL_READDIR_BOTH */
1851 if (!(dir = opendir( unix_name )))
1853 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
1854 else return FILE_GetNtStatus();
1856 unix_name[pos - 1] = '/';
1857 str.Buffer = buffer;
1858 str.MaximumLength = sizeof(buffer);
1859 while ((de = readdir( dir )))
1861 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
1862 if (ret == length && !memicmpW( buffer, name, length ))
1864 strcpy( unix_name + pos, de->d_name );
1869 if (!is_name_8_dot_3) continue;
1871 str.Length = ret * sizeof(WCHAR);
1872 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1874 WCHAR short_nameW[12];
1875 ret = hash_short_file_name( &str, short_nameW );
1876 if (ret == length && !memicmpW( short_nameW, name, length ))
1878 strcpy( unix_name + pos, de->d_name );
1885 goto not_found; /* avoid warning */
1888 unix_name[pos - 1] = 0;
1889 return STATUS_OBJECT_PATH_NOT_FOUND;
1892 if (is_win_dir && !stat( unix_name, &st )) *is_win_dir = is_same_file( &windir, &st );
1893 return STATUS_SUCCESS;
1899 static const WCHAR catrootW[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t',0};
1900 static const WCHAR catroot2W[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t','2',0};
1901 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};
1902 static const WCHAR driversetcW[] = {'s','y','s','t','e','m','3','2','\\','d','r','i','v','e','r','s','\\','e','t','c',0};
1903 static const WCHAR logfilesW[] = {'s','y','s','t','e','m','3','2','\\','l','o','g','f','i','l','e','s',0};
1904 static const WCHAR spoolW[] = {'s','y','s','t','e','m','3','2','\\','s','p','o','o','l',0};
1905 static const WCHAR system32W[] = {'s','y','s','t','e','m','3','2',0};
1906 static const WCHAR syswow64W[] = {'s','y','s','w','o','w','6','4',0};
1907 static const WCHAR sysnativeW[] = {'s','y','s','n','a','t','i','v','e',0};
1908 static const WCHAR regeditW[] = {'r','e','g','e','d','i','t','.','e','x','e',0};
1909 static const WCHAR wow_regeditW[] = {'s','y','s','w','o','w','6','4','\\','r','e','g','e','d','i','t','.','e','x','e',0};
1913 const WCHAR *source;
1914 const WCHAR *dos_target;
1915 const char *unix_target;
1918 { catrootW, NULL, NULL },
1919 { catroot2W, NULL, NULL },
1920 { driversstoreW, NULL, NULL },
1921 { driversetcW, NULL, NULL },
1922 { logfilesW, NULL, NULL },
1923 { spoolW, NULL, NULL },
1924 { system32W, syswow64W, NULL },
1925 { sysnativeW, system32W, NULL },
1926 { regeditW, wow_regeditW, NULL }
1929 static unsigned int nb_redirects;
1932 /***********************************************************************
1933 * get_redirect_target
1935 * Find the target unix name for a redirected dir.
1937 static const char *get_redirect_target( const char *windows_dir, const WCHAR *name )
1939 int used_default, len, pos, win_len = strlen( windows_dir );
1940 char *unix_name, *unix_target = NULL;
1943 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, win_len + MAX_DIR_ENTRY_LEN + 2 )))
1945 memcpy( unix_name, windows_dir, win_len );
1950 const WCHAR *end, *next;
1952 for (end = name; *end; end++) if (IS_SEPARATOR(*end)) break;
1953 for (next = end; *next; next++) if (!IS_SEPARATOR(*next)) break;
1955 status = find_file_in_dir( unix_name, pos, name, end - name, FALSE, NULL );
1956 if (status == STATUS_OBJECT_PATH_NOT_FOUND && !*next) /* not finding last element is ok */
1958 len = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
1959 MAX_DIR_ENTRY_LEN - (pos - win_len), NULL, &used_default );
1960 if (len > 0 && !used_default)
1962 unix_name[pos] = '/';
1968 if (status) goto done;
1969 pos += strlen( unix_name + pos );
1973 if ((unix_target = RtlAllocateHeap( GetProcessHeap(), 0, pos - win_len )))
1974 memcpy( unix_target, unix_name + win_len + 1, pos - win_len );
1977 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1982 /***********************************************************************
1985 static void init_redirects(void)
1987 UNICODE_STRING nt_name;
1988 ANSI_STRING unix_name;
1993 if (!RtlDosPathNameToNtPathName_U( windows_dir.Buffer, &nt_name, NULL, NULL ))
1995 ERR( "can't convert %s\n", debugstr_us(&windows_dir) );
1998 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
1999 RtlFreeUnicodeString( &nt_name );
2002 ERR( "cannot open %s (%x)\n", debugstr_us(&windows_dir), status );
2005 if (!stat( unix_name.Buffer, &st ))
2007 windir.dev = st.st_dev;
2008 windir.ino = st.st_ino;
2009 nb_redirects = sizeof(redirects) / sizeof(redirects[0]);
2010 for (i = 0; i < nb_redirects; i++)
2012 if (!redirects[i].dos_target) continue;
2013 redirects[i].unix_target = get_redirect_target( unix_name.Buffer, redirects[i].dos_target );
2014 TRACE( "%s -> %s\n", debugstr_w(redirects[i].source), redirects[i].unix_target );
2017 RtlFreeAnsiString( &unix_name );
2022 /***********************************************************************
2025 * Check if path matches a redirect name. If yes, return matched length.
2027 static int match_redirect( const WCHAR *path, int len, const WCHAR *redir, int check_case )
2031 while (i < len && *redir)
2033 if (IS_SEPARATOR(path[i]))
2035 if (*redir++ != '\\') return 0;
2036 while (i < len && IS_SEPARATOR(path[i])) i++;
2037 continue; /* move on to next path component */
2039 else if (check_case)
2041 if (path[i] != *redir) return 0;
2045 if (tolowerW(path[i]) != tolowerW(*redir)) return 0;
2050 if (*redir) return 0;
2051 if (i < len && !IS_SEPARATOR(path[i])) return 0;
2052 while (i < len && IS_SEPARATOR(path[i])) i++;
2057 /***********************************************************************
2060 * Retrieve the Unix path corresponding to a redirected path if any.
2062 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, int check_case )
2067 for (i = 0; i < nb_redirects; i++)
2069 if ((len = match_redirect( name, length, redirects[i].source, check_case )))
2071 if (!redirects[i].unix_target) break;
2072 unix_name[pos++] = '/';
2073 strcpy( unix_name + pos, redirects[i].unix_target );
2082 /* there are no redirects on 64-bit */
2084 static const unsigned int nb_redirects = 0;
2086 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, int check_case )
2093 /***********************************************************************
2094 * DIR_init_windows_dir
2096 void DIR_init_windows_dir( const WCHAR *win, const WCHAR *sys )
2098 /* FIXME: should probably store paths as NT file names */
2100 RtlCreateUnicodeString( &windows_dir, win );
2101 RtlCreateUnicodeString( &system_dir, sys );
2104 if (is_wow64) init_redirects();
2109 /******************************************************************************
2112 * Get the Unix path of a DOS device.
2114 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
2116 const char *config_dir = wine_get_config_dir();
2118 char *unix_name, *new_name, *dev;
2122 /* make sure the device name is ASCII */
2123 for (i = 0; i < name_len; i++)
2124 if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
2126 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
2128 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2129 return STATUS_NO_MEMORY;
2131 strcpy( unix_name, config_dir );
2132 strcat( unix_name, "/dosdevices/" );
2133 dev = unix_name + strlen(unix_name);
2135 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
2138 /* special case for drive devices */
2139 if (name_len == 2 && dev[1] == ':')
2147 if (!stat( unix_name, &st ))
2149 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
2150 unix_name_ret->Buffer = unix_name;
2151 unix_name_ret->Length = strlen(unix_name);
2152 unix_name_ret->MaximumLength = unix_len;
2153 return STATUS_SUCCESS;
2157 /* now try some defaults for it */
2158 if (!strcmp( dev, "aux" ))
2160 strcpy( dev, "com1" );
2163 if (!strcmp( dev, "prn" ))
2165 strcpy( dev, "lpt1" );
2168 if (!strcmp( dev, "nul" ))
2170 strcpy( unix_name, "/dev/null" );
2171 dev = NULL; /* last try */
2176 if (dev[1] == ':' && dev[2] == ':') /* drive device */
2178 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
2179 new_name = get_default_drive_device( unix_name );
2181 else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( atoi(dev + 3 ));
2182 else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( atoi(dev + 3 ));
2184 if (!new_name) break;
2186 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2187 unix_name = new_name;
2188 unix_len = strlen(unix_name) + 1;
2189 dev = NULL; /* last try */
2191 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2192 return STATUS_BAD_DEVICE_TYPE;
2196 /* return the length of the DOS namespace prefix if any */
2197 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
2199 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
2200 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
2202 if (name->Length > sizeof(nt_prefixW) &&
2203 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
2204 return sizeof(nt_prefixW) / sizeof(WCHAR);
2206 if (name->Length > sizeof(dosdev_prefixW) &&
2207 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
2208 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
2214 /******************************************************************************
2217 * Helper for nt_to_unix_file_name
2219 static NTSTATUS lookup_unix_name( const WCHAR *name, int name_len, char **buffer, int unix_len, int pos,
2220 UINT disposition, BOOLEAN check_case )
2223 int ret, used_default, len;
2225 char *unix_name = *buffer;
2226 const BOOL redirect = nb_redirects && ntdll_get_thread_data()->wow64_redir;
2228 /* try a shortcut first */
2230 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
2231 NULL, &used_default );
2233 while (name_len && IS_SEPARATOR(*name))
2239 if (ret > 0 && !used_default) /* if we used the default char the name didn't convert properly */
2242 unix_name[pos + ret] = 0;
2243 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
2244 if ((!redirect || !strstr( unix_name, "/windows/")) && !stat( unix_name, &st ))
2246 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
2247 if (disposition == FILE_CREATE)
2248 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
2249 return STATUS_SUCCESS;
2253 if (!name_len) /* empty name -> drive root doesn't exist */
2254 return STATUS_OBJECT_PATH_NOT_FOUND;
2255 if (check_case && !redirect && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
2256 return STATUS_OBJECT_NAME_NOT_FOUND;
2258 /* now do it component by component */
2262 const WCHAR *end, *next;
2266 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
2268 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
2269 name_len -= next - name;
2271 /* grow the buffer if needed */
2273 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
2276 unix_len += 2 * MAX_DIR_ENTRY_LEN;
2277 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
2278 return STATUS_NO_MEMORY;
2279 unix_name = *buffer = new_name;
2282 status = find_file_in_dir( unix_name, pos, name, end - name,
2283 check_case, redirect ? &is_win_dir : NULL );
2285 /* if this is the last element, not finding it is not necessarily fatal */
2288 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
2290 status = STATUS_OBJECT_NAME_NOT_FOUND;
2291 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
2293 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2294 MAX_DIR_ENTRY_LEN, NULL, &used_default );
2295 if (ret > 0 && !used_default)
2297 unix_name[pos] = '/';
2298 unix_name[pos + 1 + ret] = 0;
2299 status = STATUS_NO_SUCH_FILE;
2304 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
2306 status = STATUS_OBJECT_NAME_COLLISION;
2310 if (status != STATUS_SUCCESS) break;
2312 pos += strlen( unix_name + pos );
2315 if (is_win_dir && (len = get_redirect_path( unix_name, pos, name, name_len, check_case )))
2319 pos += strlen( unix_name + pos );
2320 TRACE( "redirecting -> %s + %s\n", debugstr_a(unix_name), debugstr_w(name) );
2328 /******************************************************************************
2329 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
2331 * Convert a file name from NT namespace to Unix namespace.
2333 * If disposition is not FILE_OPEN or FILE_OVERWRITE, the last path
2334 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
2335 * returned, but the unix name is still filled in properly.
2337 NTSTATUS CDECL wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
2338 UINT disposition, BOOLEAN check_case )
2340 static const WCHAR unixW[] = {'u','n','i','x'};
2341 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2343 NTSTATUS status = STATUS_SUCCESS;
2344 const char *config_dir = wine_get_config_dir();
2345 const WCHAR *name, *p;
2348 int pos, ret, name_len, unix_len, prefix_len, used_default;
2349 WCHAR prefix[MAX_DIR_ENTRY_LEN];
2350 BOOLEAN is_unix = FALSE;
2352 name = nameW->Buffer;
2353 name_len = nameW->Length / sizeof(WCHAR);
2355 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2357 if (!(pos = get_dos_prefix_len( nameW )))
2358 return STATUS_BAD_DEVICE_TYPE; /* no DOS prefix, assume NT native name */
2363 /* check for sub-directory */
2364 for (pos = 0; pos < name_len; pos++)
2366 if (IS_SEPARATOR(name[pos])) break;
2367 if (name[pos] < 32 || strchrW( invalid_charsW, name[pos] ))
2368 return STATUS_OBJECT_NAME_INVALID;
2370 if (pos > MAX_DIR_ENTRY_LEN)
2371 return STATUS_OBJECT_NAME_INVALID;
2373 if (pos == name_len) /* no subdir, plain DOS device */
2374 return get_dos_device( name, name_len, unix_name_ret );
2376 for (prefix_len = 0; prefix_len < pos; prefix_len++)
2377 prefix[prefix_len] = tolowerW(name[prefix_len]);
2380 name_len -= prefix_len;
2382 /* check for invalid characters (all chars except 0 are valid for unix) */
2383 is_unix = (prefix_len == 4 && !memcmp( prefix, unixW, sizeof(unixW) ));
2386 for (p = name; p < name + name_len; p++)
2387 if (!*p) return STATUS_OBJECT_NAME_INVALID;
2392 for (p = name; p < name + name_len; p++)
2393 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2396 unix_len = ntdll_wcstoumbs( 0, prefix, prefix_len, NULL, 0, NULL, NULL );
2397 unix_len += ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
2398 unix_len += MAX_DIR_ENTRY_LEN + 3;
2399 unix_len += strlen(config_dir) + sizeof("/dosdevices/");
2400 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2401 return STATUS_NO_MEMORY;
2402 strcpy( unix_name, config_dir );
2403 strcat( unix_name, "/dosdevices/" );
2404 pos = strlen(unix_name);
2406 ret = ntdll_wcstoumbs( 0, prefix, prefix_len, unix_name + pos, unix_len - pos - 1,
2407 NULL, &used_default );
2408 if (!ret || used_default)
2410 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2411 return STATUS_OBJECT_NAME_INVALID;
2415 /* check if prefix exists (except for DOS drives to avoid extra stat calls) */
2417 if (prefix_len != 2 || prefix[1] != ':')
2420 if (lstat( unix_name, &st ) == -1 && errno == ENOENT)
2424 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2425 return STATUS_BAD_DEVICE_TYPE;
2427 pos = 0; /* fall back to unix root */
2431 status = lookup_unix_name( name, name_len, &unix_name, unix_len, pos, disposition, check_case );
2432 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
2434 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
2435 unix_name_ret->Buffer = unix_name;
2436 unix_name_ret->Length = strlen(unix_name);
2437 unix_name_ret->MaximumLength = unix_len;
2441 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
2442 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2448 /******************************************************************
2449 * RtlWow64EnableFsRedirection (NTDLL.@)
2451 NTSTATUS WINAPI RtlWow64EnableFsRedirection( BOOLEAN enable )
2453 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
2454 ntdll_get_thread_data()->wow64_redir = enable;
2455 return STATUS_SUCCESS;
2459 /******************************************************************
2460 * RtlWow64EnableFsRedirectionEx (NTDLL.@)
2462 NTSTATUS WINAPI RtlWow64EnableFsRedirectionEx( ULONG disable, ULONG *old_value )
2464 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
2465 *old_value = !ntdll_get_thread_data()->wow64_redir;
2466 ntdll_get_thread_data()->wow64_redir = !disable;
2467 return STATUS_SUCCESS;
2471 /******************************************************************
2472 * RtlDoesFileExists_U (NTDLL.@)
2474 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
2476 UNICODE_STRING nt_name;
2477 FILE_BASIC_INFORMATION basic_info;
2478 OBJECT_ATTRIBUTES attr;
2481 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
2483 attr.Length = sizeof(attr);
2484 attr.RootDirectory = 0;
2485 attr.ObjectName = &nt_name;
2486 attr.Attributes = OBJ_CASE_INSENSITIVE;
2487 attr.SecurityDescriptor = NULL;
2488 attr.SecurityQualityOfService = NULL;
2490 ret = NtQueryAttributesFile(&attr, &basic_info) == STATUS_SUCCESS;
2492 RtlFreeUnicodeString( &nt_name );
2497 /***********************************************************************
2498 * DIR_unmount_device
2500 * Unmount the specified device.
2502 NTSTATUS DIR_unmount_device( HANDLE handle )
2505 int unix_fd, needs_close;
2507 if (!(status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )))
2510 char *mount_point = NULL;
2512 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2513 status = STATUS_INVALID_PARAMETER;
2516 if ((mount_point = get_device_mount_point( st.st_rdev )))
2519 static const char umount[] = "diskutil unmount >/dev/null 2>&1 ";
2521 static const char umount[] = "umount >/dev/null 2>&1 ";
2523 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
2526 strcpy( cmd, umount );
2527 strcat( cmd, mount_point );
2529 RtlFreeHeap( GetProcessHeap(), 0, cmd );
2531 /* umount will fail to release the loop device since we still have
2532 a handle to it, so we release it here */
2533 if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
2536 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
2539 if (needs_close) close( unix_fd );
2545 /******************************************************************************
2548 * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
2549 * Returned value must be freed by caller.
2551 NTSTATUS DIR_get_unix_cwd( char **cwd )
2553 int old_cwd, unix_fd, needs_close;
2558 RtlAcquirePebLock();
2560 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
2561 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
2563 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
2565 if (!(handle = curdir->Handle))
2567 UNICODE_STRING dirW;
2568 OBJECT_ATTRIBUTES attr;
2571 if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
2573 status = STATUS_OBJECT_NAME_INVALID;
2576 attr.Length = sizeof(attr);
2577 attr.RootDirectory = 0;
2578 attr.Attributes = OBJ_CASE_INSENSITIVE;
2579 attr.ObjectName = &dirW;
2580 attr.SecurityDescriptor = NULL;
2581 attr.SecurityQualityOfService = NULL;
2583 status = NtOpenFile( &handle, 0, &attr, &io, 0,
2584 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
2585 RtlFreeUnicodeString( &dirW );
2586 if (status != STATUS_SUCCESS) goto done;
2589 if ((status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )) == STATUS_SUCCESS)
2591 RtlEnterCriticalSection( &dir_section );
2593 if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
2595 unsigned int size = 512;
2599 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2601 status = STATUS_NO_MEMORY;
2604 if (getcwd( *cwd, size )) break;
2605 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
2606 if (errno != ERANGE)
2608 status = STATUS_OBJECT_PATH_INVALID;
2613 if (fchdir( old_cwd ) == -1) chdir( "/" );
2615 else status = FILE_GetNtStatus();
2617 RtlLeaveCriticalSection( &dir_section );
2618 if (old_cwd != -1) close( old_cwd );
2619 if (needs_close) close( unix_fd );
2621 if (!curdir->Handle) NtClose( handle );
2624 RtlReleasePebLock();
2628 struct read_changes_info
2633 PIO_APC_ROUTINE apc;
2637 /* callback for ioctl user APC */
2638 static void WINAPI read_changes_user_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
2640 struct read_changes_info *info = arg;
2641 if (info->apc) info->apc( info->apc_arg, io, reserved );
2642 RtlFreeHeap( GetProcessHeap(), 0, info );
2645 static NTSTATUS read_changes_apc( void *user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
2647 struct read_changes_info *info = user;
2648 char path[PATH_MAX];
2649 NTSTATUS ret = STATUS_SUCCESS;
2652 SERVER_START_REQ( read_change )
2654 req->handle = wine_server_obj_handle( info->FileHandle );
2655 wine_server_set_reply( req, path, PATH_MAX );
2656 ret = wine_server_call( req );
2657 action = reply->action;
2658 len = wine_server_reply_size( reply );
2662 if (ret == STATUS_SUCCESS && info->Buffer &&
2663 (info->BufferSize > (sizeof (FILE_NOTIFY_INFORMATION) + len*sizeof(WCHAR))))
2665 PFILE_NOTIFY_INFORMATION pfni;
2667 pfni = info->Buffer;
2669 /* convert to an NT style path */
2670 for (i=0; i<len; i++)
2674 len = ntdll_umbstowcs( 0, path, len, pfni->FileName,
2675 info->BufferSize - sizeof (*pfni) );
2677 pfni->NextEntryOffset = 0;
2678 pfni->Action = action;
2679 pfni->FileNameLength = len * sizeof (WCHAR);
2680 pfni->FileName[len] = 0;
2681 len = sizeof (*pfni) - sizeof (DWORD) + pfni->FileNameLength;
2685 ret = STATUS_NOTIFY_ENUM_DIR;
2689 iosb->u.Status = ret;
2690 iosb->Information = len;
2691 *apc = read_changes_user_apc;
2695 #define FILE_NOTIFY_ALL ( \
2696 FILE_NOTIFY_CHANGE_FILE_NAME | \
2697 FILE_NOTIFY_CHANGE_DIR_NAME | \
2698 FILE_NOTIFY_CHANGE_ATTRIBUTES | \
2699 FILE_NOTIFY_CHANGE_SIZE | \
2700 FILE_NOTIFY_CHANGE_LAST_WRITE | \
2701 FILE_NOTIFY_CHANGE_LAST_ACCESS | \
2702 FILE_NOTIFY_CHANGE_CREATION | \
2703 FILE_NOTIFY_CHANGE_SECURITY )
2705 /******************************************************************************
2706 * NtNotifyChangeDirectoryFile [NTDLL.@]
2709 NtNotifyChangeDirectoryFile( HANDLE FileHandle, HANDLE Event,
2710 PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext,
2711 PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer,
2712 ULONG BufferSize, ULONG CompletionFilter, BOOLEAN WatchTree )
2714 struct read_changes_info *info;
2716 ULONG_PTR cvalue = ApcRoutine ? 0 : (ULONG_PTR)ApcContext;
2718 TRACE("%p %p %p %p %p %p %u %u %d\n",
2719 FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock,
2720 Buffer, BufferSize, CompletionFilter, WatchTree );
2723 return STATUS_ACCESS_VIOLATION;
2725 if (CompletionFilter == 0 || (CompletionFilter & ~FILE_NOTIFY_ALL))
2726 return STATUS_INVALID_PARAMETER;
2728 info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof *info );
2730 return STATUS_NO_MEMORY;
2732 info->FileHandle = FileHandle;
2733 info->Buffer = Buffer;
2734 info->BufferSize = BufferSize;
2735 info->apc = ApcRoutine;
2736 info->apc_arg = ApcContext;
2738 SERVER_START_REQ( read_directory_changes )
2740 req->filter = CompletionFilter;
2741 req->want_data = (Buffer != NULL);
2742 req->subtree = WatchTree;
2743 req->async.handle = wine_server_obj_handle( FileHandle );
2744 req->async.callback = wine_server_client_ptr( read_changes_apc );
2745 req->async.iosb = wine_server_client_ptr( IoStatusBlock );
2746 req->async.arg = wine_server_client_ptr( info );
2747 req->async.event = wine_server_obj_handle( Event );
2748 req->async.cvalue = cvalue;
2749 status = wine_server_call( req );
2753 if (status != STATUS_PENDING)
2754 RtlFreeHeap( GetProcessHeap(), 0, info );