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>
34 #ifdef HAVE_SYS_IOCTL_H
35 #include <sys/ioctl.h>
37 #ifdef HAVE_LINUX_IOCTL_H
38 #include <linux/ioctl.h>
45 #define NONAMELESSUNION
46 #define NONAMELESSSTRUCT
53 #include "ntdll_misc.h"
54 #include "wine/unicode.h"
55 #include "wine/server.h"
56 #include "wine/library.h"
57 #include "wine/debug.h"
59 WINE_DEFAULT_DEBUG_CHANNEL(file);
61 /* Define the VFAT ioctl to get both short and long file names */
62 /* FIXME: is it possible to get this to work on other systems? */
64 /* We want the real kernel dirent structure, not the libc one */
69 unsigned short d_reclen;
73 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
76 # define O_DIRECTORY 0200000 /* must be directory */
79 /* Using the same seekdir value across multiple directories is not portable, */
80 /* but it works on Linux, and it's a major performance gain so we want to use */
82 /* FIXME: do some sort of runtime check instead */
86 #undef VFAT_IOCTL_READDIR_BOTH /* just in case... */
90 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
91 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
93 #define INVALID_NT_CHARS '*','?','<','>','|','"'
94 #define INVALID_DOS_CHARS INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
96 #define MAX_DIR_ENTRY_LEN 255 /* max length of a directory entry in chars */
98 static int show_dir_symlinks = -1;
99 static int show_dot_files;
101 /* at some point we may want to allow Winelib apps to set this */
102 static const int is_case_sensitive = FALSE;
104 static CRITICAL_SECTION chdir_section;
105 static CRITICAL_SECTION_DEBUG critsect_debug =
107 0, 0, &chdir_section,
108 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
109 0, 0, { 0, (DWORD)(__FILE__ ": chdir_section") }
111 static CRITICAL_SECTION chdir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
114 /***********************************************************************
117 * Wrapper for supporting seekdir across multiple directory objects.
119 static inline void seekdir_wrapper( DIR *dir, off_t pos )
124 while (pos-- > 0) if (!readdir( dir )) break;
128 /***********************************************************************
131 * Wrapper for supporting telldir across multiple directory objects.
133 static inline off_t telldir_wrapper( DIR *dir, off_t pos, int count )
136 return telldir( dir );
143 /***********************************************************************
144 * get_default_com_device
146 * Return the default device to use for serial ports.
148 static char *get_default_com_device( int num )
152 if (!num || num > 9) return ret;
154 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
157 strcpy( ret, "/dev/ttyS0" );
158 ret[strlen(ret) - 1] = '0' + num - 1;
161 FIXME( "no known default for device com%d\n", num );
167 /***********************************************************************
168 * get_default_lpt_device
170 * Return the default device to use for parallel ports.
172 static char *get_default_lpt_device( int num )
176 if (!num || num > 9) return ret;
178 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
181 strcpy( ret, "/dev/lp0" );
182 ret[strlen(ret) - 1] = '0' + num - 1;
185 FIXME( "no known default for device lpt%d\n", num );
191 /***********************************************************************
194 * Initialize the show_dir_symlinks and show_dot_files options.
196 static void init_options(void)
198 static const WCHAR WineW[] = {'M','a','c','h','i','n','e','\\',
199 'S','o','f','t','w','a','r','e','\\',
200 'W','i','n','e','\\','W','i','n','e','\\',
201 'C','o','n','f','i','g','\\','W','i','n','e',0};
202 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
203 static const WCHAR ShowDirSymlinksW[] = {'S','h','o','w','D','i','r','S','y','m','l','i','n','k','s',0};
207 OBJECT_ATTRIBUTES attr;
208 UNICODE_STRING nameW;
210 show_dot_files = show_dir_symlinks = 0;
212 attr.Length = sizeof(attr);
213 attr.RootDirectory = 0;
214 attr.ObjectName = &nameW;
216 attr.SecurityDescriptor = NULL;
217 attr.SecurityQualityOfService = NULL;
218 RtlInitUnicodeString( &nameW, WineW );
220 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
222 RtlInitUnicodeString( &nameW, ShowDotFilesW );
223 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
225 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
226 show_dot_files = IS_OPTION_TRUE( str[0] );
228 RtlInitUnicodeString( &nameW, ShowDirSymlinksW );
229 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
231 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
232 show_dir_symlinks = IS_OPTION_TRUE( str[0] );
239 /***********************************************************************
242 * Check if the specified file should be hidden based on its name and the show dot files option.
244 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
248 if (show_dir_symlinks == -1) init_options();
249 if (show_dot_files) return FALSE;
251 end = p = name->Buffer + name->Length/sizeof(WCHAR);
252 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
253 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
254 if (p == end || *p != '.') return FALSE;
255 /* make sure it isn't '.' or '..' */
256 if (p + 1 == end) return FALSE;
257 if (p[1] == '.' && p + 2 == end) return FALSE;
262 /***********************************************************************
263 * hash_short_file_name
265 * Transform a Unix file name into a hashed DOS name. If the name is a valid
266 * DOS name, it is converted to upper-case; otherwise it is replaced by a
267 * hashed version that fits in 8.3 format.
268 * 'buffer' must be at least 12 characters long.
269 * Returns length of short name in bytes; short name is NOT null-terminated.
271 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
273 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
274 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
276 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
281 /* Compute the hash code of the file name */
282 /* If you know something about hash functions, feel free to */
283 /* insert a better algorithm here... */
284 if (!is_case_sensitive)
286 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
287 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
288 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
292 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
293 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
294 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
297 /* Find last dot for start of the extension */
298 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
300 /* Copy first 4 chars, replacing invalid chars with '_' */
301 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
303 if (p == end || p == ext) break;
304 *dst++ = strchrW( invalid_chars, *p ) ? '_' : toupperW(*p);
306 /* Pad to 5 chars with '~' */
307 while (i-- >= 0) *dst++ = '~';
309 /* Insert hash code converted to 3 ASCII chars */
310 *dst++ = hash_chars[(hash >> 10) & 0x1f];
311 *dst++ = hash_chars[(hash >> 5) & 0x1f];
312 *dst++ = hash_chars[hash & 0x1f];
314 /* Copy the first 3 chars of the extension (if any) */
318 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
319 *dst++ = strchrW( invalid_chars, *ext ) ? '_' : toupperW(*ext);
325 /***********************************************************************
328 * Check a long file name against a mask.
330 * Tests (done in W95 DOS shell - case insensitive):
331 * *.txt test1.test.txt *
333 * *.t??????.t* test1.ta.tornado.txt *
334 * *tornado* test1.ta.tornado.txt *
335 * t*t test1.ta.tornado.txt *
337 * ?est??? test1.txt -
338 * *test1.txt* test1.txt *
339 * h?l?o*t.dat hellothisisatest.dat *
341 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
344 const WCHAR *name = name_str->Buffer;
345 const WCHAR *mask = mask_str->Buffer;
346 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
347 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
348 const WCHAR *lastjoker = NULL;
349 const WCHAR *next_to_retry = NULL;
351 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
353 while (name < name_end && mask < mask_end)
359 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
360 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
363 /* skip to the next match after the joker(s) */
364 if (is_case_sensitive)
365 while (name < name_end && (*name != *mask)) name++;
367 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
368 next_to_retry = name;
375 if (is_case_sensitive) mismatch = (*mask != *name);
376 else mismatch = (toupperW(*mask) != toupperW(*name));
382 if (mask == mask_end)
384 if (name == name_end) return TRUE;
385 if (lastjoker) mask = lastjoker;
388 else /* mismatch ! */
390 if (lastjoker) /* we had an '*', so we can try unlimitedly */
394 /* this scan sequence was a mismatch, so restart
395 * 1 char after the first char we checked last time */
397 name = next_to_retry;
399 else return FALSE; /* bad luck */
404 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
405 mask++; /* Ignore trailing '.' or '*' in mask */
406 return (name == name_end && mask == mask_end);
410 /***********************************************************************
413 * helper for NtQueryDirectoryFile
415 static FILE_BOTH_DIR_INFORMATION *append_entry( void *info_ptr, ULONG *pos, ULONG max_length,
416 const char *long_name, const char *short_name,
417 const UNICODE_STRING *mask )
419 FILE_BOTH_DIR_INFORMATION *info;
420 int i, long_len, short_len, total_len;
422 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
423 WCHAR short_nameW[12];
426 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
427 if (long_len == -1) return NULL;
429 str.Buffer = long_nameW;
430 str.Length = long_len * sizeof(WCHAR);
431 str.MaximumLength = sizeof(long_nameW);
435 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
436 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
437 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
439 else /* generate a short name if necessary */
444 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
445 short_len = hash_short_file_name( &str, short_nameW );
448 TRACE( "long %s short %s mask %s\n",
449 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
451 if (mask && !match_filename( &str, mask ))
453 if (!short_len) return NULL; /* no short name to match */
454 str.Buffer = short_nameW;
455 str.Length = short_len * sizeof(WCHAR);
456 str.MaximumLength = sizeof(short_nameW);
457 if (!match_filename( &str, mask )) return NULL;
460 total_len = (sizeof(*info) - sizeof(info->FileName) + long_len*sizeof(WCHAR) + 3) & ~3;
461 info = (FILE_BOTH_DIR_INFORMATION *)((char *)info_ptr + *pos);
463 if (*pos + total_len > max_length) total_len = max_length - *pos;
465 if (lstat( long_name, &st ) == -1) return NULL;
466 if (S_ISLNK( st.st_mode ))
468 if (stat( long_name, &st ) == -1) return NULL;
469 if (S_ISDIR( st.st_mode ) && !show_dir_symlinks) return NULL;
472 info->NextEntryOffset = total_len;
473 info->FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
475 RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
476 RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
477 RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
478 RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
480 if (S_ISDIR(st.st_mode))
482 info->EndOfFile.QuadPart = info->AllocationSize.QuadPart = 0;
483 info->FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
487 info->EndOfFile.QuadPart = st.st_size;
488 info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
489 info->FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
492 if (!(st.st_mode & S_IWUSR))
493 info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
495 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
496 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
498 info->EaSize = 0; /* FIXME */
499 info->ShortNameLength = short_len * sizeof(WCHAR);
500 for (i = 0; i < short_len; i++) info->ShortName[i] = toupperW(short_nameW[i]);
501 info->FileNameLength = long_len * sizeof(WCHAR);
502 memcpy( info->FileName, long_nameW,
503 min( info->FileNameLength, total_len-sizeof(*info)+sizeof(info->FileName) ));
510 /******************************************************************************
511 * NtQueryDirectoryFile [NTDLL.@]
512 * ZwQueryDirectoryFile [NTDLL.@]
514 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
515 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
517 PVOID buffer, ULONG length,
518 FILE_INFORMATION_CLASS info_class,
519 BOOLEAN single_entry,
520 PUNICODE_STRING mask,
521 BOOLEAN restart_scan )
524 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
525 static const int max_dir_info_size = sizeof(*info) + (MAX_DIR_ENTRY_LEN-1) * sizeof(WCHAR);
527 TRACE("(%p %p %p %p %p %p 0x%08lx 0x%08x 0x%08x %s 0x%08x\n",
528 handle, event, apc_routine, apc_context, io, buffer,
529 length, info_class, single_entry, debugstr_us(mask),
532 if (length < sizeof(*info)) return STATUS_INFO_LENGTH_MISMATCH;
534 if (event || apc_routine)
536 FIXME( "Unsupported yet option\n" );
537 return io->u.Status = STATUS_NOT_IMPLEMENTED;
539 if (info_class != FileBothDirectoryInformation)
541 FIXME( "Unsupported file info class %d\n", info_class );
542 return io->u.Status = STATUS_NOT_IMPLEMENTED;
545 if ((io->u.Status = wine_server_handle_to_fd( handle, GENERIC_READ,
546 &fd, NULL, NULL )) != STATUS_SUCCESS)
551 RtlEnterCriticalSection( &chdir_section );
553 if (show_dir_symlinks == -1) init_options();
555 if ((cwd = open(".", O_RDONLY)) != -1 && fchdir( fd ) != -1)
559 #ifdef VFAT_IOCTL_READDIR_BOTH
562 io->u.Status = STATUS_SUCCESS;
564 /* Check if the VFAT ioctl is supported on this directory */
566 if (restart_scan) lseek( fd, 0, SEEK_SET );
567 else old_pos = lseek( fd, 0, SEEK_CUR );
569 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) != -1)
571 if (length < max_dir_info_size) /* we may have to return a partial entry here */
575 if (!de[0].d_reclen) break;
577 info = append_entry( buffer, &io->Information, length,
578 de[1].d_name, de[0].d_name, mask );
580 info = append_entry( buffer, &io->Information, length,
581 de[0].d_name, NULL, mask );
585 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
587 io->u.Status = STATUS_BUFFER_OVERFLOW;
588 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
592 old_pos = lseek( fd, 0, SEEK_CUR );
593 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
596 else /* we'll only return full entries, no need to worry about overflow */
600 if (!de[0].d_reclen) break;
602 info = append_entry( buffer, &io->Information, length,
603 de[1].d_name, de[0].d_name, mask );
605 info = append_entry( buffer, &io->Information, length,
606 de[0].d_name, NULL, mask );
610 if (single_entry) break;
611 /* check if we still have enough space for the largest possible entry */
612 if (io->Information + max_dir_info_size > length) break;
614 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
618 else if (errno != ENOENT)
619 #endif /* VFAT_IOCTL_READDIR_BOTH */
624 if (!(dir = opendir( "." )))
626 io->u.Status = FILE_GetNtStatus();
631 old_pos = lseek( fd, 0, SEEK_CUR );
632 seekdir_wrapper( dir, old_pos );
634 io->u.Status = STATUS_SUCCESS;
636 if (length < max_dir_info_size) /* we may have to return a partial entry here */
638 while ((de = readdir( dir )))
640 info = append_entry( buffer, &io->Information, length,
641 de->d_name, NULL, mask );
645 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
646 io->u.Status = STATUS_BUFFER_OVERFLOW;
648 old_pos = telldir_wrapper( dir, old_pos, 1 );
651 old_pos = telldir_wrapper( dir, old_pos, 1 );
654 else /* we'll only return full entries, no need to worry about overflow */
657 while ((de = readdir( dir )))
660 info = append_entry( buffer, &io->Information, length,
661 de->d_name, NULL, mask );
665 if (single_entry) break;
666 /* check if we still have enough space for the largest possible entry */
667 if (io->Information + max_dir_info_size > length) break;
670 old_pos = telldir_wrapper( dir, old_pos, count );
672 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
676 if (last_info) last_info->NextEntryOffset = 0;
677 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
680 if (fchdir( cwd ) == -1) chdir( "/" );
682 else io->u.Status = FILE_GetNtStatus();
684 RtlLeaveCriticalSection( &chdir_section );
686 wine_server_release_fd( handle, fd );
687 if (cwd != -1) close( cwd );
688 TRACE( "=> %lx (%ld)\n", io->u.Status, io->Information );
693 /***********************************************************************
696 * Find a file in a directory the hard way, by doing a case-insensitive search.
697 * The file found is appended to unix_name at pos.
698 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
700 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
703 WCHAR buffer[MAX_DIR_ENTRY_LEN];
709 int ret, used_default, is_name_8_dot_3;
711 /* try a shortcut for this directory */
713 unix_name[pos++] = '/';
714 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
715 NULL, &used_default );
716 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
717 /* so it cannot match the file we are looking for */
718 if (ret >= 0 && !used_default)
720 unix_name[pos + ret] = 0;
721 if (!stat( unix_name, &st )) return STATUS_SUCCESS;
723 if (check_case) goto not_found; /* we want an exact match */
725 if (pos > 1) unix_name[pos - 1] = 0;
726 else unix_name[1] = 0; /* keep the initial slash */
728 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
730 str.Buffer = (WCHAR *)name;
731 str.Length = length * sizeof(WCHAR);
732 str.MaximumLength = str.Length;
733 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
735 /* now look for it through the directory */
737 #ifdef VFAT_IOCTL_READDIR_BOTH
740 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
745 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) != -1)
747 unix_name[pos - 1] = '/';
750 if (!de[0].d_reclen) break;
754 ret = ntdll_umbstowcs( 0, de[1].d_name, strlen(de[1].d_name),
755 buffer, MAX_DIR_ENTRY_LEN );
756 if (ret == length && !memicmpW( buffer, name, length))
758 strcpy( unix_name + pos, de[1].d_name );
760 return STATUS_SUCCESS;
763 ret = ntdll_umbstowcs( 0, de[0].d_name, strlen(de[0].d_name),
764 buffer, MAX_DIR_ENTRY_LEN );
765 if (ret == length && !memicmpW( buffer, name, length))
767 strcpy( unix_name + pos,
768 de[1].d_name[0] ? de[1].d_name : de[0].d_name );
770 return STATUS_SUCCESS;
772 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1)
781 /* fall through to normal handling */
783 #endif /* VFAT_IOCTL_READDIR_BOTH */
785 if (!(dir = opendir( unix_name )))
787 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
788 else return FILE_GetNtStatus();
790 unix_name[pos - 1] = '/';
792 str.MaximumLength = sizeof(buffer);
793 while ((de = readdir( dir )))
795 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
796 if (ret == length && !memicmpW( buffer, name, length ))
798 strcpy( unix_name + pos, de->d_name );
800 return STATUS_SUCCESS;
803 if (!is_name_8_dot_3) continue;
805 str.Length = ret * sizeof(WCHAR);
806 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
808 WCHAR short_nameW[12];
809 ret = hash_short_file_name( &str, short_nameW );
810 if (ret == length && !memicmpW( short_nameW, name, length ))
812 strcpy( unix_name + pos, de->d_name );
814 return STATUS_SUCCESS;
819 goto not_found; /* avoid warning */
822 unix_name[pos - 1] = 0;
823 return STATUS_OBJECT_PATH_NOT_FOUND;
827 /******************************************************************************
830 * Get the Unix path of a DOS device.
832 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
834 const char *config_dir = wine_get_config_dir();
836 char *unix_name, *dev;
839 /* make sure the device name is ASCII */
840 for (i = 0; i < name_len; i++)
841 if (name[i] <= 32 || name[i] >= 127) return STATUS_OBJECT_NAME_NOT_FOUND;
843 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
845 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
846 return STATUS_NO_MEMORY;
848 strcpy( unix_name, config_dir );
849 strcat( unix_name, "/dosdevices/" );
850 dev = unix_name + strlen(unix_name);
852 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
855 /* special case for drive devices */
856 if (name_len == 2 && dev[1] == ':')
864 if (!stat( unix_name, &st ))
866 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
867 unix_name_ret->Buffer = unix_name;
868 unix_name_ret->Length = strlen(unix_name);
869 unix_name_ret->MaximumLength = unix_len;
870 return STATUS_SUCCESS;
874 /* now try some defaults for it */
875 if (!strcmp( dev, "aux" ))
877 strcpy( dev, "com1" );
880 if (!strcmp( dev, "prn" ))
882 strcpy( dev, "lpt1" );
885 if (!strcmp( dev, "nul" ))
887 strcpy( unix_name, "/dev/null" );
888 dev = NULL; /* last try */
891 if (!strncmp( dev, "com", 3 ))
893 char *name = get_default_com_device( dev[3] - '0' );
896 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
898 unix_len = strlen(name) + 1;
899 dev = NULL; /* last try */
903 if (!strncmp( dev, "lpt", 3 ))
905 char *name = get_default_lpt_device( dev[3] - '0' );
908 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
910 unix_len = strlen(name) + 1;
911 dev = NULL; /* last try */
917 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
918 return STATUS_OBJECT_NAME_NOT_FOUND;
922 /* return the length of the DOS namespace prefix if any */
923 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
925 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
926 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
928 if (name->Length > sizeof(nt_prefixW) &&
929 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
930 return sizeof(nt_prefixW) / sizeof(WCHAR);
932 if (name->Length > sizeof(dosdev_prefixW) &&
933 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
934 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
940 /******************************************************************************
941 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
943 * Convert a file name from NT namespace to Unix namespace.
945 * If disposition is not FILE_OPEN or FILE_OVERWRITTE, the last path
946 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
947 * returned, but the unix name is still filled in properly.
949 NTSTATUS wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
950 UINT disposition, BOOLEAN check_case )
952 static const WCHAR uncW[] = {'U','N','C','\\'};
953 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
955 NTSTATUS status = STATUS_SUCCESS;
956 const char *config_dir = wine_get_config_dir();
957 const WCHAR *name, *p;
960 int pos, ret, name_len, unix_len, used_default;
962 name = nameW->Buffer;
963 name_len = nameW->Length / sizeof(WCHAR);
965 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
967 if ((pos = get_dos_prefix_len( nameW )))
972 /* check for UNC prefix */
973 if (name_len > 4 && !memicmpW( name, uncW, 4 ))
975 FIXME( "UNC name %s not supported\n", debugstr_us(nameW) );
976 return STATUS_OBJECT_NAME_NOT_FOUND;
979 /* check for a drive letter with path */
980 if (name_len < 3 || !isalphaW(name[0]) || name[1] != ':' || !IS_SEPARATOR(name[2]))
982 /* not a drive with path, try other DOS devices */
983 return get_dos_device( name, name_len, unix_name_ret );
986 name += 2; /* skip drive letter */
989 /* check for invalid characters */
990 for (p = name; p < name + name_len; p++)
991 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
993 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
994 unix_len += MAX_DIR_ENTRY_LEN + 3;
995 unix_len += strlen(config_dir) + sizeof("/dosdevices/a:");
996 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
997 return STATUS_NO_MEMORY;
998 strcpy( unix_name, config_dir );
999 strcat( unix_name, "/dosdevices/a:" );
1000 pos = strlen(unix_name);
1001 unix_name[pos - 2] = tolowerW( name[-2] );
1003 else /* no DOS prefix, assume NT native name, map directly to Unix */
1005 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_NAME_INVALID;
1006 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1007 unix_len += MAX_DIR_ENTRY_LEN + 3;
1008 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1009 return STATUS_NO_MEMORY;
1013 /* try a shortcut first */
1015 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
1016 NULL, &used_default );
1018 while (name_len && IS_SEPARATOR(*name))
1024 if (ret > 0 && !used_default) /* if we used the default char the name didn't convert properly */
1027 unix_name[pos + ret] = 0;
1028 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
1029 if (!stat( unix_name, &st ))
1031 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
1032 if (disposition == FILE_CREATE)
1033 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
1038 if (!name_len) /* empty name -> drive root doesn't exist */
1040 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1041 return STATUS_OBJECT_PATH_NOT_FOUND;
1043 if (check_case && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
1045 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1046 return STATUS_OBJECT_NAME_NOT_FOUND;
1049 /* now do it component by component */
1053 const WCHAR *end, *next;
1056 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
1058 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
1059 name_len -= next - name;
1061 /* grow the buffer if needed */
1063 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
1066 unix_len += 2 * MAX_DIR_ENTRY_LEN;
1067 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
1069 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1070 return STATUS_NO_MEMORY;
1072 unix_name = new_name;
1075 status = find_file_in_dir( unix_name, pos, name, end - name, check_case );
1077 /* if this is the last element, not finding it is not necessarily fatal */
1080 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
1082 status = STATUS_OBJECT_NAME_NOT_FOUND;
1083 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
1085 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
1086 MAX_DIR_ENTRY_LEN, NULL, &used_default );
1087 if (ret > 0 && !used_default)
1089 unix_name[pos] = '/';
1090 unix_name[pos + 1 + ret] = 0;
1091 status = STATUS_NO_SUCH_FILE;
1096 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
1098 status = STATUS_OBJECT_NAME_COLLISION;
1102 if (status != STATUS_SUCCESS)
1104 /* couldn't find it at all, fail */
1105 WARN( "%s not found in %s\n", debugstr_w(name), unix_name );
1106 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1110 pos += strlen( unix_name + pos );
1114 WARN( "%s -> %s required a case-insensitive search\n",
1115 debugstr_us(nameW), debugstr_a(unix_name) );
1118 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
1119 unix_name_ret->Buffer = unix_name;
1120 unix_name_ret->Length = strlen(unix_name);
1121 unix_name_ret->MaximumLength = unix_len;
1126 /******************************************************************
1127 * RtlDoesFileExists_U (NTDLL.@)
1129 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
1131 UNICODE_STRING nt_name;
1132 ANSI_STRING unix_name;
1135 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
1136 ret = (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ) == STATUS_SUCCESS);
1137 if (ret) RtlFreeAnsiString( &unix_name );
1138 RtlFreeUnicodeString( &nt_name );