2 * NTDLL directory functions
4 * Copyright 1993 Erik Bos
5 * Copyright 2003 Eric Pouech
6 * Copyright 1996, 2004 Alexandre Julliard
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 #include "wine/port.h"
27 #include <sys/types.h>
41 #ifdef HAVE_SYS_STAT_H
42 # include <sys/stat.h>
44 #ifdef HAVE_SYS_IOCTL_H
45 #include <sys/ioctl.h>
47 #ifdef HAVE_LINUX_IOCTL_H
48 #include <linux/ioctl.h>
50 #ifdef HAVE_LINUX_MAJOR_H
51 # include <linux/major.h>
53 #ifdef HAVE_SYS_PARAM_H
54 #include <sys/param.h>
56 #ifdef HAVE_SYS_MOUNT_H
57 #include <sys/mount.h>
64 #define NONAMELESSUNION
65 #define NONAMELESSSTRUCT
67 #define WIN32_NO_STATUS
71 #include "ntdll_misc.h"
72 #include "wine/unicode.h"
73 #include "wine/server.h"
74 #include "wine/library.h"
75 #include "wine/debug.h"
77 WINE_DEFAULT_DEBUG_CHANNEL(file);
80 #undef VFAT_IOCTL_READDIR_BOTH
85 /* We want the real kernel dirent structure, not the libc one */
90 unsigned short d_reclen;
94 /* Define the VFAT ioctl to get both short and long file names */
95 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
98 # define O_DIRECTORY 0200000 /* must be directory */
107 unsigned short d_reclen;
108 unsigned char d_type;
112 static inline int getdents64( int fd, char *de, unsigned int size )
115 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
117 : "0" (220 /*NR_getdents64*/), "r" (fd), "c" (de), "d" (size)
132 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
133 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
135 #define INVALID_NT_CHARS '*','?','<','>','|','"'
136 #define INVALID_DOS_CHARS INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
138 #define MAX_DIR_ENTRY_LEN 255 /* max length of a directory entry in chars */
140 #define MAX_IGNORED_FILES 4
148 static struct file_identity ignored_files[MAX_IGNORED_FILES];
149 static int ignored_files_count;
151 union file_directory_info
154 FILE_DIRECTORY_INFORMATION dir;
155 FILE_BOTH_DIRECTORY_INFORMATION both;
156 FILE_FULL_DIRECTORY_INFORMATION full;
157 FILE_ID_BOTH_DIRECTORY_INFORMATION id_both;
158 FILE_ID_FULL_DIRECTORY_INFORMATION id_full;
161 static int show_dot_files = -1;
163 /* at some point we may want to allow Winelib apps to set this */
164 static const int is_case_sensitive = FALSE;
166 UNICODE_STRING windows_dir = { 0, 0, NULL }; /* windows directory */
167 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
169 static struct file_identity curdir;
170 static struct file_identity windir;
172 static RTL_CRITICAL_SECTION dir_section;
173 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
176 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
177 0, 0, { (DWORD_PTR)(__FILE__ ": dir_section") }
179 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
182 /* check if a given Unicode char is OK in a DOS short name */
183 static inline BOOL is_invalid_dos_char( WCHAR ch )
185 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
186 if (ch > 0x7f) return TRUE;
187 return strchrW( invalid_chars, ch ) != NULL;
190 /* check if the device can be a mounted volume */
191 static inline int is_valid_mounted_device( const struct stat *st )
193 #if defined(linux) || defined(__sun__)
194 return S_ISBLK( st->st_mode );
196 /* disks are char devices on *BSD */
197 return S_ISCHR( st->st_mode );
201 static inline void ignore_file( const char *name )
204 assert( ignored_files_count < MAX_IGNORED_FILES );
205 if (!stat( name, &st ))
207 ignored_files[ignored_files_count].dev = st.st_dev;
208 ignored_files[ignored_files_count].ino = st.st_ino;
209 ignored_files_count++;
213 static inline BOOL is_same_file( const struct file_identity *file, const struct stat *st )
215 return st->st_dev == file->dev && st->st_ino == file->ino;
218 static inline BOOL is_ignored_file( const struct stat *st )
222 for (i = 0; i < ignored_files_count; i++)
223 if (is_same_file( &ignored_files[i], st )) return TRUE;
227 static inline unsigned int dir_info_size( FILE_INFORMATION_CLASS class, unsigned int len )
231 case FileDirectoryInformation:
232 return (FIELD_OFFSET( FILE_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
233 case FileBothDirectoryInformation:
234 return (FIELD_OFFSET( FILE_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
235 case FileFullDirectoryInformation:
236 return (FIELD_OFFSET( FILE_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
237 case FileIdBothDirectoryInformation:
238 return (FIELD_OFFSET( FILE_ID_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
239 case FileIdFullDirectoryInformation:
240 return (FIELD_OFFSET( FILE_ID_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
246 static inline unsigned int max_dir_info_size( FILE_INFORMATION_CLASS class )
248 return dir_info_size( class, MAX_DIR_ENTRY_LEN );
252 /***********************************************************************
253 * get_default_com_device
255 * Return the default device to use for serial ports.
257 static char *get_default_com_device( int num )
261 if (!num || num > 9) return ret;
263 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
266 strcpy( ret, "/dev/ttyS0" );
267 ret[strlen(ret) - 1] = '0' + num - 1;
269 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
270 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuad0") );
273 strcpy( ret, "/dev/cuad0" );
274 ret[strlen(ret) - 1] = '0' + num - 1;
277 FIXME( "no known default for device com%d\n", num );
283 /***********************************************************************
284 * get_default_lpt_device
286 * Return the default device to use for parallel ports.
288 static char *get_default_lpt_device( int num )
292 if (!num || num > 9) return ret;
294 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
297 strcpy( ret, "/dev/lp0" );
298 ret[strlen(ret) - 1] = '0' + num - 1;
301 FIXME( "no known default for device lpt%d\n", num );
307 /***********************************************************************
308 * DIR_get_drives_info
310 * Retrieve device/inode number for all the drives. Helper for find_drive_root.
312 unsigned int DIR_get_drives_info( struct drive_info info[MAX_DOS_DRIVES] )
314 static struct drive_info cache[MAX_DOS_DRIVES];
315 static time_t last_update;
316 static unsigned int nb_drives;
318 time_t now = time(NULL);
320 RtlEnterCriticalSection( &dir_section );
321 if (now != last_update)
323 const char *config_dir = wine_get_config_dir();
328 if ((buffer = RtlAllocateHeap( GetProcessHeap(), 0,
329 strlen(config_dir) + sizeof("/dosdevices/a:") )))
331 strcpy( buffer, config_dir );
332 strcat( buffer, "/dosdevices/a:" );
333 p = buffer + strlen(buffer) - 2;
335 for (i = nb_drives = 0; i < MAX_DOS_DRIVES; i++)
338 if (!stat( buffer, &st ))
340 cache[i].dev = st.st_dev;
341 cache[i].ino = st.st_ino;
350 RtlFreeHeap( GetProcessHeap(), 0, buffer );
354 memcpy( info, cache, sizeof(cache) );
356 RtlLeaveCriticalSection( &dir_section );
361 /***********************************************************************
362 * parse_mount_entries
364 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
368 #include <sys/vfstab.h>
369 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
375 while (! getvfsent( f, &entry ))
377 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
378 if (!strcmp( entry.vfs_fstype, "nfs" ) ||
379 !strcmp( entry.vfs_fstype, "smbfs" ) ||
380 !strcmp( entry.vfs_fstype, "ncpfs" )) continue;
382 if (stat( entry.vfs_mountp, &st ) == -1) continue;
383 if (st.st_dev != dev || st.st_ino != ino) continue;
384 if (!strcmp( entry.vfs_fstype, "fd" ))
386 if ((device = strstr( entry.vfs_mntopts, "dev=" )))
388 char *p = strchr( device + 4, ',' );
394 return entry.vfs_special;
401 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
403 struct mntent *entry;
407 while ((entry = getmntent( f )))
409 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
410 if (!strcmp( entry->mnt_type, "nfs" ) ||
411 !strcmp( entry->mnt_type, "smbfs" ) ||
412 !strcmp( entry->mnt_type, "ncpfs" )) continue;
414 if (stat( entry->mnt_dir, &st ) == -1) continue;
415 if (st.st_dev != dev || st.st_ino != ino) continue;
416 if (!strcmp( entry->mnt_type, "supermount" ))
418 if ((device = strstr( entry->mnt_opts, "dev=" )))
420 char *p = strchr( device + 4, ',' );
425 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
427 /* if device is a regular file check for a loop mount */
428 if ((device = strstr( entry->mnt_opts, "loop=" )))
430 char *p = strchr( device + 5, ',' );
436 return entry->mnt_fsname;
442 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
444 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
449 while ((entry = getfsent()))
451 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
452 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
453 !strcmp( entry->fs_vfstype, "smbfs" ) ||
454 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
456 if (stat( entry->fs_file, &st ) == -1) continue;
457 if (st.st_dev != dev || st.st_ino != ino) continue;
458 return entry->fs_spec;
465 #include <sys/mnttab.h>
466 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
473 while (( ! getmntent( f, &entry) ))
475 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
476 if (!strcmp( entry.mnt_fstype, "nfs" ) ||
477 !strcmp( entry.mnt_fstype, "smbfs" ) ||
478 !strcmp( entry.mnt_fstype, "ncpfs" )) continue;
480 if (stat( entry.mnt_mountp, &st ) == -1) continue;
481 if (st.st_dev != dev || st.st_ino != ino) continue;
482 if (!strcmp( entry.mnt_fstype, "fd" ))
484 if ((device = strstr( entry.mnt_mntopts, "dev=" )))
486 char *p = strchr( device + 4, ',' );
492 return entry.mnt_special;
498 /***********************************************************************
499 * get_default_drive_device
501 * Return the default device to use for a given drive mount point.
503 static char *get_default_drive_device( const char *root )
513 /* try to open it first to force it to get mounted */
514 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
516 res = fstat( fd, &st );
519 /* now try normal stat just in case */
520 if (res == -1) res = stat( root, &st );
521 if (res == -1) return NULL;
523 RtlEnterCriticalSection( &dir_section );
525 if ((f = fopen( "/etc/mtab", "r" )))
527 device = parse_mount_entries( f, st.st_dev, st.st_ino );
530 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
531 if (!device && (f = fopen( "/etc/fstab", "r" )))
533 device = parse_mount_entries( f, st.st_dev, st.st_ino );
538 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
539 if (ret) strcpy( ret, device );
541 RtlLeaveCriticalSection( &dir_section );
543 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ )
548 /* try to open it first to force it to get mounted */
549 if ((fd = open( root, O_RDONLY )) != -1)
551 res = fstat( fd, &st );
554 /* now try normal stat just in case */
555 if (res == -1) res = stat( root, &st );
556 if (res == -1) return NULL;
558 RtlEnterCriticalSection( &dir_section );
560 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
561 * pass NULL. Leave the argument in for symmetry.
563 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
566 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
567 if (ret) strcpy( ret, device );
569 RtlLeaveCriticalSection( &dir_section );
577 /* try to open it first to force it to get mounted */
578 if ((fd = open( root, O_RDONLY )) != -1)
580 res = fstat( fd, &st );
583 /* now try normal stat just in case */
584 if (res == -1) res = stat( root, &st );
585 if (res == -1) return NULL;
587 RtlEnterCriticalSection( &dir_section );
589 if ((f = fopen( "/etc/mnttab", "r" )))
591 device = parse_mount_entries( f, st.st_dev, st.st_ino);
594 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
595 if (!device && (f = fopen( "/etc/vfstab", "r" )))
597 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
602 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
603 if (ret) strcpy( ret, device );
605 RtlLeaveCriticalSection( &dir_section );
607 #elif defined(__APPLE__)
608 struct statfs *mntStat;
614 static const char path_bsd_device[] = "/dev/disk";
617 res = stat( root, &st );
618 if (res == -1) return NULL;
623 RtlEnterCriticalSection( &dir_section );
625 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
627 for (i = 0; i < mntSize && !ret; i++)
629 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
630 if (st.st_dev != dev || st.st_ino != ino) continue;
632 /* FIXME add support for mounted network drive */
633 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
635 /* set return value to the corresponding raw BSD node */
636 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
639 strcpy(ret, "/dev/r");
640 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
644 RtlLeaveCriticalSection( &dir_section );
647 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
653 /***********************************************************************
654 * get_device_mount_point
656 * Return the current mount point for a device.
658 static char *get_device_mount_point( dev_t dev )
665 RtlEnterCriticalSection( &dir_section );
667 if ((f = fopen( "/etc/mtab", "r" )))
669 struct mntent *entry;
673 while ((entry = getmntent( f )))
675 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
676 if (!strcmp( entry->mnt_type, "nfs" ) ||
677 !strcmp( entry->mnt_type, "smbfs" ) ||
678 !strcmp( entry->mnt_type, "ncpfs" )) continue;
680 if (!strcmp( entry->mnt_type, "supermount" ))
682 if ((device = strstr( entry->mnt_opts, "dev=" )))
685 if ((p = strchr( device, ',' ))) *p = 0;
688 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
690 /* if device is a regular file check for a loop mount */
691 if ((device = strstr( entry->mnt_opts, "loop=" )))
694 if ((p = strchr( device, ',' ))) *p = 0;
697 else device = entry->mnt_fsname;
699 if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
701 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
702 if (ret) strcpy( ret, entry->mnt_dir );
708 RtlLeaveCriticalSection( &dir_section );
709 #elif defined(__APPLE__)
710 struct statfs *entry;
714 RtlEnterCriticalSection( &dir_section );
716 size = getmntinfo( &entry, MNT_NOWAIT );
717 for (i = 0; i < size; i++)
719 if (stat( entry[i].f_mntfromname, &st ) == -1) continue;
720 if (S_ISBLK(st.st_mode) && st.st_rdev == dev)
722 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry[i].f_mntfromname) + 1 );
723 if (ret) strcpy( ret, entry[i].f_mntfromname );
727 RtlLeaveCriticalSection( &dir_section );
730 if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
736 /***********************************************************************
739 * Initialize the show_dot_files options.
741 static void init_options(void)
743 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
744 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
748 OBJECT_ATTRIBUTES attr;
749 UNICODE_STRING nameW;
753 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
754 attr.Length = sizeof(attr);
755 attr.RootDirectory = root;
756 attr.ObjectName = &nameW;
758 attr.SecurityDescriptor = NULL;
759 attr.SecurityQualityOfService = NULL;
760 RtlInitUnicodeString( &nameW, WineW );
762 /* @@ Wine registry key: HKCU\Software\Wine */
763 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
765 RtlInitUnicodeString( &nameW, ShowDotFilesW );
766 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
768 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
769 show_dot_files = IS_OPTION_TRUE( str[0] );
775 /* a couple of directories that we don't want to return in directory searches */
776 ignore_file( wine_get_config_dir() );
777 ignore_file( "/dev" );
778 ignore_file( "/proc" );
780 ignore_file( "/sys" );
785 /***********************************************************************
788 * Check if the specified file should be hidden based on its name and the show dot files option.
790 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
794 if (show_dot_files == -1) init_options();
795 if (show_dot_files) return FALSE;
797 end = p = name->Buffer + name->Length/sizeof(WCHAR);
798 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
799 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
800 if (p == end || *p != '.') return FALSE;
801 /* make sure it isn't '.' or '..' */
802 if (p + 1 == end) return FALSE;
803 if (p[1] == '.' && p + 2 == end) return FALSE;
808 /***********************************************************************
809 * hash_short_file_name
811 * Transform a Unix file name into a hashed DOS name. If the name is a valid
812 * DOS name, it is converted to upper-case; otherwise it is replaced by a
813 * hashed version that fits in 8.3 format.
814 * 'buffer' must be at least 12 characters long.
815 * Returns length of short name in bytes; short name is NOT null-terminated.
817 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
819 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
821 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
826 /* Compute the hash code of the file name */
827 /* If you know something about hash functions, feel free to */
828 /* insert a better algorithm here... */
829 if (!is_case_sensitive)
831 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
832 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
833 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
837 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
838 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
839 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
842 /* Find last dot for start of the extension */
843 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
845 /* Copy first 4 chars, replacing invalid chars with '_' */
846 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
848 if (p == end || p == ext) break;
849 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
851 /* Pad to 5 chars with '~' */
852 while (i-- >= 0) *dst++ = '~';
854 /* Insert hash code converted to 3 ASCII chars */
855 *dst++ = hash_chars[(hash >> 10) & 0x1f];
856 *dst++ = hash_chars[(hash >> 5) & 0x1f];
857 *dst++ = hash_chars[hash & 0x1f];
859 /* Copy the first 3 chars of the extension (if any) */
863 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
864 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
870 /***********************************************************************
873 * Check a long file name against a mask.
875 * Tests (done in W95 DOS shell - case insensitive):
876 * *.txt test1.test.txt *
878 * *.t??????.t* test1.ta.tornado.txt *
879 * *tornado* test1.ta.tornado.txt *
880 * t*t test1.ta.tornado.txt *
882 * ?est??? test1.txt -
883 * *test1.txt* test1.txt *
884 * h?l?o*t.dat hellothisisatest.dat *
886 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
889 const WCHAR *name = name_str->Buffer;
890 const WCHAR *mask = mask_str->Buffer;
891 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
892 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
893 const WCHAR *lastjoker = NULL;
894 const WCHAR *next_to_retry = NULL;
896 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
898 while (name < name_end && mask < mask_end)
904 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
905 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
908 /* skip to the next match after the joker(s) */
909 if (is_case_sensitive)
910 while (name < name_end && (*name != *mask)) name++;
912 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
913 next_to_retry = name;
920 if (is_case_sensitive) mismatch = (*mask != *name);
921 else mismatch = (toupperW(*mask) != toupperW(*name));
927 if (mask == mask_end)
929 if (name == name_end) return TRUE;
930 if (lastjoker) mask = lastjoker;
933 else /* mismatch ! */
935 if (lastjoker) /* we had an '*', so we can try unlimitedly */
939 /* this scan sequence was a mismatch, so restart
940 * 1 char after the first char we checked last time */
942 name = next_to_retry;
944 else return FALSE; /* bad luck */
949 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
950 mask++; /* Ignore trailing '.' or '*' in mask */
951 return (name == name_end && mask == mask_end);
955 /***********************************************************************
958 * helper for NtQueryDirectoryFile
960 static union file_directory_info *append_entry( void *info_ptr, IO_STATUS_BLOCK *io, ULONG max_length,
961 const char *long_name, const char *short_name,
962 const UNICODE_STRING *mask, FILE_INFORMATION_CLASS class )
964 union file_directory_info *info;
965 int i, long_len, short_len, total_len;
967 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
968 WCHAR short_nameW[12];
971 ULONG attributes = 0;
973 io->u.Status = STATUS_SUCCESS;
974 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
975 if (long_len == -1) return NULL;
977 str.Buffer = long_nameW;
978 str.Length = long_len * sizeof(WCHAR);
979 str.MaximumLength = sizeof(long_nameW);
983 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
984 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
985 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
987 else /* generate a short name if necessary */
992 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
993 short_len = hash_short_file_name( &str, short_nameW );
996 TRACE( "long %s short %s mask %s\n",
997 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
999 if (mask && !match_filename( &str, mask ))
1001 if (!short_len) return NULL; /* no short name to match */
1002 str.Buffer = short_nameW;
1003 str.Length = short_len * sizeof(WCHAR);
1004 str.MaximumLength = sizeof(short_nameW);
1005 if (!match_filename( &str, mask )) return NULL;
1008 if (lstat( long_name, &st ) == -1) return NULL;
1009 if (S_ISLNK( st.st_mode ))
1011 if (stat( long_name, &st ) == -1) return NULL;
1012 if (S_ISDIR( st.st_mode )) attributes |= FILE_ATTRIBUTE_REPARSE_POINT;
1014 if (is_ignored_file( &st ))
1016 TRACE( "ignoring file %s\n", long_name );
1019 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
1020 attributes |= FILE_ATTRIBUTE_HIDDEN;
1022 total_len = dir_info_size( class, long_len );
1023 if (io->Information + total_len > max_length)
1025 total_len = max_length - io->Information;
1026 io->u.Status = STATUS_BUFFER_OVERFLOW;
1028 info = (union file_directory_info *)((char *)info_ptr + io->Information);
1029 if (st.st_dev != curdir.dev) st.st_ino = 0; /* ignore inode if on a different device */
1030 /* all the structures start with a FileDirectoryInformation layout */
1031 fill_stat_info( &st, info, class );
1032 info->dir.NextEntryOffset = total_len;
1033 info->dir.FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
1034 info->dir.FileAttributes |= attributes;
1038 case FileDirectoryInformation:
1039 info->dir.FileNameLength = long_len * sizeof(WCHAR);
1040 filename = info->dir.FileName;
1043 case FileFullDirectoryInformation:
1044 info->full.EaSize = 0; /* FIXME */
1045 info->full.FileNameLength = long_len * sizeof(WCHAR);
1046 filename = info->full.FileName;
1049 case FileIdFullDirectoryInformation:
1050 info->id_full.EaSize = 0; /* FIXME */
1051 info->id_full.FileNameLength = long_len * sizeof(WCHAR);
1052 filename = info->id_full.FileName;
1055 case FileBothDirectoryInformation:
1056 info->both.EaSize = 0; /* FIXME */
1057 info->both.ShortNameLength = short_len * sizeof(WCHAR);
1058 for (i = 0; i < short_len; i++) info->both.ShortName[i] = toupperW(short_nameW[i]);
1059 info->both.FileNameLength = long_len * sizeof(WCHAR);
1060 filename = info->both.FileName;
1063 case FileIdBothDirectoryInformation:
1064 info->id_both.EaSize = 0; /* FIXME */
1065 info->id_both.ShortNameLength = short_len * sizeof(WCHAR);
1066 for (i = 0; i < short_len; i++) info->id_both.ShortName[i] = toupperW(short_nameW[i]);
1067 info->id_both.FileNameLength = long_len * sizeof(WCHAR);
1068 filename = info->id_both.FileName;
1074 memcpy( filename, long_nameW, total_len - ((char *)filename - (char *)info) );
1075 io->Information += total_len;
1080 #ifdef VFAT_IOCTL_READDIR_BOTH
1082 /***********************************************************************
1085 * Wrapper for the VFAT ioctl to work around various kernel bugs.
1086 * dir_section must be held by caller.
1088 static KERNEL_DIRENT *start_vfat_ioctl( int fd )
1090 static KERNEL_DIRENT *de;
1095 const size_t page_size = getpagesize();
1096 SIZE_T size = 2 * sizeof(*de) + page_size;
1099 if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_RESERVE, PAGE_READWRITE ))
1101 /* commit only the size needed for the dir entries */
1102 /* this leaves an extra unaccessible page, which should make the kernel */
1103 /* fail with -EFAULT before it stomps all over our memory */
1105 size = 2 * sizeof(*de);
1106 NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_COMMIT, PAGE_READWRITE );
1109 /* set d_reclen to 65535 to work around an AFS kernel bug */
1110 de[0].d_reclen = 65535;
1111 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
1114 if (errno != ENOENT) return NULL; /* VFAT ioctl probably not supported */
1115 de[0].d_reclen = 0; /* eof */
1117 else if (!res && de[0].d_reclen == 65535) return NULL; /* AFS bug */
1123 /***********************************************************************
1124 * read_directory_vfat
1126 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
1128 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1129 BOOLEAN single_entry, const UNICODE_STRING *mask,
1130 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1135 union file_directory_info *info, *last_info = NULL;
1137 io->u.Status = STATUS_SUCCESS;
1139 if (restart_scan) lseek( fd, 0, SEEK_SET );
1141 if (length < max_dir_info_size(class)) /* we may have to return a partial entry here */
1143 off_t old_pos = lseek( fd, 0, SEEK_CUR );
1145 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1147 while (de[0].d_reclen)
1149 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1150 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1151 de[0].d_name[len] = 0;
1152 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1153 de[1].d_name[len] = 0;
1155 if (de[1].d_name[0])
1156 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1158 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1162 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1163 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1166 old_pos = lseek( fd, 0, SEEK_CUR );
1167 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1170 else /* we'll only return full entries, no need to worry about overflow */
1172 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1174 while (de[0].d_reclen)
1176 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1177 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1178 de[0].d_name[len] = 0;
1179 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1180 de[1].d_name[len] = 0;
1182 if (de[1].d_name[0])
1183 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1185 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1189 if (single_entry) break;
1190 /* check if we still have enough space for the largest possible entry */
1191 if (io->Information + max_dir_info_size(class) > length) break;
1193 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1197 if (last_info) last_info->next = 0;
1198 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1201 #endif /* VFAT_IOCTL_READDIR_BOTH */
1204 /***********************************************************************
1205 * read_directory_getdents
1207 * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
1210 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1211 BOOLEAN single_entry, const UNICODE_STRING *mask,
1212 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1215 size_t size = length;
1216 int res, fake_dot_dot = 1;
1217 char *data, local_buffer[8192];
1218 KERNEL_DIRENT64 *de;
1219 union file_directory_info *info, *last_info = NULL;
1221 if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1223 size = sizeof(local_buffer);
1224 data = local_buffer;
1227 if (restart_scan) lseek( fd, 0, SEEK_SET );
1228 else if (length < max_dir_info_size(class)) /* we may have to return a partial entry here */
1230 old_pos = lseek( fd, 0, SEEK_CUR );
1231 if (old_pos == -1 && errno == ENOENT)
1233 io->u.Status = STATUS_NO_MORE_FILES;
1239 io->u.Status = STATUS_SUCCESS;
1241 res = getdents64( fd, data, size );
1244 if (errno != ENOSYS)
1246 io->u.Status = FILE_GetNtStatus();
1252 de = (KERNEL_DIRENT64 *)data;
1256 /* check if we got . and .. from getdents */
1259 if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1261 KERNEL_DIRENT64 *next_de = (KERNEL_DIRENT64 *)(data + de->d_reclen);
1262 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1265 /* make sure we have enough room for both entries */
1268 const ULONG min_info_size = dir_info_size( class, 1 ) + dir_info_size( class, 2 );
1269 if (length < min_info_size || single_entry)
1271 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1278 if ((info = append_entry( buffer, io, length, ".", NULL, mask, class )))
1280 if ((info = append_entry( buffer, io, length, "..", NULL, mask, class )))
1283 /* check if we still have enough space for the largest possible entry */
1284 if (last_info && io->Information + max_dir_info_size(class) > length)
1286 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1294 res -= de->d_reclen;
1296 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1297 (info = append_entry( buffer, io, length, de->d_name, NULL, mask, class )))
1300 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1302 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1305 /* check if we still have enough space for the largest possible entry */
1306 if (single_entry || io->Information + max_dir_info_size(class) > length)
1308 if (res > 0) lseek( fd, de->d_off, SEEK_SET ); /* set pos to next entry */
1312 old_pos = de->d_off;
1313 /* move on to the next entry */
1314 if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1317 res = getdents64( fd, data, size );
1318 de = (KERNEL_DIRENT64 *)data;
1322 if (last_info) last_info->next = 0;
1323 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1326 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1330 #elif defined HAVE_GETDIRENTRIES
1332 #if _DARWIN_FEATURE_64_BIT_INODE
1334 /* Darwin doesn't provide a version of getdirentries with support for 64-bit
1335 * inodes. When 64-bit inodes are enabled, the getdirentries symbol is mapped
1336 * to _getdirentries_is_not_available_when_64_bit_inodes_are_in_effect so that
1337 * we get link errors if we try to use it. We still need getdirentries, but we
1338 * don't need it to support 64-bit inodes. So, we use the legacy getdirentries
1339 * with 32-bit inodes. We have to be careful to use a corresponding dirent
1342 int darwin_legacy_getdirentries(int, char *, int, long *) __asm("_getdirentries");
1343 #define getdirentries darwin_legacy_getdirentries
1345 struct darwin_legacy_dirent {
1347 __uint16_t d_reclen;
1350 char d_name[__DARWIN_MAXNAMLEN + 1];
1352 #define dirent darwin_legacy_dirent
1356 /***********************************************************************
1357 * wine_getdirentries
1359 * Wrapper for the BSD getdirentries system call to fix a bug in the
1360 * Mac OS X version. For some file systems (at least Apple Filing
1361 * Protocol a.k.a. AFP), getdirentries resets the file position to 0
1362 * when it's about to return 0 (no more entries). So, a subsequent
1363 * getdirentries call starts over at the beginning again, causing an
1366 static inline int wine_getdirentries(int fd, char *buf, int nbytes, long *basep)
1368 int res = getdirentries(fd, buf, nbytes, basep);
1371 lseek(fd, *basep, SEEK_SET);
1376 /***********************************************************************
1377 * read_directory_getdirentries
1379 * Read a directory using the BSD getdirentries system call; helper for NtQueryDirectoryFile.
1381 static int read_directory_getdirentries( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1382 BOOLEAN single_entry, const UNICODE_STRING *mask,
1383 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1386 ULONG_PTR restart_info_pos = 0;
1387 size_t size, initial_size = length;
1388 int res, fake_dot_dot = 1;
1389 char *data, local_buffer[8192];
1391 union file_directory_info *info, *last_info = NULL, *restart_last_info = NULL;
1393 size = initial_size;
1394 data = local_buffer;
1395 if (size > sizeof(local_buffer) && !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1397 io->u.Status = STATUS_NO_MEMORY;
1398 return io->u.Status;
1401 if (restart_scan) lseek( fd, 0, SEEK_SET );
1403 io->u.Status = STATUS_SUCCESS;
1405 /* FIXME: should make sure size is larger than filesystem block size */
1406 res = wine_getdirentries( fd, data, size, &restart_pos );
1409 io->u.Status = FILE_GetNtStatus();
1414 de = (struct dirent *)data;
1418 /* check if we got . and .. from getdirentries */
1421 if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1423 struct dirent *next_de = (struct dirent *)(data + de->d_reclen);
1424 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1427 /* make sure we have enough room for both entries */
1430 const ULONG min_info_size = dir_info_size( class, 1 ) + dir_info_size( class, 2 );
1431 if (length < min_info_size || single_entry)
1433 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1440 if ((info = append_entry( buffer, io, length, ".", NULL, mask, class )))
1442 if ((info = append_entry( buffer, io, length, "..", NULL, mask, class )))
1445 restart_last_info = last_info;
1446 restart_info_pos = io->Information;
1448 /* check if we still have enough space for the largest possible entry */
1449 if (last_info && io->Information + max_dir_info_size(class) > length)
1451 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1459 res -= de->d_reclen;
1461 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1462 ((info = append_entry( buffer, io, length, de->d_name, NULL, mask, class ))))
1465 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1467 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1468 if (restart_info_pos) /* if we have a complete read already, return it */
1470 io->u.Status = STATUS_SUCCESS;
1471 io->Information = restart_info_pos;
1472 last_info = restart_last_info;
1475 /* otherwise restart from the start with a smaller size */
1476 size = (char *)de - data;
1478 io->Information = 0;
1482 /* if we have to return but the buffer contains more data, restart with a smaller size */
1483 if (res > 0 && (single_entry || io->Information + max_dir_info_size(class) > length))
1485 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1486 size = (char *)de - data;
1487 io->Information = restart_info_pos;
1488 last_info = restart_last_info;
1492 /* move on to the next entry */
1495 de = (struct dirent *)((char *)de + de->d_reclen);
1498 if (size < initial_size) break; /* already restarted once, give up now */
1499 size = min( size, length - io->Information );
1500 /* if size is too small don't bother to continue */
1501 if (size < max_dir_info_size(class) && last_info) break;
1502 restart_last_info = last_info;
1503 restart_info_pos = io->Information;
1505 res = wine_getdirentries( fd, data, size, &restart_pos );
1506 de = (struct dirent *)data;
1509 if (last_info) last_info->next = 0;
1510 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1513 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1517 #if _DARWIN_FEATURE_64_BIT_INODE
1518 #undef getdirentries
1522 #endif /* HAVE_GETDIRENTRIES */
1525 /***********************************************************************
1526 * read_directory_readdir
1528 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1530 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1531 BOOLEAN single_entry, const UNICODE_STRING *mask,
1532 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1535 off_t i, old_pos = 0;
1537 union file_directory_info *info, *last_info = NULL;
1539 if (!(dir = opendir( "." )))
1541 io->u.Status = FILE_GetNtStatus();
1547 old_pos = lseek( fd, 0, SEEK_CUR );
1548 /* skip the right number of entries */
1549 for (i = 0; i < old_pos - 2; i++)
1551 if (!readdir( dir ))
1554 io->u.Status = STATUS_NO_MORE_FILES;
1559 io->u.Status = STATUS_SUCCESS;
1564 info = append_entry( buffer, io, length, ".", NULL, mask, class );
1565 else if (old_pos == 1)
1566 info = append_entry( buffer, io, length, "..", NULL, mask, class );
1567 else if ((de = readdir( dir )))
1569 if (strcmp( de->d_name, "." ) && strcmp( de->d_name, ".." ))
1570 info = append_entry( buffer, io, length, de->d_name, NULL, mask, class );
1580 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1582 old_pos--; /* restore pos to previous entry */
1585 if (single_entry) break;
1586 /* check if we still have enough space for the largest possible entry */
1587 if (io->Information + max_dir_info_size(class) > length) break;
1591 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
1594 if (last_info) last_info->next = 0;
1595 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1598 /***********************************************************************
1599 * read_directory_stat
1601 * Read a single file from a directory by determining whether the file
1602 * identified by mask exists using stat.
1604 static int read_directory_stat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1605 BOOLEAN single_entry, const UNICODE_STRING *mask,
1606 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1608 int unix_len, ret, used_default;
1612 TRACE("trying optimisation for file %s\n", debugstr_us( mask ));
1614 unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
1615 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
1617 io->u.Status = STATUS_NO_MEMORY;
1620 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
1621 NULL, &used_default );
1622 if (ret > 0 && !used_default)
1627 lseek( fd, 0, SEEK_SET );
1629 else if (lseek( fd, 0, SEEK_CUR ) != 0)
1631 io->u.Status = STATUS_NO_MORE_FILES;
1636 ret = stat( unix_name, &st );
1639 union file_directory_info *info = append_entry( buffer, io, length, unix_name, NULL, NULL, class );
1643 if (io->u.Status != STATUS_BUFFER_OVERFLOW) lseek( fd, 1, SEEK_CUR );
1645 else io->u.Status = STATUS_NO_MORE_FILES;
1651 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1653 TRACE("returning %d\n", ret);
1659 static inline WCHAR *mempbrkW( const WCHAR *ptr, const WCHAR *accept, size_t n )
1662 for (end = ptr + n; ptr < end; ptr++) if (strchrW( accept, *ptr )) return (WCHAR *)ptr;
1666 /******************************************************************************
1667 * NtQueryDirectoryFile [NTDLL.@]
1668 * ZwQueryDirectoryFile [NTDLL.@]
1670 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
1671 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
1672 PIO_STATUS_BLOCK io,
1673 PVOID buffer, ULONG length,
1674 FILE_INFORMATION_CLASS info_class,
1675 BOOLEAN single_entry,
1676 PUNICODE_STRING mask,
1677 BOOLEAN restart_scan )
1679 int cwd, fd, needs_close;
1680 static const WCHAR wszWildcards[] = { '*','?',0 };
1682 TRACE("(%p %p %p %p %p %p 0x%08x 0x%08x 0x%08x %s 0x%08x\n",
1683 handle, event, apc_routine, apc_context, io, buffer,
1684 length, info_class, single_entry, debugstr_us(mask),
1687 if (event || apc_routine)
1689 FIXME( "Unsupported yet option\n" );
1690 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1694 case FileDirectoryInformation:
1695 case FileBothDirectoryInformation:
1696 case FileFullDirectoryInformation:
1697 case FileIdBothDirectoryInformation:
1698 case FileIdFullDirectoryInformation:
1699 if (length < dir_info_size( info_class, 1 )) return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
1702 FIXME( "Unsupported file info class %d\n", info_class );
1703 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1706 if ((io->u.Status = server_get_unix_fd( handle, FILE_LIST_DIRECTORY, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
1707 return io->u.Status;
1709 io->Information = 0;
1711 RtlEnterCriticalSection( &dir_section );
1713 if (show_dot_files == -1) init_options();
1715 cwd = open( ".", O_RDONLY );
1716 if (fchdir( fd ) != -1)
1720 curdir.dev = st.st_dev;
1721 curdir.ino = st.st_ino;
1722 #ifdef VFAT_IOCTL_READDIR_BOTH
1723 if ((read_directory_vfat( fd, io, buffer, length, single_entry,
1724 mask, restart_scan, info_class )) != -1) goto done;
1726 if (mask && !mempbrkW( mask->Buffer, wszWildcards, mask->Length / sizeof(WCHAR) ) &&
1727 read_directory_stat( fd, io, buffer, length, single_entry,
1728 mask, restart_scan, info_class ) != -1) goto done;
1730 if ((read_directory_getdents( fd, io, buffer, length, single_entry,
1731 mask, restart_scan, info_class )) != -1) goto done;
1732 #elif defined HAVE_GETDIRENTRIES
1733 if ((read_directory_getdirentries( fd, io, buffer, length, single_entry,
1734 mask, restart_scan, info_class )) != -1) goto done;
1736 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan, info_class );
1739 if (cwd == -1 || fchdir( cwd ) == -1) chdir( "/" );
1741 else io->u.Status = FILE_GetNtStatus();
1743 RtlLeaveCriticalSection( &dir_section );
1745 if (needs_close) close( fd );
1746 if (cwd != -1) close( cwd );
1747 TRACE( "=> %x (%ld)\n", io->u.Status, io->Information );
1748 return io->u.Status;
1752 /***********************************************************************
1755 * Find a file in a directory the hard way, by doing a case-insensitive search.
1756 * The file found is appended to unix_name at pos.
1757 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
1759 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
1760 int check_case, int *is_win_dir )
1762 WCHAR buffer[MAX_DIR_ENTRY_LEN];
1768 int ret, used_default, is_name_8_dot_3;
1770 /* try a shortcut for this directory */
1772 unix_name[pos++] = '/';
1773 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
1774 NULL, &used_default );
1775 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
1776 /* so it cannot match the file we are looking for */
1777 if (ret >= 0 && !used_default)
1779 unix_name[pos + ret] = 0;
1780 if (!stat( unix_name, &st ))
1782 if (is_win_dir) *is_win_dir = is_same_file( &windir, &st );
1783 return STATUS_SUCCESS;
1786 if (check_case) goto not_found; /* we want an exact match */
1788 if (pos > 1) unix_name[pos - 1] = 0;
1789 else unix_name[1] = 0; /* keep the initial slash */
1791 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
1793 str.Buffer = (WCHAR *)name;
1794 str.Length = length * sizeof(WCHAR);
1795 str.MaximumLength = str.Length;
1796 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
1798 /* now look for it through the directory */
1800 #ifdef VFAT_IOCTL_READDIR_BOTH
1801 if (is_name_8_dot_3)
1803 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
1808 RtlEnterCriticalSection( &dir_section );
1809 if ((de = start_vfat_ioctl( fd )))
1811 unix_name[pos - 1] = '/';
1812 while (de[0].d_reclen)
1814 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1815 size_t len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1816 de[0].d_name[len] = 0;
1817 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1818 de[1].d_name[len] = 0;
1820 if (de[1].d_name[0])
1822 ret = ntdll_umbstowcs( 0, de[1].d_name, strlen(de[1].d_name),
1823 buffer, MAX_DIR_ENTRY_LEN );
1824 if (ret == length && !memicmpW( buffer, name, length))
1826 strcpy( unix_name + pos, de[1].d_name );
1827 RtlLeaveCriticalSection( &dir_section );
1832 ret = ntdll_umbstowcs( 0, de[0].d_name, strlen(de[0].d_name),
1833 buffer, MAX_DIR_ENTRY_LEN );
1834 if (ret == length && !memicmpW( buffer, name, length))
1836 strcpy( unix_name + pos,
1837 de[1].d_name[0] ? de[1].d_name : de[0].d_name );
1838 RtlLeaveCriticalSection( &dir_section );
1842 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1)
1844 RtlLeaveCriticalSection( &dir_section );
1850 RtlLeaveCriticalSection( &dir_section );
1853 /* fall through to normal handling */
1855 #endif /* VFAT_IOCTL_READDIR_BOTH */
1857 if (!(dir = opendir( unix_name )))
1859 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
1860 else return FILE_GetNtStatus();
1862 unix_name[pos - 1] = '/';
1863 str.Buffer = buffer;
1864 str.MaximumLength = sizeof(buffer);
1865 while ((de = readdir( dir )))
1867 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
1868 if (ret == length && !memicmpW( buffer, name, length ))
1870 strcpy( unix_name + pos, de->d_name );
1875 if (!is_name_8_dot_3) continue;
1877 str.Length = ret * sizeof(WCHAR);
1878 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1880 WCHAR short_nameW[12];
1881 ret = hash_short_file_name( &str, short_nameW );
1882 if (ret == length && !memicmpW( short_nameW, name, length ))
1884 strcpy( unix_name + pos, de->d_name );
1891 goto not_found; /* avoid warning */
1894 unix_name[pos - 1] = 0;
1895 return STATUS_OBJECT_PATH_NOT_FOUND;
1898 if (is_win_dir && !stat( unix_name, &st )) *is_win_dir = is_same_file( &windir, &st );
1899 return STATUS_SUCCESS;
1905 static const WCHAR catrootW[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t',0};
1906 static const WCHAR catroot2W[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t','2',0};
1907 static const WCHAR driversstoreW[] = {'s','y','s','t','e','m','3','2','\\','d','r','i','v','e','r','s','s','t','o','r','e',0};
1908 static const WCHAR driversetcW[] = {'s','y','s','t','e','m','3','2','\\','d','r','i','v','e','r','s','\\','e','t','c',0};
1909 static const WCHAR logfilesW[] = {'s','y','s','t','e','m','3','2','\\','l','o','g','f','i','l','e','s',0};
1910 static const WCHAR spoolW[] = {'s','y','s','t','e','m','3','2','\\','s','p','o','o','l',0};
1911 static const WCHAR system32W[] = {'s','y','s','t','e','m','3','2',0};
1912 static const WCHAR syswow64W[] = {'s','y','s','w','o','w','6','4',0};
1913 static const WCHAR sysnativeW[] = {'s','y','s','n','a','t','i','v','e',0};
1914 static const WCHAR regeditW[] = {'r','e','g','e','d','i','t','.','e','x','e',0};
1915 static const WCHAR wow_regeditW[] = {'s','y','s','w','o','w','6','4','\\','r','e','g','e','d','i','t','.','e','x','e',0};
1919 const WCHAR *source;
1920 const WCHAR *dos_target;
1921 const char *unix_target;
1924 { catrootW, NULL, NULL },
1925 { catroot2W, NULL, NULL },
1926 { driversstoreW, NULL, NULL },
1927 { driversetcW, NULL, NULL },
1928 { logfilesW, NULL, NULL },
1929 { spoolW, NULL, NULL },
1930 { system32W, syswow64W, NULL },
1931 { sysnativeW, system32W, NULL },
1932 { regeditW, wow_regeditW, NULL }
1935 static unsigned int nb_redirects;
1938 /***********************************************************************
1939 * get_redirect_target
1941 * Find the target unix name for a redirected dir.
1943 static const char *get_redirect_target( const char *windows_dir, const WCHAR *name )
1945 int used_default, len, pos, win_len = strlen( windows_dir );
1946 char *unix_name, *unix_target = NULL;
1949 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, win_len + MAX_DIR_ENTRY_LEN + 2 )))
1951 memcpy( unix_name, windows_dir, win_len );
1956 const WCHAR *end, *next;
1958 for (end = name; *end; end++) if (IS_SEPARATOR(*end)) break;
1959 for (next = end; *next; next++) if (!IS_SEPARATOR(*next)) break;
1961 status = find_file_in_dir( unix_name, pos, name, end - name, FALSE, NULL );
1962 if (status == STATUS_OBJECT_PATH_NOT_FOUND && !*next) /* not finding last element is ok */
1964 len = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
1965 MAX_DIR_ENTRY_LEN - (pos - win_len), NULL, &used_default );
1966 if (len > 0 && !used_default)
1968 unix_name[pos] = '/';
1974 if (status) goto done;
1975 pos += strlen( unix_name + pos );
1979 if ((unix_target = RtlAllocateHeap( GetProcessHeap(), 0, pos - win_len )))
1980 memcpy( unix_target, unix_name + win_len + 1, pos - win_len );
1983 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1988 /***********************************************************************
1991 static void init_redirects(void)
1993 UNICODE_STRING nt_name;
1994 ANSI_STRING unix_name;
1999 if (!RtlDosPathNameToNtPathName_U( windows_dir.Buffer, &nt_name, NULL, NULL ))
2001 ERR( "can't convert %s\n", debugstr_us(&windows_dir) );
2004 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
2005 RtlFreeUnicodeString( &nt_name );
2008 ERR( "cannot open %s (%x)\n", debugstr_us(&windows_dir), status );
2011 if (!stat( unix_name.Buffer, &st ))
2013 windir.dev = st.st_dev;
2014 windir.ino = st.st_ino;
2015 nb_redirects = sizeof(redirects) / sizeof(redirects[0]);
2016 for (i = 0; i < nb_redirects; i++)
2018 if (!redirects[i].dos_target) continue;
2019 redirects[i].unix_target = get_redirect_target( unix_name.Buffer, redirects[i].dos_target );
2020 TRACE( "%s -> %s\n", debugstr_w(redirects[i].source), redirects[i].unix_target );
2023 RtlFreeAnsiString( &unix_name );
2028 /***********************************************************************
2031 * Check if path matches a redirect name. If yes, return matched length.
2033 static int match_redirect( const WCHAR *path, int len, const WCHAR *redir, int check_case )
2037 while (i < len && *redir)
2039 if (IS_SEPARATOR(path[i]))
2041 if (*redir++ != '\\') return 0;
2042 while (i < len && IS_SEPARATOR(path[i])) i++;
2043 continue; /* move on to next path component */
2045 else if (check_case)
2047 if (path[i] != *redir) return 0;
2051 if (tolowerW(path[i]) != tolowerW(*redir)) return 0;
2056 if (*redir) return 0;
2057 if (i < len && !IS_SEPARATOR(path[i])) return 0;
2058 while (i < len && IS_SEPARATOR(path[i])) i++;
2063 /***********************************************************************
2066 * Retrieve the Unix path corresponding to a redirected path if any.
2068 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, int check_case )
2073 for (i = 0; i < nb_redirects; i++)
2075 if ((len = match_redirect( name, length, redirects[i].source, check_case )))
2077 if (!redirects[i].unix_target) break;
2078 unix_name[pos++] = '/';
2079 strcpy( unix_name + pos, redirects[i].unix_target );
2088 /* there are no redirects on 64-bit */
2090 static const unsigned int nb_redirects = 0;
2092 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, int check_case )
2099 /***********************************************************************
2100 * DIR_init_windows_dir
2102 void DIR_init_windows_dir( const WCHAR *win, const WCHAR *sys )
2104 /* FIXME: should probably store paths as NT file names */
2106 RtlCreateUnicodeString( &windows_dir, win );
2107 RtlCreateUnicodeString( &system_dir, sys );
2110 if (is_wow64) init_redirects();
2115 /******************************************************************************
2118 * Get the Unix path of a DOS device.
2120 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
2122 const char *config_dir = wine_get_config_dir();
2124 char *unix_name, *new_name, *dev;
2128 /* make sure the device name is ASCII */
2129 for (i = 0; i < name_len; i++)
2130 if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
2132 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
2134 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2135 return STATUS_NO_MEMORY;
2137 strcpy( unix_name, config_dir );
2138 strcat( unix_name, "/dosdevices/" );
2139 dev = unix_name + strlen(unix_name);
2141 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
2144 /* special case for drive devices */
2145 if (name_len == 2 && dev[1] == ':')
2153 if (!stat( unix_name, &st ))
2155 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
2156 unix_name_ret->Buffer = unix_name;
2157 unix_name_ret->Length = strlen(unix_name);
2158 unix_name_ret->MaximumLength = unix_len;
2159 return STATUS_SUCCESS;
2163 /* now try some defaults for it */
2164 if (!strcmp( dev, "aux" ))
2166 strcpy( dev, "com1" );
2169 if (!strcmp( dev, "prn" ))
2171 strcpy( dev, "lpt1" );
2174 if (!strcmp( dev, "nul" ))
2176 strcpy( unix_name, "/dev/null" );
2177 dev = NULL; /* last try */
2182 if (dev[1] == ':' && dev[2] == ':') /* drive device */
2184 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
2185 new_name = get_default_drive_device( unix_name );
2187 else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( atoi(dev + 3 ));
2188 else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( atoi(dev + 3 ));
2190 if (!new_name) break;
2192 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2193 unix_name = new_name;
2194 unix_len = strlen(unix_name) + 1;
2195 dev = NULL; /* last try */
2197 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2198 return STATUS_BAD_DEVICE_TYPE;
2202 /* return the length of the DOS namespace prefix if any */
2203 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
2205 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
2206 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
2208 if (name->Length > sizeof(nt_prefixW) &&
2209 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
2210 return sizeof(nt_prefixW) / sizeof(WCHAR);
2212 if (name->Length > sizeof(dosdev_prefixW) &&
2213 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
2214 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
2220 /******************************************************************************
2223 * Helper for nt_to_unix_file_name
2225 static NTSTATUS lookup_unix_name( const WCHAR *name, int name_len, char **buffer, int unix_len, int pos,
2226 UINT disposition, BOOLEAN check_case )
2229 int ret, used_default, len;
2231 char *unix_name = *buffer;
2232 const BOOL redirect = nb_redirects && ntdll_get_thread_data()->wow64_redir;
2234 /* try a shortcut first */
2236 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
2237 NULL, &used_default );
2239 while (name_len && IS_SEPARATOR(*name))
2245 if (ret >= 0 && !used_default) /* if we used the default char the name didn't convert properly */
2248 unix_name[pos + ret] = 0;
2249 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
2250 if (!redirect || (!strstr( unix_name, "/windows/") && strncmp( unix_name, "windows/", 8 )))
2252 if (!stat( unix_name, &st ))
2254 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
2255 if (disposition == FILE_CREATE)
2256 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
2257 return STATUS_SUCCESS;
2262 if (!name_len) /* empty name -> drive root doesn't exist */
2263 return STATUS_OBJECT_PATH_NOT_FOUND;
2264 if (check_case && !redirect && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
2265 return STATUS_OBJECT_NAME_NOT_FOUND;
2267 /* now do it component by component */
2271 const WCHAR *end, *next;
2275 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
2277 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
2278 name_len -= next - name;
2280 /* grow the buffer if needed */
2282 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
2285 unix_len += 2 * MAX_DIR_ENTRY_LEN;
2286 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
2287 return STATUS_NO_MEMORY;
2288 unix_name = *buffer = new_name;
2291 status = find_file_in_dir( unix_name, pos, name, end - name,
2292 check_case, redirect ? &is_win_dir : NULL );
2294 /* if this is the last element, not finding it is not necessarily fatal */
2297 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
2299 status = STATUS_OBJECT_NAME_NOT_FOUND;
2300 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
2302 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2303 MAX_DIR_ENTRY_LEN, NULL, &used_default );
2304 if (ret > 0 && !used_default)
2306 unix_name[pos] = '/';
2307 unix_name[pos + 1 + ret] = 0;
2308 status = STATUS_NO_SUCH_FILE;
2313 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
2315 status = STATUS_OBJECT_NAME_COLLISION;
2319 if (status != STATUS_SUCCESS) break;
2321 pos += strlen( unix_name + pos );
2324 if (is_win_dir && (len = get_redirect_path( unix_name, pos, name, name_len, check_case )))
2328 pos += strlen( unix_name + pos );
2329 TRACE( "redirecting -> %s + %s\n", debugstr_a(unix_name), debugstr_w(name) );
2337 /******************************************************************************
2338 * nt_to_unix_file_name_attr
2340 NTSTATUS nt_to_unix_file_name_attr( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name_ret,
2343 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2344 enum server_fd_type type;
2345 int old_cwd, root_fd, needs_close;
2346 const WCHAR *name, *p;
2348 int name_len, unix_len;
2350 BOOLEAN check_case = !(attr->Attributes & OBJ_CASE_INSENSITIVE);
2352 if (!attr->RootDirectory) /* without root dir fall back to normal lookup */
2353 return wine_nt_to_unix_file_name( attr->ObjectName, unix_name_ret, disposition, check_case );
2355 name = attr->ObjectName->Buffer;
2356 name_len = attr->ObjectName->Length / sizeof(WCHAR);
2358 if (name_len && IS_SEPARATOR(name[0])) return STATUS_INVALID_PARAMETER;
2360 /* check for invalid characters */
2361 for (p = name; p < name + name_len; p++)
2362 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2364 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
2365 unix_len += MAX_DIR_ENTRY_LEN + 3;
2366 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2367 return STATUS_NO_MEMORY;
2370 if (!(status = server_get_unix_fd( attr->RootDirectory, FILE_READ_DATA, &root_fd,
2371 &needs_close, &type, NULL )))
2373 if (type != FD_TYPE_DIR)
2375 if (needs_close) close( root_fd );
2376 status = STATUS_BAD_DEVICE_TYPE;
2380 RtlEnterCriticalSection( &dir_section );
2381 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2383 status = lookup_unix_name( name, name_len, &unix_name, unix_len, 1,
2384 disposition, check_case );
2385 if (fchdir( old_cwd ) == -1) chdir( "/" );
2387 else status = FILE_GetNtStatus();
2388 RtlLeaveCriticalSection( &dir_section );
2389 if (old_cwd != -1) close( old_cwd );
2390 if (needs_close) close( root_fd );
2393 else if (status == STATUS_OBJECT_TYPE_MISMATCH) status = STATUS_BAD_DEVICE_TYPE;
2395 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
2397 TRACE( "%s -> %s\n", debugstr_us(attr->ObjectName), debugstr_a(unix_name) );
2398 unix_name_ret->Buffer = unix_name;
2399 unix_name_ret->Length = strlen(unix_name);
2400 unix_name_ret->MaximumLength = unix_len;
2404 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
2405 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2411 /******************************************************************************
2412 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
2414 * Convert a file name from NT namespace to Unix namespace.
2416 * If disposition is not FILE_OPEN or FILE_OVERWRITE, the last path
2417 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
2418 * returned, but the unix name is still filled in properly.
2420 NTSTATUS CDECL wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
2421 UINT disposition, BOOLEAN check_case )
2423 static const WCHAR unixW[] = {'u','n','i','x'};
2424 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2426 NTSTATUS status = STATUS_SUCCESS;
2427 const char *config_dir = wine_get_config_dir();
2428 const WCHAR *name, *p;
2431 int pos, ret, name_len, unix_len, prefix_len, used_default;
2432 WCHAR prefix[MAX_DIR_ENTRY_LEN];
2433 BOOLEAN is_unix = FALSE;
2435 name = nameW->Buffer;
2436 name_len = nameW->Length / sizeof(WCHAR);
2438 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2440 if (!(pos = get_dos_prefix_len( nameW )))
2441 return STATUS_BAD_DEVICE_TYPE; /* no DOS prefix, assume NT native name */
2446 /* check for sub-directory */
2447 for (pos = 0; pos < name_len; pos++)
2449 if (IS_SEPARATOR(name[pos])) break;
2450 if (name[pos] < 32 || strchrW( invalid_charsW, name[pos] ))
2451 return STATUS_OBJECT_NAME_INVALID;
2453 if (pos > MAX_DIR_ENTRY_LEN)
2454 return STATUS_OBJECT_NAME_INVALID;
2456 if (pos == name_len) /* no subdir, plain DOS device */
2457 return get_dos_device( name, name_len, unix_name_ret );
2459 for (prefix_len = 0; prefix_len < pos; prefix_len++)
2460 prefix[prefix_len] = tolowerW(name[prefix_len]);
2463 name_len -= prefix_len;
2465 /* check for invalid characters (all chars except 0 are valid for unix) */
2466 is_unix = (prefix_len == 4 && !memcmp( prefix, unixW, sizeof(unixW) ));
2469 for (p = name; p < name + name_len; p++)
2470 if (!*p) return STATUS_OBJECT_NAME_INVALID;
2475 for (p = name; p < name + name_len; p++)
2476 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2479 unix_len = ntdll_wcstoumbs( 0, prefix, prefix_len, NULL, 0, NULL, NULL );
2480 unix_len += ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
2481 unix_len += MAX_DIR_ENTRY_LEN + 3;
2482 unix_len += strlen(config_dir) + sizeof("/dosdevices/");
2483 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2484 return STATUS_NO_MEMORY;
2485 strcpy( unix_name, config_dir );
2486 strcat( unix_name, "/dosdevices/" );
2487 pos = strlen(unix_name);
2489 ret = ntdll_wcstoumbs( 0, prefix, prefix_len, unix_name + pos, unix_len - pos - 1,
2490 NULL, &used_default );
2491 if (!ret || used_default)
2493 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2494 return STATUS_OBJECT_NAME_INVALID;
2498 /* check if prefix exists (except for DOS drives to avoid extra stat calls) */
2500 if (prefix_len != 2 || prefix[1] != ':')
2503 if (lstat( unix_name, &st ) == -1 && errno == ENOENT)
2507 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2508 return STATUS_BAD_DEVICE_TYPE;
2510 pos = 0; /* fall back to unix root */
2514 status = lookup_unix_name( name, name_len, &unix_name, unix_len, pos, disposition, check_case );
2515 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
2517 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
2518 unix_name_ret->Buffer = unix_name;
2519 unix_name_ret->Length = strlen(unix_name);
2520 unix_name_ret->MaximumLength = unix_len;
2524 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
2525 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2531 /******************************************************************
2532 * RtlWow64EnableFsRedirection (NTDLL.@)
2534 NTSTATUS WINAPI RtlWow64EnableFsRedirection( BOOLEAN enable )
2536 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
2537 ntdll_get_thread_data()->wow64_redir = enable;
2538 return STATUS_SUCCESS;
2542 /******************************************************************
2543 * RtlWow64EnableFsRedirectionEx (NTDLL.@)
2545 NTSTATUS WINAPI RtlWow64EnableFsRedirectionEx( ULONG disable, ULONG *old_value )
2547 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
2548 *old_value = !ntdll_get_thread_data()->wow64_redir;
2549 ntdll_get_thread_data()->wow64_redir = !disable;
2550 return STATUS_SUCCESS;
2554 /******************************************************************
2555 * RtlDoesFileExists_U (NTDLL.@)
2557 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
2559 UNICODE_STRING nt_name;
2560 FILE_BASIC_INFORMATION basic_info;
2561 OBJECT_ATTRIBUTES attr;
2564 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
2566 attr.Length = sizeof(attr);
2567 attr.RootDirectory = 0;
2568 attr.ObjectName = &nt_name;
2569 attr.Attributes = OBJ_CASE_INSENSITIVE;
2570 attr.SecurityDescriptor = NULL;
2571 attr.SecurityQualityOfService = NULL;
2573 ret = NtQueryAttributesFile(&attr, &basic_info) == STATUS_SUCCESS;
2575 RtlFreeUnicodeString( &nt_name );
2580 /***********************************************************************
2581 * DIR_unmount_device
2583 * Unmount the specified device.
2585 NTSTATUS DIR_unmount_device( HANDLE handle )
2588 int unix_fd, needs_close;
2590 if (!(status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )))
2593 char *mount_point = NULL;
2595 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2596 status = STATUS_INVALID_PARAMETER;
2599 if ((mount_point = get_device_mount_point( st.st_rdev )))
2602 static const char umount[] = "diskutil unmount >/dev/null 2>&1 ";
2604 static const char umount[] = "umount >/dev/null 2>&1 ";
2606 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
2609 strcpy( cmd, umount );
2610 strcat( cmd, mount_point );
2612 RtlFreeHeap( GetProcessHeap(), 0, cmd );
2614 /* umount will fail to release the loop device since we still have
2615 a handle to it, so we release it here */
2616 if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
2619 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
2622 if (needs_close) close( unix_fd );
2628 /******************************************************************************
2631 * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
2632 * Returned value must be freed by caller.
2634 NTSTATUS DIR_get_unix_cwd( char **cwd )
2636 int old_cwd, unix_fd, needs_close;
2641 RtlAcquirePebLock();
2643 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
2644 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
2646 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
2648 if (!(handle = curdir->Handle))
2650 UNICODE_STRING dirW;
2651 OBJECT_ATTRIBUTES attr;
2654 if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
2656 status = STATUS_OBJECT_NAME_INVALID;
2659 attr.Length = sizeof(attr);
2660 attr.RootDirectory = 0;
2661 attr.Attributes = OBJ_CASE_INSENSITIVE;
2662 attr.ObjectName = &dirW;
2663 attr.SecurityDescriptor = NULL;
2664 attr.SecurityQualityOfService = NULL;
2666 status = NtOpenFile( &handle, 0, &attr, &io, 0,
2667 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
2668 RtlFreeUnicodeString( &dirW );
2669 if (status != STATUS_SUCCESS) goto done;
2672 if ((status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )) == STATUS_SUCCESS)
2674 RtlEnterCriticalSection( &dir_section );
2676 if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
2678 unsigned int size = 512;
2682 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2684 status = STATUS_NO_MEMORY;
2687 if (getcwd( *cwd, size )) break;
2688 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
2689 if (errno != ERANGE)
2691 status = STATUS_OBJECT_PATH_INVALID;
2696 if (fchdir( old_cwd ) == -1) chdir( "/" );
2698 else status = FILE_GetNtStatus();
2700 RtlLeaveCriticalSection( &dir_section );
2701 if (old_cwd != -1) close( old_cwd );
2702 if (needs_close) close( unix_fd );
2704 if (!curdir->Handle) NtClose( handle );
2707 RtlReleasePebLock();
2711 struct read_changes_info
2716 PIO_APC_ROUTINE apc;
2720 /* callback for ioctl user APC */
2721 static void WINAPI read_changes_user_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
2723 struct read_changes_info *info = arg;
2724 if (info->apc) info->apc( info->apc_arg, io, reserved );
2725 RtlFreeHeap( GetProcessHeap(), 0, info );
2728 static NTSTATUS read_changes_apc( void *user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
2730 struct read_changes_info *info = user;
2731 char path[PATH_MAX];
2732 NTSTATUS ret = STATUS_SUCCESS;
2735 SERVER_START_REQ( read_change )
2737 req->handle = wine_server_obj_handle( info->FileHandle );
2738 wine_server_set_reply( req, path, PATH_MAX );
2739 ret = wine_server_call( req );
2740 action = reply->action;
2741 len = wine_server_reply_size( reply );
2745 if (ret == STATUS_SUCCESS && info->Buffer &&
2746 (info->BufferSize > (sizeof (FILE_NOTIFY_INFORMATION) + len*sizeof(WCHAR))))
2748 PFILE_NOTIFY_INFORMATION pfni;
2750 pfni = info->Buffer;
2752 /* convert to an NT style path */
2753 for (i=0; i<len; i++)
2757 len = ntdll_umbstowcs( 0, path, len, pfni->FileName,
2758 info->BufferSize - sizeof (*pfni) );
2760 pfni->NextEntryOffset = 0;
2761 pfni->Action = action;
2762 pfni->FileNameLength = len * sizeof (WCHAR);
2763 pfni->FileName[len] = 0;
2764 len = sizeof (*pfni) - sizeof (DWORD) + pfni->FileNameLength;
2768 ret = STATUS_NOTIFY_ENUM_DIR;
2772 iosb->u.Status = ret;
2773 iosb->Information = len;
2774 *apc = read_changes_user_apc;
2778 #define FILE_NOTIFY_ALL ( \
2779 FILE_NOTIFY_CHANGE_FILE_NAME | \
2780 FILE_NOTIFY_CHANGE_DIR_NAME | \
2781 FILE_NOTIFY_CHANGE_ATTRIBUTES | \
2782 FILE_NOTIFY_CHANGE_SIZE | \
2783 FILE_NOTIFY_CHANGE_LAST_WRITE | \
2784 FILE_NOTIFY_CHANGE_LAST_ACCESS | \
2785 FILE_NOTIFY_CHANGE_CREATION | \
2786 FILE_NOTIFY_CHANGE_SECURITY )
2788 /******************************************************************************
2789 * NtNotifyChangeDirectoryFile [NTDLL.@]
2792 NtNotifyChangeDirectoryFile( HANDLE FileHandle, HANDLE Event,
2793 PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext,
2794 PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer,
2795 ULONG BufferSize, ULONG CompletionFilter, BOOLEAN WatchTree )
2797 struct read_changes_info *info;
2799 ULONG_PTR cvalue = ApcRoutine ? 0 : (ULONG_PTR)ApcContext;
2801 TRACE("%p %p %p %p %p %p %u %u %d\n",
2802 FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock,
2803 Buffer, BufferSize, CompletionFilter, WatchTree );
2806 return STATUS_ACCESS_VIOLATION;
2808 if (CompletionFilter == 0 || (CompletionFilter & ~FILE_NOTIFY_ALL))
2809 return STATUS_INVALID_PARAMETER;
2811 info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof *info );
2813 return STATUS_NO_MEMORY;
2815 info->FileHandle = FileHandle;
2816 info->Buffer = Buffer;
2817 info->BufferSize = BufferSize;
2818 info->apc = ApcRoutine;
2819 info->apc_arg = ApcContext;
2821 SERVER_START_REQ( read_directory_changes )
2823 req->filter = CompletionFilter;
2824 req->want_data = (Buffer != NULL);
2825 req->subtree = WatchTree;
2826 req->async.handle = wine_server_obj_handle( FileHandle );
2827 req->async.callback = wine_server_client_ptr( read_changes_apc );
2828 req->async.iosb = wine_server_client_ptr( IoStatusBlock );
2829 req->async.arg = wine_server_client_ptr( info );
2830 req->async.event = wine_server_obj_handle( Event );
2831 req->async.cvalue = cvalue;
2832 status = wine_server_call( req );
2836 if (status != STATUS_PENDING)
2837 RtlFreeHeap( GetProcessHeap(), 0, info );