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;
248 static inline unsigned int max_dir_info_size( FILE_INFORMATION_CLASS class )
250 return dir_info_size( class, MAX_DIR_ENTRY_LEN );
254 /* support for a directory queue for filesystem searches */
262 static struct list dir_queue = LIST_INIT( dir_queue );
264 static NTSTATUS add_dir_to_queue( const char *name )
266 int len = strlen( name ) + 1;
267 struct dir_name *dir = RtlAllocateHeap( GetProcessHeap(), 0,
268 FIELD_OFFSET( struct dir_name, name[len] ));
269 if (!dir) return STATUS_NO_MEMORY;
270 strcpy( dir->name, name );
271 list_add_tail( &dir_queue, &dir->entry );
272 return STATUS_SUCCESS;
275 static NTSTATUS next_dir_in_queue( char *name )
277 struct list *head = list_head( &dir_queue );
280 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
281 strcpy( name, dir->name );
282 list_remove( &dir->entry );
283 RtlFreeHeap( GetProcessHeap(), 0, dir );
284 return STATUS_SUCCESS;
286 return STATUS_OBJECT_NAME_NOT_FOUND;
289 static void flush_dir_queue(void)
293 while ((head = list_head( &dir_queue )))
295 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
296 list_remove( &dir->entry );
297 RtlFreeHeap( GetProcessHeap(), 0, dir );
302 /***********************************************************************
303 * get_default_com_device
305 * Return the default device to use for serial ports.
307 static char *get_default_com_device( int num )
311 if (!num || num > 9) return ret;
313 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
316 strcpy( ret, "/dev/ttyS0" );
317 ret[strlen(ret) - 1] = '0' + num - 1;
319 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
320 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuad0") );
323 strcpy( ret, "/dev/cuad0" );
324 ret[strlen(ret) - 1] = '0' + num - 1;
327 FIXME( "no known default for device com%d\n", num );
333 /***********************************************************************
334 * get_default_lpt_device
336 * Return the default device to use for parallel ports.
338 static char *get_default_lpt_device( int num )
342 if (!num || num > 9) return ret;
344 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
347 strcpy( ret, "/dev/lp0" );
348 ret[strlen(ret) - 1] = '0' + num - 1;
351 FIXME( "no known default for device lpt%d\n", num );
357 /***********************************************************************
358 * DIR_get_drives_info
360 * Retrieve device/inode number for all the drives. Helper for find_drive_root.
362 unsigned int DIR_get_drives_info( struct drive_info info[MAX_DOS_DRIVES] )
364 static struct drive_info cache[MAX_DOS_DRIVES];
365 static time_t last_update;
366 static unsigned int nb_drives;
368 time_t now = time(NULL);
370 RtlEnterCriticalSection( &dir_section );
371 if (now != last_update)
373 const char *config_dir = wine_get_config_dir();
378 if ((buffer = RtlAllocateHeap( GetProcessHeap(), 0,
379 strlen(config_dir) + sizeof("/dosdevices/a:") )))
381 strcpy( buffer, config_dir );
382 strcat( buffer, "/dosdevices/a:" );
383 p = buffer + strlen(buffer) - 2;
385 for (i = nb_drives = 0; i < MAX_DOS_DRIVES; i++)
388 if (!stat( buffer, &st ))
390 cache[i].dev = st.st_dev;
391 cache[i].ino = st.st_ino;
400 RtlFreeHeap( GetProcessHeap(), 0, buffer );
404 memcpy( info, cache, sizeof(cache) );
406 RtlLeaveCriticalSection( &dir_section );
411 /***********************************************************************
412 * parse_mount_entries
414 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
418 #include <sys/vfstab.h>
419 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
425 while (! getvfsent( f, &entry ))
427 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
428 if (!strcmp( entry.vfs_fstype, "nfs" ) ||
429 !strcmp( entry.vfs_fstype, "smbfs" ) ||
430 !strcmp( entry.vfs_fstype, "ncpfs" )) continue;
432 if (stat( entry.vfs_mountp, &st ) == -1) continue;
433 if (st.st_dev != dev || st.st_ino != ino) continue;
434 if (!strcmp( entry.vfs_fstype, "fd" ))
436 if ((device = strstr( entry.vfs_mntopts, "dev=" )))
438 char *p = strchr( device + 4, ',' );
444 return entry.vfs_special;
451 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
453 struct mntent *entry;
457 while ((entry = getmntent( f )))
459 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
460 if (!strcmp( entry->mnt_type, "nfs" ) ||
461 !strcmp( entry->mnt_type, "smbfs" ) ||
462 !strcmp( entry->mnt_type, "ncpfs" )) continue;
464 if (stat( entry->mnt_dir, &st ) == -1) continue;
465 if (st.st_dev != dev || st.st_ino != ino) continue;
466 if (!strcmp( entry->mnt_type, "supermount" ))
468 if ((device = strstr( entry->mnt_opts, "dev=" )))
470 char *p = strchr( device + 4, ',' );
475 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
477 /* if device is a regular file check for a loop mount */
478 if ((device = strstr( entry->mnt_opts, "loop=" )))
480 char *p = strchr( device + 5, ',' );
486 return entry->mnt_fsname;
492 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
494 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
499 while ((entry = getfsent()))
501 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
502 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
503 !strcmp( entry->fs_vfstype, "smbfs" ) ||
504 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
506 if (stat( entry->fs_file, &st ) == -1) continue;
507 if (st.st_dev != dev || st.st_ino != ino) continue;
508 return entry->fs_spec;
515 #include <sys/mnttab.h>
516 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
523 while (( ! getmntent( f, &entry) ))
525 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
526 if (!strcmp( entry.mnt_fstype, "nfs" ) ||
527 !strcmp( entry.mnt_fstype, "smbfs" ) ||
528 !strcmp( entry.mnt_fstype, "ncpfs" )) continue;
530 if (stat( entry.mnt_mountp, &st ) == -1) continue;
531 if (st.st_dev != dev || st.st_ino != ino) continue;
532 if (!strcmp( entry.mnt_fstype, "fd" ))
534 if ((device = strstr( entry.mnt_mntopts, "dev=" )))
536 char *p = strchr( device + 4, ',' );
542 return entry.mnt_special;
548 /***********************************************************************
549 * get_default_drive_device
551 * Return the default device to use for a given drive mount point.
553 static char *get_default_drive_device( const char *root )
563 /* try to open it first to force it to get mounted */
564 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
566 res = fstat( fd, &st );
569 /* now try normal stat just in case */
570 if (res == -1) res = stat( root, &st );
571 if (res == -1) return NULL;
573 RtlEnterCriticalSection( &dir_section );
575 if ((f = fopen( "/etc/mtab", "r" )))
577 device = parse_mount_entries( f, st.st_dev, st.st_ino );
580 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
581 if (!device && (f = fopen( "/etc/fstab", "r" )))
583 device = parse_mount_entries( f, st.st_dev, st.st_ino );
588 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
589 if (ret) strcpy( ret, device );
591 RtlLeaveCriticalSection( &dir_section );
593 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ )
598 /* try to open it first to force it to get mounted */
599 if ((fd = open( root, O_RDONLY )) != -1)
601 res = fstat( fd, &st );
604 /* now try normal stat just in case */
605 if (res == -1) res = stat( root, &st );
606 if (res == -1) return NULL;
608 RtlEnterCriticalSection( &dir_section );
610 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
611 * pass NULL. Leave the argument in for symmetry.
613 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
616 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
617 if (ret) strcpy( ret, device );
619 RtlLeaveCriticalSection( &dir_section );
627 /* try to open it first to force it to get mounted */
628 if ((fd = open( root, O_RDONLY )) != -1)
630 res = fstat( fd, &st );
633 /* now try normal stat just in case */
634 if (res == -1) res = stat( root, &st );
635 if (res == -1) return NULL;
637 RtlEnterCriticalSection( &dir_section );
639 if ((f = fopen( "/etc/mnttab", "r" )))
641 device = parse_mount_entries( f, st.st_dev, st.st_ino);
644 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
645 if (!device && (f = fopen( "/etc/vfstab", "r" )))
647 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
652 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
653 if (ret) strcpy( ret, device );
655 RtlLeaveCriticalSection( &dir_section );
657 #elif defined(__APPLE__)
658 struct statfs *mntStat;
664 static const char path_bsd_device[] = "/dev/disk";
667 res = stat( root, &st );
668 if (res == -1) return NULL;
673 RtlEnterCriticalSection( &dir_section );
675 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
677 for (i = 0; i < mntSize && !ret; i++)
679 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
680 if (st.st_dev != dev || st.st_ino != ino) continue;
682 /* FIXME add support for mounted network drive */
683 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
685 /* set return value to the corresponding raw BSD node */
686 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
689 strcpy(ret, "/dev/r");
690 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
694 RtlLeaveCriticalSection( &dir_section );
697 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
703 /***********************************************************************
704 * get_device_mount_point
706 * Return the current mount point for a device.
708 static char *get_device_mount_point( dev_t dev )
715 RtlEnterCriticalSection( &dir_section );
717 if ((f = fopen( "/etc/mtab", "r" )))
719 struct mntent *entry;
723 while ((entry = getmntent( f )))
725 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
726 if (!strcmp( entry->mnt_type, "nfs" ) ||
727 !strcmp( entry->mnt_type, "smbfs" ) ||
728 !strcmp( entry->mnt_type, "ncpfs" )) continue;
730 if (!strcmp( entry->mnt_type, "supermount" ))
732 if ((device = strstr( entry->mnt_opts, "dev=" )))
735 if ((p = strchr( device, ',' ))) *p = 0;
738 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
740 /* if device is a regular file check for a loop mount */
741 if ((device = strstr( entry->mnt_opts, "loop=" )))
744 if ((p = strchr( device, ',' ))) *p = 0;
747 else device = entry->mnt_fsname;
749 if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
751 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
752 if (ret) strcpy( ret, entry->mnt_dir );
758 RtlLeaveCriticalSection( &dir_section );
759 #elif defined(__APPLE__)
760 struct statfs *entry;
764 RtlEnterCriticalSection( &dir_section );
766 size = getmntinfo( &entry, MNT_NOWAIT );
767 for (i = 0; i < size; i++)
769 if (stat( entry[i].f_mntfromname, &st ) == -1) continue;
770 if (S_ISBLK(st.st_mode) && st.st_rdev == dev)
772 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry[i].f_mntfromname) + 1 );
773 if (ret) strcpy( ret, entry[i].f_mntfromname );
777 RtlLeaveCriticalSection( &dir_section );
780 if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
786 /***********************************************************************
789 * Initialize the show_dot_files options.
791 static void init_options(void)
793 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
794 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
798 OBJECT_ATTRIBUTES attr;
799 UNICODE_STRING nameW;
803 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
804 attr.Length = sizeof(attr);
805 attr.RootDirectory = root;
806 attr.ObjectName = &nameW;
808 attr.SecurityDescriptor = NULL;
809 attr.SecurityQualityOfService = NULL;
810 RtlInitUnicodeString( &nameW, WineW );
812 /* @@ Wine registry key: HKCU\Software\Wine */
813 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
815 RtlInitUnicodeString( &nameW, ShowDotFilesW );
816 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
818 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
819 show_dot_files = IS_OPTION_TRUE( str[0] );
825 /* a couple of directories that we don't want to return in directory searches */
826 ignore_file( wine_get_config_dir() );
827 ignore_file( "/dev" );
828 ignore_file( "/proc" );
830 ignore_file( "/sys" );
835 /***********************************************************************
838 * Check if the specified file should be hidden based on its name and the show dot files option.
840 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
844 if (show_dot_files == -1) init_options();
845 if (show_dot_files) return FALSE;
847 end = p = name->Buffer + name->Length/sizeof(WCHAR);
848 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
849 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
850 if (p == end || *p != '.') return FALSE;
851 /* make sure it isn't '.' or '..' */
852 if (p + 1 == end) return FALSE;
853 if (p[1] == '.' && p + 2 == end) return FALSE;
858 /***********************************************************************
859 * hash_short_file_name
861 * Transform a Unix file name into a hashed DOS name. If the name is a valid
862 * DOS name, it is converted to upper-case; otherwise it is replaced by a
863 * hashed version that fits in 8.3 format.
864 * 'buffer' must be at least 12 characters long.
865 * Returns length of short name in bytes; short name is NOT null-terminated.
867 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
869 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
871 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
876 /* Compute the hash code of the file name */
877 /* If you know something about hash functions, feel free to */
878 /* insert a better algorithm here... */
879 if (!is_case_sensitive)
881 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
882 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
883 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
887 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
888 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
889 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
892 /* Find last dot for start of the extension */
893 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
895 /* Copy first 4 chars, replacing invalid chars with '_' */
896 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
898 if (p == end || p == ext) break;
899 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
901 /* Pad to 5 chars with '~' */
902 while (i-- >= 0) *dst++ = '~';
904 /* Insert hash code converted to 3 ASCII chars */
905 *dst++ = hash_chars[(hash >> 10) & 0x1f];
906 *dst++ = hash_chars[(hash >> 5) & 0x1f];
907 *dst++ = hash_chars[hash & 0x1f];
909 /* Copy the first 3 chars of the extension (if any) */
913 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
914 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
920 /***********************************************************************
923 * Check a long file name against a mask.
925 * Tests (done in W95 DOS shell - case insensitive):
926 * *.txt test1.test.txt *
928 * *.t??????.t* test1.ta.tornado.txt *
929 * *tornado* test1.ta.tornado.txt *
930 * t*t test1.ta.tornado.txt *
932 * ?est??? test1.txt -
933 * *test1.txt* test1.txt *
934 * h?l?o*t.dat hellothisisatest.dat *
936 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
939 const WCHAR *name = name_str->Buffer;
940 const WCHAR *mask = mask_str->Buffer;
941 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
942 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
943 const WCHAR *lastjoker = NULL;
944 const WCHAR *next_to_retry = NULL;
946 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
948 while (name < name_end && mask < mask_end)
954 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
955 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
958 /* skip to the next match after the joker(s) */
959 if (is_case_sensitive)
960 while (name < name_end && (*name != *mask)) name++;
962 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
963 next_to_retry = name;
970 if (is_case_sensitive) mismatch = (*mask != *name);
971 else mismatch = (toupperW(*mask) != toupperW(*name));
977 if (mask == mask_end)
979 if (name == name_end) return TRUE;
980 if (lastjoker) mask = lastjoker;
983 else /* mismatch ! */
985 if (lastjoker) /* we had an '*', so we can try unlimitedly */
989 /* this scan sequence was a mismatch, so restart
990 * 1 char after the first char we checked last time */
992 name = next_to_retry;
994 else return FALSE; /* bad luck */
999 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
1000 mask++; /* Ignore trailing '.' or '*' in mask */
1001 return (name == name_end && mask == mask_end);
1005 /***********************************************************************
1008 * helper for NtQueryDirectoryFile
1010 static union file_directory_info *append_entry( void *info_ptr, IO_STATUS_BLOCK *io, ULONG max_length,
1011 const char *long_name, const char *short_name,
1012 const UNICODE_STRING *mask, FILE_INFORMATION_CLASS class )
1014 union file_directory_info *info;
1015 int i, long_len, short_len, total_len;
1017 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
1018 WCHAR short_nameW[12];
1021 ULONG attributes = 0;
1023 io->u.Status = STATUS_SUCCESS;
1024 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
1025 if (long_len == -1) return NULL;
1027 str.Buffer = long_nameW;
1028 str.Length = long_len * sizeof(WCHAR);
1029 str.MaximumLength = sizeof(long_nameW);
1033 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
1034 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
1035 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
1037 else /* generate a short name if necessary */
1042 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1043 short_len = hash_short_file_name( &str, short_nameW );
1046 TRACE( "long %s short %s mask %s\n",
1047 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
1049 if (mask && !match_filename( &str, mask ))
1051 if (!short_len) return NULL; /* no short name to match */
1052 str.Buffer = short_nameW;
1053 str.Length = short_len * sizeof(WCHAR);
1054 str.MaximumLength = sizeof(short_nameW);
1055 if (!match_filename( &str, mask )) return NULL;
1058 if (lstat( long_name, &st ) == -1) return NULL;
1059 if (S_ISLNK( st.st_mode ))
1061 if (stat( long_name, &st ) == -1) return NULL;
1062 if (S_ISDIR( st.st_mode )) attributes |= FILE_ATTRIBUTE_REPARSE_POINT;
1064 if (is_ignored_file( &st ))
1066 TRACE( "ignoring file %s\n", long_name );
1069 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
1070 attributes |= FILE_ATTRIBUTE_HIDDEN;
1072 total_len = dir_info_size( class, long_len );
1073 if (io->Information + total_len > max_length)
1075 total_len = max_length - io->Information;
1076 io->u.Status = STATUS_BUFFER_OVERFLOW;
1078 info = (union file_directory_info *)((char *)info_ptr + io->Information);
1079 if (st.st_dev != curdir.dev) st.st_ino = 0; /* ignore inode if on a different device */
1080 /* all the structures start with a FileDirectoryInformation layout */
1081 fill_stat_info( &st, info, class );
1082 info->dir.NextEntryOffset = total_len;
1083 info->dir.FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
1084 info->dir.FileAttributes |= attributes;
1088 case FileDirectoryInformation:
1089 info->dir.FileNameLength = long_len * sizeof(WCHAR);
1090 filename = info->dir.FileName;
1093 case FileFullDirectoryInformation:
1094 info->full.EaSize = 0; /* FIXME */
1095 info->full.FileNameLength = long_len * sizeof(WCHAR);
1096 filename = info->full.FileName;
1099 case FileIdFullDirectoryInformation:
1100 info->id_full.EaSize = 0; /* FIXME */
1101 info->id_full.FileNameLength = long_len * sizeof(WCHAR);
1102 filename = info->id_full.FileName;
1105 case FileBothDirectoryInformation:
1106 info->both.EaSize = 0; /* FIXME */
1107 info->both.ShortNameLength = short_len * sizeof(WCHAR);
1108 for (i = 0; i < short_len; i++) info->both.ShortName[i] = toupperW(short_nameW[i]);
1109 info->both.FileNameLength = long_len * sizeof(WCHAR);
1110 filename = info->both.FileName;
1113 case FileIdBothDirectoryInformation:
1114 info->id_both.EaSize = 0; /* FIXME */
1115 info->id_both.ShortNameLength = short_len * sizeof(WCHAR);
1116 for (i = 0; i < short_len; i++) info->id_both.ShortName[i] = toupperW(short_nameW[i]);
1117 info->id_both.FileNameLength = long_len * sizeof(WCHAR);
1118 filename = info->id_both.FileName;
1125 memcpy( filename, long_nameW, total_len - ((char *)filename - (char *)info) );
1126 io->Information += total_len;
1131 #ifdef VFAT_IOCTL_READDIR_BOTH
1133 /***********************************************************************
1136 * Wrapper for the VFAT ioctl to work around various kernel bugs.
1137 * dir_section must be held by caller.
1139 static KERNEL_DIRENT *start_vfat_ioctl( int fd )
1141 static KERNEL_DIRENT *de;
1146 const size_t page_size = getpagesize();
1147 SIZE_T size = 2 * sizeof(*de) + page_size;
1150 if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_RESERVE, PAGE_READWRITE ))
1152 /* commit only the size needed for the dir entries */
1153 /* this leaves an extra unaccessible page, which should make the kernel */
1154 /* fail with -EFAULT before it stomps all over our memory */
1156 size = 2 * sizeof(*de);
1157 NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_COMMIT, PAGE_READWRITE );
1160 /* set d_reclen to 65535 to work around an AFS kernel bug */
1161 de[0].d_reclen = 65535;
1162 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
1165 if (errno != ENOENT) return NULL; /* VFAT ioctl probably not supported */
1166 de[0].d_reclen = 0; /* eof */
1168 else if (!res && de[0].d_reclen == 65535) return NULL; /* AFS bug */
1174 /***********************************************************************
1175 * read_directory_vfat
1177 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
1179 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1180 BOOLEAN single_entry, const UNICODE_STRING *mask,
1181 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1186 union file_directory_info *info, *last_info = NULL;
1188 io->u.Status = STATUS_SUCCESS;
1190 if (restart_scan) lseek( fd, 0, SEEK_SET );
1192 if (length < max_dir_info_size(class)) /* we may have to return a partial entry here */
1194 off_t old_pos = lseek( fd, 0, SEEK_CUR );
1196 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1198 while (de[0].d_reclen)
1200 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1201 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1202 de[0].d_name[len] = 0;
1203 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1204 de[1].d_name[len] = 0;
1206 if (de[1].d_name[0])
1207 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1209 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1213 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1214 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1217 old_pos = lseek( fd, 0, SEEK_CUR );
1218 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1221 else /* we'll only return full entries, no need to worry about overflow */
1223 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1225 while (de[0].d_reclen)
1227 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1228 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1229 de[0].d_name[len] = 0;
1230 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1231 de[1].d_name[len] = 0;
1233 if (de[1].d_name[0])
1234 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1236 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1240 if (single_entry) break;
1241 /* check if we still have enough space for the largest possible entry */
1242 if (io->Information + max_dir_info_size(class) > length) break;
1244 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1248 if (last_info) last_info->next = 0;
1249 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1252 #endif /* VFAT_IOCTL_READDIR_BOTH */
1255 /***********************************************************************
1256 * read_directory_getdents
1258 * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
1261 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1262 BOOLEAN single_entry, const UNICODE_STRING *mask,
1263 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1266 size_t size = length;
1267 int res, fake_dot_dot = 1;
1268 char *data, local_buffer[8192];
1269 KERNEL_DIRENT64 *de;
1270 union file_directory_info *info, *last_info = NULL;
1272 if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1274 size = sizeof(local_buffer);
1275 data = local_buffer;
1278 if (restart_scan) lseek( fd, 0, SEEK_SET );
1279 else if (length < max_dir_info_size(class)) /* we may have to return a partial entry here */
1281 old_pos = lseek( fd, 0, SEEK_CUR );
1282 if (old_pos == -1 && errno == ENOENT)
1284 io->u.Status = STATUS_NO_MORE_FILES;
1290 io->u.Status = STATUS_SUCCESS;
1292 res = getdents64( fd, data, size );
1295 if (errno != ENOSYS)
1297 io->u.Status = FILE_GetNtStatus();
1303 de = (KERNEL_DIRENT64 *)data;
1307 /* check if we got . and .. from getdents */
1310 if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1312 KERNEL_DIRENT64 *next_de = (KERNEL_DIRENT64 *)(data + de->d_reclen);
1313 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1316 /* make sure we have enough room for both entries */
1319 const ULONG min_info_size = dir_info_size( class, 1 ) + dir_info_size( class, 2 );
1320 if (length < min_info_size || single_entry)
1322 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1329 if ((info = append_entry( buffer, io, length, ".", NULL, mask, class )))
1331 if ((info = append_entry( buffer, io, length, "..", NULL, mask, class )))
1334 /* check if we still have enough space for the largest possible entry */
1335 if (last_info && io->Information + max_dir_info_size(class) > length)
1337 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1345 res -= de->d_reclen;
1347 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1348 (info = append_entry( buffer, io, length, de->d_name, NULL, mask, class )))
1351 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1353 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1356 /* check if we still have enough space for the largest possible entry */
1357 if (single_entry || io->Information + max_dir_info_size(class) > length)
1359 if (res > 0) lseek( fd, de->d_off, SEEK_SET ); /* set pos to next entry */
1363 old_pos = de->d_off;
1364 /* move on to the next entry */
1365 if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1368 res = getdents64( fd, data, size );
1369 de = (KERNEL_DIRENT64 *)data;
1373 if (last_info) last_info->next = 0;
1374 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1377 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1381 #elif defined HAVE_GETDIRENTRIES
1383 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1385 /* Darwin doesn't provide a version of getdirentries with support for 64-bit
1386 * inodes. When 64-bit inodes are enabled, the getdirentries symbol is mapped
1387 * to _getdirentries_is_not_available_when_64_bit_inodes_are_in_effect so that
1388 * we get link errors if we try to use it. We still need getdirentries, but we
1389 * don't need it to support 64-bit inodes. So, we use the legacy getdirentries
1390 * with 32-bit inodes. We have to be careful to use a corresponding dirent
1393 int darwin_legacy_getdirentries(int, char *, int, long *) __asm("_getdirentries");
1394 #define getdirentries darwin_legacy_getdirentries
1396 struct darwin_legacy_dirent {
1398 __uint16_t d_reclen;
1401 char d_name[__DARWIN_MAXNAMLEN + 1];
1403 #define dirent darwin_legacy_dirent
1407 /***********************************************************************
1408 * wine_getdirentries
1410 * Wrapper for the BSD getdirentries system call to fix a bug in the
1411 * Mac OS X version. For some file systems (at least Apple Filing
1412 * Protocol a.k.a. AFP), getdirentries resets the file position to 0
1413 * when it's about to return 0 (no more entries). So, a subsequent
1414 * getdirentries call starts over at the beginning again, causing an
1417 static inline int wine_getdirentries(int fd, char *buf, int nbytes, long *basep)
1419 int res = getdirentries(fd, buf, nbytes, basep);
1422 lseek(fd, *basep, SEEK_SET);
1427 /***********************************************************************
1428 * read_directory_getdirentries
1430 * Read a directory using the BSD getdirentries system call; helper for NtQueryDirectoryFile.
1432 static int read_directory_getdirentries( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1433 BOOLEAN single_entry, const UNICODE_STRING *mask,
1434 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1437 ULONG_PTR restart_info_pos = 0;
1438 size_t size, initial_size = length;
1439 int res, fake_dot_dot = 1;
1440 char *data, local_buffer[8192];
1442 union file_directory_info *info, *last_info = NULL, *restart_last_info = NULL;
1444 size = initial_size;
1445 data = local_buffer;
1446 if (size > sizeof(local_buffer) && !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1448 io->u.Status = STATUS_NO_MEMORY;
1449 return io->u.Status;
1452 if (restart_scan) lseek( fd, 0, SEEK_SET );
1454 io->u.Status = STATUS_SUCCESS;
1456 /* FIXME: should make sure size is larger than filesystem block size */
1457 res = wine_getdirentries( fd, data, size, &restart_pos );
1460 io->u.Status = FILE_GetNtStatus();
1465 de = (struct dirent *)data;
1469 /* check if we got . and .. from getdirentries */
1472 if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1474 struct dirent *next_de = (struct dirent *)(data + de->d_reclen);
1475 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1478 /* make sure we have enough room for both entries */
1481 const ULONG min_info_size = dir_info_size( class, 1 ) + dir_info_size( class, 2 );
1482 if (length < min_info_size || single_entry)
1484 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1491 if ((info = append_entry( buffer, io, length, ".", NULL, mask, class )))
1493 if ((info = append_entry( buffer, io, length, "..", NULL, mask, class )))
1496 restart_last_info = last_info;
1497 restart_info_pos = io->Information;
1499 /* check if we still have enough space for the largest possible entry */
1500 if (last_info && io->Information + max_dir_info_size(class) > length)
1502 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1510 res -= de->d_reclen;
1512 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1513 ((info = append_entry( buffer, io, length, de->d_name, NULL, mask, class ))))
1516 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1518 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1519 if (restart_info_pos) /* if we have a complete read already, return it */
1521 io->u.Status = STATUS_SUCCESS;
1522 io->Information = restart_info_pos;
1523 last_info = restart_last_info;
1526 /* otherwise restart from the start with a smaller size */
1527 size = (char *)de - data;
1529 io->Information = 0;
1533 /* if we have to return but the buffer contains more data, restart with a smaller size */
1534 if (res > 0 && (single_entry || io->Information + max_dir_info_size(class) > length))
1536 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1537 size = (char *)de - data;
1538 io->Information = restart_info_pos;
1539 last_info = restart_last_info;
1543 /* move on to the next entry */
1546 de = (struct dirent *)((char *)de + de->d_reclen);
1549 if (size < initial_size) break; /* already restarted once, give up now */
1550 size = min( size, length - io->Information );
1551 /* if size is too small don't bother to continue */
1552 if (size < max_dir_info_size(class) && last_info) break;
1553 restart_last_info = last_info;
1554 restart_info_pos = io->Information;
1556 res = wine_getdirentries( fd, data, size, &restart_pos );
1557 de = (struct dirent *)data;
1560 if (last_info) last_info->next = 0;
1561 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1564 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1568 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1569 #undef getdirentries
1573 #endif /* HAVE_GETDIRENTRIES */
1576 /***********************************************************************
1577 * read_directory_readdir
1579 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1581 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1582 BOOLEAN single_entry, const UNICODE_STRING *mask,
1583 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1586 off_t i, old_pos = 0;
1588 union file_directory_info *info, *last_info = NULL;
1590 if (!(dir = opendir( "." )))
1592 io->u.Status = FILE_GetNtStatus();
1598 old_pos = lseek( fd, 0, SEEK_CUR );
1599 /* skip the right number of entries */
1600 for (i = 0; i < old_pos - 2; i++)
1602 if (!readdir( dir ))
1605 io->u.Status = STATUS_NO_MORE_FILES;
1610 io->u.Status = STATUS_SUCCESS;
1615 info = append_entry( buffer, io, length, ".", NULL, mask, class );
1616 else if (old_pos == 1)
1617 info = append_entry( buffer, io, length, "..", NULL, mask, class );
1618 else if ((de = readdir( dir )))
1620 if (strcmp( de->d_name, "." ) && strcmp( de->d_name, ".." ))
1621 info = append_entry( buffer, io, length, de->d_name, NULL, mask, class );
1631 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1633 old_pos--; /* restore pos to previous entry */
1636 if (single_entry) break;
1637 /* check if we still have enough space for the largest possible entry */
1638 if (io->Information + max_dir_info_size(class) > length) break;
1642 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
1645 if (last_info) last_info->next = 0;
1646 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1649 /***********************************************************************
1650 * read_directory_stat
1652 * Read a single file from a directory by determining whether the file
1653 * identified by mask exists using stat.
1655 static int read_directory_stat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1656 BOOLEAN single_entry, const UNICODE_STRING *mask,
1657 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1659 int unix_len, ret, used_default;
1663 TRACE("trying optimisation for file %s\n", debugstr_us( mask ));
1665 unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
1666 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
1668 io->u.Status = STATUS_NO_MEMORY;
1671 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
1672 NULL, &used_default );
1673 if (ret > 0 && !used_default)
1678 lseek( fd, 0, SEEK_SET );
1680 else if (lseek( fd, 0, SEEK_CUR ) != 0)
1682 io->u.Status = STATUS_NO_MORE_FILES;
1687 ret = stat( unix_name, &st );
1690 union file_directory_info *info = append_entry( buffer, io, length, unix_name, NULL, NULL, class );
1694 if (io->u.Status != STATUS_BUFFER_OVERFLOW) lseek( fd, 1, SEEK_CUR );
1696 else io->u.Status = STATUS_NO_MORE_FILES;
1702 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1704 TRACE("returning %d\n", ret);
1710 static inline WCHAR *mempbrkW( const WCHAR *ptr, const WCHAR *accept, size_t n )
1713 for (end = ptr + n; ptr < end; ptr++) if (strchrW( accept, *ptr )) return (WCHAR *)ptr;
1717 /******************************************************************************
1718 * NtQueryDirectoryFile [NTDLL.@]
1719 * ZwQueryDirectoryFile [NTDLL.@]
1721 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
1722 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
1723 PIO_STATUS_BLOCK io,
1724 PVOID buffer, ULONG length,
1725 FILE_INFORMATION_CLASS info_class,
1726 BOOLEAN single_entry,
1727 PUNICODE_STRING mask,
1728 BOOLEAN restart_scan )
1730 int cwd, fd, needs_close;
1731 static const WCHAR wszWildcards[] = { '*','?',0 };
1733 TRACE("(%p %p %p %p %p %p 0x%08x 0x%08x 0x%08x %s 0x%08x\n",
1734 handle, event, apc_routine, apc_context, io, buffer,
1735 length, info_class, single_entry, debugstr_us(mask),
1738 if (event || apc_routine)
1740 FIXME( "Unsupported yet option\n" );
1741 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1745 case FileDirectoryInformation:
1746 case FileBothDirectoryInformation:
1747 case FileFullDirectoryInformation:
1748 case FileIdBothDirectoryInformation:
1749 case FileIdFullDirectoryInformation:
1750 if (length < dir_info_size( info_class, 1 )) return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
1753 FIXME( "Unsupported file info class %d\n", info_class );
1754 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1757 if ((io->u.Status = server_get_unix_fd( handle, FILE_LIST_DIRECTORY, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
1758 return io->u.Status;
1760 io->Information = 0;
1762 RtlEnterCriticalSection( &dir_section );
1764 if (show_dot_files == -1) init_options();
1766 cwd = open( ".", O_RDONLY );
1767 if (fchdir( fd ) != -1)
1771 curdir.dev = st.st_dev;
1772 curdir.ino = st.st_ino;
1773 #ifdef VFAT_IOCTL_READDIR_BOTH
1774 if ((read_directory_vfat( fd, io, buffer, length, single_entry,
1775 mask, restart_scan, info_class )) != -1) goto done;
1777 if (mask && !mempbrkW( mask->Buffer, wszWildcards, mask->Length / sizeof(WCHAR) ) &&
1778 read_directory_stat( fd, io, buffer, length, single_entry,
1779 mask, restart_scan, info_class ) != -1) goto done;
1781 if ((read_directory_getdents( fd, io, buffer, length, single_entry,
1782 mask, restart_scan, info_class )) != -1) goto done;
1783 #elif defined HAVE_GETDIRENTRIES
1784 if ((read_directory_getdirentries( fd, io, buffer, length, single_entry,
1785 mask, restart_scan, info_class )) != -1) goto done;
1787 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan, info_class );
1790 if (cwd == -1 || fchdir( cwd ) == -1) chdir( "/" );
1792 else io->u.Status = FILE_GetNtStatus();
1794 RtlLeaveCriticalSection( &dir_section );
1796 if (needs_close) close( fd );
1797 if (cwd != -1) close( cwd );
1798 TRACE( "=> %x (%ld)\n", io->u.Status, io->Information );
1799 return io->u.Status;
1803 /***********************************************************************
1806 * Find a file in a directory the hard way, by doing a case-insensitive search.
1807 * The file found is appended to unix_name at pos.
1808 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
1810 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
1811 int check_case, int *is_win_dir )
1813 WCHAR buffer[MAX_DIR_ENTRY_LEN];
1819 int ret, used_default, is_name_8_dot_3;
1821 /* try a shortcut for this directory */
1823 unix_name[pos++] = '/';
1824 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
1825 NULL, &used_default );
1826 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
1827 /* so it cannot match the file we are looking for */
1828 if (ret >= 0 && !used_default)
1830 unix_name[pos + ret] = 0;
1831 if (!stat( unix_name, &st ))
1833 if (is_win_dir) *is_win_dir = is_same_file( &windir, &st );
1834 return STATUS_SUCCESS;
1837 if (check_case) goto not_found; /* we want an exact match */
1839 if (pos > 1) unix_name[pos - 1] = 0;
1840 else unix_name[1] = 0; /* keep the initial slash */
1842 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
1844 str.Buffer = (WCHAR *)name;
1845 str.Length = length * sizeof(WCHAR);
1846 str.MaximumLength = str.Length;
1847 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
1849 /* now look for it through the directory */
1851 #ifdef VFAT_IOCTL_READDIR_BOTH
1852 if (is_name_8_dot_3)
1854 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
1859 RtlEnterCriticalSection( &dir_section );
1860 if ((de = start_vfat_ioctl( fd )))
1862 unix_name[pos - 1] = '/';
1863 while (de[0].d_reclen)
1865 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1866 size_t len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1867 de[0].d_name[len] = 0;
1868 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1869 de[1].d_name[len] = 0;
1871 if (de[1].d_name[0])
1873 ret = ntdll_umbstowcs( 0, de[1].d_name, strlen(de[1].d_name),
1874 buffer, MAX_DIR_ENTRY_LEN );
1875 if (ret == length && !memicmpW( buffer, name, length))
1877 strcpy( unix_name + pos, de[1].d_name );
1878 RtlLeaveCriticalSection( &dir_section );
1883 ret = ntdll_umbstowcs( 0, de[0].d_name, strlen(de[0].d_name),
1884 buffer, MAX_DIR_ENTRY_LEN );
1885 if (ret == length && !memicmpW( buffer, name, length))
1887 strcpy( unix_name + pos,
1888 de[1].d_name[0] ? de[1].d_name : de[0].d_name );
1889 RtlLeaveCriticalSection( &dir_section );
1893 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1)
1895 RtlLeaveCriticalSection( &dir_section );
1901 RtlLeaveCriticalSection( &dir_section );
1904 /* fall through to normal handling */
1906 #endif /* VFAT_IOCTL_READDIR_BOTH */
1908 if (!(dir = opendir( unix_name )))
1910 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
1911 else return FILE_GetNtStatus();
1913 unix_name[pos - 1] = '/';
1914 str.Buffer = buffer;
1915 str.MaximumLength = sizeof(buffer);
1916 while ((de = readdir( dir )))
1918 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
1919 if (ret == length && !memicmpW( buffer, name, length ))
1921 strcpy( unix_name + pos, de->d_name );
1926 if (!is_name_8_dot_3) continue;
1928 str.Length = ret * sizeof(WCHAR);
1929 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1931 WCHAR short_nameW[12];
1932 ret = hash_short_file_name( &str, short_nameW );
1933 if (ret == length && !memicmpW( short_nameW, name, length ))
1935 strcpy( unix_name + pos, de->d_name );
1942 goto not_found; /* avoid warning */
1945 unix_name[pos - 1] = 0;
1946 return STATUS_OBJECT_PATH_NOT_FOUND;
1949 if (is_win_dir && !stat( unix_name, &st )) *is_win_dir = is_same_file( &windir, &st );
1950 return STATUS_SUCCESS;
1956 static const WCHAR catrootW[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t',0};
1957 static const WCHAR catroot2W[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t','2',0};
1958 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};
1959 static const WCHAR driversetcW[] = {'s','y','s','t','e','m','3','2','\\','d','r','i','v','e','r','s','\\','e','t','c',0};
1960 static const WCHAR logfilesW[] = {'s','y','s','t','e','m','3','2','\\','l','o','g','f','i','l','e','s',0};
1961 static const WCHAR spoolW[] = {'s','y','s','t','e','m','3','2','\\','s','p','o','o','l',0};
1962 static const WCHAR system32W[] = {'s','y','s','t','e','m','3','2',0};
1963 static const WCHAR syswow64W[] = {'s','y','s','w','o','w','6','4',0};
1964 static const WCHAR sysnativeW[] = {'s','y','s','n','a','t','i','v','e',0};
1965 static const WCHAR regeditW[] = {'r','e','g','e','d','i','t','.','e','x','e',0};
1966 static const WCHAR wow_regeditW[] = {'s','y','s','w','o','w','6','4','\\','r','e','g','e','d','i','t','.','e','x','e',0};
1970 const WCHAR *source;
1971 const WCHAR *dos_target;
1972 const char *unix_target;
1975 { catrootW, NULL, NULL },
1976 { catroot2W, NULL, NULL },
1977 { driversstoreW, NULL, NULL },
1978 { driversetcW, NULL, NULL },
1979 { logfilesW, NULL, NULL },
1980 { spoolW, NULL, NULL },
1981 { system32W, syswow64W, NULL },
1982 { sysnativeW, system32W, NULL },
1983 { regeditW, wow_regeditW, NULL }
1986 static unsigned int nb_redirects;
1989 /***********************************************************************
1990 * get_redirect_target
1992 * Find the target unix name for a redirected dir.
1994 static const char *get_redirect_target( const char *windows_dir, const WCHAR *name )
1996 int used_default, len, pos, win_len = strlen( windows_dir );
1997 char *unix_name, *unix_target = NULL;
2000 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, win_len + MAX_DIR_ENTRY_LEN + 2 )))
2002 memcpy( unix_name, windows_dir, win_len );
2007 const WCHAR *end, *next;
2009 for (end = name; *end; end++) if (IS_SEPARATOR(*end)) break;
2010 for (next = end; *next; next++) if (!IS_SEPARATOR(*next)) break;
2012 status = find_file_in_dir( unix_name, pos, name, end - name, FALSE, NULL );
2013 if (status == STATUS_OBJECT_PATH_NOT_FOUND && !*next) /* not finding last element is ok */
2015 len = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2016 MAX_DIR_ENTRY_LEN - (pos - win_len), NULL, &used_default );
2017 if (len > 0 && !used_default)
2019 unix_name[pos] = '/';
2025 if (status) goto done;
2026 pos += strlen( unix_name + pos );
2030 if ((unix_target = RtlAllocateHeap( GetProcessHeap(), 0, pos - win_len )))
2031 memcpy( unix_target, unix_name + win_len + 1, pos - win_len );
2034 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2039 /***********************************************************************
2042 static void init_redirects(void)
2044 UNICODE_STRING nt_name;
2045 ANSI_STRING unix_name;
2050 if (!RtlDosPathNameToNtPathName_U( windows_dir.Buffer, &nt_name, NULL, NULL ))
2052 ERR( "can't convert %s\n", debugstr_us(&windows_dir) );
2055 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
2056 RtlFreeUnicodeString( &nt_name );
2059 ERR( "cannot open %s (%x)\n", debugstr_us(&windows_dir), status );
2062 if (!stat( unix_name.Buffer, &st ))
2064 windir.dev = st.st_dev;
2065 windir.ino = st.st_ino;
2066 nb_redirects = sizeof(redirects) / sizeof(redirects[0]);
2067 for (i = 0; i < nb_redirects; i++)
2069 if (!redirects[i].dos_target) continue;
2070 redirects[i].unix_target = get_redirect_target( unix_name.Buffer, redirects[i].dos_target );
2071 TRACE( "%s -> %s\n", debugstr_w(redirects[i].source), redirects[i].unix_target );
2074 RtlFreeAnsiString( &unix_name );
2079 /***********************************************************************
2082 * Check if path matches a redirect name. If yes, return matched length.
2084 static int match_redirect( const WCHAR *path, int len, const WCHAR *redir, int check_case )
2088 while (i < len && *redir)
2090 if (IS_SEPARATOR(path[i]))
2092 if (*redir++ != '\\') return 0;
2093 while (i < len && IS_SEPARATOR(path[i])) i++;
2094 continue; /* move on to next path component */
2096 else if (check_case)
2098 if (path[i] != *redir) return 0;
2102 if (tolowerW(path[i]) != tolowerW(*redir)) return 0;
2107 if (*redir) return 0;
2108 if (i < len && !IS_SEPARATOR(path[i])) return 0;
2109 while (i < len && IS_SEPARATOR(path[i])) i++;
2114 /***********************************************************************
2117 * Retrieve the Unix path corresponding to a redirected path if any.
2119 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, int check_case )
2124 for (i = 0; i < nb_redirects; i++)
2126 if ((len = match_redirect( name, length, redirects[i].source, check_case )))
2128 if (!redirects[i].unix_target) break;
2129 unix_name[pos++] = '/';
2130 strcpy( unix_name + pos, redirects[i].unix_target );
2139 /* there are no redirects on 64-bit */
2141 static const unsigned int nb_redirects = 0;
2143 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, int check_case )
2150 /***********************************************************************
2151 * DIR_init_windows_dir
2153 void DIR_init_windows_dir( const WCHAR *win, const WCHAR *sys )
2155 /* FIXME: should probably store paths as NT file names */
2157 RtlCreateUnicodeString( &windows_dir, win );
2158 RtlCreateUnicodeString( &system_dir, sys );
2161 if (is_wow64) init_redirects();
2166 /******************************************************************************
2169 * Get the Unix path of a DOS device.
2171 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
2173 const char *config_dir = wine_get_config_dir();
2175 char *unix_name, *new_name, *dev;
2179 /* make sure the device name is ASCII */
2180 for (i = 0; i < name_len; i++)
2181 if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
2183 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
2185 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2186 return STATUS_NO_MEMORY;
2188 strcpy( unix_name, config_dir );
2189 strcat( unix_name, "/dosdevices/" );
2190 dev = unix_name + strlen(unix_name);
2192 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
2195 /* special case for drive devices */
2196 if (name_len == 2 && dev[1] == ':')
2204 if (!stat( unix_name, &st ))
2206 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
2207 unix_name_ret->Buffer = unix_name;
2208 unix_name_ret->Length = strlen(unix_name);
2209 unix_name_ret->MaximumLength = unix_len;
2210 return STATUS_SUCCESS;
2214 /* now try some defaults for it */
2215 if (!strcmp( dev, "aux" ))
2217 strcpy( dev, "com1" );
2220 if (!strcmp( dev, "prn" ))
2222 strcpy( dev, "lpt1" );
2225 if (!strcmp( dev, "nul" ))
2227 strcpy( unix_name, "/dev/null" );
2228 dev = NULL; /* last try */
2233 if (dev[1] == ':' && dev[2] == ':') /* drive device */
2235 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
2236 new_name = get_default_drive_device( unix_name );
2238 else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( atoi(dev + 3 ));
2239 else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( atoi(dev + 3 ));
2241 if (!new_name) break;
2243 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2244 unix_name = new_name;
2245 unix_len = strlen(unix_name) + 1;
2246 dev = NULL; /* last try */
2248 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2249 return STATUS_BAD_DEVICE_TYPE;
2253 /* return the length of the DOS namespace prefix if any */
2254 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
2256 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
2257 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
2259 if (name->Length > sizeof(nt_prefixW) &&
2260 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
2261 return sizeof(nt_prefixW) / sizeof(WCHAR);
2263 if (name->Length > sizeof(dosdev_prefixW) &&
2264 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
2265 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
2271 /******************************************************************************
2274 * Recursively search directories from the dir queue for a given inode.
2276 static NTSTATUS find_file_id( ANSI_STRING *unix_name, ULONGLONG file_id, dev_t dev )
2284 while (!(status = next_dir_in_queue( unix_name->Buffer )))
2286 if (!(dir = opendir( unix_name->Buffer ))) continue;
2287 TRACE( "searching %s for %s\n", unix_name->Buffer, wine_dbgstr_longlong(file_id) );
2288 pos = strlen( unix_name->Buffer );
2289 if (pos + MAX_DIR_ENTRY_LEN >= unix_name->MaximumLength/sizeof(WCHAR))
2291 char *new = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name->Buffer,
2292 unix_name->MaximumLength * 2 );
2296 return STATUS_NO_MEMORY;
2298 unix_name->MaximumLength *= 2;
2299 unix_name->Buffer = new;
2301 unix_name->Buffer[pos++] = '/';
2302 while ((de = readdir( dir )))
2304 if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
2305 strcpy( unix_name->Buffer + pos, de->d_name );
2306 if (lstat( unix_name->Buffer, &st ) == -1) continue;
2307 if (st.st_dev != dev) continue;
2308 if (st.st_ino == file_id)
2311 return STATUS_SUCCESS;
2313 if (!S_ISDIR( st.st_mode )) continue;
2314 if ((status = add_dir_to_queue( unix_name->Buffer )) != STATUS_SUCCESS)
2326 /******************************************************************************
2327 * file_id_to_unix_file_name
2329 * Lookup a file from its file id instead of its name.
2331 NTSTATUS file_id_to_unix_file_name( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name )
2333 enum server_fd_type type;
2334 int old_cwd, root_fd, needs_close;
2337 struct stat st, root_st;
2339 if (attr->ObjectName->Length != sizeof(ULONGLONG)) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2340 if (!attr->RootDirectory) return STATUS_INVALID_PARAMETER;
2341 memcpy( &file_id, attr->ObjectName->Buffer, sizeof(file_id) );
2343 unix_name->MaximumLength = 2 * MAX_DIR_ENTRY_LEN + 4;
2344 if (!(unix_name->Buffer = RtlAllocateHeap( GetProcessHeap(), 0, unix_name->MaximumLength )))
2345 return STATUS_NO_MEMORY;
2346 strcpy( unix_name->Buffer, "." );
2348 if ((status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
2351 if (type != FD_TYPE_DIR)
2353 status = STATUS_OBJECT_TYPE_MISMATCH;
2357 fstat( root_fd, &root_st );
2358 if (root_st.st_ino == file_id) /* shortcut for "." */
2360 status = STATUS_SUCCESS;
2364 RtlEnterCriticalSection( &dir_section );
2365 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2367 /* shortcut for ".." */
2368 if (!stat( "..", &st ) && st.st_dev == root_st.st_dev && st.st_ino == file_id)
2370 strcpy( unix_name->Buffer, ".." );
2371 status = STATUS_SUCCESS;
2375 status = add_dir_to_queue( "." );
2377 status = find_file_id( unix_name, file_id, root_st.st_dev );
2378 if (!status) /* get rid of "./" prefix */
2379 memmove( unix_name->Buffer, unix_name->Buffer + 2, strlen(unix_name->Buffer) - 1 );
2382 if (fchdir( old_cwd ) == -1) chdir( "/" );
2384 else status = FILE_GetNtStatus();
2385 RtlLeaveCriticalSection( &dir_section );
2386 if (old_cwd != -1) close( old_cwd );
2389 if (status == STATUS_SUCCESS)
2391 TRACE( "%s -> %s\n", wine_dbgstr_longlong(file_id), debugstr_a(unix_name->Buffer) );
2392 unix_name->Length = strlen( unix_name->Buffer );
2396 TRACE( "%s not found in dir %p\n", wine_dbgstr_longlong(file_id), attr->RootDirectory );
2397 RtlFreeHeap( GetProcessHeap(), 0, unix_name->Buffer );
2399 if (needs_close) close( root_fd );
2404 /******************************************************************************
2407 * Helper for nt_to_unix_file_name
2409 static NTSTATUS lookup_unix_name( const WCHAR *name, int name_len, char **buffer, int unix_len, int pos,
2410 UINT disposition, BOOLEAN check_case )
2413 int ret, used_default, len;
2415 char *unix_name = *buffer;
2416 const BOOL redirect = nb_redirects && ntdll_get_thread_data()->wow64_redir;
2418 /* try a shortcut first */
2420 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
2421 NULL, &used_default );
2423 while (name_len && IS_SEPARATOR(*name))
2429 if (ret >= 0 && !used_default) /* if we used the default char the name didn't convert properly */
2432 unix_name[pos + ret] = 0;
2433 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
2434 if (!redirect || (!strstr( unix_name, "/windows/") && strncmp( unix_name, "windows/", 8 )))
2436 if (!stat( unix_name, &st ))
2438 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
2439 if (disposition == FILE_CREATE)
2440 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
2441 return STATUS_SUCCESS;
2446 if (!name_len) /* empty name -> drive root doesn't exist */
2447 return STATUS_OBJECT_PATH_NOT_FOUND;
2448 if (check_case && !redirect && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
2449 return STATUS_OBJECT_NAME_NOT_FOUND;
2451 /* now do it component by component */
2455 const WCHAR *end, *next;
2459 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
2461 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
2462 name_len -= next - name;
2464 /* grow the buffer if needed */
2466 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
2469 unix_len += 2 * MAX_DIR_ENTRY_LEN;
2470 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
2471 return STATUS_NO_MEMORY;
2472 unix_name = *buffer = new_name;
2475 status = find_file_in_dir( unix_name, pos, name, end - name,
2476 check_case, redirect ? &is_win_dir : NULL );
2478 /* if this is the last element, not finding it is not necessarily fatal */
2481 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
2483 status = STATUS_OBJECT_NAME_NOT_FOUND;
2484 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
2486 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2487 MAX_DIR_ENTRY_LEN, NULL, &used_default );
2488 if (ret > 0 && !used_default)
2490 unix_name[pos] = '/';
2491 unix_name[pos + 1 + ret] = 0;
2492 status = STATUS_NO_SUCH_FILE;
2497 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
2499 status = STATUS_OBJECT_NAME_COLLISION;
2503 if (status != STATUS_SUCCESS) break;
2505 pos += strlen( unix_name + pos );
2508 if (is_win_dir && (len = get_redirect_path( unix_name, pos, name, name_len, check_case )))
2512 pos += strlen( unix_name + pos );
2513 TRACE( "redirecting -> %s + %s\n", debugstr_a(unix_name), debugstr_w(name) );
2521 /******************************************************************************
2522 * nt_to_unix_file_name_attr
2524 NTSTATUS nt_to_unix_file_name_attr( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name_ret,
2527 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2528 enum server_fd_type type;
2529 int old_cwd, root_fd, needs_close;
2530 const WCHAR *name, *p;
2532 int name_len, unix_len;
2534 BOOLEAN check_case = !(attr->Attributes & OBJ_CASE_INSENSITIVE);
2536 if (!attr->RootDirectory) /* without root dir fall back to normal lookup */
2537 return wine_nt_to_unix_file_name( attr->ObjectName, unix_name_ret, disposition, check_case );
2539 name = attr->ObjectName->Buffer;
2540 name_len = attr->ObjectName->Length / sizeof(WCHAR);
2542 if (name_len && IS_SEPARATOR(name[0])) return STATUS_INVALID_PARAMETER;
2544 /* check for invalid characters */
2545 for (p = name; p < name + name_len; p++)
2546 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2548 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
2549 unix_len += MAX_DIR_ENTRY_LEN + 3;
2550 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2551 return STATUS_NO_MEMORY;
2554 if (!(status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
2556 if (type != FD_TYPE_DIR)
2558 if (needs_close) close( root_fd );
2559 status = STATUS_BAD_DEVICE_TYPE;
2563 RtlEnterCriticalSection( &dir_section );
2564 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2566 status = lookup_unix_name( name, name_len, &unix_name, unix_len, 1,
2567 disposition, check_case );
2568 if (fchdir( old_cwd ) == -1) chdir( "/" );
2570 else status = FILE_GetNtStatus();
2571 RtlLeaveCriticalSection( &dir_section );
2572 if (old_cwd != -1) close( old_cwd );
2573 if (needs_close) close( root_fd );
2576 else if (status == STATUS_OBJECT_TYPE_MISMATCH) status = STATUS_BAD_DEVICE_TYPE;
2578 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
2580 TRACE( "%s -> %s\n", debugstr_us(attr->ObjectName), debugstr_a(unix_name) );
2581 unix_name_ret->Buffer = unix_name;
2582 unix_name_ret->Length = strlen(unix_name);
2583 unix_name_ret->MaximumLength = unix_len;
2587 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
2588 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2594 /******************************************************************************
2595 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
2597 * Convert a file name from NT namespace to Unix namespace.
2599 * If disposition is not FILE_OPEN or FILE_OVERWRITE, the last path
2600 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
2601 * returned, but the unix name is still filled in properly.
2603 NTSTATUS CDECL wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
2604 UINT disposition, BOOLEAN check_case )
2606 static const WCHAR unixW[] = {'u','n','i','x'};
2607 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2609 NTSTATUS status = STATUS_SUCCESS;
2610 const char *config_dir = wine_get_config_dir();
2611 const WCHAR *name, *p;
2614 int pos, ret, name_len, unix_len, prefix_len, used_default;
2615 WCHAR prefix[MAX_DIR_ENTRY_LEN];
2616 BOOLEAN is_unix = FALSE;
2618 name = nameW->Buffer;
2619 name_len = nameW->Length / sizeof(WCHAR);
2621 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2623 if (!(pos = get_dos_prefix_len( nameW )))
2624 return STATUS_BAD_DEVICE_TYPE; /* no DOS prefix, assume NT native name */
2629 /* check for sub-directory */
2630 for (pos = 0; pos < name_len; pos++)
2632 if (IS_SEPARATOR(name[pos])) break;
2633 if (name[pos] < 32 || strchrW( invalid_charsW, name[pos] ))
2634 return STATUS_OBJECT_NAME_INVALID;
2636 if (pos > MAX_DIR_ENTRY_LEN)
2637 return STATUS_OBJECT_NAME_INVALID;
2639 if (pos == name_len) /* no subdir, plain DOS device */
2640 return get_dos_device( name, name_len, unix_name_ret );
2642 for (prefix_len = 0; prefix_len < pos; prefix_len++)
2643 prefix[prefix_len] = tolowerW(name[prefix_len]);
2646 name_len -= prefix_len;
2648 /* check for invalid characters (all chars except 0 are valid for unix) */
2649 is_unix = (prefix_len == 4 && !memcmp( prefix, unixW, sizeof(unixW) ));
2652 for (p = name; p < name + name_len; p++)
2653 if (!*p) return STATUS_OBJECT_NAME_INVALID;
2658 for (p = name; p < name + name_len; p++)
2659 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2662 unix_len = ntdll_wcstoumbs( 0, prefix, prefix_len, NULL, 0, NULL, NULL );
2663 unix_len += ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
2664 unix_len += MAX_DIR_ENTRY_LEN + 3;
2665 unix_len += strlen(config_dir) + sizeof("/dosdevices/");
2666 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2667 return STATUS_NO_MEMORY;
2668 strcpy( unix_name, config_dir );
2669 strcat( unix_name, "/dosdevices/" );
2670 pos = strlen(unix_name);
2672 ret = ntdll_wcstoumbs( 0, prefix, prefix_len, unix_name + pos, unix_len - pos - 1,
2673 NULL, &used_default );
2674 if (!ret || used_default)
2676 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2677 return STATUS_OBJECT_NAME_INVALID;
2681 /* check if prefix exists (except for DOS drives to avoid extra stat calls) */
2683 if (prefix_len != 2 || prefix[1] != ':')
2686 if (lstat( unix_name, &st ) == -1 && errno == ENOENT)
2690 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2691 return STATUS_BAD_DEVICE_TYPE;
2693 pos = 0; /* fall back to unix root */
2697 status = lookup_unix_name( name, name_len, &unix_name, unix_len, pos, disposition, check_case );
2698 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
2700 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
2701 unix_name_ret->Buffer = unix_name;
2702 unix_name_ret->Length = strlen(unix_name);
2703 unix_name_ret->MaximumLength = unix_len;
2707 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
2708 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2714 /******************************************************************
2715 * RtlWow64EnableFsRedirection (NTDLL.@)
2717 NTSTATUS WINAPI RtlWow64EnableFsRedirection( BOOLEAN enable )
2719 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
2720 ntdll_get_thread_data()->wow64_redir = enable;
2721 return STATUS_SUCCESS;
2725 /******************************************************************
2726 * RtlWow64EnableFsRedirectionEx (NTDLL.@)
2728 NTSTATUS WINAPI RtlWow64EnableFsRedirectionEx( ULONG disable, ULONG *old_value )
2730 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
2731 *old_value = !ntdll_get_thread_data()->wow64_redir;
2732 ntdll_get_thread_data()->wow64_redir = !disable;
2733 return STATUS_SUCCESS;
2737 /******************************************************************
2738 * RtlDoesFileExists_U (NTDLL.@)
2740 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
2742 UNICODE_STRING nt_name;
2743 FILE_BASIC_INFORMATION basic_info;
2744 OBJECT_ATTRIBUTES attr;
2747 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
2749 attr.Length = sizeof(attr);
2750 attr.RootDirectory = 0;
2751 attr.ObjectName = &nt_name;
2752 attr.Attributes = OBJ_CASE_INSENSITIVE;
2753 attr.SecurityDescriptor = NULL;
2754 attr.SecurityQualityOfService = NULL;
2756 ret = NtQueryAttributesFile(&attr, &basic_info) == STATUS_SUCCESS;
2758 RtlFreeUnicodeString( &nt_name );
2763 /***********************************************************************
2764 * DIR_unmount_device
2766 * Unmount the specified device.
2768 NTSTATUS DIR_unmount_device( HANDLE handle )
2771 int unix_fd, needs_close;
2773 if (!(status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )))
2776 char *mount_point = NULL;
2778 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2779 status = STATUS_INVALID_PARAMETER;
2782 if ((mount_point = get_device_mount_point( st.st_rdev )))
2785 static const char umount[] = "diskutil unmount >/dev/null 2>&1 ";
2787 static const char umount[] = "umount >/dev/null 2>&1 ";
2789 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
2792 strcpy( cmd, umount );
2793 strcat( cmd, mount_point );
2795 RtlFreeHeap( GetProcessHeap(), 0, cmd );
2797 /* umount will fail to release the loop device since we still have
2798 a handle to it, so we release it here */
2799 if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
2802 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
2805 if (needs_close) close( unix_fd );
2811 /******************************************************************************
2814 * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
2815 * Returned value must be freed by caller.
2817 NTSTATUS DIR_get_unix_cwd( char **cwd )
2819 int old_cwd, unix_fd, needs_close;
2824 RtlAcquirePebLock();
2826 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
2827 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
2829 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
2831 if (!(handle = curdir->Handle))
2833 UNICODE_STRING dirW;
2834 OBJECT_ATTRIBUTES attr;
2837 if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
2839 status = STATUS_OBJECT_NAME_INVALID;
2842 attr.Length = sizeof(attr);
2843 attr.RootDirectory = 0;
2844 attr.Attributes = OBJ_CASE_INSENSITIVE;
2845 attr.ObjectName = &dirW;
2846 attr.SecurityDescriptor = NULL;
2847 attr.SecurityQualityOfService = NULL;
2849 status = NtOpenFile( &handle, 0, &attr, &io, 0,
2850 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
2851 RtlFreeUnicodeString( &dirW );
2852 if (status != STATUS_SUCCESS) goto done;
2855 if ((status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )) == STATUS_SUCCESS)
2857 RtlEnterCriticalSection( &dir_section );
2859 if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
2861 unsigned int size = 512;
2865 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2867 status = STATUS_NO_MEMORY;
2870 if (getcwd( *cwd, size )) break;
2871 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
2872 if (errno != ERANGE)
2874 status = STATUS_OBJECT_PATH_INVALID;
2879 if (fchdir( old_cwd ) == -1) chdir( "/" );
2881 else status = FILE_GetNtStatus();
2883 RtlLeaveCriticalSection( &dir_section );
2884 if (old_cwd != -1) close( old_cwd );
2885 if (needs_close) close( unix_fd );
2887 if (!curdir->Handle) NtClose( handle );
2890 RtlReleasePebLock();
2894 struct read_changes_info
2899 PIO_APC_ROUTINE apc;
2903 /* callback for ioctl user APC */
2904 static void WINAPI read_changes_user_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
2906 struct read_changes_info *info = arg;
2907 if (info->apc) info->apc( info->apc_arg, io, reserved );
2908 RtlFreeHeap( GetProcessHeap(), 0, info );
2911 static NTSTATUS read_changes_apc( void *user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
2913 struct read_changes_info *info = user;
2914 char path[PATH_MAX];
2915 NTSTATUS ret = STATUS_SUCCESS;
2918 SERVER_START_REQ( read_change )
2920 req->handle = wine_server_obj_handle( info->FileHandle );
2921 wine_server_set_reply( req, path, PATH_MAX );
2922 ret = wine_server_call( req );
2923 action = reply->action;
2924 len = wine_server_reply_size( reply );
2928 if (ret == STATUS_SUCCESS && info->Buffer &&
2929 (info->BufferSize > (sizeof (FILE_NOTIFY_INFORMATION) + len*sizeof(WCHAR))))
2931 PFILE_NOTIFY_INFORMATION pfni;
2933 pfni = info->Buffer;
2935 /* convert to an NT style path */
2936 for (i=0; i<len; i++)
2940 len = ntdll_umbstowcs( 0, path, len, pfni->FileName,
2941 info->BufferSize - sizeof (*pfni) );
2943 pfni->NextEntryOffset = 0;
2944 pfni->Action = action;
2945 pfni->FileNameLength = len * sizeof (WCHAR);
2946 pfni->FileName[len] = 0;
2947 len = sizeof (*pfni) - sizeof (DWORD) + pfni->FileNameLength;
2951 ret = STATUS_NOTIFY_ENUM_DIR;
2955 iosb->u.Status = ret;
2956 iosb->Information = len;
2957 *apc = read_changes_user_apc;
2961 #define FILE_NOTIFY_ALL ( \
2962 FILE_NOTIFY_CHANGE_FILE_NAME | \
2963 FILE_NOTIFY_CHANGE_DIR_NAME | \
2964 FILE_NOTIFY_CHANGE_ATTRIBUTES | \
2965 FILE_NOTIFY_CHANGE_SIZE | \
2966 FILE_NOTIFY_CHANGE_LAST_WRITE | \
2967 FILE_NOTIFY_CHANGE_LAST_ACCESS | \
2968 FILE_NOTIFY_CHANGE_CREATION | \
2969 FILE_NOTIFY_CHANGE_SECURITY )
2971 /******************************************************************************
2972 * NtNotifyChangeDirectoryFile [NTDLL.@]
2975 NtNotifyChangeDirectoryFile( HANDLE FileHandle, HANDLE Event,
2976 PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext,
2977 PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer,
2978 ULONG BufferSize, ULONG CompletionFilter, BOOLEAN WatchTree )
2980 struct read_changes_info *info;
2982 ULONG_PTR cvalue = ApcRoutine ? 0 : (ULONG_PTR)ApcContext;
2984 TRACE("%p %p %p %p %p %p %u %u %d\n",
2985 FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock,
2986 Buffer, BufferSize, CompletionFilter, WatchTree );
2989 return STATUS_ACCESS_VIOLATION;
2991 if (CompletionFilter == 0 || (CompletionFilter & ~FILE_NOTIFY_ALL))
2992 return STATUS_INVALID_PARAMETER;
2994 info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof *info );
2996 return STATUS_NO_MEMORY;
2998 info->FileHandle = FileHandle;
2999 info->Buffer = Buffer;
3000 info->BufferSize = BufferSize;
3001 info->apc = ApcRoutine;
3002 info->apc_arg = ApcContext;
3004 SERVER_START_REQ( read_directory_changes )
3006 req->filter = CompletionFilter;
3007 req->want_data = (Buffer != NULL);
3008 req->subtree = WatchTree;
3009 req->async.handle = wine_server_obj_handle( FileHandle );
3010 req->async.callback = wine_server_client_ptr( read_changes_apc );
3011 req->async.iosb = wine_server_client_ptr( IoStatusBlock );
3012 req->async.arg = wine_server_client_ptr( info );
3013 req->async.event = wine_server_obj_handle( Event );
3014 req->async.cvalue = cvalue;
3015 status = wine_server_call( req );
3019 if (status != STATUS_PENDING)
3020 RtlFreeHeap( GetProcessHeap(), 0, info );