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/list.h"
75 #include "wine/library.h"
76 #include "wine/debug.h"
78 WINE_DEFAULT_DEBUG_CHANNEL(file);
81 #undef VFAT_IOCTL_READDIR_BOTH
86 /* We want the real kernel dirent structure, not the libc one */
91 unsigned short d_reclen;
95 /* Define the VFAT ioctl to get both short and long file names */
96 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
99 # define O_DIRECTORY 0200000 /* must be directory */
108 unsigned short d_reclen;
109 unsigned char d_type;
113 static inline int getdents64( int fd, char *de, unsigned int size )
116 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
118 : "0" (220 /*NR_getdents64*/), "r" (fd), "c" (de), "d" (size)
133 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
134 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
136 #define INVALID_NT_CHARS '*','?','<','>','|','"'
137 #define INVALID_DOS_CHARS INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
139 #define MAX_DIR_ENTRY_LEN 255 /* max length of a directory entry in chars */
141 #define MAX_IGNORED_FILES 4
149 static struct file_identity ignored_files[MAX_IGNORED_FILES];
150 static int ignored_files_count;
152 union file_directory_info
155 FILE_DIRECTORY_INFORMATION dir;
156 FILE_BOTH_DIRECTORY_INFORMATION both;
157 FILE_FULL_DIRECTORY_INFORMATION full;
158 FILE_ID_BOTH_DIRECTORY_INFORMATION id_both;
159 FILE_ID_FULL_DIRECTORY_INFORMATION id_full;
162 static int show_dot_files = -1;
164 /* at some point we may want to allow Winelib apps to set this */
165 static const int is_case_sensitive = FALSE;
167 UNICODE_STRING windows_dir = { 0, 0, NULL }; /* windows directory */
168 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
170 static struct file_identity curdir;
171 static struct file_identity windir;
173 static RTL_CRITICAL_SECTION dir_section;
174 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
177 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
178 0, 0, { (DWORD_PTR)(__FILE__ ": dir_section") }
180 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
183 /* check if a given Unicode char is OK in a DOS short name */
184 static inline BOOL is_invalid_dos_char( WCHAR ch )
186 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
187 if (ch > 0x7f) return TRUE;
188 return strchrW( invalid_chars, ch ) != NULL;
191 /* check if the device can be a mounted volume */
192 static inline int is_valid_mounted_device( const struct stat *st )
194 #if defined(linux) || defined(__sun__)
195 return S_ISBLK( st->st_mode );
197 /* disks are char devices on *BSD */
198 return S_ISCHR( st->st_mode );
202 static inline void ignore_file( const char *name )
205 assert( ignored_files_count < MAX_IGNORED_FILES );
206 if (!stat( name, &st ))
208 ignored_files[ignored_files_count].dev = st.st_dev;
209 ignored_files[ignored_files_count].ino = st.st_ino;
210 ignored_files_count++;
214 static inline BOOL is_same_file( const struct file_identity *file, const struct stat *st )
216 return st->st_dev == file->dev && st->st_ino == file->ino;
219 static inline BOOL is_ignored_file( const struct stat *st )
223 for (i = 0; i < ignored_files_count; i++)
224 if (is_same_file( &ignored_files[i], st )) return TRUE;
228 static inline unsigned int dir_info_size( FILE_INFORMATION_CLASS class, unsigned int len )
232 case FileDirectoryInformation:
233 return (FIELD_OFFSET( FILE_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
234 case FileBothDirectoryInformation:
235 return (FIELD_OFFSET( FILE_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
236 case FileFullDirectoryInformation:
237 return (FIELD_OFFSET( FILE_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
238 case FileIdBothDirectoryInformation:
239 return (FIELD_OFFSET( FILE_ID_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
240 case FileIdFullDirectoryInformation:
241 return (FIELD_OFFSET( FILE_ID_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
247 static inline unsigned int max_dir_info_size( FILE_INFORMATION_CLASS class )
249 return dir_info_size( class, MAX_DIR_ENTRY_LEN );
253 /* support for a directory queue for filesystem searches */
261 static struct list dir_queue = LIST_INIT( dir_queue );
263 static NTSTATUS add_dir_to_queue( const char *name )
265 int len = strlen( name ) + 1;
266 struct dir_name *dir = RtlAllocateHeap( GetProcessHeap(), 0,
267 FIELD_OFFSET( struct dir_name, name[len] ));
268 if (!dir) return STATUS_NO_MEMORY;
269 strcpy( dir->name, name );
270 list_add_tail( &dir_queue, &dir->entry );
271 return STATUS_SUCCESS;
274 static NTSTATUS next_dir_in_queue( char *name )
276 struct list *head = list_head( &dir_queue );
279 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
280 strcpy( name, dir->name );
281 list_remove( &dir->entry );
282 RtlFreeHeap( GetProcessHeap(), 0, dir );
283 return STATUS_SUCCESS;
285 return STATUS_OBJECT_NAME_NOT_FOUND;
288 static void flush_dir_queue(void)
292 while ((head = list_head( &dir_queue )))
294 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
295 list_remove( &dir->entry );
296 RtlFreeHeap( GetProcessHeap(), 0, dir );
301 /***********************************************************************
302 * get_default_com_device
304 * Return the default device to use for serial ports.
306 static char *get_default_com_device( int num )
310 if (!num || num > 9) return ret;
312 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
315 strcpy( ret, "/dev/ttyS0" );
316 ret[strlen(ret) - 1] = '0' + num - 1;
318 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
319 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuad0") );
322 strcpy( ret, "/dev/cuad0" );
323 ret[strlen(ret) - 1] = '0' + num - 1;
326 FIXME( "no known default for device com%d\n", num );
332 /***********************************************************************
333 * get_default_lpt_device
335 * Return the default device to use for parallel ports.
337 static char *get_default_lpt_device( int num )
341 if (!num || num > 9) return ret;
343 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
346 strcpy( ret, "/dev/lp0" );
347 ret[strlen(ret) - 1] = '0' + num - 1;
350 FIXME( "no known default for device lpt%d\n", num );
356 /***********************************************************************
357 * DIR_get_drives_info
359 * Retrieve device/inode number for all the drives. Helper for find_drive_root.
361 unsigned int DIR_get_drives_info( struct drive_info info[MAX_DOS_DRIVES] )
363 static struct drive_info cache[MAX_DOS_DRIVES];
364 static time_t last_update;
365 static unsigned int nb_drives;
367 time_t now = time(NULL);
369 RtlEnterCriticalSection( &dir_section );
370 if (now != last_update)
372 const char *config_dir = wine_get_config_dir();
377 if ((buffer = RtlAllocateHeap( GetProcessHeap(), 0,
378 strlen(config_dir) + sizeof("/dosdevices/a:") )))
380 strcpy( buffer, config_dir );
381 strcat( buffer, "/dosdevices/a:" );
382 p = buffer + strlen(buffer) - 2;
384 for (i = nb_drives = 0; i < MAX_DOS_DRIVES; i++)
387 if (!stat( buffer, &st ))
389 cache[i].dev = st.st_dev;
390 cache[i].ino = st.st_ino;
399 RtlFreeHeap( GetProcessHeap(), 0, buffer );
403 memcpy( info, cache, sizeof(cache) );
405 RtlLeaveCriticalSection( &dir_section );
410 /***********************************************************************
411 * parse_mount_entries
413 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
417 #include <sys/vfstab.h>
418 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
424 while (! getvfsent( f, &entry ))
426 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
427 if (!strcmp( entry.vfs_fstype, "nfs" ) ||
428 !strcmp( entry.vfs_fstype, "smbfs" ) ||
429 !strcmp( entry.vfs_fstype, "ncpfs" )) continue;
431 if (stat( entry.vfs_mountp, &st ) == -1) continue;
432 if (st.st_dev != dev || st.st_ino != ino) continue;
433 if (!strcmp( entry.vfs_fstype, "fd" ))
435 if ((device = strstr( entry.vfs_mntopts, "dev=" )))
437 char *p = strchr( device + 4, ',' );
443 return entry.vfs_special;
450 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
452 struct mntent *entry;
456 while ((entry = getmntent( f )))
458 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
459 if (!strcmp( entry->mnt_type, "nfs" ) ||
460 !strcmp( entry->mnt_type, "smbfs" ) ||
461 !strcmp( entry->mnt_type, "ncpfs" )) continue;
463 if (stat( entry->mnt_dir, &st ) == -1) continue;
464 if (st.st_dev != dev || st.st_ino != ino) continue;
465 if (!strcmp( entry->mnt_type, "supermount" ))
467 if ((device = strstr( entry->mnt_opts, "dev=" )))
469 char *p = strchr( device + 4, ',' );
474 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
476 /* if device is a regular file check for a loop mount */
477 if ((device = strstr( entry->mnt_opts, "loop=" )))
479 char *p = strchr( device + 5, ',' );
485 return entry->mnt_fsname;
491 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
493 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
498 while ((entry = getfsent()))
500 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
501 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
502 !strcmp( entry->fs_vfstype, "smbfs" ) ||
503 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
505 if (stat( entry->fs_file, &st ) == -1) continue;
506 if (st.st_dev != dev || st.st_ino != ino) continue;
507 return entry->fs_spec;
514 #include <sys/mnttab.h>
515 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
522 while (( ! getmntent( f, &entry) ))
524 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
525 if (!strcmp( entry.mnt_fstype, "nfs" ) ||
526 !strcmp( entry.mnt_fstype, "smbfs" ) ||
527 !strcmp( entry.mnt_fstype, "ncpfs" )) continue;
529 if (stat( entry.mnt_mountp, &st ) == -1) continue;
530 if (st.st_dev != dev || st.st_ino != ino) continue;
531 if (!strcmp( entry.mnt_fstype, "fd" ))
533 if ((device = strstr( entry.mnt_mntopts, "dev=" )))
535 char *p = strchr( device + 4, ',' );
541 return entry.mnt_special;
547 /***********************************************************************
548 * get_default_drive_device
550 * Return the default device to use for a given drive mount point.
552 static char *get_default_drive_device( const char *root )
562 /* try to open it first to force it to get mounted */
563 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
565 res = fstat( fd, &st );
568 /* now try normal stat just in case */
569 if (res == -1) res = stat( root, &st );
570 if (res == -1) return NULL;
572 RtlEnterCriticalSection( &dir_section );
574 if ((f = fopen( "/etc/mtab", "r" )))
576 device = parse_mount_entries( f, st.st_dev, st.st_ino );
579 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
580 if (!device && (f = fopen( "/etc/fstab", "r" )))
582 device = parse_mount_entries( f, st.st_dev, st.st_ino );
587 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
588 if (ret) strcpy( ret, device );
590 RtlLeaveCriticalSection( &dir_section );
592 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ )
597 /* try to open it first to force it to get mounted */
598 if ((fd = open( root, O_RDONLY )) != -1)
600 res = fstat( fd, &st );
603 /* now try normal stat just in case */
604 if (res == -1) res = stat( root, &st );
605 if (res == -1) return NULL;
607 RtlEnterCriticalSection( &dir_section );
609 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
610 * pass NULL. Leave the argument in for symmetry.
612 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
615 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
616 if (ret) strcpy( ret, device );
618 RtlLeaveCriticalSection( &dir_section );
626 /* try to open it first to force it to get mounted */
627 if ((fd = open( root, O_RDONLY )) != -1)
629 res = fstat( fd, &st );
632 /* now try normal stat just in case */
633 if (res == -1) res = stat( root, &st );
634 if (res == -1) return NULL;
636 RtlEnterCriticalSection( &dir_section );
638 if ((f = fopen( "/etc/mnttab", "r" )))
640 device = parse_mount_entries( f, st.st_dev, st.st_ino);
643 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
644 if (!device && (f = fopen( "/etc/vfstab", "r" )))
646 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
651 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
652 if (ret) strcpy( ret, device );
654 RtlLeaveCriticalSection( &dir_section );
656 #elif defined(__APPLE__)
657 struct statfs *mntStat;
663 static const char path_bsd_device[] = "/dev/disk";
666 res = stat( root, &st );
667 if (res == -1) return NULL;
672 RtlEnterCriticalSection( &dir_section );
674 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
676 for (i = 0; i < mntSize && !ret; i++)
678 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
679 if (st.st_dev != dev || st.st_ino != ino) continue;
681 /* FIXME add support for mounted network drive */
682 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
684 /* set return value to the corresponding raw BSD node */
685 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
688 strcpy(ret, "/dev/r");
689 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
693 RtlLeaveCriticalSection( &dir_section );
696 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
702 /***********************************************************************
703 * get_device_mount_point
705 * Return the current mount point for a device.
707 static char *get_device_mount_point( dev_t dev )
714 RtlEnterCriticalSection( &dir_section );
716 if ((f = fopen( "/etc/mtab", "r" )))
718 struct mntent *entry;
722 while ((entry = getmntent( f )))
724 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
725 if (!strcmp( entry->mnt_type, "nfs" ) ||
726 !strcmp( entry->mnt_type, "smbfs" ) ||
727 !strcmp( entry->mnt_type, "ncpfs" )) continue;
729 if (!strcmp( entry->mnt_type, "supermount" ))
731 if ((device = strstr( entry->mnt_opts, "dev=" )))
734 if ((p = strchr( device, ',' ))) *p = 0;
737 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
739 /* if device is a regular file check for a loop mount */
740 if ((device = strstr( entry->mnt_opts, "loop=" )))
743 if ((p = strchr( device, ',' ))) *p = 0;
746 else device = entry->mnt_fsname;
748 if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
750 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
751 if (ret) strcpy( ret, entry->mnt_dir );
757 RtlLeaveCriticalSection( &dir_section );
758 #elif defined(__APPLE__)
759 struct statfs *entry;
763 RtlEnterCriticalSection( &dir_section );
765 size = getmntinfo( &entry, MNT_NOWAIT );
766 for (i = 0; i < size; i++)
768 if (stat( entry[i].f_mntfromname, &st ) == -1) continue;
769 if (S_ISBLK(st.st_mode) && st.st_rdev == dev)
771 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry[i].f_mntfromname) + 1 );
772 if (ret) strcpy( ret, entry[i].f_mntfromname );
776 RtlLeaveCriticalSection( &dir_section );
779 if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
785 /***********************************************************************
788 * Initialize the show_dot_files options.
790 static void init_options(void)
792 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
793 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
797 OBJECT_ATTRIBUTES attr;
798 UNICODE_STRING nameW;
802 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
803 attr.Length = sizeof(attr);
804 attr.RootDirectory = root;
805 attr.ObjectName = &nameW;
807 attr.SecurityDescriptor = NULL;
808 attr.SecurityQualityOfService = NULL;
809 RtlInitUnicodeString( &nameW, WineW );
811 /* @@ Wine registry key: HKCU\Software\Wine */
812 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
814 RtlInitUnicodeString( &nameW, ShowDotFilesW );
815 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
817 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
818 show_dot_files = IS_OPTION_TRUE( str[0] );
824 /* a couple of directories that we don't want to return in directory searches */
825 ignore_file( wine_get_config_dir() );
826 ignore_file( "/dev" );
827 ignore_file( "/proc" );
829 ignore_file( "/sys" );
834 /***********************************************************************
837 * Check if the specified file should be hidden based on its name and the show dot files option.
839 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
843 if (show_dot_files == -1) init_options();
844 if (show_dot_files) return FALSE;
846 end = p = name->Buffer + name->Length/sizeof(WCHAR);
847 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
848 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
849 if (p == end || *p != '.') return FALSE;
850 /* make sure it isn't '.' or '..' */
851 if (p + 1 == end) return FALSE;
852 if (p[1] == '.' && p + 2 == end) return FALSE;
857 /***********************************************************************
858 * hash_short_file_name
860 * Transform a Unix file name into a hashed DOS name. If the name is a valid
861 * DOS name, it is converted to upper-case; otherwise it is replaced by a
862 * hashed version that fits in 8.3 format.
863 * 'buffer' must be at least 12 characters long.
864 * Returns length of short name in bytes; short name is NOT null-terminated.
866 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
868 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
870 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
875 /* Compute the hash code of the file name */
876 /* If you know something about hash functions, feel free to */
877 /* insert a better algorithm here... */
878 if (!is_case_sensitive)
880 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
881 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
882 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
886 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
887 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
888 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
891 /* Find last dot for start of the extension */
892 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
894 /* Copy first 4 chars, replacing invalid chars with '_' */
895 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
897 if (p == end || p == ext) break;
898 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
900 /* Pad to 5 chars with '~' */
901 while (i-- >= 0) *dst++ = '~';
903 /* Insert hash code converted to 3 ASCII chars */
904 *dst++ = hash_chars[(hash >> 10) & 0x1f];
905 *dst++ = hash_chars[(hash >> 5) & 0x1f];
906 *dst++ = hash_chars[hash & 0x1f];
908 /* Copy the first 3 chars of the extension (if any) */
912 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
913 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
919 /***********************************************************************
922 * Check a long file name against a mask.
924 * Tests (done in W95 DOS shell - case insensitive):
925 * *.txt test1.test.txt *
927 * *.t??????.t* test1.ta.tornado.txt *
928 * *tornado* test1.ta.tornado.txt *
929 * t*t test1.ta.tornado.txt *
931 * ?est??? test1.txt -
932 * *test1.txt* test1.txt *
933 * h?l?o*t.dat hellothisisatest.dat *
935 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
938 const WCHAR *name = name_str->Buffer;
939 const WCHAR *mask = mask_str->Buffer;
940 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
941 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
942 const WCHAR *lastjoker = NULL;
943 const WCHAR *next_to_retry = NULL;
945 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
947 while (name < name_end && mask < mask_end)
953 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
954 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
957 /* skip to the next match after the joker(s) */
958 if (is_case_sensitive)
959 while (name < name_end && (*name != *mask)) name++;
961 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
962 next_to_retry = name;
969 if (is_case_sensitive) mismatch = (*mask != *name);
970 else mismatch = (toupperW(*mask) != toupperW(*name));
976 if (mask == mask_end)
978 if (name == name_end) return TRUE;
979 if (lastjoker) mask = lastjoker;
982 else /* mismatch ! */
984 if (lastjoker) /* we had an '*', so we can try unlimitedly */
988 /* this scan sequence was a mismatch, so restart
989 * 1 char after the first char we checked last time */
991 name = next_to_retry;
993 else return FALSE; /* bad luck */
998 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
999 mask++; /* Ignore trailing '.' or '*' in mask */
1000 return (name == name_end && mask == mask_end);
1004 /***********************************************************************
1007 * helper for NtQueryDirectoryFile
1009 static union file_directory_info *append_entry( void *info_ptr, IO_STATUS_BLOCK *io, ULONG max_length,
1010 const char *long_name, const char *short_name,
1011 const UNICODE_STRING *mask, FILE_INFORMATION_CLASS class )
1013 union file_directory_info *info;
1014 int i, long_len, short_len, total_len;
1016 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
1017 WCHAR short_nameW[12];
1020 ULONG attributes = 0;
1022 io->u.Status = STATUS_SUCCESS;
1023 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
1024 if (long_len == -1) return NULL;
1026 str.Buffer = long_nameW;
1027 str.Length = long_len * sizeof(WCHAR);
1028 str.MaximumLength = sizeof(long_nameW);
1032 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
1033 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
1034 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
1036 else /* generate a short name if necessary */
1041 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1042 short_len = hash_short_file_name( &str, short_nameW );
1045 TRACE( "long %s short %s mask %s\n",
1046 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
1048 if (mask && !match_filename( &str, mask ))
1050 if (!short_len) return NULL; /* no short name to match */
1051 str.Buffer = short_nameW;
1052 str.Length = short_len * sizeof(WCHAR);
1053 str.MaximumLength = sizeof(short_nameW);
1054 if (!match_filename( &str, mask )) return NULL;
1057 if (lstat( long_name, &st ) == -1) return NULL;
1058 if (S_ISLNK( st.st_mode ))
1060 if (stat( long_name, &st ) == -1) return NULL;
1061 if (S_ISDIR( st.st_mode )) attributes |= FILE_ATTRIBUTE_REPARSE_POINT;
1063 if (is_ignored_file( &st ))
1065 TRACE( "ignoring file %s\n", long_name );
1068 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
1069 attributes |= FILE_ATTRIBUTE_HIDDEN;
1071 total_len = dir_info_size( class, long_len );
1072 if (io->Information + total_len > max_length)
1074 total_len = max_length - io->Information;
1075 io->u.Status = STATUS_BUFFER_OVERFLOW;
1077 info = (union file_directory_info *)((char *)info_ptr + io->Information);
1078 if (st.st_dev != curdir.dev) st.st_ino = 0; /* ignore inode if on a different device */
1079 /* all the structures start with a FileDirectoryInformation layout */
1080 fill_stat_info( &st, info, class );
1081 info->dir.NextEntryOffset = total_len;
1082 info->dir.FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
1083 info->dir.FileAttributes |= attributes;
1087 case FileDirectoryInformation:
1088 info->dir.FileNameLength = long_len * sizeof(WCHAR);
1089 filename = info->dir.FileName;
1092 case FileFullDirectoryInformation:
1093 info->full.EaSize = 0; /* FIXME */
1094 info->full.FileNameLength = long_len * sizeof(WCHAR);
1095 filename = info->full.FileName;
1098 case FileIdFullDirectoryInformation:
1099 info->id_full.EaSize = 0; /* FIXME */
1100 info->id_full.FileNameLength = long_len * sizeof(WCHAR);
1101 filename = info->id_full.FileName;
1104 case FileBothDirectoryInformation:
1105 info->both.EaSize = 0; /* FIXME */
1106 info->both.ShortNameLength = short_len * sizeof(WCHAR);
1107 for (i = 0; i < short_len; i++) info->both.ShortName[i] = toupperW(short_nameW[i]);
1108 info->both.FileNameLength = long_len * sizeof(WCHAR);
1109 filename = info->both.FileName;
1112 case FileIdBothDirectoryInformation:
1113 info->id_both.EaSize = 0; /* FIXME */
1114 info->id_both.ShortNameLength = short_len * sizeof(WCHAR);
1115 for (i = 0; i < short_len; i++) info->id_both.ShortName[i] = toupperW(short_nameW[i]);
1116 info->id_both.FileNameLength = long_len * sizeof(WCHAR);
1117 filename = info->id_both.FileName;
1123 memcpy( filename, long_nameW, total_len - ((char *)filename - (char *)info) );
1124 io->Information += total_len;
1129 #ifdef VFAT_IOCTL_READDIR_BOTH
1131 /***********************************************************************
1134 * Wrapper for the VFAT ioctl to work around various kernel bugs.
1135 * dir_section must be held by caller.
1137 static KERNEL_DIRENT *start_vfat_ioctl( int fd )
1139 static KERNEL_DIRENT *de;
1144 const size_t page_size = getpagesize();
1145 SIZE_T size = 2 * sizeof(*de) + page_size;
1148 if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_RESERVE, PAGE_READWRITE ))
1150 /* commit only the size needed for the dir entries */
1151 /* this leaves an extra unaccessible page, which should make the kernel */
1152 /* fail with -EFAULT before it stomps all over our memory */
1154 size = 2 * sizeof(*de);
1155 NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_COMMIT, PAGE_READWRITE );
1158 /* set d_reclen to 65535 to work around an AFS kernel bug */
1159 de[0].d_reclen = 65535;
1160 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
1163 if (errno != ENOENT) return NULL; /* VFAT ioctl probably not supported */
1164 de[0].d_reclen = 0; /* eof */
1166 else if (!res && de[0].d_reclen == 65535) return NULL; /* AFS bug */
1172 /***********************************************************************
1173 * read_directory_vfat
1175 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
1177 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1178 BOOLEAN single_entry, const UNICODE_STRING *mask,
1179 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1184 union file_directory_info *info, *last_info = NULL;
1186 io->u.Status = STATUS_SUCCESS;
1188 if (restart_scan) lseek( fd, 0, SEEK_SET );
1190 if (length < max_dir_info_size(class)) /* we may have to return a partial entry here */
1192 off_t old_pos = lseek( fd, 0, SEEK_CUR );
1194 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1196 while (de[0].d_reclen)
1198 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1199 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1200 de[0].d_name[len] = 0;
1201 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1202 de[1].d_name[len] = 0;
1204 if (de[1].d_name[0])
1205 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1207 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1211 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1212 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1215 old_pos = lseek( fd, 0, SEEK_CUR );
1216 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1219 else /* we'll only return full entries, no need to worry about overflow */
1221 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1223 while (de[0].d_reclen)
1225 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1226 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1227 de[0].d_name[len] = 0;
1228 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1229 de[1].d_name[len] = 0;
1231 if (de[1].d_name[0])
1232 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1234 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1238 if (single_entry) break;
1239 /* check if we still have enough space for the largest possible entry */
1240 if (io->Information + max_dir_info_size(class) > length) break;
1242 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1246 if (last_info) last_info->next = 0;
1247 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1250 #endif /* VFAT_IOCTL_READDIR_BOTH */
1253 /***********************************************************************
1254 * read_directory_getdents
1256 * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
1259 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1260 BOOLEAN single_entry, const UNICODE_STRING *mask,
1261 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1264 size_t size = length;
1265 int res, fake_dot_dot = 1;
1266 char *data, local_buffer[8192];
1267 KERNEL_DIRENT64 *de;
1268 union file_directory_info *info, *last_info = NULL;
1270 if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1272 size = sizeof(local_buffer);
1273 data = local_buffer;
1276 if (restart_scan) lseek( fd, 0, SEEK_SET );
1277 else if (length < max_dir_info_size(class)) /* we may have to return a partial entry here */
1279 old_pos = lseek( fd, 0, SEEK_CUR );
1280 if (old_pos == -1 && errno == ENOENT)
1282 io->u.Status = STATUS_NO_MORE_FILES;
1288 io->u.Status = STATUS_SUCCESS;
1290 res = getdents64( fd, data, size );
1293 if (errno != ENOSYS)
1295 io->u.Status = FILE_GetNtStatus();
1301 de = (KERNEL_DIRENT64 *)data;
1305 /* check if we got . and .. from getdents */
1308 if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1310 KERNEL_DIRENT64 *next_de = (KERNEL_DIRENT64 *)(data + de->d_reclen);
1311 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1314 /* make sure we have enough room for both entries */
1317 const ULONG min_info_size = dir_info_size( class, 1 ) + dir_info_size( class, 2 );
1318 if (length < min_info_size || single_entry)
1320 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1327 if ((info = append_entry( buffer, io, length, ".", NULL, mask, class )))
1329 if ((info = append_entry( buffer, io, length, "..", NULL, mask, class )))
1332 /* check if we still have enough space for the largest possible entry */
1333 if (last_info && io->Information + max_dir_info_size(class) > length)
1335 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1343 res -= de->d_reclen;
1345 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1346 (info = append_entry( buffer, io, length, de->d_name, NULL, mask, class )))
1349 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1351 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1354 /* check if we still have enough space for the largest possible entry */
1355 if (single_entry || io->Information + max_dir_info_size(class) > length)
1357 if (res > 0) lseek( fd, de->d_off, SEEK_SET ); /* set pos to next entry */
1361 old_pos = de->d_off;
1362 /* move on to the next entry */
1363 if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1366 res = getdents64( fd, data, size );
1367 de = (KERNEL_DIRENT64 *)data;
1371 if (last_info) last_info->next = 0;
1372 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1375 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1379 #elif defined HAVE_GETDIRENTRIES
1381 #if _DARWIN_FEATURE_64_BIT_INODE
1383 /* Darwin doesn't provide a version of getdirentries with support for 64-bit
1384 * inodes. When 64-bit inodes are enabled, the getdirentries symbol is mapped
1385 * to _getdirentries_is_not_available_when_64_bit_inodes_are_in_effect so that
1386 * we get link errors if we try to use it. We still need getdirentries, but we
1387 * don't need it to support 64-bit inodes. So, we use the legacy getdirentries
1388 * with 32-bit inodes. We have to be careful to use a corresponding dirent
1391 int darwin_legacy_getdirentries(int, char *, int, long *) __asm("_getdirentries");
1392 #define getdirentries darwin_legacy_getdirentries
1394 struct darwin_legacy_dirent {
1396 __uint16_t d_reclen;
1399 char d_name[__DARWIN_MAXNAMLEN + 1];
1401 #define dirent darwin_legacy_dirent
1405 /***********************************************************************
1406 * wine_getdirentries
1408 * Wrapper for the BSD getdirentries system call to fix a bug in the
1409 * Mac OS X version. For some file systems (at least Apple Filing
1410 * Protocol a.k.a. AFP), getdirentries resets the file position to 0
1411 * when it's about to return 0 (no more entries). So, a subsequent
1412 * getdirentries call starts over at the beginning again, causing an
1415 static inline int wine_getdirentries(int fd, char *buf, int nbytes, long *basep)
1417 int res = getdirentries(fd, buf, nbytes, basep);
1420 lseek(fd, *basep, SEEK_SET);
1425 /***********************************************************************
1426 * read_directory_getdirentries
1428 * Read a directory using the BSD getdirentries system call; helper for NtQueryDirectoryFile.
1430 static int read_directory_getdirentries( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1431 BOOLEAN single_entry, const UNICODE_STRING *mask,
1432 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1435 ULONG_PTR restart_info_pos = 0;
1436 size_t size, initial_size = length;
1437 int res, fake_dot_dot = 1;
1438 char *data, local_buffer[8192];
1440 union file_directory_info *info, *last_info = NULL, *restart_last_info = NULL;
1442 size = initial_size;
1443 data = local_buffer;
1444 if (size > sizeof(local_buffer) && !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1446 io->u.Status = STATUS_NO_MEMORY;
1447 return io->u.Status;
1450 if (restart_scan) lseek( fd, 0, SEEK_SET );
1452 io->u.Status = STATUS_SUCCESS;
1454 /* FIXME: should make sure size is larger than filesystem block size */
1455 res = wine_getdirentries( fd, data, size, &restart_pos );
1458 io->u.Status = FILE_GetNtStatus();
1463 de = (struct dirent *)data;
1467 /* check if we got . and .. from getdirentries */
1470 if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1472 struct dirent *next_de = (struct dirent *)(data + de->d_reclen);
1473 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1476 /* make sure we have enough room for both entries */
1479 const ULONG min_info_size = dir_info_size( class, 1 ) + dir_info_size( class, 2 );
1480 if (length < min_info_size || single_entry)
1482 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1489 if ((info = append_entry( buffer, io, length, ".", NULL, mask, class )))
1491 if ((info = append_entry( buffer, io, length, "..", NULL, mask, class )))
1494 restart_last_info = last_info;
1495 restart_info_pos = io->Information;
1497 /* check if we still have enough space for the largest possible entry */
1498 if (last_info && io->Information + max_dir_info_size(class) > length)
1500 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1508 res -= de->d_reclen;
1510 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1511 ((info = append_entry( buffer, io, length, de->d_name, NULL, mask, class ))))
1514 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1516 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1517 if (restart_info_pos) /* if we have a complete read already, return it */
1519 io->u.Status = STATUS_SUCCESS;
1520 io->Information = restart_info_pos;
1521 last_info = restart_last_info;
1524 /* otherwise restart from the start with a smaller size */
1525 size = (char *)de - data;
1527 io->Information = 0;
1531 /* if we have to return but the buffer contains more data, restart with a smaller size */
1532 if (res > 0 && (single_entry || io->Information + max_dir_info_size(class) > length))
1534 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1535 size = (char *)de - data;
1536 io->Information = restart_info_pos;
1537 last_info = restart_last_info;
1541 /* move on to the next entry */
1544 de = (struct dirent *)((char *)de + de->d_reclen);
1547 if (size < initial_size) break; /* already restarted once, give up now */
1548 size = min( size, length - io->Information );
1549 /* if size is too small don't bother to continue */
1550 if (size < max_dir_info_size(class) && last_info) break;
1551 restart_last_info = last_info;
1552 restart_info_pos = io->Information;
1554 res = wine_getdirentries( fd, data, size, &restart_pos );
1555 de = (struct dirent *)data;
1558 if (last_info) last_info->next = 0;
1559 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1562 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1566 #if _DARWIN_FEATURE_64_BIT_INODE
1567 #undef getdirentries
1571 #endif /* HAVE_GETDIRENTRIES */
1574 /***********************************************************************
1575 * read_directory_readdir
1577 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1579 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1580 BOOLEAN single_entry, const UNICODE_STRING *mask,
1581 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1584 off_t i, old_pos = 0;
1586 union file_directory_info *info, *last_info = NULL;
1588 if (!(dir = opendir( "." )))
1590 io->u.Status = FILE_GetNtStatus();
1596 old_pos = lseek( fd, 0, SEEK_CUR );
1597 /* skip the right number of entries */
1598 for (i = 0; i < old_pos - 2; i++)
1600 if (!readdir( dir ))
1603 io->u.Status = STATUS_NO_MORE_FILES;
1608 io->u.Status = STATUS_SUCCESS;
1613 info = append_entry( buffer, io, length, ".", NULL, mask, class );
1614 else if (old_pos == 1)
1615 info = append_entry( buffer, io, length, "..", NULL, mask, class );
1616 else if ((de = readdir( dir )))
1618 if (strcmp( de->d_name, "." ) && strcmp( de->d_name, ".." ))
1619 info = append_entry( buffer, io, length, de->d_name, NULL, mask, class );
1629 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1631 old_pos--; /* restore pos to previous entry */
1634 if (single_entry) break;
1635 /* check if we still have enough space for the largest possible entry */
1636 if (io->Information + max_dir_info_size(class) > length) break;
1640 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
1643 if (last_info) last_info->next = 0;
1644 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1647 /***********************************************************************
1648 * read_directory_stat
1650 * Read a single file from a directory by determining whether the file
1651 * identified by mask exists using stat.
1653 static int read_directory_stat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1654 BOOLEAN single_entry, const UNICODE_STRING *mask,
1655 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1657 int unix_len, ret, used_default;
1661 TRACE("trying optimisation for file %s\n", debugstr_us( mask ));
1663 unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
1664 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
1666 io->u.Status = STATUS_NO_MEMORY;
1669 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
1670 NULL, &used_default );
1671 if (ret > 0 && !used_default)
1676 lseek( fd, 0, SEEK_SET );
1678 else if (lseek( fd, 0, SEEK_CUR ) != 0)
1680 io->u.Status = STATUS_NO_MORE_FILES;
1685 ret = stat( unix_name, &st );
1688 union file_directory_info *info = append_entry( buffer, io, length, unix_name, NULL, NULL, class );
1692 if (io->u.Status != STATUS_BUFFER_OVERFLOW) lseek( fd, 1, SEEK_CUR );
1694 else io->u.Status = STATUS_NO_MORE_FILES;
1700 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1702 TRACE("returning %d\n", ret);
1708 static inline WCHAR *mempbrkW( const WCHAR *ptr, const WCHAR *accept, size_t n )
1711 for (end = ptr + n; ptr < end; ptr++) if (strchrW( accept, *ptr )) return (WCHAR *)ptr;
1715 /******************************************************************************
1716 * NtQueryDirectoryFile [NTDLL.@]
1717 * ZwQueryDirectoryFile [NTDLL.@]
1719 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
1720 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
1721 PIO_STATUS_BLOCK io,
1722 PVOID buffer, ULONG length,
1723 FILE_INFORMATION_CLASS info_class,
1724 BOOLEAN single_entry,
1725 PUNICODE_STRING mask,
1726 BOOLEAN restart_scan )
1728 int cwd, fd, needs_close;
1729 static const WCHAR wszWildcards[] = { '*','?',0 };
1731 TRACE("(%p %p %p %p %p %p 0x%08x 0x%08x 0x%08x %s 0x%08x\n",
1732 handle, event, apc_routine, apc_context, io, buffer,
1733 length, info_class, single_entry, debugstr_us(mask),
1736 if (event || apc_routine)
1738 FIXME( "Unsupported yet option\n" );
1739 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1743 case FileDirectoryInformation:
1744 case FileBothDirectoryInformation:
1745 case FileFullDirectoryInformation:
1746 case FileIdBothDirectoryInformation:
1747 case FileIdFullDirectoryInformation:
1748 if (length < dir_info_size( info_class, 1 )) return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
1751 FIXME( "Unsupported file info class %d\n", info_class );
1752 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1755 if ((io->u.Status = server_get_unix_fd( handle, FILE_LIST_DIRECTORY, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
1756 return io->u.Status;
1758 io->Information = 0;
1760 RtlEnterCriticalSection( &dir_section );
1762 if (show_dot_files == -1) init_options();
1764 cwd = open( ".", O_RDONLY );
1765 if (fchdir( fd ) != -1)
1769 curdir.dev = st.st_dev;
1770 curdir.ino = st.st_ino;
1771 #ifdef VFAT_IOCTL_READDIR_BOTH
1772 if ((read_directory_vfat( fd, io, buffer, length, single_entry,
1773 mask, restart_scan, info_class )) != -1) goto done;
1775 if (mask && !mempbrkW( mask->Buffer, wszWildcards, mask->Length / sizeof(WCHAR) ) &&
1776 read_directory_stat( fd, io, buffer, length, single_entry,
1777 mask, restart_scan, info_class ) != -1) goto done;
1779 if ((read_directory_getdents( fd, io, buffer, length, single_entry,
1780 mask, restart_scan, info_class )) != -1) goto done;
1781 #elif defined HAVE_GETDIRENTRIES
1782 if ((read_directory_getdirentries( fd, io, buffer, length, single_entry,
1783 mask, restart_scan, info_class )) != -1) goto done;
1785 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan, info_class );
1788 if (cwd == -1 || fchdir( cwd ) == -1) chdir( "/" );
1790 else io->u.Status = FILE_GetNtStatus();
1792 RtlLeaveCriticalSection( &dir_section );
1794 if (needs_close) close( fd );
1795 if (cwd != -1) close( cwd );
1796 TRACE( "=> %x (%ld)\n", io->u.Status, io->Information );
1797 return io->u.Status;
1801 /***********************************************************************
1804 * Find a file in a directory the hard way, by doing a case-insensitive search.
1805 * The file found is appended to unix_name at pos.
1806 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
1808 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
1809 int check_case, int *is_win_dir )
1811 WCHAR buffer[MAX_DIR_ENTRY_LEN];
1817 int ret, used_default, is_name_8_dot_3;
1819 /* try a shortcut for this directory */
1821 unix_name[pos++] = '/';
1822 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
1823 NULL, &used_default );
1824 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
1825 /* so it cannot match the file we are looking for */
1826 if (ret >= 0 && !used_default)
1828 unix_name[pos + ret] = 0;
1829 if (!stat( unix_name, &st ))
1831 if (is_win_dir) *is_win_dir = is_same_file( &windir, &st );
1832 return STATUS_SUCCESS;
1835 if (check_case) goto not_found; /* we want an exact match */
1837 if (pos > 1) unix_name[pos - 1] = 0;
1838 else unix_name[1] = 0; /* keep the initial slash */
1840 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
1842 str.Buffer = (WCHAR *)name;
1843 str.Length = length * sizeof(WCHAR);
1844 str.MaximumLength = str.Length;
1845 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
1847 /* now look for it through the directory */
1849 #ifdef VFAT_IOCTL_READDIR_BOTH
1850 if (is_name_8_dot_3)
1852 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
1857 RtlEnterCriticalSection( &dir_section );
1858 if ((de = start_vfat_ioctl( fd )))
1860 unix_name[pos - 1] = '/';
1861 while (de[0].d_reclen)
1863 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1864 size_t len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1865 de[0].d_name[len] = 0;
1866 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1867 de[1].d_name[len] = 0;
1869 if (de[1].d_name[0])
1871 ret = ntdll_umbstowcs( 0, de[1].d_name, strlen(de[1].d_name),
1872 buffer, MAX_DIR_ENTRY_LEN );
1873 if (ret == length && !memicmpW( buffer, name, length))
1875 strcpy( unix_name + pos, de[1].d_name );
1876 RtlLeaveCriticalSection( &dir_section );
1881 ret = ntdll_umbstowcs( 0, de[0].d_name, strlen(de[0].d_name),
1882 buffer, MAX_DIR_ENTRY_LEN );
1883 if (ret == length && !memicmpW( buffer, name, length))
1885 strcpy( unix_name + pos,
1886 de[1].d_name[0] ? de[1].d_name : de[0].d_name );
1887 RtlLeaveCriticalSection( &dir_section );
1891 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1)
1893 RtlLeaveCriticalSection( &dir_section );
1899 RtlLeaveCriticalSection( &dir_section );
1902 /* fall through to normal handling */
1904 #endif /* VFAT_IOCTL_READDIR_BOTH */
1906 if (!(dir = opendir( unix_name )))
1908 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
1909 else return FILE_GetNtStatus();
1911 unix_name[pos - 1] = '/';
1912 str.Buffer = buffer;
1913 str.MaximumLength = sizeof(buffer);
1914 while ((de = readdir( dir )))
1916 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
1917 if (ret == length && !memicmpW( buffer, name, length ))
1919 strcpy( unix_name + pos, de->d_name );
1924 if (!is_name_8_dot_3) continue;
1926 str.Length = ret * sizeof(WCHAR);
1927 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1929 WCHAR short_nameW[12];
1930 ret = hash_short_file_name( &str, short_nameW );
1931 if (ret == length && !memicmpW( short_nameW, name, length ))
1933 strcpy( unix_name + pos, de->d_name );
1940 goto not_found; /* avoid warning */
1943 unix_name[pos - 1] = 0;
1944 return STATUS_OBJECT_PATH_NOT_FOUND;
1947 if (is_win_dir && !stat( unix_name, &st )) *is_win_dir = is_same_file( &windir, &st );
1948 return STATUS_SUCCESS;
1954 static const WCHAR catrootW[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t',0};
1955 static const WCHAR catroot2W[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t','2',0};
1956 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};
1957 static const WCHAR driversetcW[] = {'s','y','s','t','e','m','3','2','\\','d','r','i','v','e','r','s','\\','e','t','c',0};
1958 static const WCHAR logfilesW[] = {'s','y','s','t','e','m','3','2','\\','l','o','g','f','i','l','e','s',0};
1959 static const WCHAR spoolW[] = {'s','y','s','t','e','m','3','2','\\','s','p','o','o','l',0};
1960 static const WCHAR system32W[] = {'s','y','s','t','e','m','3','2',0};
1961 static const WCHAR syswow64W[] = {'s','y','s','w','o','w','6','4',0};
1962 static const WCHAR sysnativeW[] = {'s','y','s','n','a','t','i','v','e',0};
1963 static const WCHAR regeditW[] = {'r','e','g','e','d','i','t','.','e','x','e',0};
1964 static const WCHAR wow_regeditW[] = {'s','y','s','w','o','w','6','4','\\','r','e','g','e','d','i','t','.','e','x','e',0};
1968 const WCHAR *source;
1969 const WCHAR *dos_target;
1970 const char *unix_target;
1973 { catrootW, NULL, NULL },
1974 { catroot2W, NULL, NULL },
1975 { driversstoreW, NULL, NULL },
1976 { driversetcW, NULL, NULL },
1977 { logfilesW, NULL, NULL },
1978 { spoolW, NULL, NULL },
1979 { system32W, syswow64W, NULL },
1980 { sysnativeW, system32W, NULL },
1981 { regeditW, wow_regeditW, NULL }
1984 static unsigned int nb_redirects;
1987 /***********************************************************************
1988 * get_redirect_target
1990 * Find the target unix name for a redirected dir.
1992 static const char *get_redirect_target( const char *windows_dir, const WCHAR *name )
1994 int used_default, len, pos, win_len = strlen( windows_dir );
1995 char *unix_name, *unix_target = NULL;
1998 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, win_len + MAX_DIR_ENTRY_LEN + 2 )))
2000 memcpy( unix_name, windows_dir, win_len );
2005 const WCHAR *end, *next;
2007 for (end = name; *end; end++) if (IS_SEPARATOR(*end)) break;
2008 for (next = end; *next; next++) if (!IS_SEPARATOR(*next)) break;
2010 status = find_file_in_dir( unix_name, pos, name, end - name, FALSE, NULL );
2011 if (status == STATUS_OBJECT_PATH_NOT_FOUND && !*next) /* not finding last element is ok */
2013 len = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2014 MAX_DIR_ENTRY_LEN - (pos - win_len), NULL, &used_default );
2015 if (len > 0 && !used_default)
2017 unix_name[pos] = '/';
2023 if (status) goto done;
2024 pos += strlen( unix_name + pos );
2028 if ((unix_target = RtlAllocateHeap( GetProcessHeap(), 0, pos - win_len )))
2029 memcpy( unix_target, unix_name + win_len + 1, pos - win_len );
2032 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2037 /***********************************************************************
2040 static void init_redirects(void)
2042 UNICODE_STRING nt_name;
2043 ANSI_STRING unix_name;
2048 if (!RtlDosPathNameToNtPathName_U( windows_dir.Buffer, &nt_name, NULL, NULL ))
2050 ERR( "can't convert %s\n", debugstr_us(&windows_dir) );
2053 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
2054 RtlFreeUnicodeString( &nt_name );
2057 ERR( "cannot open %s (%x)\n", debugstr_us(&windows_dir), status );
2060 if (!stat( unix_name.Buffer, &st ))
2062 windir.dev = st.st_dev;
2063 windir.ino = st.st_ino;
2064 nb_redirects = sizeof(redirects) / sizeof(redirects[0]);
2065 for (i = 0; i < nb_redirects; i++)
2067 if (!redirects[i].dos_target) continue;
2068 redirects[i].unix_target = get_redirect_target( unix_name.Buffer, redirects[i].dos_target );
2069 TRACE( "%s -> %s\n", debugstr_w(redirects[i].source), redirects[i].unix_target );
2072 RtlFreeAnsiString( &unix_name );
2077 /***********************************************************************
2080 * Check if path matches a redirect name. If yes, return matched length.
2082 static int match_redirect( const WCHAR *path, int len, const WCHAR *redir, int check_case )
2086 while (i < len && *redir)
2088 if (IS_SEPARATOR(path[i]))
2090 if (*redir++ != '\\') return 0;
2091 while (i < len && IS_SEPARATOR(path[i])) i++;
2092 continue; /* move on to next path component */
2094 else if (check_case)
2096 if (path[i] != *redir) return 0;
2100 if (tolowerW(path[i]) != tolowerW(*redir)) return 0;
2105 if (*redir) return 0;
2106 if (i < len && !IS_SEPARATOR(path[i])) return 0;
2107 while (i < len && IS_SEPARATOR(path[i])) i++;
2112 /***********************************************************************
2115 * Retrieve the Unix path corresponding to a redirected path if any.
2117 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, int check_case )
2122 for (i = 0; i < nb_redirects; i++)
2124 if ((len = match_redirect( name, length, redirects[i].source, check_case )))
2126 if (!redirects[i].unix_target) break;
2127 unix_name[pos++] = '/';
2128 strcpy( unix_name + pos, redirects[i].unix_target );
2137 /* there are no redirects on 64-bit */
2139 static const unsigned int nb_redirects = 0;
2141 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, int check_case )
2148 /***********************************************************************
2149 * DIR_init_windows_dir
2151 void DIR_init_windows_dir( const WCHAR *win, const WCHAR *sys )
2153 /* FIXME: should probably store paths as NT file names */
2155 RtlCreateUnicodeString( &windows_dir, win );
2156 RtlCreateUnicodeString( &system_dir, sys );
2159 if (is_wow64) init_redirects();
2164 /******************************************************************************
2167 * Get the Unix path of a DOS device.
2169 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
2171 const char *config_dir = wine_get_config_dir();
2173 char *unix_name, *new_name, *dev;
2177 /* make sure the device name is ASCII */
2178 for (i = 0; i < name_len; i++)
2179 if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
2181 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
2183 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2184 return STATUS_NO_MEMORY;
2186 strcpy( unix_name, config_dir );
2187 strcat( unix_name, "/dosdevices/" );
2188 dev = unix_name + strlen(unix_name);
2190 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
2193 /* special case for drive devices */
2194 if (name_len == 2 && dev[1] == ':')
2202 if (!stat( unix_name, &st ))
2204 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
2205 unix_name_ret->Buffer = unix_name;
2206 unix_name_ret->Length = strlen(unix_name);
2207 unix_name_ret->MaximumLength = unix_len;
2208 return STATUS_SUCCESS;
2212 /* now try some defaults for it */
2213 if (!strcmp( dev, "aux" ))
2215 strcpy( dev, "com1" );
2218 if (!strcmp( dev, "prn" ))
2220 strcpy( dev, "lpt1" );
2223 if (!strcmp( dev, "nul" ))
2225 strcpy( unix_name, "/dev/null" );
2226 dev = NULL; /* last try */
2231 if (dev[1] == ':' && dev[2] == ':') /* drive device */
2233 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
2234 new_name = get_default_drive_device( unix_name );
2236 else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( atoi(dev + 3 ));
2237 else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( atoi(dev + 3 ));
2239 if (!new_name) break;
2241 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2242 unix_name = new_name;
2243 unix_len = strlen(unix_name) + 1;
2244 dev = NULL; /* last try */
2246 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2247 return STATUS_BAD_DEVICE_TYPE;
2251 /* return the length of the DOS namespace prefix if any */
2252 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
2254 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
2255 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
2257 if (name->Length > sizeof(nt_prefixW) &&
2258 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
2259 return sizeof(nt_prefixW) / sizeof(WCHAR);
2261 if (name->Length > sizeof(dosdev_prefixW) &&
2262 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
2263 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
2269 /******************************************************************************
2272 * Recursively search directories from the dir queue for a given inode.
2274 static NTSTATUS find_file_id( ANSI_STRING *unix_name, ULONGLONG file_id, dev_t dev )
2282 while (!(status = next_dir_in_queue( unix_name->Buffer )))
2284 if (!(dir = opendir( unix_name->Buffer ))) continue;
2285 TRACE( "searching %s for %s\n", unix_name->Buffer, wine_dbgstr_longlong(file_id) );
2286 pos = strlen( unix_name->Buffer );
2287 if (pos + MAX_DIR_ENTRY_LEN >= unix_name->MaximumLength/sizeof(WCHAR))
2289 char *new = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name->Buffer,
2290 unix_name->MaximumLength * 2 );
2294 return STATUS_NO_MEMORY;
2296 unix_name->MaximumLength *= 2;
2297 unix_name->Buffer = new;
2299 unix_name->Buffer[pos++] = '/';
2300 while ((de = readdir( dir )))
2302 if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
2303 strcpy( unix_name->Buffer + pos, de->d_name );
2304 if (lstat( unix_name->Buffer, &st ) == -1) continue;
2305 if (st.st_dev != dev) continue;
2306 if (st.st_ino == file_id)
2309 return STATUS_SUCCESS;
2311 if (!S_ISDIR( st.st_mode )) continue;
2312 if ((status = add_dir_to_queue( unix_name->Buffer )) != STATUS_SUCCESS)
2324 /******************************************************************************
2325 * file_id_to_unix_file_name
2327 * Lookup a file from its file id instead of its name.
2329 NTSTATUS file_id_to_unix_file_name( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name )
2331 enum server_fd_type type;
2332 int old_cwd, root_fd, needs_close;
2335 struct stat st, root_st;
2337 if (attr->ObjectName->Length != sizeof(ULONGLONG)) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2338 if (!attr->RootDirectory) return STATUS_INVALID_PARAMETER;
2339 memcpy( &file_id, attr->ObjectName->Buffer, sizeof(file_id) );
2341 unix_name->MaximumLength = 2 * MAX_DIR_ENTRY_LEN + 4;
2342 if (!(unix_name->Buffer = RtlAllocateHeap( GetProcessHeap(), 0, unix_name->MaximumLength )))
2343 return STATUS_NO_MEMORY;
2344 strcpy( unix_name->Buffer, "." );
2346 if ((status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
2349 if (type != FD_TYPE_DIR)
2351 status = STATUS_OBJECT_TYPE_MISMATCH;
2355 fstat( root_fd, &root_st );
2356 if (root_st.st_ino == file_id) /* shortcut for "." */
2358 status = STATUS_SUCCESS;
2362 RtlEnterCriticalSection( &dir_section );
2363 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2365 /* shortcut for ".." */
2366 if (!stat( "..", &st ) && st.st_dev == root_st.st_dev && st.st_ino == file_id)
2368 strcpy( unix_name->Buffer, ".." );
2369 status = STATUS_SUCCESS;
2373 status = add_dir_to_queue( "." );
2375 status = find_file_id( unix_name, file_id, root_st.st_dev );
2376 if (!status) /* get rid of "./" prefix */
2377 memmove( unix_name->Buffer, unix_name->Buffer + 2, strlen(unix_name->Buffer) - 1 );
2380 if (fchdir( old_cwd ) == -1) chdir( "/" );
2382 else status = FILE_GetNtStatus();
2383 RtlLeaveCriticalSection( &dir_section );
2384 if (old_cwd != -1) close( old_cwd );
2387 if (status == STATUS_SUCCESS)
2389 TRACE( "%s -> %s\n", wine_dbgstr_longlong(file_id), debugstr_a(unix_name->Buffer) );
2390 unix_name->Length = strlen( unix_name->Buffer );
2394 TRACE( "%s not found in dir %p\n", wine_dbgstr_longlong(file_id), attr->RootDirectory );
2395 RtlFreeHeap( GetProcessHeap(), 0, unix_name->Buffer );
2397 if (needs_close) close( root_fd );
2402 /******************************************************************************
2405 * Helper for nt_to_unix_file_name
2407 static NTSTATUS lookup_unix_name( const WCHAR *name, int name_len, char **buffer, int unix_len, int pos,
2408 UINT disposition, BOOLEAN check_case )
2411 int ret, used_default, len;
2413 char *unix_name = *buffer;
2414 const BOOL redirect = nb_redirects && ntdll_get_thread_data()->wow64_redir;
2416 /* try a shortcut first */
2418 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
2419 NULL, &used_default );
2421 while (name_len && IS_SEPARATOR(*name))
2427 if (ret >= 0 && !used_default) /* if we used the default char the name didn't convert properly */
2430 unix_name[pos + ret] = 0;
2431 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
2432 if (!redirect || (!strstr( unix_name, "/windows/") && strncmp( unix_name, "windows/", 8 )))
2434 if (!stat( unix_name, &st ))
2436 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
2437 if (disposition == FILE_CREATE)
2438 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
2439 return STATUS_SUCCESS;
2444 if (!name_len) /* empty name -> drive root doesn't exist */
2445 return STATUS_OBJECT_PATH_NOT_FOUND;
2446 if (check_case && !redirect && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
2447 return STATUS_OBJECT_NAME_NOT_FOUND;
2449 /* now do it component by component */
2453 const WCHAR *end, *next;
2457 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
2459 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
2460 name_len -= next - name;
2462 /* grow the buffer if needed */
2464 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
2467 unix_len += 2 * MAX_DIR_ENTRY_LEN;
2468 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
2469 return STATUS_NO_MEMORY;
2470 unix_name = *buffer = new_name;
2473 status = find_file_in_dir( unix_name, pos, name, end - name,
2474 check_case, redirect ? &is_win_dir : NULL );
2476 /* if this is the last element, not finding it is not necessarily fatal */
2479 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
2481 status = STATUS_OBJECT_NAME_NOT_FOUND;
2482 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
2484 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2485 MAX_DIR_ENTRY_LEN, NULL, &used_default );
2486 if (ret > 0 && !used_default)
2488 unix_name[pos] = '/';
2489 unix_name[pos + 1 + ret] = 0;
2490 status = STATUS_NO_SUCH_FILE;
2495 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
2497 status = STATUS_OBJECT_NAME_COLLISION;
2501 if (status != STATUS_SUCCESS) break;
2503 pos += strlen( unix_name + pos );
2506 if (is_win_dir && (len = get_redirect_path( unix_name, pos, name, name_len, check_case )))
2510 pos += strlen( unix_name + pos );
2511 TRACE( "redirecting -> %s + %s\n", debugstr_a(unix_name), debugstr_w(name) );
2519 /******************************************************************************
2520 * nt_to_unix_file_name_attr
2522 NTSTATUS nt_to_unix_file_name_attr( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name_ret,
2525 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2526 enum server_fd_type type;
2527 int old_cwd, root_fd, needs_close;
2528 const WCHAR *name, *p;
2530 int name_len, unix_len;
2532 BOOLEAN check_case = !(attr->Attributes & OBJ_CASE_INSENSITIVE);
2534 if (!attr->RootDirectory) /* without root dir fall back to normal lookup */
2535 return wine_nt_to_unix_file_name( attr->ObjectName, unix_name_ret, disposition, check_case );
2537 name = attr->ObjectName->Buffer;
2538 name_len = attr->ObjectName->Length / sizeof(WCHAR);
2540 if (name_len && IS_SEPARATOR(name[0])) return STATUS_INVALID_PARAMETER;
2542 /* check for invalid characters */
2543 for (p = name; p < name + name_len; p++)
2544 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2546 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
2547 unix_len += MAX_DIR_ENTRY_LEN + 3;
2548 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2549 return STATUS_NO_MEMORY;
2552 if (!(status = server_get_unix_fd( attr->RootDirectory, FILE_READ_DATA, &root_fd,
2553 &needs_close, &type, NULL )))
2555 if (type != FD_TYPE_DIR)
2557 if (needs_close) close( root_fd );
2558 status = STATUS_BAD_DEVICE_TYPE;
2562 RtlEnterCriticalSection( &dir_section );
2563 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2565 status = lookup_unix_name( name, name_len, &unix_name, unix_len, 1,
2566 disposition, check_case );
2567 if (fchdir( old_cwd ) == -1) chdir( "/" );
2569 else status = FILE_GetNtStatus();
2570 RtlLeaveCriticalSection( &dir_section );
2571 if (old_cwd != -1) close( old_cwd );
2572 if (needs_close) close( root_fd );
2575 else if (status == STATUS_OBJECT_TYPE_MISMATCH) status = STATUS_BAD_DEVICE_TYPE;
2577 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
2579 TRACE( "%s -> %s\n", debugstr_us(attr->ObjectName), debugstr_a(unix_name) );
2580 unix_name_ret->Buffer = unix_name;
2581 unix_name_ret->Length = strlen(unix_name);
2582 unix_name_ret->MaximumLength = unix_len;
2586 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
2587 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2593 /******************************************************************************
2594 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
2596 * Convert a file name from NT namespace to Unix namespace.
2598 * If disposition is not FILE_OPEN or FILE_OVERWRITE, the last path
2599 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
2600 * returned, but the unix name is still filled in properly.
2602 NTSTATUS CDECL wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
2603 UINT disposition, BOOLEAN check_case )
2605 static const WCHAR unixW[] = {'u','n','i','x'};
2606 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2608 NTSTATUS status = STATUS_SUCCESS;
2609 const char *config_dir = wine_get_config_dir();
2610 const WCHAR *name, *p;
2613 int pos, ret, name_len, unix_len, prefix_len, used_default;
2614 WCHAR prefix[MAX_DIR_ENTRY_LEN];
2615 BOOLEAN is_unix = FALSE;
2617 name = nameW->Buffer;
2618 name_len = nameW->Length / sizeof(WCHAR);
2620 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2622 if (!(pos = get_dos_prefix_len( nameW )))
2623 return STATUS_BAD_DEVICE_TYPE; /* no DOS prefix, assume NT native name */
2628 /* check for sub-directory */
2629 for (pos = 0; pos < name_len; pos++)
2631 if (IS_SEPARATOR(name[pos])) break;
2632 if (name[pos] < 32 || strchrW( invalid_charsW, name[pos] ))
2633 return STATUS_OBJECT_NAME_INVALID;
2635 if (pos > MAX_DIR_ENTRY_LEN)
2636 return STATUS_OBJECT_NAME_INVALID;
2638 if (pos == name_len) /* no subdir, plain DOS device */
2639 return get_dos_device( name, name_len, unix_name_ret );
2641 for (prefix_len = 0; prefix_len < pos; prefix_len++)
2642 prefix[prefix_len] = tolowerW(name[prefix_len]);
2645 name_len -= prefix_len;
2647 /* check for invalid characters (all chars except 0 are valid for unix) */
2648 is_unix = (prefix_len == 4 && !memcmp( prefix, unixW, sizeof(unixW) ));
2651 for (p = name; p < name + name_len; p++)
2652 if (!*p) return STATUS_OBJECT_NAME_INVALID;
2657 for (p = name; p < name + name_len; p++)
2658 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2661 unix_len = ntdll_wcstoumbs( 0, prefix, prefix_len, NULL, 0, NULL, NULL );
2662 unix_len += ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
2663 unix_len += MAX_DIR_ENTRY_LEN + 3;
2664 unix_len += strlen(config_dir) + sizeof("/dosdevices/");
2665 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2666 return STATUS_NO_MEMORY;
2667 strcpy( unix_name, config_dir );
2668 strcat( unix_name, "/dosdevices/" );
2669 pos = strlen(unix_name);
2671 ret = ntdll_wcstoumbs( 0, prefix, prefix_len, unix_name + pos, unix_len - pos - 1,
2672 NULL, &used_default );
2673 if (!ret || used_default)
2675 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2676 return STATUS_OBJECT_NAME_INVALID;
2680 /* check if prefix exists (except for DOS drives to avoid extra stat calls) */
2682 if (prefix_len != 2 || prefix[1] != ':')
2685 if (lstat( unix_name, &st ) == -1 && errno == ENOENT)
2689 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2690 return STATUS_BAD_DEVICE_TYPE;
2692 pos = 0; /* fall back to unix root */
2696 status = lookup_unix_name( name, name_len, &unix_name, unix_len, pos, disposition, check_case );
2697 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
2699 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
2700 unix_name_ret->Buffer = unix_name;
2701 unix_name_ret->Length = strlen(unix_name);
2702 unix_name_ret->MaximumLength = unix_len;
2706 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
2707 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2713 /******************************************************************
2714 * RtlWow64EnableFsRedirection (NTDLL.@)
2716 NTSTATUS WINAPI RtlWow64EnableFsRedirection( BOOLEAN enable )
2718 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
2719 ntdll_get_thread_data()->wow64_redir = enable;
2720 return STATUS_SUCCESS;
2724 /******************************************************************
2725 * RtlWow64EnableFsRedirectionEx (NTDLL.@)
2727 NTSTATUS WINAPI RtlWow64EnableFsRedirectionEx( ULONG disable, ULONG *old_value )
2729 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
2730 *old_value = !ntdll_get_thread_data()->wow64_redir;
2731 ntdll_get_thread_data()->wow64_redir = !disable;
2732 return STATUS_SUCCESS;
2736 /******************************************************************
2737 * RtlDoesFileExists_U (NTDLL.@)
2739 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
2741 UNICODE_STRING nt_name;
2742 FILE_BASIC_INFORMATION basic_info;
2743 OBJECT_ATTRIBUTES attr;
2746 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
2748 attr.Length = sizeof(attr);
2749 attr.RootDirectory = 0;
2750 attr.ObjectName = &nt_name;
2751 attr.Attributes = OBJ_CASE_INSENSITIVE;
2752 attr.SecurityDescriptor = NULL;
2753 attr.SecurityQualityOfService = NULL;
2755 ret = NtQueryAttributesFile(&attr, &basic_info) == STATUS_SUCCESS;
2757 RtlFreeUnicodeString( &nt_name );
2762 /***********************************************************************
2763 * DIR_unmount_device
2765 * Unmount the specified device.
2767 NTSTATUS DIR_unmount_device( HANDLE handle )
2770 int unix_fd, needs_close;
2772 if (!(status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )))
2775 char *mount_point = NULL;
2777 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2778 status = STATUS_INVALID_PARAMETER;
2781 if ((mount_point = get_device_mount_point( st.st_rdev )))
2784 static const char umount[] = "diskutil unmount >/dev/null 2>&1 ";
2786 static const char umount[] = "umount >/dev/null 2>&1 ";
2788 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
2791 strcpy( cmd, umount );
2792 strcat( cmd, mount_point );
2794 RtlFreeHeap( GetProcessHeap(), 0, cmd );
2796 /* umount will fail to release the loop device since we still have
2797 a handle to it, so we release it here */
2798 if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
2801 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
2804 if (needs_close) close( unix_fd );
2810 /******************************************************************************
2813 * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
2814 * Returned value must be freed by caller.
2816 NTSTATUS DIR_get_unix_cwd( char **cwd )
2818 int old_cwd, unix_fd, needs_close;
2823 RtlAcquirePebLock();
2825 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
2826 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
2828 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
2830 if (!(handle = curdir->Handle))
2832 UNICODE_STRING dirW;
2833 OBJECT_ATTRIBUTES attr;
2836 if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
2838 status = STATUS_OBJECT_NAME_INVALID;
2841 attr.Length = sizeof(attr);
2842 attr.RootDirectory = 0;
2843 attr.Attributes = OBJ_CASE_INSENSITIVE;
2844 attr.ObjectName = &dirW;
2845 attr.SecurityDescriptor = NULL;
2846 attr.SecurityQualityOfService = NULL;
2848 status = NtOpenFile( &handle, 0, &attr, &io, 0,
2849 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
2850 RtlFreeUnicodeString( &dirW );
2851 if (status != STATUS_SUCCESS) goto done;
2854 if ((status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )) == STATUS_SUCCESS)
2856 RtlEnterCriticalSection( &dir_section );
2858 if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
2860 unsigned int size = 512;
2864 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2866 status = STATUS_NO_MEMORY;
2869 if (getcwd( *cwd, size )) break;
2870 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
2871 if (errno != ERANGE)
2873 status = STATUS_OBJECT_PATH_INVALID;
2878 if (fchdir( old_cwd ) == -1) chdir( "/" );
2880 else status = FILE_GetNtStatus();
2882 RtlLeaveCriticalSection( &dir_section );
2883 if (old_cwd != -1) close( old_cwd );
2884 if (needs_close) close( unix_fd );
2886 if (!curdir->Handle) NtClose( handle );
2889 RtlReleasePebLock();
2893 struct read_changes_info
2898 PIO_APC_ROUTINE apc;
2902 /* callback for ioctl user APC */
2903 static void WINAPI read_changes_user_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
2905 struct read_changes_info *info = arg;
2906 if (info->apc) info->apc( info->apc_arg, io, reserved );
2907 RtlFreeHeap( GetProcessHeap(), 0, info );
2910 static NTSTATUS read_changes_apc( void *user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
2912 struct read_changes_info *info = user;
2913 char path[PATH_MAX];
2914 NTSTATUS ret = STATUS_SUCCESS;
2917 SERVER_START_REQ( read_change )
2919 req->handle = wine_server_obj_handle( info->FileHandle );
2920 wine_server_set_reply( req, path, PATH_MAX );
2921 ret = wine_server_call( req );
2922 action = reply->action;
2923 len = wine_server_reply_size( reply );
2927 if (ret == STATUS_SUCCESS && info->Buffer &&
2928 (info->BufferSize > (sizeof (FILE_NOTIFY_INFORMATION) + len*sizeof(WCHAR))))
2930 PFILE_NOTIFY_INFORMATION pfni;
2932 pfni = info->Buffer;
2934 /* convert to an NT style path */
2935 for (i=0; i<len; i++)
2939 len = ntdll_umbstowcs( 0, path, len, pfni->FileName,
2940 info->BufferSize - sizeof (*pfni) );
2942 pfni->NextEntryOffset = 0;
2943 pfni->Action = action;
2944 pfni->FileNameLength = len * sizeof (WCHAR);
2945 pfni->FileName[len] = 0;
2946 len = sizeof (*pfni) - sizeof (DWORD) + pfni->FileNameLength;
2950 ret = STATUS_NOTIFY_ENUM_DIR;
2954 iosb->u.Status = ret;
2955 iosb->Information = len;
2956 *apc = read_changes_user_apc;
2960 #define FILE_NOTIFY_ALL ( \
2961 FILE_NOTIFY_CHANGE_FILE_NAME | \
2962 FILE_NOTIFY_CHANGE_DIR_NAME | \
2963 FILE_NOTIFY_CHANGE_ATTRIBUTES | \
2964 FILE_NOTIFY_CHANGE_SIZE | \
2965 FILE_NOTIFY_CHANGE_LAST_WRITE | \
2966 FILE_NOTIFY_CHANGE_LAST_ACCESS | \
2967 FILE_NOTIFY_CHANGE_CREATION | \
2968 FILE_NOTIFY_CHANGE_SECURITY )
2970 /******************************************************************************
2971 * NtNotifyChangeDirectoryFile [NTDLL.@]
2974 NtNotifyChangeDirectoryFile( HANDLE FileHandle, HANDLE Event,
2975 PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext,
2976 PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer,
2977 ULONG BufferSize, ULONG CompletionFilter, BOOLEAN WatchTree )
2979 struct read_changes_info *info;
2981 ULONG_PTR cvalue = ApcRoutine ? 0 : (ULONG_PTR)ApcContext;
2983 TRACE("%p %p %p %p %p %p %u %u %d\n",
2984 FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock,
2985 Buffer, BufferSize, CompletionFilter, WatchTree );
2988 return STATUS_ACCESS_VIOLATION;
2990 if (CompletionFilter == 0 || (CompletionFilter & ~FILE_NOTIFY_ALL))
2991 return STATUS_INVALID_PARAMETER;
2993 info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof *info );
2995 return STATUS_NO_MEMORY;
2997 info->FileHandle = FileHandle;
2998 info->Buffer = Buffer;
2999 info->BufferSize = BufferSize;
3000 info->apc = ApcRoutine;
3001 info->apc_arg = ApcContext;
3003 SERVER_START_REQ( read_directory_changes )
3005 req->filter = CompletionFilter;
3006 req->want_data = (Buffer != NULL);
3007 req->subtree = WatchTree;
3008 req->async.handle = wine_server_obj_handle( FileHandle );
3009 req->async.callback = wine_server_client_ptr( read_changes_apc );
3010 req->async.iosb = wine_server_client_ptr( IoStatusBlock );
3011 req->async.arg = wine_server_client_ptr( info );
3012 req->async.event = wine_server_obj_handle( Event );
3013 req->async.cvalue = cvalue;
3014 status = wine_server_call( req );
3018 if (status != STATUS_PENDING)
3019 RtlFreeHeap( GetProcessHeap(), 0, info );