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
65 #include "ntdll_misc.h"
66 #include "wine/unicode.h"
67 #include "wine/server.h"
68 #include "wine/library.h"
69 #include "wine/debug.h"
71 WINE_DEFAULT_DEBUG_CHANNEL(file);
74 #undef VFAT_IOCTL_READDIR_BOTH
79 /* We want the real kernel dirent structure, not the libc one */
84 unsigned short d_reclen;
88 /* Define the VFAT ioctl to get both short and long file names */
89 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
92 # define O_DIRECTORY 0200000 /* must be directory */
101 unsigned short d_reclen;
102 unsigned char d_type;
106 static inline int getdents64( int fd, KERNEL_DIRENT64 *de, unsigned int size )
109 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
111 : "0" (220 /*NR_getdents64*/), "r" (fd), "c" (de), "d" (size)
126 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
127 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
129 #define INVALID_NT_CHARS '*','?','<','>','|','"'
130 #define INVALID_DOS_CHARS INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
132 #define MAX_DIR_ENTRY_LEN 255 /* max length of a directory entry in chars */
134 static int show_dir_symlinks = -1;
135 static int show_dot_files;
137 /* at some point we may want to allow Winelib apps to set this */
138 static const int is_case_sensitive = FALSE;
140 static CRITICAL_SECTION dir_section;
141 static CRITICAL_SECTION_DEBUG critsect_debug =
144 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
145 0, 0, { 0, (DWORD)(__FILE__ ": dir_section") }
147 static CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
150 /* check if a given Unicode char is OK in a DOS short name */
151 static inline BOOL is_invalid_dos_char( WCHAR ch )
153 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
154 if (ch > 0x7f) return TRUE;
155 return strchrW( invalid_chars, ch ) != NULL;
158 /***********************************************************************
159 * get_default_com_device
161 * Return the default device to use for serial ports.
163 static char *get_default_com_device( int num )
167 if (!num || num > 9) return ret;
169 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
172 strcpy( ret, "/dev/ttyS0" );
173 ret[strlen(ret) - 1] = '0' + num - 1;
176 FIXME( "no known default for device com%d\n", num );
182 /***********************************************************************
183 * get_default_lpt_device
185 * Return the default device to use for parallel ports.
187 static char *get_default_lpt_device( int num )
191 if (!num || num > 9) return ret;
193 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
196 strcpy( ret, "/dev/lp0" );
197 ret[strlen(ret) - 1] = '0' + num - 1;
200 FIXME( "no known default for device lpt%d\n", num );
206 /***********************************************************************
207 * parse_mount_entries
209 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
213 #include <sys/vfstab.h>
214 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
217 struct vfstab vfs_entry;
218 struct vfstab *entry=&vfs_entry;
222 while (! getvfsent( f, entry ))
224 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
225 if (!strcmp( entry->vfs_fstype, "nfs" ) ||
226 !strcmp( entry->vfs_fstype, "smbfs" ) ||
227 !strcmp( entry->vfs_fstype, "ncpfs" )) continue;
229 if (stat( entry->vfs_mountp, &st ) == -1) continue;
230 if (st.st_dev != dev || st.st_ino != ino) continue;
231 if (!strcmp( entry->vfs_fstype, "fd" ))
233 if ((device = strstr( entry->vfs_mntopts, "dev=" )))
235 char *p = strchr( device + 4, ',' );
241 return entry->vfs_special;
248 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
250 struct mntent *entry;
254 while ((entry = getmntent( f )))
256 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
257 if (!strcmp( entry->mnt_type, "nfs" ) ||
258 !strcmp( entry->mnt_type, "smbfs" ) ||
259 !strcmp( entry->mnt_type, "ncpfs" )) continue;
261 if (stat( entry->mnt_dir, &st ) == -1) continue;
262 if (st.st_dev != dev || st.st_ino != ino) continue;
263 if (!strcmp( entry->mnt_type, "supermount" ))
265 if ((device = strstr( entry->mnt_opts, "dev=" )))
267 char *p = strchr( device + 4, ',' );
273 return entry->mnt_fsname;
281 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
286 while ((entry = getfsent()))
288 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
289 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
290 !strcmp( entry->fs_vfstype, "smbfs" ) ||
291 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
293 if (stat( entry->fs_file, &st ) == -1) continue;
294 if (st.st_dev != dev || st.st_ino != ino) continue;
295 return entry->fs_spec;
302 #include <sys/mnttab.h>
303 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
306 volatile struct mnttab mntentry;
307 struct mnttab *entry=&mntentry;
312 while (( ! getmntent( f , entry) ))
314 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
315 if (!strcmp( entry->mnt_fstype, "nfs" ) ||
316 !strcmp( entry->mnt_fstype, "smbfs" ) ||
317 !strcmp( entry->mnt_fstype, "ncpfs" )) continue;
319 if (stat( entry->mnt_mountp, &st ) == -1) continue;
320 if (st.st_dev != dev || st.st_ino != ino) continue;
321 if (!strcmp( entry->mnt_fstype, "fd" ))
323 if ((device = strstr( entry->mnt_mntopts, "dev=" )))
325 char *p = strchr( device + 4, ',' );
331 return entry->mnt_special;
337 /***********************************************************************
338 * get_default_drive_device
340 * Return the default device to use for a given drive mount point.
342 static char *get_default_drive_device( const char *root )
352 /* try to open it first to force it to get mounted */
353 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
355 res = fstat( fd, &st );
358 /* now try normal stat just in case */
359 if (res == -1) res = stat( root, &st );
360 if (res == -1) return NULL;
362 RtlEnterCriticalSection( &dir_section );
364 if ((f = fopen( "/etc/mtab", "r" )))
366 device = parse_mount_entries( f, st.st_dev, st.st_ino );
369 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
370 if (!device && (f = fopen( "/etc/fstab", "r" )))
372 device = parse_mount_entries( f, st.st_dev, st.st_ino );
377 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
378 if (ret) strcpy( ret, device );
380 RtlLeaveCriticalSection( &dir_section );
382 #elif defined( __FreeBSD__ )
387 /* try to open it first to force it to get mounted */
388 if ((fd = open( root, O_RDONLY )) != -1)
390 res = fstat( fd, &st );
393 /* now try normal stat just in case */
394 if (res == -1) res = stat( root, &st );
395 if (res == -1) return NULL;
397 RtlEnterCriticalSection( &dir_section );
399 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
400 * pass NULL. Leave the argument in for symmetry.
402 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
405 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
406 if (ret) strcpy( ret, device );
408 RtlLeaveCriticalSection( &dir_section );
416 /* try to open it first to force it to get mounted */
417 if ((fd = open( root, O_RDONLY )) != -1)
419 res = fstat( fd, &st );
422 /* now try normal stat just in case */
423 if (res == -1) res = stat( root, &st );
424 if (res == -1) return NULL;
426 RtlEnterCriticalSection( &dir_section );
428 if ((f = fopen( "/etc/mnttab", "r" )))
430 device = parse_mount_entries( f, st.st_dev, st.st_ino);
433 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
434 if (!device && (f = fopen( "/etc/vfstab", "r" )))
436 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
441 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
442 if (ret) strcpy( ret, device );
444 RtlLeaveCriticalSection( &dir_section );
446 #elif defined(__APPLE__)
447 struct statfs *mntStat;
453 static const char path_bsd_device[] = "/dev/disk";
456 res = stat( root, &st );
457 if (res == -1) return NULL;
462 RtlEnterCriticalSection( &dir_section );
464 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
466 for (i = 0; i < mntSize && !ret; i++)
468 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
469 if (st.st_dev != dev || st.st_ino != ino) continue;
471 /* FIXME add support for mounted network drive */
472 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
474 /* set return value to the corresponding raw BSD node */
475 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
478 strcpy(ret, "/dev/r");
479 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
483 RtlLeaveCriticalSection( &dir_section );
486 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
492 /***********************************************************************
495 * Initialize the show_dir_symlinks and show_dot_files options.
497 static void init_options(void)
499 static const WCHAR WineW[] = {'M','a','c','h','i','n','e','\\',
500 'S','o','f','t','w','a','r','e','\\',
501 'W','i','n','e','\\','W','i','n','e','\\',
502 'C','o','n','f','i','g','\\','W','i','n','e',0};
503 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
504 static const WCHAR ShowDirSymlinksW[] = {'S','h','o','w','D','i','r','S','y','m','l','i','n','k','s',0};
508 OBJECT_ATTRIBUTES attr;
509 UNICODE_STRING nameW;
511 show_dot_files = show_dir_symlinks = 0;
513 attr.Length = sizeof(attr);
514 attr.RootDirectory = 0;
515 attr.ObjectName = &nameW;
517 attr.SecurityDescriptor = NULL;
518 attr.SecurityQualityOfService = NULL;
519 RtlInitUnicodeString( &nameW, WineW );
521 /* @@ Wine registry key: HKLM\Software\Wine\Wine\Config\Wine */
522 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
524 RtlInitUnicodeString( &nameW, ShowDotFilesW );
525 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
527 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
528 show_dot_files = IS_OPTION_TRUE( str[0] );
530 RtlInitUnicodeString( &nameW, ShowDirSymlinksW );
531 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
533 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
534 show_dir_symlinks = IS_OPTION_TRUE( str[0] );
541 /***********************************************************************
544 * Check if the specified file should be hidden based on its name and the show dot files option.
546 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
550 if (show_dir_symlinks == -1) init_options();
551 if (show_dot_files) return FALSE;
553 end = p = name->Buffer + name->Length/sizeof(WCHAR);
554 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
555 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
556 if (p == end || *p != '.') return FALSE;
557 /* make sure it isn't '.' or '..' */
558 if (p + 1 == end) return FALSE;
559 if (p[1] == '.' && p + 2 == end) return FALSE;
564 /***********************************************************************
565 * hash_short_file_name
567 * Transform a Unix file name into a hashed DOS name. If the name is a valid
568 * DOS name, it is converted to upper-case; otherwise it is replaced by a
569 * hashed version that fits in 8.3 format.
570 * 'buffer' must be at least 12 characters long.
571 * Returns length of short name in bytes; short name is NOT null-terminated.
573 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
575 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
577 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
582 /* Compute the hash code of the file name */
583 /* If you know something about hash functions, feel free to */
584 /* insert a better algorithm here... */
585 if (!is_case_sensitive)
587 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
588 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
589 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
593 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
594 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
595 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
598 /* Find last dot for start of the extension */
599 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
601 /* Copy first 4 chars, replacing invalid chars with '_' */
602 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
604 if (p == end || p == ext) break;
605 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
607 /* Pad to 5 chars with '~' */
608 while (i-- >= 0) *dst++ = '~';
610 /* Insert hash code converted to 3 ASCII chars */
611 *dst++ = hash_chars[(hash >> 10) & 0x1f];
612 *dst++ = hash_chars[(hash >> 5) & 0x1f];
613 *dst++ = hash_chars[hash & 0x1f];
615 /* Copy the first 3 chars of the extension (if any) */
619 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
620 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
626 /***********************************************************************
629 * Check a long file name against a mask.
631 * Tests (done in W95 DOS shell - case insensitive):
632 * *.txt test1.test.txt *
634 * *.t??????.t* test1.ta.tornado.txt *
635 * *tornado* test1.ta.tornado.txt *
636 * t*t test1.ta.tornado.txt *
638 * ?est??? test1.txt -
639 * *test1.txt* test1.txt *
640 * h?l?o*t.dat hellothisisatest.dat *
642 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
645 const WCHAR *name = name_str->Buffer;
646 const WCHAR *mask = mask_str->Buffer;
647 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
648 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
649 const WCHAR *lastjoker = NULL;
650 const WCHAR *next_to_retry = NULL;
652 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
654 while (name < name_end && mask < mask_end)
660 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
661 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
664 /* skip to the next match after the joker(s) */
665 if (is_case_sensitive)
666 while (name < name_end && (*name != *mask)) name++;
668 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
669 next_to_retry = name;
676 if (is_case_sensitive) mismatch = (*mask != *name);
677 else mismatch = (toupperW(*mask) != toupperW(*name));
683 if (mask == mask_end)
685 if (name == name_end) return TRUE;
686 if (lastjoker) mask = lastjoker;
689 else /* mismatch ! */
691 if (lastjoker) /* we had an '*', so we can try unlimitedly */
695 /* this scan sequence was a mismatch, so restart
696 * 1 char after the first char we checked last time */
698 name = next_to_retry;
700 else return FALSE; /* bad luck */
705 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
706 mask++; /* Ignore trailing '.' or '*' in mask */
707 return (name == name_end && mask == mask_end);
711 /***********************************************************************
714 * helper for NtQueryDirectoryFile
716 static FILE_BOTH_DIR_INFORMATION *append_entry( void *info_ptr, ULONG *pos, ULONG max_length,
717 const char *long_name, const char *short_name,
718 const UNICODE_STRING *mask )
720 FILE_BOTH_DIR_INFORMATION *info;
721 int i, long_len, short_len, total_len;
723 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
724 WCHAR short_nameW[12];
727 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
728 if (long_len == -1) return NULL;
730 str.Buffer = long_nameW;
731 str.Length = long_len * sizeof(WCHAR);
732 str.MaximumLength = sizeof(long_nameW);
736 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
737 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
738 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
740 else /* generate a short name if necessary */
745 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
746 short_len = hash_short_file_name( &str, short_nameW );
749 TRACE( "long %s short %s mask %s\n",
750 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
752 if (mask && !match_filename( &str, mask ))
754 if (!short_len) return NULL; /* no short name to match */
755 str.Buffer = short_nameW;
756 str.Length = short_len * sizeof(WCHAR);
757 str.MaximumLength = sizeof(short_nameW);
758 if (!match_filename( &str, mask )) return NULL;
761 total_len = (sizeof(*info) - sizeof(info->FileName) + long_len*sizeof(WCHAR) + 3) & ~3;
762 info = (FILE_BOTH_DIR_INFORMATION *)((char *)info_ptr + *pos);
764 if (*pos + total_len > max_length) total_len = max_length - *pos;
766 info->FileAttributes = 0;
767 if (lstat( long_name, &st ) == -1) return NULL;
768 if (S_ISLNK( st.st_mode ))
770 if (stat( long_name, &st ) == -1) return NULL;
771 if (S_ISDIR( st.st_mode ))
773 if (!show_dir_symlinks) return NULL;
774 info->FileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT;
778 info->NextEntryOffset = total_len;
779 info->FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
781 RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
782 RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
783 RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
784 RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
786 if (S_ISDIR(st.st_mode))
788 info->EndOfFile.QuadPart = info->AllocationSize.QuadPart = 0;
789 info->FileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
793 info->EndOfFile.QuadPart = st.st_size;
794 info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
795 info->FileAttributes |= FILE_ATTRIBUTE_ARCHIVE;
798 if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
799 info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
801 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
802 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
804 info->EaSize = 0; /* FIXME */
805 info->ShortNameLength = short_len * sizeof(WCHAR);
806 for (i = 0; i < short_len; i++) info->ShortName[i] = toupperW(short_nameW[i]);
807 info->FileNameLength = long_len * sizeof(WCHAR);
808 memcpy( info->FileName, long_nameW,
809 min( info->FileNameLength, total_len-sizeof(*info)+sizeof(info->FileName) ));
816 /***********************************************************************
817 * read_directory_vfat
819 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
821 #ifdef VFAT_IOCTL_READDIR_BOTH
822 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
823 BOOLEAN single_entry, const UNICODE_STRING *mask,
824 BOOLEAN restart_scan )
829 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
830 static const unsigned int max_dir_info_size = sizeof(*info) + (MAX_DIR_ENTRY_LEN-1) * sizeof(WCHAR);
832 io->u.Status = STATUS_SUCCESS;
834 if (restart_scan) lseek( fd, 0, SEEK_SET );
836 if (length < max_dir_info_size) /* we may have to return a partial entry here */
838 off_t old_pos = lseek( fd, 0, SEEK_CUR );
840 /* Set d_reclen to 65535 to work around an AFS kernel bug */
841 de[0].d_reclen = 65535;
842 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
843 if (res == -1 && errno != ENOENT) return -1; /* VFAT ioctl probably not supported */
844 if (!res && de[0].d_reclen == 65535) return -1; /* AFS bug */
848 if (!de[0].d_reclen) break;
850 info = append_entry( buffer, &io->Information, length,
851 de[1].d_name, de[0].d_name, mask );
853 info = append_entry( buffer, &io->Information, length,
854 de[0].d_name, NULL, mask );
858 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
860 io->u.Status = STATUS_BUFFER_OVERFLOW;
861 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
865 old_pos = lseek( fd, 0, SEEK_CUR );
866 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
869 else /* we'll only return full entries, no need to worry about overflow */
871 /* Set d_reclen to 65535 to work around an AFS kernel bug */
872 de[0].d_reclen = 65535;
873 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
874 if (res == -1 && errno != ENOENT) return -1; /* VFAT ioctl probably not supported */
875 if (!res && de[0].d_reclen == 65535) return -1; /* AFS bug */
879 if (!de[0].d_reclen) break;
881 info = append_entry( buffer, &io->Information, length,
882 de[1].d_name, de[0].d_name, mask );
884 info = append_entry( buffer, &io->Information, length,
885 de[0].d_name, NULL, mask );
889 if (single_entry) break;
890 /* check if we still have enough space for the largest possible entry */
891 if (io->Information + max_dir_info_size > length) break;
893 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
897 if (last_info) last_info->NextEntryOffset = 0;
898 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
901 #endif /* VFAT_IOCTL_READDIR_BOTH */
904 /***********************************************************************
905 * read_directory_getdents
907 * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
910 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
911 BOOLEAN single_entry, const UNICODE_STRING *mask,
912 BOOLEAN restart_scan )
915 size_t size = length;
917 char local_buffer[8192];
918 KERNEL_DIRENT64 *data, *de;
919 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
920 static const unsigned int max_dir_info_size = sizeof(*info) + (MAX_DIR_ENTRY_LEN-1) * sizeof(WCHAR);
922 if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
924 size = sizeof(local_buffer);
925 data = (KERNEL_DIRENT64 *)local_buffer;
928 if (restart_scan) lseek( fd, 0, SEEK_SET );
929 else if (length < max_dir_info_size) /* we may have to return a partial entry here */
931 old_pos = lseek( fd, 0, SEEK_CUR );
932 if (old_pos == -1 && errno == ENOENT)
934 io->u.Status = STATUS_NO_MORE_FILES;
940 io->u.Status = STATUS_SUCCESS;
942 res = getdents64( fd, data, size );
947 io->u.Status = FILE_GetNtStatus();
958 info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask );
962 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
964 io->u.Status = STATUS_BUFFER_OVERFLOW;
965 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
968 /* check if we still have enough space for the largest possible entry */
969 if (single_entry || io->Information + max_dir_info_size > length)
971 if (res > 0) lseek( fd, de->d_off, SEEK_SET ); /* set pos to next entry */
976 /* move on to the next entry */
977 if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
980 res = getdents64( fd, data, size );
985 if (last_info) last_info->NextEntryOffset = 0;
986 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
989 if ((char *)data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
992 #endif /* USE_GETDENTS */
995 /***********************************************************************
996 * read_directory_readdir
998 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1000 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1001 BOOLEAN single_entry, const UNICODE_STRING *mask,
1002 BOOLEAN restart_scan )
1005 off_t i, old_pos = 0;
1007 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
1008 static const unsigned int max_dir_info_size = sizeof(*info) + (MAX_DIR_ENTRY_LEN-1) * sizeof(WCHAR);
1010 if (!(dir = opendir( "." )))
1012 io->u.Status = FILE_GetNtStatus();
1018 old_pos = lseek( fd, 0, SEEK_CUR );
1019 /* skip the right number of entries */
1020 for (i = 0; i < old_pos; i++)
1022 if (!readdir( dir ))
1025 io->u.Status = STATUS_NO_MORE_FILES;
1030 io->u.Status = STATUS_SUCCESS;
1032 while ((de = readdir( dir )))
1035 info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask );
1039 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1041 io->u.Status = STATUS_BUFFER_OVERFLOW;
1042 old_pos--; /* restore pos to previous entry */
1045 if (single_entry) break;
1046 /* check if we still have enough space for the largest possible entry */
1047 if (io->Information + max_dir_info_size > length) break;
1051 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
1054 if (last_info) last_info->NextEntryOffset = 0;
1055 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1059 /******************************************************************************
1060 * NtQueryDirectoryFile [NTDLL.@]
1061 * ZwQueryDirectoryFile [NTDLL.@]
1063 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
1064 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
1065 PIO_STATUS_BLOCK io,
1066 PVOID buffer, ULONG length,
1067 FILE_INFORMATION_CLASS info_class,
1068 BOOLEAN single_entry,
1069 PUNICODE_STRING mask,
1070 BOOLEAN restart_scan )
1074 TRACE("(%p %p %p %p %p %p 0x%08lx 0x%08x 0x%08x %s 0x%08x\n",
1075 handle, event, apc_routine, apc_context, io, buffer,
1076 length, info_class, single_entry, debugstr_us(mask),
1079 if (length < sizeof(FILE_BOTH_DIR_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
1081 if (event || apc_routine)
1083 FIXME( "Unsupported yet option\n" );
1084 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1086 if (info_class != FileBothDirectoryInformation)
1088 FIXME( "Unsupported file info class %d\n", info_class );
1089 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1092 if ((io->u.Status = wine_server_handle_to_fd( handle, GENERIC_READ, &fd, NULL )) != STATUS_SUCCESS)
1093 return io->u.Status;
1095 io->Information = 0;
1097 RtlEnterCriticalSection( &dir_section );
1099 if (show_dir_symlinks == -1) init_options();
1101 if ((cwd = open(".", O_RDONLY)) != -1 && fchdir( fd ) != -1)
1103 #ifdef VFAT_IOCTL_READDIR_BOTH
1104 if ((read_directory_vfat( fd, io, buffer, length, single_entry, mask, restart_scan )) == -1)
1107 if ((read_directory_getdents( fd, io, buffer, length, single_entry, mask, restart_scan )) == -1)
1109 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan );
1111 if (fchdir( cwd ) == -1) chdir( "/" );
1113 else io->u.Status = FILE_GetNtStatus();
1115 RtlLeaveCriticalSection( &dir_section );
1117 wine_server_release_fd( handle, fd );
1118 if (cwd != -1) close( cwd );
1119 TRACE( "=> %lx (%ld)\n", io->u.Status, io->Information );
1120 return io->u.Status;
1124 /***********************************************************************
1127 * Find a file in a directory the hard way, by doing a case-insensitive search.
1128 * The file found is appended to unix_name at pos.
1129 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
1131 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
1134 WCHAR buffer[MAX_DIR_ENTRY_LEN];
1140 int ret, used_default, is_name_8_dot_3;
1142 /* try a shortcut for this directory */
1144 unix_name[pos++] = '/';
1145 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
1146 NULL, &used_default );
1147 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
1148 /* so it cannot match the file we are looking for */
1149 if (ret >= 0 && !used_default)
1151 unix_name[pos + ret] = 0;
1152 if (!stat( unix_name, &st )) return STATUS_SUCCESS;
1154 if (check_case) goto not_found; /* we want an exact match */
1156 if (pos > 1) unix_name[pos - 1] = 0;
1157 else unix_name[1] = 0; /* keep the initial slash */
1159 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
1161 str.Buffer = (WCHAR *)name;
1162 str.Length = length * sizeof(WCHAR);
1163 str.MaximumLength = str.Length;
1164 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
1166 /* now look for it through the directory */
1168 #ifdef VFAT_IOCTL_READDIR_BOTH
1169 if (is_name_8_dot_3)
1171 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
1174 KERNEL_DIRENT de[2];
1176 /* Set d_reclen to 65535 to work around an AFS kernel bug */
1177 de[0].d_reclen = 65535;
1178 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) != -1 &&
1179 de[0].d_reclen != 65535)
1181 unix_name[pos - 1] = '/';
1184 if (!de[0].d_reclen) break;
1186 if (de[1].d_name[0])
1188 ret = ntdll_umbstowcs( 0, de[1].d_name, strlen(de[1].d_name),
1189 buffer, MAX_DIR_ENTRY_LEN );
1190 if (ret == length && !memicmpW( buffer, name, length))
1192 strcpy( unix_name + pos, de[1].d_name );
1194 return STATUS_SUCCESS;
1197 ret = ntdll_umbstowcs( 0, de[0].d_name, strlen(de[0].d_name),
1198 buffer, MAX_DIR_ENTRY_LEN );
1199 if (ret == length && !memicmpW( buffer, name, length))
1201 strcpy( unix_name + pos,
1202 de[1].d_name[0] ? de[1].d_name : de[0].d_name );
1204 return STATUS_SUCCESS;
1206 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1)
1215 /* fall through to normal handling */
1217 #endif /* VFAT_IOCTL_READDIR_BOTH */
1219 if (!(dir = opendir( unix_name )))
1221 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
1222 else return FILE_GetNtStatus();
1224 unix_name[pos - 1] = '/';
1225 str.Buffer = buffer;
1226 str.MaximumLength = sizeof(buffer);
1227 while ((de = readdir( dir )))
1229 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
1230 if (ret == length && !memicmpW( buffer, name, length ))
1232 strcpy( unix_name + pos, de->d_name );
1234 return STATUS_SUCCESS;
1237 if (!is_name_8_dot_3) continue;
1239 str.Length = ret * sizeof(WCHAR);
1240 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1242 WCHAR short_nameW[12];
1243 ret = hash_short_file_name( &str, short_nameW );
1244 if (ret == length && !memicmpW( short_nameW, name, length ))
1246 strcpy( unix_name + pos, de->d_name );
1248 return STATUS_SUCCESS;
1253 goto not_found; /* avoid warning */
1256 unix_name[pos - 1] = 0;
1257 return STATUS_OBJECT_PATH_NOT_FOUND;
1261 /******************************************************************************
1264 * Get the Unix path of a DOS device.
1266 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
1268 const char *config_dir = wine_get_config_dir();
1270 char *unix_name, *new_name, *dev;
1274 /* make sure the device name is ASCII */
1275 for (i = 0; i < name_len; i++)
1276 if (name[i] <= 32 || name[i] >= 127) return STATUS_OBJECT_NAME_NOT_FOUND;
1278 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
1280 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1281 return STATUS_NO_MEMORY;
1283 strcpy( unix_name, config_dir );
1284 strcat( unix_name, "/dosdevices/" );
1285 dev = unix_name + strlen(unix_name);
1287 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
1290 /* special case for drive devices */
1291 if (name_len == 2 && dev[1] == ':')
1299 if (!stat( unix_name, &st ))
1301 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
1302 unix_name_ret->Buffer = unix_name;
1303 unix_name_ret->Length = strlen(unix_name);
1304 unix_name_ret->MaximumLength = unix_len;
1305 return STATUS_SUCCESS;
1309 /* now try some defaults for it */
1310 if (!strcmp( dev, "aux" ))
1312 strcpy( dev, "com1" );
1315 if (!strcmp( dev, "prn" ))
1317 strcpy( dev, "lpt1" );
1320 if (!strcmp( dev, "nul" ))
1322 strcpy( unix_name, "/dev/null" );
1323 dev = NULL; /* last try */
1328 if (dev[1] == ':' && dev[2] == ':') /* drive device */
1330 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
1331 new_name = get_default_drive_device( unix_name );
1333 else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( dev[3] - '0' );
1334 else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( dev[3] - '0' );
1336 if (!new_name) break;
1338 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1339 unix_name = new_name;
1340 unix_len = strlen(unix_name) + 1;
1341 dev = NULL; /* last try */
1343 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1344 return STATUS_OBJECT_NAME_NOT_FOUND;
1348 /* return the length of the DOS namespace prefix if any */
1349 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
1351 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
1352 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
1354 if (name->Length > sizeof(nt_prefixW) &&
1355 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
1356 return sizeof(nt_prefixW) / sizeof(WCHAR);
1358 if (name->Length > sizeof(dosdev_prefixW) &&
1359 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
1360 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
1366 /******************************************************************************
1367 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
1369 * Convert a file name from NT namespace to Unix namespace.
1371 * If disposition is not FILE_OPEN or FILE_OVERWRITTE, the last path
1372 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
1373 * returned, but the unix name is still filled in properly.
1375 NTSTATUS wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
1376 UINT disposition, BOOLEAN check_case )
1378 static const WCHAR uncW[] = {'U','N','C','\\'};
1379 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
1381 NTSTATUS status = STATUS_SUCCESS;
1382 const char *config_dir = wine_get_config_dir();
1383 const WCHAR *name, *p;
1386 int pos, ret, name_len, unix_len, used_default;
1388 name = nameW->Buffer;
1389 name_len = nameW->Length / sizeof(WCHAR);
1391 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
1393 if ((pos = get_dos_prefix_len( nameW )))
1395 BOOLEAN is_unc = FALSE;
1400 /* check for UNC prefix */
1401 if (name_len > 4 && !memicmpW( name, uncW, 4 ))
1409 /* check for a drive letter with path */
1410 if (name_len < 3 || !isalphaW(name[0]) || name[1] != ':' || !IS_SEPARATOR(name[2]))
1412 /* not a drive with path, try other DOS devices */
1413 return get_dos_device( name, name_len, unix_name_ret );
1415 name += 2; /* skip drive letter */
1419 /* check for invalid characters */
1420 for (p = name; p < name + name_len; p++)
1421 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
1423 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1424 unix_len += MAX_DIR_ENTRY_LEN + 3;
1425 unix_len += strlen(config_dir) + sizeof("/dosdevices/") + 3;
1426 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1427 return STATUS_NO_MEMORY;
1428 strcpy( unix_name, config_dir );
1429 strcat( unix_name, "/dosdevices/" );
1430 pos = strlen(unix_name);
1433 strcpy( unix_name + pos, "unc" );
1438 unix_name[pos++] = tolowerW( name[-2] );
1439 unix_name[pos++] = ':';
1443 else /* no DOS prefix, assume NT native name, map directly to Unix */
1445 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_NAME_INVALID;
1446 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1447 unix_len += MAX_DIR_ENTRY_LEN + 3;
1448 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1449 return STATUS_NO_MEMORY;
1453 /* try a shortcut first */
1455 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
1456 NULL, &used_default );
1458 while (name_len && IS_SEPARATOR(*name))
1464 if (ret > 0 && !used_default) /* if we used the default char the name didn't convert properly */
1467 unix_name[pos + ret] = 0;
1468 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
1469 if (!stat( unix_name, &st ))
1471 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
1472 if (disposition == FILE_CREATE)
1473 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
1478 if (!name_len) /* empty name -> drive root doesn't exist */
1480 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1481 return STATUS_OBJECT_PATH_NOT_FOUND;
1483 if (check_case && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
1485 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1486 return STATUS_OBJECT_NAME_NOT_FOUND;
1489 /* now do it component by component */
1493 const WCHAR *end, *next;
1496 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
1498 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
1499 name_len -= next - name;
1501 /* grow the buffer if needed */
1503 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
1506 unix_len += 2 * MAX_DIR_ENTRY_LEN;
1507 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
1509 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1510 return STATUS_NO_MEMORY;
1512 unix_name = new_name;
1515 status = find_file_in_dir( unix_name, pos, name, end - name, check_case );
1517 /* if this is the last element, not finding it is not necessarily fatal */
1520 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
1522 status = STATUS_OBJECT_NAME_NOT_FOUND;
1523 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
1525 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
1526 MAX_DIR_ENTRY_LEN, NULL, &used_default );
1527 if (ret > 0 && !used_default)
1529 unix_name[pos] = '/';
1530 unix_name[pos + 1 + ret] = 0;
1531 status = STATUS_NO_SUCH_FILE;
1536 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
1538 status = STATUS_OBJECT_NAME_COLLISION;
1542 if (status != STATUS_SUCCESS)
1544 /* couldn't find it at all, fail */
1545 WARN( "%s not found in %s\n", debugstr_w(name), unix_name );
1546 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1550 pos += strlen( unix_name + pos );
1554 WARN( "%s -> %s required a case-insensitive search\n",
1555 debugstr_us(nameW), debugstr_a(unix_name) );
1558 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
1559 unix_name_ret->Buffer = unix_name;
1560 unix_name_ret->Length = strlen(unix_name);
1561 unix_name_ret->MaximumLength = unix_len;
1566 /******************************************************************
1567 * RtlDoesFileExists_U (NTDLL.@)
1569 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
1571 UNICODE_STRING nt_name;
1572 ANSI_STRING unix_name;
1575 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
1576 ret = (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ) == STATUS_SUCCESS);
1577 if (ret) RtlFreeAnsiString( &unix_name );
1578 RtlFreeUnicodeString( &nt_name );