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>
38 #ifdef HAVE_SYS_IOCTL_H
39 #include <sys/ioctl.h>
41 #ifdef HAVE_LINUX_IOCTL_H
42 #include <linux/ioctl.h>
49 #define NONAMELESSUNION
50 #define NONAMELESSSTRUCT
57 #include "ntdll_misc.h"
58 #include "wine/unicode.h"
59 #include "wine/server.h"
60 #include "wine/library.h"
61 #include "wine/debug.h"
63 WINE_DEFAULT_DEBUG_CHANNEL(file);
65 /* Define the VFAT ioctl to get both short and long file names */
66 /* FIXME: is it possible to get this to work on other systems? */
68 /* We want the real kernel dirent structure, not the libc one */
73 unsigned short d_reclen;
77 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
80 # define O_DIRECTORY 0200000 /* must be directory */
83 /* Using the same seekdir value across multiple directories is not portable, */
84 /* but it works on Linux, and it's a major performance gain so we want to use */
86 /* FIXME: do some sort of runtime check instead */
90 #undef VFAT_IOCTL_READDIR_BOTH /* just in case... */
94 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
95 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
97 #define INVALID_NT_CHARS '*','?','<','>','|','"'
98 #define INVALID_DOS_CHARS INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
100 #define MAX_DIR_ENTRY_LEN 255 /* max length of a directory entry in chars */
102 static int show_dir_symlinks = -1;
103 static int show_dot_files;
105 /* at some point we may want to allow Winelib apps to set this */
106 static const int is_case_sensitive = FALSE;
108 static CRITICAL_SECTION dir_section;
109 static CRITICAL_SECTION_DEBUG critsect_debug =
112 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
113 0, 0, { 0, (DWORD)(__FILE__ ": dir_section") }
115 static CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
118 /***********************************************************************
121 * Wrapper for supporting seekdir across multiple directory objects.
123 static inline void seekdir_wrapper( DIR *dir, off_t pos )
128 while (pos-- > 0) if (!readdir( dir )) break;
132 /***********************************************************************
135 * Wrapper for supporting telldir across multiple directory objects.
137 static inline off_t telldir_wrapper( DIR *dir, off_t pos, int count )
140 return telldir( dir );
147 /***********************************************************************
148 * get_default_com_device
150 * Return the default device to use for serial ports.
152 static char *get_default_com_device( int num )
156 if (!num || num > 9) return ret;
158 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
161 strcpy( ret, "/dev/ttyS0" );
162 ret[strlen(ret) - 1] = '0' + num - 1;
165 FIXME( "no known default for device com%d\n", num );
171 /***********************************************************************
172 * get_default_lpt_device
174 * Return the default device to use for parallel ports.
176 static char *get_default_lpt_device( int num )
180 if (!num || num > 9) return ret;
182 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
185 strcpy( ret, "/dev/lp0" );
186 ret[strlen(ret) - 1] = '0' + num - 1;
189 FIXME( "no known default for device lpt%d\n", num );
195 /***********************************************************************
196 * parse_mount_entries
198 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
201 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
203 struct mntent *entry;
207 while ((entry = getmntent( f )))
209 if (stat( entry->mnt_dir, &st ) == -1) continue;
210 if (st.st_dev != dev || st.st_ino != ino) continue;
211 if (!strcmp( entry->mnt_type, "supermount" ))
213 if ((device = strstr( entry->mnt_opts, "dev=" )))
215 char *p = strchr( device + 4, ',' );
221 return entry->mnt_fsname;
227 /***********************************************************************
228 * get_default_drive_device
230 * Return the default device to use for a given drive mount point.
232 static char *get_default_drive_device( const char *root )
242 /* try to open it first to force it to get mounted */
243 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
245 res = fstat( fd, &st );
248 /* now try normal stat just in case */
249 if (res == -1) res = stat( root, &st );
250 if (res == -1) return NULL;
252 RtlEnterCriticalSection( &dir_section );
254 if ((f = fopen( "/etc/mtab", "r" )))
256 device = parse_mount_entries( f, st.st_dev, st.st_ino );
259 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
260 if (!device && (f = fopen( "/etc/fstab", "r" )))
262 device = parse_mount_entries( f, st.st_dev, st.st_ino );
267 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
268 if (ret) strcpy( ret, device );
270 RtlLeaveCriticalSection( &dir_section );
273 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
279 /***********************************************************************
282 * Initialize the show_dir_symlinks and show_dot_files options.
284 static void init_options(void)
286 static const WCHAR WineW[] = {'M','a','c','h','i','n','e','\\',
287 'S','o','f','t','w','a','r','e','\\',
288 'W','i','n','e','\\','W','i','n','e','\\',
289 'C','o','n','f','i','g','\\','W','i','n','e',0};
290 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
291 static const WCHAR ShowDirSymlinksW[] = {'S','h','o','w','D','i','r','S','y','m','l','i','n','k','s',0};
295 OBJECT_ATTRIBUTES attr;
296 UNICODE_STRING nameW;
298 show_dot_files = show_dir_symlinks = 0;
300 attr.Length = sizeof(attr);
301 attr.RootDirectory = 0;
302 attr.ObjectName = &nameW;
304 attr.SecurityDescriptor = NULL;
305 attr.SecurityQualityOfService = NULL;
306 RtlInitUnicodeString( &nameW, WineW );
308 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
310 RtlInitUnicodeString( &nameW, ShowDotFilesW );
311 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
313 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
314 show_dot_files = IS_OPTION_TRUE( str[0] );
316 RtlInitUnicodeString( &nameW, ShowDirSymlinksW );
317 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
319 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
320 show_dir_symlinks = IS_OPTION_TRUE( str[0] );
327 /***********************************************************************
330 * Check if the specified file should be hidden based on its name and the show dot files option.
332 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
336 if (show_dir_symlinks == -1) init_options();
337 if (show_dot_files) return FALSE;
339 end = p = name->Buffer + name->Length/sizeof(WCHAR);
340 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
341 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
342 if (p == end || *p != '.') return FALSE;
343 /* make sure it isn't '.' or '..' */
344 if (p + 1 == end) return FALSE;
345 if (p[1] == '.' && p + 2 == end) return FALSE;
350 /***********************************************************************
351 * hash_short_file_name
353 * Transform a Unix file name into a hashed DOS name. If the name is a valid
354 * DOS name, it is converted to upper-case; otherwise it is replaced by a
355 * hashed version that fits in 8.3 format.
356 * 'buffer' must be at least 12 characters long.
357 * Returns length of short name in bytes; short name is NOT null-terminated.
359 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
361 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
362 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
364 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
369 /* Compute the hash code of the file name */
370 /* If you know something about hash functions, feel free to */
371 /* insert a better algorithm here... */
372 if (!is_case_sensitive)
374 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
375 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
376 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
380 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
381 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
382 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
385 /* Find last dot for start of the extension */
386 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
388 /* Copy first 4 chars, replacing invalid chars with '_' */
389 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
391 if (p == end || p == ext) break;
392 *dst++ = strchrW( invalid_chars, *p ) ? '_' : toupperW(*p);
394 /* Pad to 5 chars with '~' */
395 while (i-- >= 0) *dst++ = '~';
397 /* Insert hash code converted to 3 ASCII chars */
398 *dst++ = hash_chars[(hash >> 10) & 0x1f];
399 *dst++ = hash_chars[(hash >> 5) & 0x1f];
400 *dst++ = hash_chars[hash & 0x1f];
402 /* Copy the first 3 chars of the extension (if any) */
406 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
407 *dst++ = strchrW( invalid_chars, *ext ) ? '_' : toupperW(*ext);
413 /***********************************************************************
416 * Check a long file name against a mask.
418 * Tests (done in W95 DOS shell - case insensitive):
419 * *.txt test1.test.txt *
421 * *.t??????.t* test1.ta.tornado.txt *
422 * *tornado* test1.ta.tornado.txt *
423 * t*t test1.ta.tornado.txt *
425 * ?est??? test1.txt -
426 * *test1.txt* test1.txt *
427 * h?l?o*t.dat hellothisisatest.dat *
429 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
432 const WCHAR *name = name_str->Buffer;
433 const WCHAR *mask = mask_str->Buffer;
434 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
435 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
436 const WCHAR *lastjoker = NULL;
437 const WCHAR *next_to_retry = NULL;
439 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
441 while (name < name_end && mask < mask_end)
447 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
448 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
451 /* skip to the next match after the joker(s) */
452 if (is_case_sensitive)
453 while (name < name_end && (*name != *mask)) name++;
455 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
456 next_to_retry = name;
463 if (is_case_sensitive) mismatch = (*mask != *name);
464 else mismatch = (toupperW(*mask) != toupperW(*name));
470 if (mask == mask_end)
472 if (name == name_end) return TRUE;
473 if (lastjoker) mask = lastjoker;
476 else /* mismatch ! */
478 if (lastjoker) /* we had an '*', so we can try unlimitedly */
482 /* this scan sequence was a mismatch, so restart
483 * 1 char after the first char we checked last time */
485 name = next_to_retry;
487 else return FALSE; /* bad luck */
492 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
493 mask++; /* Ignore trailing '.' or '*' in mask */
494 return (name == name_end && mask == mask_end);
498 /***********************************************************************
501 * helper for NtQueryDirectoryFile
503 static FILE_BOTH_DIR_INFORMATION *append_entry( void *info_ptr, ULONG *pos, ULONG max_length,
504 const char *long_name, const char *short_name,
505 const UNICODE_STRING *mask )
507 FILE_BOTH_DIR_INFORMATION *info;
508 int i, long_len, short_len, total_len;
510 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
511 WCHAR short_nameW[12];
514 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
515 if (long_len == -1) return NULL;
517 str.Buffer = long_nameW;
518 str.Length = long_len * sizeof(WCHAR);
519 str.MaximumLength = sizeof(long_nameW);
523 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
524 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
525 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
527 else /* generate a short name if necessary */
532 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
533 short_len = hash_short_file_name( &str, short_nameW );
536 TRACE( "long %s short %s mask %s\n",
537 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
539 if (mask && !match_filename( &str, mask ))
541 if (!short_len) return NULL; /* no short name to match */
542 str.Buffer = short_nameW;
543 str.Length = short_len * sizeof(WCHAR);
544 str.MaximumLength = sizeof(short_nameW);
545 if (!match_filename( &str, mask )) return NULL;
548 total_len = (sizeof(*info) - sizeof(info->FileName) + long_len*sizeof(WCHAR) + 3) & ~3;
549 info = (FILE_BOTH_DIR_INFORMATION *)((char *)info_ptr + *pos);
551 if (*pos + total_len > max_length) total_len = max_length - *pos;
553 if (lstat( long_name, &st ) == -1) return NULL;
554 if (S_ISLNK( st.st_mode ))
556 if (stat( long_name, &st ) == -1) return NULL;
557 if (S_ISDIR( st.st_mode ) && !show_dir_symlinks) return NULL;
560 info->NextEntryOffset = total_len;
561 info->FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
563 RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
564 RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
565 RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
566 RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
568 if (S_ISDIR(st.st_mode))
570 info->EndOfFile.QuadPart = info->AllocationSize.QuadPart = 0;
571 info->FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
575 info->EndOfFile.QuadPart = st.st_size;
576 info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
577 info->FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
580 if (!(st.st_mode & S_IWUSR))
581 info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
583 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
584 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
586 info->EaSize = 0; /* FIXME */
587 info->ShortNameLength = short_len * sizeof(WCHAR);
588 for (i = 0; i < short_len; i++) info->ShortName[i] = toupperW(short_nameW[i]);
589 info->FileNameLength = long_len * sizeof(WCHAR);
590 memcpy( info->FileName, long_nameW,
591 min( info->FileNameLength, total_len-sizeof(*info)+sizeof(info->FileName) ));
598 /******************************************************************************
599 * NtQueryDirectoryFile [NTDLL.@]
600 * ZwQueryDirectoryFile [NTDLL.@]
602 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
603 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
605 PVOID buffer, ULONG length,
606 FILE_INFORMATION_CLASS info_class,
607 BOOLEAN single_entry,
608 PUNICODE_STRING mask,
609 BOOLEAN restart_scan )
612 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
613 static const int max_dir_info_size = sizeof(*info) + (MAX_DIR_ENTRY_LEN-1) * sizeof(WCHAR);
615 TRACE("(%p %p %p %p %p %p 0x%08lx 0x%08x 0x%08x %s 0x%08x\n",
616 handle, event, apc_routine, apc_context, io, buffer,
617 length, info_class, single_entry, debugstr_us(mask),
620 if (length < sizeof(*info)) return STATUS_INFO_LENGTH_MISMATCH;
622 if (event || apc_routine)
624 FIXME( "Unsupported yet option\n" );
625 return io->u.Status = STATUS_NOT_IMPLEMENTED;
627 if (info_class != FileBothDirectoryInformation)
629 FIXME( "Unsupported file info class %d\n", info_class );
630 return io->u.Status = STATUS_NOT_IMPLEMENTED;
633 if ((io->u.Status = wine_server_handle_to_fd( handle, GENERIC_READ,
634 &fd, NULL, NULL )) != STATUS_SUCCESS)
639 RtlEnterCriticalSection( &dir_section );
641 if (show_dir_symlinks == -1) init_options();
643 if ((cwd = open(".", O_RDONLY)) != -1 && fchdir( fd ) != -1)
647 #ifdef VFAT_IOCTL_READDIR_BOTH
650 io->u.Status = STATUS_SUCCESS;
652 /* Check if the VFAT ioctl is supported on this directory */
654 if (restart_scan) lseek( fd, 0, SEEK_SET );
655 else old_pos = lseek( fd, 0, SEEK_CUR );
657 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) != -1)
659 if (length < max_dir_info_size) /* we may have to return a partial entry here */
663 if (!de[0].d_reclen) break;
665 info = append_entry( buffer, &io->Information, length,
666 de[1].d_name, de[0].d_name, mask );
668 info = append_entry( buffer, &io->Information, length,
669 de[0].d_name, NULL, mask );
673 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
675 io->u.Status = STATUS_BUFFER_OVERFLOW;
676 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
680 old_pos = lseek( fd, 0, SEEK_CUR );
681 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
684 else /* we'll only return full entries, no need to worry about overflow */
688 if (!de[0].d_reclen) break;
690 info = append_entry( buffer, &io->Information, length,
691 de[1].d_name, de[0].d_name, mask );
693 info = append_entry( buffer, &io->Information, length,
694 de[0].d_name, NULL, mask );
698 if (single_entry) break;
699 /* check if we still have enough space for the largest possible entry */
700 if (io->Information + max_dir_info_size > length) break;
702 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
706 else if (errno != ENOENT)
707 #endif /* VFAT_IOCTL_READDIR_BOTH */
712 if (!(dir = opendir( "." )))
714 io->u.Status = FILE_GetNtStatus();
719 old_pos = lseek( fd, 0, SEEK_CUR );
720 seekdir_wrapper( dir, old_pos );
722 io->u.Status = STATUS_SUCCESS;
724 if (length < max_dir_info_size) /* we may have to return a partial entry here */
726 while ((de = readdir( dir )))
728 info = append_entry( buffer, &io->Information, length,
729 de->d_name, NULL, mask );
733 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
734 io->u.Status = STATUS_BUFFER_OVERFLOW;
736 old_pos = telldir_wrapper( dir, old_pos, 1 );
739 old_pos = telldir_wrapper( dir, old_pos, 1 );
742 else /* we'll only return full entries, no need to worry about overflow */
745 while ((de = readdir( dir )))
748 info = append_entry( buffer, &io->Information, length,
749 de->d_name, NULL, mask );
753 if (single_entry) break;
754 /* check if we still have enough space for the largest possible entry */
755 if (io->Information + max_dir_info_size > length) break;
758 old_pos = telldir_wrapper( dir, old_pos, count );
760 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
764 if (last_info) last_info->NextEntryOffset = 0;
765 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
768 if (fchdir( cwd ) == -1) chdir( "/" );
770 else io->u.Status = FILE_GetNtStatus();
772 RtlLeaveCriticalSection( &dir_section );
774 wine_server_release_fd( handle, fd );
775 if (cwd != -1) close( cwd );
776 TRACE( "=> %lx (%ld)\n", io->u.Status, io->Information );
781 /***********************************************************************
784 * Find a file in a directory the hard way, by doing a case-insensitive search.
785 * The file found is appended to unix_name at pos.
786 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
788 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
791 WCHAR buffer[MAX_DIR_ENTRY_LEN];
797 int ret, used_default, is_name_8_dot_3;
799 /* try a shortcut for this directory */
801 unix_name[pos++] = '/';
802 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
803 NULL, &used_default );
804 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
805 /* so it cannot match the file we are looking for */
806 if (ret >= 0 && !used_default)
808 unix_name[pos + ret] = 0;
809 if (!stat( unix_name, &st )) return STATUS_SUCCESS;
811 if (check_case) goto not_found; /* we want an exact match */
813 if (pos > 1) unix_name[pos - 1] = 0;
814 else unix_name[1] = 0; /* keep the initial slash */
816 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
818 str.Buffer = (WCHAR *)name;
819 str.Length = length * sizeof(WCHAR);
820 str.MaximumLength = str.Length;
821 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
823 /* now look for it through the directory */
825 #ifdef VFAT_IOCTL_READDIR_BOTH
828 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
833 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) != -1)
835 unix_name[pos - 1] = '/';
838 if (!de[0].d_reclen) break;
842 ret = ntdll_umbstowcs( 0, de[1].d_name, strlen(de[1].d_name),
843 buffer, MAX_DIR_ENTRY_LEN );
844 if (ret == length && !memicmpW( buffer, name, length))
846 strcpy( unix_name + pos, de[1].d_name );
848 return STATUS_SUCCESS;
851 ret = ntdll_umbstowcs( 0, de[0].d_name, strlen(de[0].d_name),
852 buffer, MAX_DIR_ENTRY_LEN );
853 if (ret == length && !memicmpW( buffer, name, length))
855 strcpy( unix_name + pos,
856 de[1].d_name[0] ? de[1].d_name : de[0].d_name );
858 return STATUS_SUCCESS;
860 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1)
869 /* fall through to normal handling */
871 #endif /* VFAT_IOCTL_READDIR_BOTH */
873 if (!(dir = opendir( unix_name )))
875 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
876 else return FILE_GetNtStatus();
878 unix_name[pos - 1] = '/';
880 str.MaximumLength = sizeof(buffer);
881 while ((de = readdir( dir )))
883 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
884 if (ret == length && !memicmpW( buffer, name, length ))
886 strcpy( unix_name + pos, de->d_name );
888 return STATUS_SUCCESS;
891 if (!is_name_8_dot_3) continue;
893 str.Length = ret * sizeof(WCHAR);
894 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
896 WCHAR short_nameW[12];
897 ret = hash_short_file_name( &str, short_nameW );
898 if (ret == length && !memicmpW( short_nameW, name, length ))
900 strcpy( unix_name + pos, de->d_name );
902 return STATUS_SUCCESS;
907 goto not_found; /* avoid warning */
910 unix_name[pos - 1] = 0;
911 return STATUS_OBJECT_PATH_NOT_FOUND;
915 /******************************************************************************
918 * Get the Unix path of a DOS device.
920 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
922 const char *config_dir = wine_get_config_dir();
924 char *unix_name, *new_name, *dev;
927 /* make sure the device name is ASCII */
928 for (i = 0; i < name_len; i++)
929 if (name[i] <= 32 || name[i] >= 127) return STATUS_OBJECT_NAME_NOT_FOUND;
931 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
933 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
934 return STATUS_NO_MEMORY;
936 strcpy( unix_name, config_dir );
937 strcat( unix_name, "/dosdevices/" );
938 dev = unix_name + strlen(unix_name);
940 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
943 /* special case for drive devices */
944 if (name_len == 2 && dev[1] == ':')
952 if (!stat( unix_name, &st ))
954 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
955 unix_name_ret->Buffer = unix_name;
956 unix_name_ret->Length = strlen(unix_name);
957 unix_name_ret->MaximumLength = unix_len;
958 return STATUS_SUCCESS;
962 /* now try some defaults for it */
963 if (!strcmp( dev, "aux" ))
965 strcpy( dev, "com1" );
968 if (!strcmp( dev, "prn" ))
970 strcpy( dev, "lpt1" );
973 if (!strcmp( dev, "nul" ))
975 strcpy( unix_name, "/dev/null" );
976 dev = NULL; /* last try */
981 if (dev[1] == ':' && dev[2] == ':') /* drive device */
983 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
984 new_name = get_default_drive_device( unix_name );
986 else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( dev[3] - '0' );
987 else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( dev[3] - '0' );
989 if (!new_name) break;
991 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
992 unix_name = new_name;
993 unix_len = strlen(unix_name) + 1;
994 dev = NULL; /* last try */
996 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
997 return STATUS_OBJECT_NAME_NOT_FOUND;
1001 /* return the length of the DOS namespace prefix if any */
1002 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
1004 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
1005 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
1007 if (name->Length > sizeof(nt_prefixW) &&
1008 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
1009 return sizeof(nt_prefixW) / sizeof(WCHAR);
1011 if (name->Length > sizeof(dosdev_prefixW) &&
1012 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
1013 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
1019 /******************************************************************************
1020 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
1022 * Convert a file name from NT namespace to Unix namespace.
1024 * If disposition is not FILE_OPEN or FILE_OVERWRITTE, the last path
1025 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
1026 * returned, but the unix name is still filled in properly.
1028 NTSTATUS wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
1029 UINT disposition, BOOLEAN check_case )
1031 static const WCHAR uncW[] = {'U','N','C','\\'};
1032 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
1034 NTSTATUS status = STATUS_SUCCESS;
1035 const char *config_dir = wine_get_config_dir();
1036 const WCHAR *name, *p;
1039 int pos, ret, name_len, unix_len, used_default;
1041 name = nameW->Buffer;
1042 name_len = nameW->Length / sizeof(WCHAR);
1044 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
1046 if ((pos = get_dos_prefix_len( nameW )))
1048 BOOLEAN is_unc = FALSE;
1053 /* check for UNC prefix */
1054 if (name_len > 4 && !memicmpW( name, uncW, 4 ))
1062 /* check for a drive letter with path */
1063 if (name_len < 3 || !isalphaW(name[0]) || name[1] != ':' || !IS_SEPARATOR(name[2]))
1065 /* not a drive with path, try other DOS devices */
1066 return get_dos_device( name, name_len, unix_name_ret );
1068 name += 2; /* skip drive letter */
1072 /* check for invalid characters */
1073 for (p = name; p < name + name_len; p++)
1074 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
1076 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1077 unix_len += MAX_DIR_ENTRY_LEN + 3;
1078 unix_len += strlen(config_dir) + sizeof("/dosdevices/") + 3;
1079 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1080 return STATUS_NO_MEMORY;
1081 strcpy( unix_name, config_dir );
1082 strcat( unix_name, "/dosdevices/" );
1083 pos = strlen(unix_name);
1086 strcpy( unix_name + pos, "unc" );
1091 unix_name[pos++] = tolowerW( name[-2] );
1092 unix_name[pos++] = ':';
1096 else /* no DOS prefix, assume NT native name, map directly to Unix */
1098 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_NAME_INVALID;
1099 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1100 unix_len += MAX_DIR_ENTRY_LEN + 3;
1101 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1102 return STATUS_NO_MEMORY;
1106 /* try a shortcut first */
1108 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
1109 NULL, &used_default );
1111 while (name_len && IS_SEPARATOR(*name))
1117 if (ret > 0 && !used_default) /* if we used the default char the name didn't convert properly */
1120 unix_name[pos + ret] = 0;
1121 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
1122 if (!stat( unix_name, &st ))
1124 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
1125 if (disposition == FILE_CREATE)
1126 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
1131 if (!name_len) /* empty name -> drive root doesn't exist */
1133 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1134 return STATUS_OBJECT_PATH_NOT_FOUND;
1136 if (check_case && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
1138 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1139 return STATUS_OBJECT_NAME_NOT_FOUND;
1142 /* now do it component by component */
1146 const WCHAR *end, *next;
1149 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
1151 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
1152 name_len -= next - name;
1154 /* grow the buffer if needed */
1156 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
1159 unix_len += 2 * MAX_DIR_ENTRY_LEN;
1160 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
1162 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1163 return STATUS_NO_MEMORY;
1165 unix_name = new_name;
1168 status = find_file_in_dir( unix_name, pos, name, end - name, check_case );
1170 /* if this is the last element, not finding it is not necessarily fatal */
1173 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
1175 status = STATUS_OBJECT_NAME_NOT_FOUND;
1176 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
1178 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
1179 MAX_DIR_ENTRY_LEN, NULL, &used_default );
1180 if (ret > 0 && !used_default)
1182 unix_name[pos] = '/';
1183 unix_name[pos + 1 + ret] = 0;
1184 status = STATUS_NO_SUCH_FILE;
1189 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
1191 status = STATUS_OBJECT_NAME_COLLISION;
1195 if (status != STATUS_SUCCESS)
1197 /* couldn't find it at all, fail */
1198 WARN( "%s not found in %s\n", debugstr_w(name), unix_name );
1199 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1203 pos += strlen( unix_name + pos );
1207 WARN( "%s -> %s required a case-insensitive search\n",
1208 debugstr_us(nameW), debugstr_a(unix_name) );
1211 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
1212 unix_name_ret->Buffer = unix_name;
1213 unix_name_ret->Length = strlen(unix_name);
1214 unix_name_ret->MaximumLength = unix_len;
1219 /******************************************************************
1220 * RtlDoesFileExists_U (NTDLL.@)
1222 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
1224 UNICODE_STRING nt_name;
1225 ANSI_STRING unix_name;
1228 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
1229 ret = (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ) == STATUS_SUCCESS);
1230 if (ret) RtlFreeAnsiString( &unix_name );
1231 RtlFreeUnicodeString( &nt_name );