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"
26 #include <sys/types.h>
38 #ifdef HAVE_SYS_STAT_H
39 # include <sys/stat.h>
41 #ifdef HAVE_SYS_IOCTL_H
42 #include <sys/ioctl.h>
44 #ifdef HAVE_LINUX_IOCTL_H
45 #include <linux/ioctl.h>
47 #ifdef HAVE_LINUX_MAJOR_H
48 # include <linux/major.h>
50 #ifdef HAVE_SYS_PARAM_H
51 #include <sys/param.h>
53 #ifdef HAVE_SYS_MOUNT_H
54 #include <sys/mount.h>
61 #define NONAMELESSUNION
62 #define NONAMELESSSTRUCT
64 #define WIN32_NO_STATUS
69 #include "ntdll_misc.h"
70 #include "wine/unicode.h"
71 #include "wine/server.h"
72 #include "wine/library.h"
73 #include "wine/debug.h"
75 WINE_DEFAULT_DEBUG_CHANNEL(file);
78 #undef VFAT_IOCTL_READDIR_BOTH
83 /* We want the real kernel dirent structure, not the libc one */
88 unsigned short d_reclen;
92 /* Define the VFAT ioctl to get both short and long file names */
93 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
96 # define O_DIRECTORY 0200000 /* must be directory */
105 unsigned short d_reclen;
106 unsigned char d_type;
110 static inline int getdents64( int fd, KERNEL_DIRENT64 *de, unsigned int size )
113 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
115 : "0" (220 /*NR_getdents64*/), "r" (fd), "c" (de), "d" (size)
130 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
131 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
133 #define INVALID_NT_CHARS '*','?','<','>','|','"'
134 #define INVALID_DOS_CHARS INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
136 #define MAX_DIR_ENTRY_LEN 255 /* max length of a directory entry in chars */
138 static int show_dot_files = -1;
140 /* at some point we may want to allow Winelib apps to set this */
141 static const int is_case_sensitive = FALSE;
143 static RTL_CRITICAL_SECTION dir_section;
144 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
147 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
148 0, 0, { (DWORD_PTR)(__FILE__ ": dir_section") }
150 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
153 /* check if a given Unicode char is OK in a DOS short name */
154 static inline BOOL is_invalid_dos_char( WCHAR ch )
156 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
157 if (ch > 0x7f) return TRUE;
158 return strchrW( invalid_chars, ch ) != NULL;
161 /***********************************************************************
162 * get_default_com_device
164 * Return the default device to use for serial ports.
166 static char *get_default_com_device( int num )
170 if (!num || num > 9) return ret;
172 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
175 strcpy( ret, "/dev/ttyS0" );
176 ret[strlen(ret) - 1] = '0' + num - 1;
179 FIXME( "no known default for device com%d\n", num );
185 /***********************************************************************
186 * get_default_lpt_device
188 * Return the default device to use for parallel ports.
190 static char *get_default_lpt_device( int num )
194 if (!num || num > 9) return ret;
196 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
199 strcpy( ret, "/dev/lp0" );
200 ret[strlen(ret) - 1] = '0' + num - 1;
203 FIXME( "no known default for device lpt%d\n", num );
209 /***********************************************************************
210 * parse_mount_entries
212 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
216 #include <sys/vfstab.h>
217 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
220 struct vfstab vfs_entry;
221 struct vfstab *entry=&vfs_entry;
225 while (! getvfsent( f, entry ))
227 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
228 if (!strcmp( entry->vfs_fstype, "nfs" ) ||
229 !strcmp( entry->vfs_fstype, "smbfs" ) ||
230 !strcmp( entry->vfs_fstype, "ncpfs" )) continue;
232 if (stat( entry->vfs_mountp, &st ) == -1) continue;
233 if (st.st_dev != dev || st.st_ino != ino) continue;
234 if (!strcmp( entry->vfs_fstype, "fd" ))
236 if ((device = strstr( entry->vfs_mntopts, "dev=" )))
238 char *p = strchr( device + 4, ',' );
244 return entry->vfs_special;
251 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
253 struct mntent *entry;
257 while ((entry = getmntent( f )))
259 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
260 if (!strcmp( entry->mnt_type, "nfs" ) ||
261 !strcmp( entry->mnt_type, "smbfs" ) ||
262 !strcmp( entry->mnt_type, "ncpfs" )) continue;
264 if (stat( entry->mnt_dir, &st ) == -1) continue;
265 if (st.st_dev != dev || st.st_ino != ino) continue;
266 if (!strcmp( entry->mnt_type, "supermount" ))
268 if ((device = strstr( entry->mnt_opts, "dev=" )))
270 char *p = strchr( device + 4, ',' );
275 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
277 /* if device is a regular file check for a loop mount */
278 if ((device = strstr( entry->mnt_opts, "loop=" )))
280 char *p = strchr( device + 5, ',' );
286 return entry->mnt_fsname;
292 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
294 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
299 while ((entry = getfsent()))
301 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
302 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
303 !strcmp( entry->fs_vfstype, "smbfs" ) ||
304 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
306 if (stat( entry->fs_file, &st ) == -1) continue;
307 if (st.st_dev != dev || st.st_ino != ino) continue;
308 return entry->fs_spec;
315 #include <sys/mnttab.h>
316 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
319 volatile struct mnttab mntentry;
320 struct mnttab *entry=&mntentry;
325 while (( ! getmntent( f , entry) ))
327 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
328 if (!strcmp( entry->mnt_fstype, "nfs" ) ||
329 !strcmp( entry->mnt_fstype, "smbfs" ) ||
330 !strcmp( entry->mnt_fstype, "ncpfs" )) continue;
332 if (stat( entry->mnt_mountp, &st ) == -1) continue;
333 if (st.st_dev != dev || st.st_ino != ino) continue;
334 if (!strcmp( entry->mnt_fstype, "fd" ))
336 if ((device = strstr( entry->mnt_mntopts, "dev=" )))
338 char *p = strchr( device + 4, ',' );
344 return entry->mnt_special;
350 /***********************************************************************
351 * get_default_drive_device
353 * Return the default device to use for a given drive mount point.
355 static char *get_default_drive_device( const char *root )
365 /* try to open it first to force it to get mounted */
366 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
368 res = fstat( fd, &st );
371 /* now try normal stat just in case */
372 if (res == -1) res = stat( root, &st );
373 if (res == -1) return NULL;
375 RtlEnterCriticalSection( &dir_section );
377 if ((f = fopen( "/etc/mtab", "r" )))
379 device = parse_mount_entries( f, st.st_dev, st.st_ino );
382 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
383 if (!device && (f = fopen( "/etc/fstab", "r" )))
385 device = parse_mount_entries( f, st.st_dev, st.st_ino );
390 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
391 if (ret) strcpy( ret, device );
393 RtlLeaveCriticalSection( &dir_section );
395 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ )
400 /* try to open it first to force it to get mounted */
401 if ((fd = open( root, O_RDONLY )) != -1)
403 res = fstat( fd, &st );
406 /* now try normal stat just in case */
407 if (res == -1) res = stat( root, &st );
408 if (res == -1) return NULL;
410 RtlEnterCriticalSection( &dir_section );
412 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
413 * pass NULL. Leave the argument in for symmetry.
415 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
418 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
419 if (ret) strcpy( ret, device );
421 RtlLeaveCriticalSection( &dir_section );
429 /* try to open it first to force it to get mounted */
430 if ((fd = open( root, O_RDONLY )) != -1)
432 res = fstat( fd, &st );
435 /* now try normal stat just in case */
436 if (res == -1) res = stat( root, &st );
437 if (res == -1) return NULL;
439 RtlEnterCriticalSection( &dir_section );
441 if ((f = fopen( "/etc/mnttab", "r" )))
443 device = parse_mount_entries( f, st.st_dev, st.st_ino);
446 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
447 if (!device && (f = fopen( "/etc/vfstab", "r" )))
449 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
454 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
455 if (ret) strcpy( ret, device );
457 RtlLeaveCriticalSection( &dir_section );
459 #elif defined(__APPLE__)
460 struct statfs *mntStat;
466 static const char path_bsd_device[] = "/dev/disk";
469 res = stat( root, &st );
470 if (res == -1) return NULL;
475 RtlEnterCriticalSection( &dir_section );
477 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
479 for (i = 0; i < mntSize && !ret; i++)
481 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
482 if (st.st_dev != dev || st.st_ino != ino) continue;
484 /* FIXME add support for mounted network drive */
485 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
487 /* set return value to the corresponding raw BSD node */
488 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
491 strcpy(ret, "/dev/r");
492 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
496 RtlLeaveCriticalSection( &dir_section );
499 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
505 /***********************************************************************
506 * get_device_mount_point
508 * Return the current mount point for a device.
510 static char *get_device_mount_point( dev_t dev )
517 RtlEnterCriticalSection( &dir_section );
519 if ((f = fopen( "/etc/mtab", "r" )))
521 struct mntent *entry;
525 while ((entry = getmntent( f )))
527 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
528 if (!strcmp( entry->mnt_type, "nfs" ) ||
529 !strcmp( entry->mnt_type, "smbfs" ) ||
530 !strcmp( entry->mnt_type, "ncpfs" )) continue;
532 if (!strcmp( entry->mnt_type, "supermount" ))
534 if ((device = strstr( entry->mnt_opts, "dev=" )))
537 if ((p = strchr( device, ',' ))) *p = 0;
540 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
542 /* if device is a regular file check for a loop mount */
543 if ((device = strstr( entry->mnt_opts, "loop=" )))
546 if ((p = strchr( device, ',' ))) *p = 0;
549 else device = entry->mnt_fsname;
551 if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
553 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
554 if (ret) strcpy( ret, entry->mnt_dir );
560 RtlLeaveCriticalSection( &dir_section );
563 if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
569 /***********************************************************************
572 * Initialize the show_dot_files options.
574 static void init_options(void)
576 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
577 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
581 OBJECT_ATTRIBUTES attr;
582 UNICODE_STRING nameW;
586 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
587 attr.Length = sizeof(attr);
588 attr.RootDirectory = root;
589 attr.ObjectName = &nameW;
591 attr.SecurityDescriptor = NULL;
592 attr.SecurityQualityOfService = NULL;
593 RtlInitUnicodeString( &nameW, WineW );
595 /* @@ Wine registry key: HKCU\Software\Wine */
596 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
598 RtlInitUnicodeString( &nameW, ShowDotFilesW );
599 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
601 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
602 show_dot_files = IS_OPTION_TRUE( str[0] );
610 /***********************************************************************
613 * Check if the specified file should be hidden based on its name and the show dot files option.
615 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
619 if (show_dot_files == -1) init_options();
620 if (show_dot_files) return FALSE;
622 end = p = name->Buffer + name->Length/sizeof(WCHAR);
623 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
624 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
625 if (p == end || *p != '.') return FALSE;
626 /* make sure it isn't '.' or '..' */
627 if (p + 1 == end) return FALSE;
628 if (p[1] == '.' && p + 2 == end) return FALSE;
633 /***********************************************************************
634 * hash_short_file_name
636 * Transform a Unix file name into a hashed DOS name. If the name is a valid
637 * DOS name, it is converted to upper-case; otherwise it is replaced by a
638 * hashed version that fits in 8.3 format.
639 * 'buffer' must be at least 12 characters long.
640 * Returns length of short name in bytes; short name is NOT null-terminated.
642 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
644 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
646 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
651 /* Compute the hash code of the file name */
652 /* If you know something about hash functions, feel free to */
653 /* insert a better algorithm here... */
654 if (!is_case_sensitive)
656 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
657 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
658 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
662 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
663 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
664 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
667 /* Find last dot for start of the extension */
668 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
670 /* Copy first 4 chars, replacing invalid chars with '_' */
671 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
673 if (p == end || p == ext) break;
674 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
676 /* Pad to 5 chars with '~' */
677 while (i-- >= 0) *dst++ = '~';
679 /* Insert hash code converted to 3 ASCII chars */
680 *dst++ = hash_chars[(hash >> 10) & 0x1f];
681 *dst++ = hash_chars[(hash >> 5) & 0x1f];
682 *dst++ = hash_chars[hash & 0x1f];
684 /* Copy the first 3 chars of the extension (if any) */
688 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
689 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
695 /***********************************************************************
698 * Check a long file name against a mask.
700 * Tests (done in W95 DOS shell - case insensitive):
701 * *.txt test1.test.txt *
703 * *.t??????.t* test1.ta.tornado.txt *
704 * *tornado* test1.ta.tornado.txt *
705 * t*t test1.ta.tornado.txt *
707 * ?est??? test1.txt -
708 * *test1.txt* test1.txt *
709 * h?l?o*t.dat hellothisisatest.dat *
711 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
714 const WCHAR *name = name_str->Buffer;
715 const WCHAR *mask = mask_str->Buffer;
716 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
717 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
718 const WCHAR *lastjoker = NULL;
719 const WCHAR *next_to_retry = NULL;
721 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
723 while (name < name_end && mask < mask_end)
729 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
730 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
733 /* skip to the next match after the joker(s) */
734 if (is_case_sensitive)
735 while (name < name_end && (*name != *mask)) name++;
737 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
738 next_to_retry = name;
745 if (is_case_sensitive) mismatch = (*mask != *name);
746 else mismatch = (toupperW(*mask) != toupperW(*name));
752 if (mask == mask_end)
754 if (name == name_end) return TRUE;
755 if (lastjoker) mask = lastjoker;
758 else /* mismatch ! */
760 if (lastjoker) /* we had an '*', so we can try unlimitedly */
764 /* this scan sequence was a mismatch, so restart
765 * 1 char after the first char we checked last time */
767 name = next_to_retry;
769 else return FALSE; /* bad luck */
774 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
775 mask++; /* Ignore trailing '.' or '*' in mask */
776 return (name == name_end && mask == mask_end);
780 /***********************************************************************
783 * helper for NtQueryDirectoryFile
785 static FILE_BOTH_DIR_INFORMATION *append_entry( void *info_ptr, ULONG_PTR *pos, ULONG max_length,
786 const char *long_name, const char *short_name,
787 const UNICODE_STRING *mask )
789 FILE_BOTH_DIR_INFORMATION *info;
790 int i, long_len, short_len, total_len;
792 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
793 WCHAR short_nameW[12];
796 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
797 if (long_len == -1) return NULL;
799 str.Buffer = long_nameW;
800 str.Length = long_len * sizeof(WCHAR);
801 str.MaximumLength = sizeof(long_nameW);
805 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
806 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
807 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
809 else /* generate a short name if necessary */
814 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
815 short_len = hash_short_file_name( &str, short_nameW );
818 TRACE( "long %s short %s mask %s\n",
819 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
821 if (mask && !match_filename( &str, mask ))
823 if (!short_len) return NULL; /* no short name to match */
824 str.Buffer = short_nameW;
825 str.Length = short_len * sizeof(WCHAR);
826 str.MaximumLength = sizeof(short_nameW);
827 if (!match_filename( &str, mask )) return NULL;
830 total_len = (sizeof(*info) - sizeof(info->FileName) + long_len*sizeof(WCHAR) + 3) & ~3;
831 info = (FILE_BOTH_DIR_INFORMATION *)((char *)info_ptr + *pos);
833 if (*pos + total_len > max_length) total_len = max_length - *pos;
835 info->FileAttributes = 0;
836 if (lstat( long_name, &st ) == -1) return NULL;
837 if (S_ISLNK( st.st_mode ))
839 if (stat( long_name, &st ) == -1) return NULL;
840 if (S_ISDIR( st.st_mode )) info->FileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT;
843 info->NextEntryOffset = total_len;
844 info->FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
846 RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
847 RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
848 RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
849 RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
851 if (S_ISDIR(st.st_mode))
853 info->EndOfFile.QuadPart = info->AllocationSize.QuadPart = 0;
854 info->FileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
858 info->EndOfFile.QuadPart = st.st_size;
859 info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
860 info->FileAttributes |= FILE_ATTRIBUTE_ARCHIVE;
863 if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
864 info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
866 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
867 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
869 info->EaSize = 0; /* FIXME */
870 info->ShortNameLength = short_len * sizeof(WCHAR);
871 for (i = 0; i < short_len; i++) info->ShortName[i] = toupperW(short_nameW[i]);
872 info->FileNameLength = long_len * sizeof(WCHAR);
873 memcpy( info->FileName, long_nameW,
874 min( info->FileNameLength, total_len-sizeof(*info)+sizeof(info->FileName) ));
881 /***********************************************************************
882 * read_directory_vfat
884 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
886 #ifdef VFAT_IOCTL_READDIR_BOTH
887 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
888 BOOLEAN single_entry, const UNICODE_STRING *mask,
889 BOOLEAN restart_scan )
894 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
895 static const unsigned int max_dir_info_size = sizeof(*info) + (MAX_DIR_ENTRY_LEN-1) * sizeof(WCHAR);
897 io->u.Status = STATUS_SUCCESS;
899 if (restart_scan) lseek( fd, 0, SEEK_SET );
901 if (length < max_dir_info_size) /* we may have to return a partial entry here */
903 off_t old_pos = lseek( fd, 0, SEEK_CUR );
905 /* Set d_reclen to 65535 to work around an AFS kernel bug */
906 de[0].d_reclen = 65535;
907 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
908 if (res == -1 && errno != ENOENT) return -1; /* VFAT ioctl probably not supported */
909 if (!res && de[0].d_reclen == 65535) return -1; /* AFS bug */
913 if (!de[0].d_reclen) break;
915 info = append_entry( buffer, &io->Information, length,
916 de[1].d_name, de[0].d_name, mask );
918 info = append_entry( buffer, &io->Information, length,
919 de[0].d_name, NULL, mask );
923 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
925 io->u.Status = STATUS_BUFFER_OVERFLOW;
926 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
930 old_pos = lseek( fd, 0, SEEK_CUR );
931 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
934 else /* we'll only return full entries, no need to worry about overflow */
936 /* Set d_reclen to 65535 to work around an AFS kernel bug */
937 de[0].d_reclen = 65535;
938 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
939 if (res == -1 && errno != ENOENT) return -1; /* VFAT ioctl probably not supported */
940 if (!res && de[0].d_reclen == 65535) return -1; /* AFS bug */
944 if (!de[0].d_reclen) break;
946 info = append_entry( buffer, &io->Information, length,
947 de[1].d_name, de[0].d_name, mask );
949 info = append_entry( buffer, &io->Information, length,
950 de[0].d_name, NULL, mask );
954 if (single_entry) break;
955 /* check if we still have enough space for the largest possible entry */
956 if (io->Information + max_dir_info_size > length) break;
958 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
962 if (last_info) last_info->NextEntryOffset = 0;
963 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
966 #endif /* VFAT_IOCTL_READDIR_BOTH */
969 /***********************************************************************
970 * read_directory_getdents
972 * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
975 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
976 BOOLEAN single_entry, const UNICODE_STRING *mask,
977 BOOLEAN restart_scan )
980 size_t size = length;
982 char local_buffer[8192];
983 KERNEL_DIRENT64 *data, *de;
984 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
985 static const unsigned int max_dir_info_size = sizeof(*info) + (MAX_DIR_ENTRY_LEN-1) * sizeof(WCHAR);
987 if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
989 size = sizeof(local_buffer);
990 data = (KERNEL_DIRENT64 *)local_buffer;
993 if (restart_scan) lseek( fd, 0, SEEK_SET );
994 else if (length < max_dir_info_size) /* we may have to return a partial entry here */
996 old_pos = lseek( fd, 0, SEEK_CUR );
997 if (old_pos == -1 && errno == ENOENT)
999 io->u.Status = STATUS_NO_MORE_FILES;
1005 io->u.Status = STATUS_SUCCESS;
1007 res = getdents64( fd, data, size );
1010 if (errno != ENOSYS)
1012 io->u.Status = FILE_GetNtStatus();
1022 res -= de->d_reclen;
1023 info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask );
1027 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1029 io->u.Status = STATUS_BUFFER_OVERFLOW;
1030 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1033 /* check if we still have enough space for the largest possible entry */
1034 if (single_entry || io->Information + max_dir_info_size > length)
1036 if (res > 0) lseek( fd, de->d_off, SEEK_SET ); /* set pos to next entry */
1040 old_pos = de->d_off;
1041 /* move on to the next entry */
1042 if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1045 res = getdents64( fd, data, size );
1050 if (last_info) last_info->NextEntryOffset = 0;
1051 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1054 if ((char *)data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1057 #endif /* USE_GETDENTS */
1060 /***********************************************************************
1061 * read_directory_readdir
1063 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1065 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1066 BOOLEAN single_entry, const UNICODE_STRING *mask,
1067 BOOLEAN restart_scan )
1070 off_t i, old_pos = 0;
1072 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
1073 static const unsigned int max_dir_info_size = sizeof(*info) + (MAX_DIR_ENTRY_LEN-1) * sizeof(WCHAR);
1075 if (!(dir = opendir( "." )))
1077 io->u.Status = FILE_GetNtStatus();
1083 old_pos = lseek( fd, 0, SEEK_CUR );
1084 /* skip the right number of entries */
1085 for (i = 0; i < old_pos; i++)
1087 if (!readdir( dir ))
1090 io->u.Status = STATUS_NO_MORE_FILES;
1095 io->u.Status = STATUS_SUCCESS;
1097 while ((de = readdir( dir )))
1100 info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask );
1104 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1106 io->u.Status = STATUS_BUFFER_OVERFLOW;
1107 old_pos--; /* restore pos to previous entry */
1110 if (single_entry) break;
1111 /* check if we still have enough space for the largest possible entry */
1112 if (io->Information + max_dir_info_size > length) break;
1116 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
1119 if (last_info) last_info->NextEntryOffset = 0;
1120 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1124 /******************************************************************************
1125 * NtQueryDirectoryFile [NTDLL.@]
1126 * ZwQueryDirectoryFile [NTDLL.@]
1128 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
1129 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
1130 PIO_STATUS_BLOCK io,
1131 PVOID buffer, ULONG length,
1132 FILE_INFORMATION_CLASS info_class,
1133 BOOLEAN single_entry,
1134 PUNICODE_STRING mask,
1135 BOOLEAN restart_scan )
1139 TRACE("(%p %p %p %p %p %p 0x%08lx 0x%08x 0x%08x %s 0x%08x\n",
1140 handle, event, apc_routine, apc_context, io, buffer,
1141 length, info_class, single_entry, debugstr_us(mask),
1144 if (length < sizeof(FILE_BOTH_DIR_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
1146 if (event || apc_routine)
1148 FIXME( "Unsupported yet option\n" );
1149 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1151 if (info_class != FileBothDirectoryInformation)
1153 FIXME( "Unsupported file info class %d\n", info_class );
1154 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1157 if ((io->u.Status = wine_server_handle_to_fd( handle, FILE_LIST_DIRECTORY, &fd, NULL )) != STATUS_SUCCESS)
1158 return io->u.Status;
1160 io->Information = 0;
1162 RtlEnterCriticalSection( &dir_section );
1164 if (show_dot_files == -1) init_options();
1166 if ((cwd = open(".", O_RDONLY)) != -1 && fchdir( fd ) != -1)
1168 #ifdef VFAT_IOCTL_READDIR_BOTH
1169 if ((read_directory_vfat( fd, io, buffer, length, single_entry, mask, restart_scan )) == -1)
1172 if ((read_directory_getdents( fd, io, buffer, length, single_entry, mask, restart_scan )) == -1)
1174 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan );
1176 if (fchdir( cwd ) == -1) chdir( "/" );
1178 else io->u.Status = FILE_GetNtStatus();
1180 RtlLeaveCriticalSection( &dir_section );
1182 wine_server_release_fd( handle, fd );
1183 if (cwd != -1) close( cwd );
1184 TRACE( "=> %lx (%ld)\n", io->u.Status, io->Information );
1185 return io->u.Status;
1189 /***********************************************************************
1192 * Find a file in a directory the hard way, by doing a case-insensitive search.
1193 * The file found is appended to unix_name at pos.
1194 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
1196 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
1199 WCHAR buffer[MAX_DIR_ENTRY_LEN];
1205 int ret, used_default, is_name_8_dot_3;
1207 /* try a shortcut for this directory */
1209 unix_name[pos++] = '/';
1210 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
1211 NULL, &used_default );
1212 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
1213 /* so it cannot match the file we are looking for */
1214 if (ret >= 0 && !used_default)
1216 unix_name[pos + ret] = 0;
1217 if (!stat( unix_name, &st )) return STATUS_SUCCESS;
1219 if (check_case) goto not_found; /* we want an exact match */
1221 if (pos > 1) unix_name[pos - 1] = 0;
1222 else unix_name[1] = 0; /* keep the initial slash */
1224 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
1226 str.Buffer = (WCHAR *)name;
1227 str.Length = length * sizeof(WCHAR);
1228 str.MaximumLength = str.Length;
1229 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
1231 /* now look for it through the directory */
1233 #ifdef VFAT_IOCTL_READDIR_BOTH
1234 if (is_name_8_dot_3)
1236 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
1239 KERNEL_DIRENT de[2];
1241 /* Set d_reclen to 65535 to work around an AFS kernel bug */
1242 de[0].d_reclen = 65535;
1243 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) != -1 &&
1244 de[0].d_reclen != 65535)
1246 unix_name[pos - 1] = '/';
1249 if (!de[0].d_reclen) break;
1251 if (de[1].d_name[0])
1253 ret = ntdll_umbstowcs( 0, de[1].d_name, strlen(de[1].d_name),
1254 buffer, MAX_DIR_ENTRY_LEN );
1255 if (ret == length && !memicmpW( buffer, name, length))
1257 strcpy( unix_name + pos, de[1].d_name );
1259 return STATUS_SUCCESS;
1262 ret = ntdll_umbstowcs( 0, de[0].d_name, strlen(de[0].d_name),
1263 buffer, MAX_DIR_ENTRY_LEN );
1264 if (ret == length && !memicmpW( buffer, name, length))
1266 strcpy( unix_name + pos,
1267 de[1].d_name[0] ? de[1].d_name : de[0].d_name );
1269 return STATUS_SUCCESS;
1271 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1)
1280 /* fall through to normal handling */
1282 #endif /* VFAT_IOCTL_READDIR_BOTH */
1284 if (!(dir = opendir( unix_name )))
1286 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
1287 else return FILE_GetNtStatus();
1289 unix_name[pos - 1] = '/';
1290 str.Buffer = buffer;
1291 str.MaximumLength = sizeof(buffer);
1292 while ((de = readdir( dir )))
1294 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
1295 if (ret == length && !memicmpW( buffer, name, length ))
1297 strcpy( unix_name + pos, de->d_name );
1299 return STATUS_SUCCESS;
1302 if (!is_name_8_dot_3) continue;
1304 str.Length = ret * sizeof(WCHAR);
1305 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1307 WCHAR short_nameW[12];
1308 ret = hash_short_file_name( &str, short_nameW );
1309 if (ret == length && !memicmpW( short_nameW, name, length ))
1311 strcpy( unix_name + pos, de->d_name );
1313 return STATUS_SUCCESS;
1318 goto not_found; /* avoid warning */
1321 unix_name[pos - 1] = 0;
1322 return STATUS_OBJECT_PATH_NOT_FOUND;
1326 /******************************************************************************
1329 * Get the Unix path of a DOS device.
1331 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
1333 const char *config_dir = wine_get_config_dir();
1335 char *unix_name, *new_name, *dev;
1339 /* make sure the device name is ASCII */
1340 for (i = 0; i < name_len; i++)
1341 if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
1343 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
1345 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1346 return STATUS_NO_MEMORY;
1348 strcpy( unix_name, config_dir );
1349 strcat( unix_name, "/dosdevices/" );
1350 dev = unix_name + strlen(unix_name);
1352 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
1355 /* special case for drive devices */
1356 if (name_len == 2 && dev[1] == ':')
1364 if (!stat( unix_name, &st ))
1366 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
1367 unix_name_ret->Buffer = unix_name;
1368 unix_name_ret->Length = strlen(unix_name);
1369 unix_name_ret->MaximumLength = unix_len;
1370 return STATUS_SUCCESS;
1374 /* now try some defaults for it */
1375 if (!strcmp( dev, "aux" ))
1377 strcpy( dev, "com1" );
1380 if (!strcmp( dev, "prn" ))
1382 strcpy( dev, "lpt1" );
1385 if (!strcmp( dev, "nul" ))
1387 strcpy( unix_name, "/dev/null" );
1388 dev = NULL; /* last try */
1393 if (dev[1] == ':' && dev[2] == ':') /* drive device */
1395 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
1396 new_name = get_default_drive_device( unix_name );
1398 else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( dev[3] - '0' );
1399 else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( dev[3] - '0' );
1401 if (!new_name) break;
1403 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1404 unix_name = new_name;
1405 unix_len = strlen(unix_name) + 1;
1406 dev = NULL; /* last try */
1408 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1409 return STATUS_BAD_DEVICE_TYPE;
1413 /* return the length of the DOS namespace prefix if any */
1414 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
1416 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
1417 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
1419 if (name->Length > sizeof(nt_prefixW) &&
1420 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
1421 return sizeof(nt_prefixW) / sizeof(WCHAR);
1423 if (name->Length > sizeof(dosdev_prefixW) &&
1424 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
1425 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
1431 /******************************************************************************
1432 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
1434 * Convert a file name from NT namespace to Unix namespace.
1436 * If disposition is not FILE_OPEN or FILE_OVERWRITTE, the last path
1437 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
1438 * returned, but the unix name is still filled in properly.
1440 NTSTATUS wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
1441 UINT disposition, BOOLEAN check_case )
1443 static const WCHAR uncW[] = {'U','N','C','\\'};
1444 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
1446 NTSTATUS status = STATUS_SUCCESS;
1447 const char *config_dir = wine_get_config_dir();
1448 const WCHAR *name, *p;
1451 int pos, ret, name_len, unix_len, used_default;
1453 name = nameW->Buffer;
1454 name_len = nameW->Length / sizeof(WCHAR);
1456 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
1458 if ((pos = get_dos_prefix_len( nameW )))
1460 BOOLEAN is_unc = FALSE;
1465 /* check for UNC prefix */
1466 if (name_len > 4 && !memicmpW( name, uncW, 4 ))
1474 /* check for a drive letter with path */
1475 if (name_len < 3 || !isalphaW(name[0]) || name[1] != ':' || !IS_SEPARATOR(name[2]))
1477 /* not a drive with path, try other DOS devices */
1478 return get_dos_device( name, name_len, unix_name_ret );
1480 name += 2; /* skip drive letter */
1484 /* check for invalid characters */
1485 for (p = name; p < name + name_len; p++)
1486 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
1488 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1489 unix_len += MAX_DIR_ENTRY_LEN + 3;
1490 unix_len += strlen(config_dir) + sizeof("/dosdevices/") + 3;
1491 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1492 return STATUS_NO_MEMORY;
1493 strcpy( unix_name, config_dir );
1494 strcat( unix_name, "/dosdevices/" );
1495 pos = strlen(unix_name);
1498 strcpy( unix_name + pos, "unc" );
1503 unix_name[pos++] = tolowerW( name[-2] );
1504 unix_name[pos++] = ':';
1508 else /* no DOS prefix, assume NT native name, map directly to Unix */
1510 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_NAME_INVALID;
1511 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1512 unix_len += MAX_DIR_ENTRY_LEN + 3;
1513 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1514 return STATUS_NO_MEMORY;
1518 /* try a shortcut first */
1520 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
1521 NULL, &used_default );
1523 while (name_len && IS_SEPARATOR(*name))
1529 if (ret > 0 && !used_default) /* if we used the default char the name didn't convert properly */
1532 unix_name[pos + ret] = 0;
1533 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
1534 if (!stat( unix_name, &st ))
1536 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
1537 if (disposition == FILE_CREATE)
1538 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
1543 if (!name_len) /* empty name -> drive root doesn't exist */
1545 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1546 return STATUS_OBJECT_PATH_NOT_FOUND;
1548 if (check_case && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
1550 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1551 return STATUS_OBJECT_NAME_NOT_FOUND;
1554 /* now do it component by component */
1558 const WCHAR *end, *next;
1561 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
1563 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
1564 name_len -= next - name;
1566 /* grow the buffer if needed */
1568 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
1571 unix_len += 2 * MAX_DIR_ENTRY_LEN;
1572 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
1574 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1575 return STATUS_NO_MEMORY;
1577 unix_name = new_name;
1580 status = find_file_in_dir( unix_name, pos, name, end - name, check_case );
1582 /* if this is the last element, not finding it is not necessarily fatal */
1585 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
1587 status = STATUS_OBJECT_NAME_NOT_FOUND;
1588 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
1590 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
1591 MAX_DIR_ENTRY_LEN, NULL, &used_default );
1592 if (ret > 0 && !used_default)
1594 unix_name[pos] = '/';
1595 unix_name[pos + 1 + ret] = 0;
1596 status = STATUS_NO_SUCH_FILE;
1601 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
1603 status = STATUS_OBJECT_NAME_COLLISION;
1607 if (status != STATUS_SUCCESS)
1609 /* couldn't find it at all, fail */
1610 WARN( "%s not found in %s\n", debugstr_w(name), unix_name );
1611 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1615 pos += strlen( unix_name + pos );
1619 WARN( "%s -> %s required a case-insensitive search\n",
1620 debugstr_us(nameW), debugstr_a(unix_name) );
1623 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
1624 unix_name_ret->Buffer = unix_name;
1625 unix_name_ret->Length = strlen(unix_name);
1626 unix_name_ret->MaximumLength = unix_len;
1631 /******************************************************************
1632 * RtlDoesFileExists_U (NTDLL.@)
1634 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
1636 UNICODE_STRING nt_name;
1637 ANSI_STRING unix_name;
1640 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
1641 ret = (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ) == STATUS_SUCCESS);
1642 if (ret) RtlFreeAnsiString( &unix_name );
1643 RtlFreeUnicodeString( &nt_name );
1648 /***********************************************************************
1649 * DIR_unmount_device
1651 * Unmount the specified device.
1653 NTSTATUS DIR_unmount_device( HANDLE handle )
1658 SERVER_START_REQ( unmount_device )
1660 req->handle = handle;
1661 status = wine_server_call( req );
1664 if (status) return status;
1666 if (!(status = wine_server_handle_to_fd( handle, 0, &unix_fd, NULL )))
1669 char *mount_point = NULL;
1671 if (fstat( unix_fd, &st ) == -1 || !S_ISBLK(st.st_mode))
1672 status = STATUS_INVALID_PARAMETER;
1675 if ((mount_point = get_device_mount_point( st.st_rdev )))
1677 static const char umount[] = "umount >/dev/null 2>&1 ";
1678 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
1681 strcpy( cmd, umount );
1682 strcat( cmd, mount_point );
1684 RtlFreeHeap( GetProcessHeap(), 0, cmd );
1686 /* umount will fail to release the loop device since we still have
1687 a handle to it, so we release it here */
1688 if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
1691 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
1694 wine_server_release_fd( handle, unix_fd );
1700 /******************************************************************************
1703 * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
1704 * Returned value must be freed by caller.
1706 NTSTATUS DIR_get_unix_cwd( char **cwd )
1708 int old_cwd, unix_fd;
1713 RtlAcquirePebLock();
1715 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1716 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
1718 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
1720 if (!(handle = curdir->Handle))
1722 UNICODE_STRING dirW;
1723 OBJECT_ATTRIBUTES attr;
1726 if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
1728 status = STATUS_OBJECT_NAME_INVALID;
1731 attr.Length = sizeof(attr);
1732 attr.RootDirectory = 0;
1733 attr.Attributes = OBJ_CASE_INSENSITIVE;
1734 attr.ObjectName = &dirW;
1735 attr.SecurityDescriptor = NULL;
1736 attr.SecurityQualityOfService = NULL;
1738 status = NtOpenFile( &handle, 0, &attr, &io, 0,
1739 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1740 RtlFreeUnicodeString( &dirW );
1741 if (status != STATUS_SUCCESS) goto done;
1744 if ((status = wine_server_handle_to_fd( handle, 0, &unix_fd, NULL )) == STATUS_SUCCESS)
1746 RtlEnterCriticalSection( &dir_section );
1748 if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
1750 unsigned int size = 512;
1754 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1756 status = STATUS_NO_MEMORY;
1759 if (getcwd( *cwd, size )) break;
1760 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
1761 if (errno != ERANGE)
1763 status = STATUS_OBJECT_PATH_INVALID;
1768 if (fchdir( old_cwd ) == -1) chdir( "/" );
1770 else status = FILE_GetNtStatus();
1772 RtlLeaveCriticalSection( &dir_section );
1773 wine_server_release_fd( handle, unix_fd );
1775 if (!curdir->Handle) NtClose( handle );
1778 RtlReleasePebLock();
1782 struct read_changes_info
1786 PIO_APC_ROUTINE ApcRoutine;
1792 static void WINAPI read_changes_apc( void *user, PIO_STATUS_BLOCK iosb, ULONG status )
1794 struct read_changes_info *info = user;
1795 char path[PATH_MAX];
1796 NTSTATUS ret = STATUS_SUCCESS;
1799 TRACE("%p %p %p %08lx\n", info, info->ApcContext, iosb, status);
1804 * hEvent/hDir is set before the output buffer and iosb is updated.
1805 * Since the thread that called NtNotifyChangeDirectoryFile is usually
1806 * waiting, we'll be safe since we're called in that thread's context.
1807 * If a different thread is waiting on our hEvent/hDir we're going to be
1810 SERVER_START_REQ( read_change )
1812 req->handle = info->FileHandle;
1813 wine_server_set_reply( req, path, PATH_MAX );
1814 ret = wine_server_call( req );
1815 action = reply->action;
1816 len = wine_server_reply_size( reply );
1820 if (ret == STATUS_SUCCESS && info->Buffer &&
1821 (info->BufferSize > (sizeof (FILE_NOTIFY_INFORMATION) + len*sizeof(WCHAR))))
1823 PFILE_NOTIFY_INFORMATION pfni;
1825 pfni = (PFILE_NOTIFY_INFORMATION) info->Buffer;
1827 /* convert to an NT style path */
1828 for (i=0; i<len; i++)
1832 len = ntdll_umbstowcs( 0, path, len, pfni->FileName,
1833 info->BufferSize - sizeof (*pfni) );
1835 pfni->NextEntryOffset = 0;
1836 pfni->Action = action;
1837 pfni->FileNameLength = len * sizeof (WCHAR);
1838 pfni->FileName[len] = 0;
1840 TRACE("action = %ld name = %s\n", pfni->Action,
1841 debugstr_w(pfni->FileName) );
1842 len = sizeof (*pfni) - sizeof (DWORD) + pfni->FileNameLength;
1846 ret = STATUS_NOTIFY_ENUM_DIR;
1850 iosb->u.Status = ret;
1851 iosb->Information = len;
1853 RtlFreeHeap( GetProcessHeap(), 0, info );
1856 #define FILE_NOTIFY_ALL ( \
1857 FILE_NOTIFY_CHANGE_FILE_NAME | \
1858 FILE_NOTIFY_CHANGE_DIR_NAME | \
1859 FILE_NOTIFY_CHANGE_ATTRIBUTES | \
1860 FILE_NOTIFY_CHANGE_SIZE | \
1861 FILE_NOTIFY_CHANGE_LAST_WRITE | \
1862 FILE_NOTIFY_CHANGE_LAST_ACCESS | \
1863 FILE_NOTIFY_CHANGE_CREATION | \
1864 FILE_NOTIFY_CHANGE_SECURITY )
1866 /******************************************************************************
1867 * NtNotifyChangeDirectoryFile [NTDLL.@]
1870 NtNotifyChangeDirectoryFile( HANDLE FileHandle, HANDLE Event,
1871 PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext,
1872 PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer,
1873 ULONG BufferSize, ULONG CompletionFilter, BOOLEAN WatchTree )
1875 struct read_changes_info *info;
1878 TRACE("%p %p %p %p %p %p %lu %lu %d\n",
1879 FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock,
1880 Buffer, BufferSize, CompletionFilter, WatchTree );
1883 return STATUS_ACCESS_VIOLATION;
1885 if (CompletionFilter == 0 || (CompletionFilter & ~FILE_NOTIFY_ALL))
1886 return STATUS_INVALID_PARAMETER;
1889 FIXME("parameters ignored %p %p\n", ApcRoutine, ApcContext );
1891 info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof *info );
1893 return STATUS_NO_MEMORY;
1895 info->FileHandle = FileHandle;
1896 info->Event = Event;
1897 info->Buffer = Buffer;
1898 info->BufferSize = BufferSize;
1899 info->ApcRoutine = ApcRoutine;
1900 info->ApcContext = ApcContext;
1902 SERVER_START_REQ( read_directory_changes )
1904 req->handle = FileHandle;
1906 req->filter = CompletionFilter;
1907 req->want_data = (Buffer != NULL);
1908 req->subtree = WatchTree;
1909 req->io_apc = read_changes_apc;
1910 req->io_sb = IoStatusBlock;
1911 req->io_user = info;
1912 status = wine_server_call( req );
1916 if (status != STATUS_PENDING)
1917 RtlFreeHeap( GetProcessHeap(), 0, info );