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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include "wine/port.h"
26 #include <sys/types.h>
37 #ifdef HAVE_SYS_STAT_H
38 # include <sys/stat.h>
40 #ifdef HAVE_SYS_IOCTL_H
41 #include <sys/ioctl.h>
43 #ifdef HAVE_LINUX_IOCTL_H
44 #include <linux/ioctl.h>
46 #ifdef HAVE_SYS_PARAM_H
47 #include <sys/param.h>
49 #ifdef HAVE_SYS_MOUNT_H
50 #include <sys/mount.h>
57 #define NONAMELESSUNION
58 #define NONAMELESSSTRUCT
63 #include "ntdll_misc.h"
64 #include "wine/unicode.h"
65 #include "wine/server.h"
66 #include "wine/library.h"
67 #include "wine/debug.h"
69 WINE_DEFAULT_DEBUG_CHANNEL(file);
72 #undef VFAT_IOCTL_READDIR_BOTH
77 /* We want the real kernel dirent structure, not the libc one */
82 unsigned short d_reclen;
86 /* Define the VFAT ioctl to get both short and long file names */
87 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
90 # define O_DIRECTORY 0200000 /* must be directory */
99 unsigned short d_reclen;
100 unsigned char d_type;
104 static inline int getdents64( int fd, KERNEL_DIRENT64 *de, unsigned int size )
107 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
109 : "0" (220 /*NR_getdents64*/), "r" (fd), "c" (de), "d" (size)
124 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
125 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
127 #define INVALID_NT_CHARS '*','?','<','>','|','"'
128 #define INVALID_DOS_CHARS INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
130 #define MAX_DIR_ENTRY_LEN 255 /* max length of a directory entry in chars */
132 static int show_dir_symlinks = -1;
133 static int show_dot_files;
135 /* at some point we may want to allow Winelib apps to set this */
136 static const int is_case_sensitive = FALSE;
138 static RTL_CRITICAL_SECTION dir_section;
139 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
142 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
143 0, 0, { 0, (DWORD)(__FILE__ ": dir_section") }
145 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
148 /* check if a given Unicode char is OK in a DOS short name */
149 static inline BOOL is_invalid_dos_char( WCHAR ch )
151 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
152 if (ch > 0x7f) return TRUE;
153 return strchrW( invalid_chars, ch ) != NULL;
156 /***********************************************************************
157 * get_default_com_device
159 * Return the default device to use for serial ports.
161 static char *get_default_com_device( int num )
165 if (!num || num > 9) return ret;
167 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
170 strcpy( ret, "/dev/ttyS0" );
171 ret[strlen(ret) - 1] = '0' + num - 1;
174 FIXME( "no known default for device com%d\n", num );
180 /***********************************************************************
181 * get_default_lpt_device
183 * Return the default device to use for parallel ports.
185 static char *get_default_lpt_device( int num )
189 if (!num || num > 9) return ret;
191 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
194 strcpy( ret, "/dev/lp0" );
195 ret[strlen(ret) - 1] = '0' + num - 1;
198 FIXME( "no known default for device lpt%d\n", num );
204 /***********************************************************************
205 * parse_mount_entries
207 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
211 #include <sys/vfstab.h>
212 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
215 struct vfstab vfs_entry;
216 struct vfstab *entry=&vfs_entry;
220 while (! getvfsent( f, entry ))
222 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
223 if (!strcmp( entry->vfs_fstype, "nfs" ) ||
224 !strcmp( entry->vfs_fstype, "smbfs" ) ||
225 !strcmp( entry->vfs_fstype, "ncpfs" )) continue;
227 if (stat( entry->vfs_mountp, &st ) == -1) continue;
228 if (st.st_dev != dev || st.st_ino != ino) continue;
229 if (!strcmp( entry->vfs_fstype, "fd" ))
231 if ((device = strstr( entry->vfs_mntopts, "dev=" )))
233 char *p = strchr( device + 4, ',' );
239 return entry->vfs_special;
246 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
248 struct mntent *entry;
252 while ((entry = getmntent( f )))
254 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
255 if (!strcmp( entry->mnt_type, "nfs" ) ||
256 !strcmp( entry->mnt_type, "smbfs" ) ||
257 !strcmp( entry->mnt_type, "ncpfs" )) continue;
259 if (stat( entry->mnt_dir, &st ) == -1) continue;
260 if (st.st_dev != dev || st.st_ino != ino) continue;
261 if (!strcmp( entry->mnt_type, "supermount" ))
263 if ((device = strstr( entry->mnt_opts, "dev=" )))
265 char *p = strchr( device + 4, ',' );
271 return entry->mnt_fsname;
279 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
284 while ((entry = getfsent()))
286 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
287 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
288 !strcmp( entry->fs_vfstype, "smbfs" ) ||
289 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
291 if (stat( entry->fs_file, &st ) == -1) continue;
292 if (st.st_dev != dev || st.st_ino != ino) continue;
293 return entry->fs_spec;
300 #include <sys/mnttab.h>
301 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
304 volatile struct mnttab mntentry;
305 struct mnttab *entry=&mntentry;
310 while (( ! getmntent( f , entry) ))
312 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
313 if (!strcmp( entry->mnt_fstype, "nfs" ) ||
314 !strcmp( entry->mnt_fstype, "smbfs" ) ||
315 !strcmp( entry->mnt_fstype, "ncpfs" )) continue;
317 if (stat( entry->mnt_mountp, &st ) == -1) continue;
318 if (st.st_dev != dev || st.st_ino != ino) continue;
319 if (!strcmp( entry->mnt_fstype, "fd" ))
321 if ((device = strstr( entry->mnt_mntopts, "dev=" )))
323 char *p = strchr( device + 4, ',' );
329 return entry->mnt_special;
335 /***********************************************************************
336 * get_default_drive_device
338 * Return the default device to use for a given drive mount point.
340 static char *get_default_drive_device( const char *root )
350 /* try to open it first to force it to get mounted */
351 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
353 res = fstat( fd, &st );
356 /* now try normal stat just in case */
357 if (res == -1) res = stat( root, &st );
358 if (res == -1) return NULL;
360 RtlEnterCriticalSection( &dir_section );
362 if ((f = fopen( "/etc/mtab", "r" )))
364 device = parse_mount_entries( f, st.st_dev, st.st_ino );
367 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
368 if (!device && (f = fopen( "/etc/fstab", "r" )))
370 device = parse_mount_entries( f, st.st_dev, st.st_ino );
375 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
376 if (ret) strcpy( ret, device );
378 RtlLeaveCriticalSection( &dir_section );
380 #elif defined( __FreeBSD__ )
385 /* try to open it first to force it to get mounted */
386 if ((fd = open( root, O_RDONLY )) != -1)
388 res = fstat( fd, &st );
391 /* now try normal stat just in case */
392 if (res == -1) res = stat( root, &st );
393 if (res == -1) return NULL;
395 RtlEnterCriticalSection( &dir_section );
397 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
398 * pass NULL. Leave the argument in for symmetry.
400 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
403 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
404 if (ret) strcpy( ret, device );
406 RtlLeaveCriticalSection( &dir_section );
414 /* try to open it first to force it to get mounted */
415 if ((fd = open( root, O_RDONLY )) != -1)
417 res = fstat( fd, &st );
420 /* now try normal stat just in case */
421 if (res == -1) res = stat( root, &st );
422 if (res == -1) return NULL;
424 RtlEnterCriticalSection( &dir_section );
426 if ((f = fopen( "/etc/mnttab", "r" )))
428 device = parse_mount_entries( f, st.st_dev, st.st_ino);
431 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
432 if (!device && (f = fopen( "/etc/vfstab", "r" )))
434 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
439 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
440 if (ret) strcpy( ret, device );
442 RtlLeaveCriticalSection( &dir_section );
444 #elif defined(__APPLE__)
445 struct statfs *mntStat;
451 static const char path_bsd_device[] = "/dev/disk";
454 res = stat( root, &st );
455 if (res == -1) return NULL;
460 RtlEnterCriticalSection( &dir_section );
462 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
464 for (i = 0; i < mntSize && !ret; i++)
466 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
467 if (st.st_dev != dev || st.st_ino != ino) continue;
469 /* FIXME add support for mounted network drive */
470 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
472 /* set return value to the corresponding raw BSD node */
473 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
476 strcpy(ret, "/dev/r");
477 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
481 RtlLeaveCriticalSection( &dir_section );
484 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
490 /***********************************************************************
493 * Initialize the show_dir_symlinks and show_dot_files options.
495 static void init_options(void)
497 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
498 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
499 static const WCHAR ShowDirSymlinksW[] = {'S','h','o','w','D','i','r','S','y','m','l','i','n','k','s',0};
503 OBJECT_ATTRIBUTES attr;
504 UNICODE_STRING nameW;
506 show_dot_files = show_dir_symlinks = 0;
508 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
509 attr.Length = sizeof(attr);
510 attr.RootDirectory = root;
511 attr.ObjectName = &nameW;
513 attr.SecurityDescriptor = NULL;
514 attr.SecurityQualityOfService = NULL;
515 RtlInitUnicodeString( &nameW, WineW );
517 /* @@ Wine registry key: HKCU\Software\Wine */
518 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
520 RtlInitUnicodeString( &nameW, ShowDotFilesW );
521 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
523 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
524 show_dot_files = IS_OPTION_TRUE( str[0] );
526 RtlInitUnicodeString( &nameW, ShowDirSymlinksW );
527 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
529 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
530 show_dir_symlinks = IS_OPTION_TRUE( str[0] );
538 /***********************************************************************
541 * Check if the specified file should be hidden based on its name and the show dot files option.
543 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
547 if (show_dir_symlinks == -1) init_options();
548 if (show_dot_files) return FALSE;
550 end = p = name->Buffer + name->Length/sizeof(WCHAR);
551 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
552 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
553 if (p == end || *p != '.') return FALSE;
554 /* make sure it isn't '.' or '..' */
555 if (p + 1 == end) return FALSE;
556 if (p[1] == '.' && p + 2 == end) return FALSE;
561 /***********************************************************************
562 * hash_short_file_name
564 * Transform a Unix file name into a hashed DOS name. If the name is a valid
565 * DOS name, it is converted to upper-case; otherwise it is replaced by a
566 * hashed version that fits in 8.3 format.
567 * 'buffer' must be at least 12 characters long.
568 * Returns length of short name in bytes; short name is NOT null-terminated.
570 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
572 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
574 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
579 /* Compute the hash code of the file name */
580 /* If you know something about hash functions, feel free to */
581 /* insert a better algorithm here... */
582 if (!is_case_sensitive)
584 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
585 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
586 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
590 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
591 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
592 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
595 /* Find last dot for start of the extension */
596 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
598 /* Copy first 4 chars, replacing invalid chars with '_' */
599 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
601 if (p == end || p == ext) break;
602 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
604 /* Pad to 5 chars with '~' */
605 while (i-- >= 0) *dst++ = '~';
607 /* Insert hash code converted to 3 ASCII chars */
608 *dst++ = hash_chars[(hash >> 10) & 0x1f];
609 *dst++ = hash_chars[(hash >> 5) & 0x1f];
610 *dst++ = hash_chars[hash & 0x1f];
612 /* Copy the first 3 chars of the extension (if any) */
616 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
617 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
623 /***********************************************************************
626 * Check a long file name against a mask.
628 * Tests (done in W95 DOS shell - case insensitive):
629 * *.txt test1.test.txt *
631 * *.t??????.t* test1.ta.tornado.txt *
632 * *tornado* test1.ta.tornado.txt *
633 * t*t test1.ta.tornado.txt *
635 * ?est??? test1.txt -
636 * *test1.txt* test1.txt *
637 * h?l?o*t.dat hellothisisatest.dat *
639 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
642 const WCHAR *name = name_str->Buffer;
643 const WCHAR *mask = mask_str->Buffer;
644 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
645 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
646 const WCHAR *lastjoker = NULL;
647 const WCHAR *next_to_retry = NULL;
649 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
651 while (name < name_end && mask < mask_end)
657 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
658 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
661 /* skip to the next match after the joker(s) */
662 if (is_case_sensitive)
663 while (name < name_end && (*name != *mask)) name++;
665 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
666 next_to_retry = name;
673 if (is_case_sensitive) mismatch = (*mask != *name);
674 else mismatch = (toupperW(*mask) != toupperW(*name));
680 if (mask == mask_end)
682 if (name == name_end) return TRUE;
683 if (lastjoker) mask = lastjoker;
686 else /* mismatch ! */
688 if (lastjoker) /* we had an '*', so we can try unlimitedly */
692 /* this scan sequence was a mismatch, so restart
693 * 1 char after the first char we checked last time */
695 name = next_to_retry;
697 else return FALSE; /* bad luck */
702 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
703 mask++; /* Ignore trailing '.' or '*' in mask */
704 return (name == name_end && mask == mask_end);
708 /***********************************************************************
711 * helper for NtQueryDirectoryFile
713 static FILE_BOTH_DIR_INFORMATION *append_entry( void *info_ptr, ULONG *pos, ULONG max_length,
714 const char *long_name, const char *short_name,
715 const UNICODE_STRING *mask )
717 FILE_BOTH_DIR_INFORMATION *info;
718 int i, long_len, short_len, total_len;
720 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
721 WCHAR short_nameW[12];
724 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
725 if (long_len == -1) return NULL;
727 str.Buffer = long_nameW;
728 str.Length = long_len * sizeof(WCHAR);
729 str.MaximumLength = sizeof(long_nameW);
733 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
734 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
735 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
737 else /* generate a short name if necessary */
742 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
743 short_len = hash_short_file_name( &str, short_nameW );
746 TRACE( "long %s short %s mask %s\n",
747 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
749 if (mask && !match_filename( &str, mask ))
751 if (!short_len) return NULL; /* no short name to match */
752 str.Buffer = short_nameW;
753 str.Length = short_len * sizeof(WCHAR);
754 str.MaximumLength = sizeof(short_nameW);
755 if (!match_filename( &str, mask )) return NULL;
758 total_len = (sizeof(*info) - sizeof(info->FileName) + long_len*sizeof(WCHAR) + 3) & ~3;
759 info = (FILE_BOTH_DIR_INFORMATION *)((char *)info_ptr + *pos);
761 if (*pos + total_len > max_length) total_len = max_length - *pos;
763 info->FileAttributes = 0;
764 if (lstat( long_name, &st ) == -1) return NULL;
765 if (S_ISLNK( st.st_mode ))
767 if (stat( long_name, &st ) == -1) return NULL;
768 if (S_ISDIR( st.st_mode ))
770 if (!show_dir_symlinks) return NULL;
771 info->FileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT;
775 info->NextEntryOffset = total_len;
776 info->FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
778 RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
779 RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
780 RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
781 RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
783 if (S_ISDIR(st.st_mode))
785 info->EndOfFile.QuadPart = info->AllocationSize.QuadPart = 0;
786 info->FileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
790 info->EndOfFile.QuadPart = st.st_size;
791 info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
792 info->FileAttributes |= FILE_ATTRIBUTE_ARCHIVE;
795 if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
796 info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
798 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
799 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
801 info->EaSize = 0; /* FIXME */
802 info->ShortNameLength = short_len * sizeof(WCHAR);
803 for (i = 0; i < short_len; i++) info->ShortName[i] = toupperW(short_nameW[i]);
804 info->FileNameLength = long_len * sizeof(WCHAR);
805 memcpy( info->FileName, long_nameW,
806 min( info->FileNameLength, total_len-sizeof(*info)+sizeof(info->FileName) ));
813 /***********************************************************************
814 * read_directory_vfat
816 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
818 #ifdef VFAT_IOCTL_READDIR_BOTH
819 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
820 BOOLEAN single_entry, const UNICODE_STRING *mask,
821 BOOLEAN restart_scan )
826 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
827 static const unsigned int max_dir_info_size = sizeof(*info) + (MAX_DIR_ENTRY_LEN-1) * sizeof(WCHAR);
829 io->u.Status = STATUS_SUCCESS;
831 if (restart_scan) lseek( fd, 0, SEEK_SET );
833 if (length < max_dir_info_size) /* we may have to return a partial entry here */
835 off_t old_pos = lseek( fd, 0, SEEK_CUR );
837 /* Set d_reclen to 65535 to work around an AFS kernel bug */
838 de[0].d_reclen = 65535;
839 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
840 if (res == -1 && errno != ENOENT) return -1; /* VFAT ioctl probably not supported */
841 if (!res && de[0].d_reclen == 65535) return -1; /* AFS bug */
845 if (!de[0].d_reclen) break;
847 info = append_entry( buffer, &io->Information, length,
848 de[1].d_name, de[0].d_name, mask );
850 info = append_entry( buffer, &io->Information, length,
851 de[0].d_name, NULL, mask );
855 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
857 io->u.Status = STATUS_BUFFER_OVERFLOW;
858 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
862 old_pos = lseek( fd, 0, SEEK_CUR );
863 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
866 else /* we'll only return full entries, no need to worry about overflow */
868 /* Set d_reclen to 65535 to work around an AFS kernel bug */
869 de[0].d_reclen = 65535;
870 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
871 if (res == -1 && errno != ENOENT) return -1; /* VFAT ioctl probably not supported */
872 if (!res && de[0].d_reclen == 65535) return -1; /* AFS bug */
876 if (!de[0].d_reclen) break;
878 info = append_entry( buffer, &io->Information, length,
879 de[1].d_name, de[0].d_name, mask );
881 info = append_entry( buffer, &io->Information, length,
882 de[0].d_name, NULL, mask );
886 if (single_entry) break;
887 /* check if we still have enough space for the largest possible entry */
888 if (io->Information + max_dir_info_size > length) break;
890 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
894 if (last_info) last_info->NextEntryOffset = 0;
895 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
898 #endif /* VFAT_IOCTL_READDIR_BOTH */
901 /***********************************************************************
902 * read_directory_getdents
904 * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
907 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
908 BOOLEAN single_entry, const UNICODE_STRING *mask,
909 BOOLEAN restart_scan )
912 size_t size = length;
914 char local_buffer[8192];
915 KERNEL_DIRENT64 *data, *de;
916 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
917 static const unsigned int max_dir_info_size = sizeof(*info) + (MAX_DIR_ENTRY_LEN-1) * sizeof(WCHAR);
919 if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
921 size = sizeof(local_buffer);
922 data = (KERNEL_DIRENT64 *)local_buffer;
925 if (restart_scan) lseek( fd, 0, SEEK_SET );
926 else if (length < max_dir_info_size) /* we may have to return a partial entry here */
928 old_pos = lseek( fd, 0, SEEK_CUR );
929 if (old_pos == -1 && errno == ENOENT)
931 io->u.Status = STATUS_NO_MORE_FILES;
937 io->u.Status = STATUS_SUCCESS;
939 res = getdents64( fd, data, size );
944 io->u.Status = FILE_GetNtStatus();
955 info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask );
959 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
961 io->u.Status = STATUS_BUFFER_OVERFLOW;
962 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
965 /* check if we still have enough space for the largest possible entry */
966 if (single_entry || io->Information + max_dir_info_size > length)
968 if (res > 0) lseek( fd, de->d_off, SEEK_SET ); /* set pos to next entry */
973 /* move on to the next entry */
974 if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
977 res = getdents64( fd, data, size );
982 if (last_info) last_info->NextEntryOffset = 0;
983 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
986 if ((char *)data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
989 #endif /* USE_GETDENTS */
992 /***********************************************************************
993 * read_directory_readdir
995 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
997 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
998 BOOLEAN single_entry, const UNICODE_STRING *mask,
999 BOOLEAN restart_scan )
1002 off_t i, old_pos = 0;
1004 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
1005 static const unsigned int max_dir_info_size = sizeof(*info) + (MAX_DIR_ENTRY_LEN-1) * sizeof(WCHAR);
1007 if (!(dir = opendir( "." )))
1009 io->u.Status = FILE_GetNtStatus();
1015 old_pos = lseek( fd, 0, SEEK_CUR );
1016 /* skip the right number of entries */
1017 for (i = 0; i < old_pos; i++)
1019 if (!readdir( dir ))
1022 io->u.Status = STATUS_NO_MORE_FILES;
1027 io->u.Status = STATUS_SUCCESS;
1029 while ((de = readdir( dir )))
1032 info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask );
1036 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1038 io->u.Status = STATUS_BUFFER_OVERFLOW;
1039 old_pos--; /* restore pos to previous entry */
1042 if (single_entry) break;
1043 /* check if we still have enough space for the largest possible entry */
1044 if (io->Information + max_dir_info_size > length) break;
1048 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
1051 if (last_info) last_info->NextEntryOffset = 0;
1052 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1056 /******************************************************************************
1057 * NtQueryDirectoryFile [NTDLL.@]
1058 * ZwQueryDirectoryFile [NTDLL.@]
1060 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
1061 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
1062 PIO_STATUS_BLOCK io,
1063 PVOID buffer, ULONG length,
1064 FILE_INFORMATION_CLASS info_class,
1065 BOOLEAN single_entry,
1066 PUNICODE_STRING mask,
1067 BOOLEAN restart_scan )
1071 TRACE("(%p %p %p %p %p %p 0x%08lx 0x%08x 0x%08x %s 0x%08x\n",
1072 handle, event, apc_routine, apc_context, io, buffer,
1073 length, info_class, single_entry, debugstr_us(mask),
1076 if (length < sizeof(FILE_BOTH_DIR_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
1078 if (event || apc_routine)
1080 FIXME( "Unsupported yet option\n" );
1081 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1083 if (info_class != FileBothDirectoryInformation)
1085 FIXME( "Unsupported file info class %d\n", info_class );
1086 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1089 if ((io->u.Status = wine_server_handle_to_fd( handle, GENERIC_READ, &fd, NULL )) != STATUS_SUCCESS)
1090 return io->u.Status;
1092 io->Information = 0;
1094 RtlEnterCriticalSection( &dir_section );
1096 if (show_dir_symlinks == -1) init_options();
1098 if ((cwd = open(".", O_RDONLY)) != -1 && fchdir( fd ) != -1)
1100 #ifdef VFAT_IOCTL_READDIR_BOTH
1101 if ((read_directory_vfat( fd, io, buffer, length, single_entry, mask, restart_scan )) == -1)
1104 if ((read_directory_getdents( fd, io, buffer, length, single_entry, mask, restart_scan )) == -1)
1106 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan );
1108 if (fchdir( cwd ) == -1) chdir( "/" );
1110 else io->u.Status = FILE_GetNtStatus();
1112 RtlLeaveCriticalSection( &dir_section );
1114 wine_server_release_fd( handle, fd );
1115 if (cwd != -1) close( cwd );
1116 TRACE( "=> %lx (%ld)\n", io->u.Status, io->Information );
1117 return io->u.Status;
1121 /***********************************************************************
1124 * Find a file in a directory the hard way, by doing a case-insensitive search.
1125 * The file found is appended to unix_name at pos.
1126 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
1128 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
1131 WCHAR buffer[MAX_DIR_ENTRY_LEN];
1137 int ret, used_default, is_name_8_dot_3;
1139 /* try a shortcut for this directory */
1141 unix_name[pos++] = '/';
1142 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
1143 NULL, &used_default );
1144 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
1145 /* so it cannot match the file we are looking for */
1146 if (ret >= 0 && !used_default)
1148 unix_name[pos + ret] = 0;
1149 if (!stat( unix_name, &st )) return STATUS_SUCCESS;
1151 if (check_case) goto not_found; /* we want an exact match */
1153 if (pos > 1) unix_name[pos - 1] = 0;
1154 else unix_name[1] = 0; /* keep the initial slash */
1156 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
1158 str.Buffer = (WCHAR *)name;
1159 str.Length = length * sizeof(WCHAR);
1160 str.MaximumLength = str.Length;
1161 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
1163 /* now look for it through the directory */
1165 #ifdef VFAT_IOCTL_READDIR_BOTH
1166 if (is_name_8_dot_3)
1168 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
1171 KERNEL_DIRENT de[2];
1173 /* Set d_reclen to 65535 to work around an AFS kernel bug */
1174 de[0].d_reclen = 65535;
1175 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) != -1 &&
1176 de[0].d_reclen != 65535)
1178 unix_name[pos - 1] = '/';
1181 if (!de[0].d_reclen) break;
1183 if (de[1].d_name[0])
1185 ret = ntdll_umbstowcs( 0, de[1].d_name, strlen(de[1].d_name),
1186 buffer, MAX_DIR_ENTRY_LEN );
1187 if (ret == length && !memicmpW( buffer, name, length))
1189 strcpy( unix_name + pos, de[1].d_name );
1191 return STATUS_SUCCESS;
1194 ret = ntdll_umbstowcs( 0, de[0].d_name, strlen(de[0].d_name),
1195 buffer, MAX_DIR_ENTRY_LEN );
1196 if (ret == length && !memicmpW( buffer, name, length))
1198 strcpy( unix_name + pos,
1199 de[1].d_name[0] ? de[1].d_name : de[0].d_name );
1201 return STATUS_SUCCESS;
1203 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1)
1212 /* fall through to normal handling */
1214 #endif /* VFAT_IOCTL_READDIR_BOTH */
1216 if (!(dir = opendir( unix_name )))
1218 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
1219 else return FILE_GetNtStatus();
1221 unix_name[pos - 1] = '/';
1222 str.Buffer = buffer;
1223 str.MaximumLength = sizeof(buffer);
1224 while ((de = readdir( dir )))
1226 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
1227 if (ret == length && !memicmpW( buffer, name, length ))
1229 strcpy( unix_name + pos, de->d_name );
1231 return STATUS_SUCCESS;
1234 if (!is_name_8_dot_3) continue;
1236 str.Length = ret * sizeof(WCHAR);
1237 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1239 WCHAR short_nameW[12];
1240 ret = hash_short_file_name( &str, short_nameW );
1241 if (ret == length && !memicmpW( short_nameW, name, length ))
1243 strcpy( unix_name + pos, de->d_name );
1245 return STATUS_SUCCESS;
1250 goto not_found; /* avoid warning */
1253 unix_name[pos - 1] = 0;
1254 return STATUS_OBJECT_PATH_NOT_FOUND;
1258 /******************************************************************************
1261 * Get the Unix path of a DOS device.
1263 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
1265 const char *config_dir = wine_get_config_dir();
1267 char *unix_name, *new_name, *dev;
1271 /* make sure the device name is ASCII */
1272 for (i = 0; i < name_len; i++)
1273 if (name[i] <= 32 || name[i] >= 127) return STATUS_OBJECT_NAME_NOT_FOUND;
1275 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
1277 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1278 return STATUS_NO_MEMORY;
1280 strcpy( unix_name, config_dir );
1281 strcat( unix_name, "/dosdevices/" );
1282 dev = unix_name + strlen(unix_name);
1284 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
1287 /* special case for drive devices */
1288 if (name_len == 2 && dev[1] == ':')
1296 if (!stat( unix_name, &st ))
1298 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
1299 unix_name_ret->Buffer = unix_name;
1300 unix_name_ret->Length = strlen(unix_name);
1301 unix_name_ret->MaximumLength = unix_len;
1302 return STATUS_SUCCESS;
1306 /* now try some defaults for it */
1307 if (!strcmp( dev, "aux" ))
1309 strcpy( dev, "com1" );
1312 if (!strcmp( dev, "prn" ))
1314 strcpy( dev, "lpt1" );
1317 if (!strcmp( dev, "nul" ))
1319 strcpy( unix_name, "/dev/null" );
1320 dev = NULL; /* last try */
1325 if (dev[1] == ':' && dev[2] == ':') /* drive device */
1327 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
1328 new_name = get_default_drive_device( unix_name );
1330 else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( dev[3] - '0' );
1331 else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( dev[3] - '0' );
1333 if (!new_name) break;
1335 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1336 unix_name = new_name;
1337 unix_len = strlen(unix_name) + 1;
1338 dev = NULL; /* last try */
1340 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1341 return STATUS_OBJECT_NAME_NOT_FOUND;
1345 /* return the length of the DOS namespace prefix if any */
1346 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
1348 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
1349 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
1351 if (name->Length > sizeof(nt_prefixW) &&
1352 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
1353 return sizeof(nt_prefixW) / sizeof(WCHAR);
1355 if (name->Length > sizeof(dosdev_prefixW) &&
1356 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
1357 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
1363 /******************************************************************************
1364 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
1366 * Convert a file name from NT namespace to Unix namespace.
1368 * If disposition is not FILE_OPEN or FILE_OVERWRITTE, the last path
1369 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
1370 * returned, but the unix name is still filled in properly.
1372 NTSTATUS wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
1373 UINT disposition, BOOLEAN check_case )
1375 static const WCHAR uncW[] = {'U','N','C','\\'};
1376 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
1378 NTSTATUS status = STATUS_SUCCESS;
1379 const char *config_dir = wine_get_config_dir();
1380 const WCHAR *name, *p;
1383 int pos, ret, name_len, unix_len, used_default;
1385 name = nameW->Buffer;
1386 name_len = nameW->Length / sizeof(WCHAR);
1388 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
1390 if ((pos = get_dos_prefix_len( nameW )))
1392 BOOLEAN is_unc = FALSE;
1397 /* check for UNC prefix */
1398 if (name_len > 4 && !memicmpW( name, uncW, 4 ))
1406 /* check for a drive letter with path */
1407 if (name_len < 3 || !isalphaW(name[0]) || name[1] != ':' || !IS_SEPARATOR(name[2]))
1409 /* not a drive with path, try other DOS devices */
1410 return get_dos_device( name, name_len, unix_name_ret );
1412 name += 2; /* skip drive letter */
1416 /* check for invalid characters */
1417 for (p = name; p < name + name_len; p++)
1418 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
1420 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1421 unix_len += MAX_DIR_ENTRY_LEN + 3;
1422 unix_len += strlen(config_dir) + sizeof("/dosdevices/") + 3;
1423 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1424 return STATUS_NO_MEMORY;
1425 strcpy( unix_name, config_dir );
1426 strcat( unix_name, "/dosdevices/" );
1427 pos = strlen(unix_name);
1430 strcpy( unix_name + pos, "unc" );
1435 unix_name[pos++] = tolowerW( name[-2] );
1436 unix_name[pos++] = ':';
1440 else /* no DOS prefix, assume NT native name, map directly to Unix */
1442 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_NAME_INVALID;
1443 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1444 unix_len += MAX_DIR_ENTRY_LEN + 3;
1445 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1446 return STATUS_NO_MEMORY;
1450 /* try a shortcut first */
1452 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
1453 NULL, &used_default );
1455 while (name_len && IS_SEPARATOR(*name))
1461 if (ret > 0 && !used_default) /* if we used the default char the name didn't convert properly */
1464 unix_name[pos + ret] = 0;
1465 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
1466 if (!stat( unix_name, &st ))
1468 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
1469 if (disposition == FILE_CREATE)
1470 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
1475 if (!name_len) /* empty name -> drive root doesn't exist */
1477 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1478 return STATUS_OBJECT_PATH_NOT_FOUND;
1480 if (check_case && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
1482 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1483 return STATUS_OBJECT_NAME_NOT_FOUND;
1486 /* now do it component by component */
1490 const WCHAR *end, *next;
1493 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
1495 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
1496 name_len -= next - name;
1498 /* grow the buffer if needed */
1500 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
1503 unix_len += 2 * MAX_DIR_ENTRY_LEN;
1504 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
1506 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1507 return STATUS_NO_MEMORY;
1509 unix_name = new_name;
1512 status = find_file_in_dir( unix_name, pos, name, end - name, check_case );
1514 /* if this is the last element, not finding it is not necessarily fatal */
1517 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
1519 status = STATUS_OBJECT_NAME_NOT_FOUND;
1520 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
1522 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
1523 MAX_DIR_ENTRY_LEN, NULL, &used_default );
1524 if (ret > 0 && !used_default)
1526 unix_name[pos] = '/';
1527 unix_name[pos + 1 + ret] = 0;
1528 status = STATUS_NO_SUCH_FILE;
1533 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
1535 status = STATUS_OBJECT_NAME_COLLISION;
1539 if (status != STATUS_SUCCESS)
1541 /* couldn't find it at all, fail */
1542 WARN( "%s not found in %s\n", debugstr_w(name), unix_name );
1543 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1547 pos += strlen( unix_name + pos );
1551 WARN( "%s -> %s required a case-insensitive search\n",
1552 debugstr_us(nameW), debugstr_a(unix_name) );
1555 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
1556 unix_name_ret->Buffer = unix_name;
1557 unix_name_ret->Length = strlen(unix_name);
1558 unix_name_ret->MaximumLength = unix_len;
1563 /******************************************************************
1564 * RtlDoesFileExists_U (NTDLL.@)
1566 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
1568 UNICODE_STRING nt_name;
1569 ANSI_STRING unix_name;
1572 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
1573 ret = (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ) == STATUS_SUCCESS);
1574 if (ret) RtlFreeAnsiString( &unix_name );
1575 RtlFreeUnicodeString( &nt_name );