Make CryptImport/ExportPublicKeyInfoEx behave the way MSDN describes
[wine/gsoc-2012-control.git] / dlls / ntdll / directory.c
blob4e4809b069dfd53fcbe123450eccc157a497738d
1 /*
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
23 #include "config.h"
24 #include "wine/port.h"
26 #include <sys/types.h>
27 #include <dirent.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <stdarg.h>
31 #include <string.h>
32 #include <stdlib.h>
33 #include <stdio.h>
34 #ifdef HAVE_MNTENT_H
35 #include <mntent.h>
36 #endif
37 #ifdef HAVE_SYS_STAT_H
38 # include <sys/stat.h>
39 #endif
40 #ifdef HAVE_SYS_IOCTL_H
41 #include <sys/ioctl.h>
42 #endif
43 #ifdef HAVE_LINUX_IOCTL_H
44 #include <linux/ioctl.h>
45 #endif
46 #ifdef HAVE_SYS_PARAM_H
47 #include <sys/param.h>
48 #endif
49 #ifdef HAVE_SYS_MOUNT_H
50 #include <sys/mount.h>
51 #endif
52 #include <time.h>
53 #ifdef HAVE_UNISTD_H
54 # include <unistd.h>
55 #endif
57 #define NONAMELESSUNION
58 #define NONAMELESSSTRUCT
59 #include "windef.h"
60 #include "winnt.h"
61 #include "ntstatus.h"
62 #include "thread.h"
63 #include "winternl.h"
64 #include "ntdll_misc.h"
65 #include "wine/unicode.h"
66 #include "wine/server.h"
67 #include "wine/library.h"
68 #include "wine/debug.h"
70 WINE_DEFAULT_DEBUG_CHANNEL(file);
72 /* just in case... */
73 #undef VFAT_IOCTL_READDIR_BOTH
74 #undef USE_GETDENTS
76 #ifdef linux
78 /* We want the real kernel dirent structure, not the libc one */
79 typedef struct
81 long d_ino;
82 long d_off;
83 unsigned short d_reclen;
84 char d_name[256];
85 } KERNEL_DIRENT;
87 /* Define the VFAT ioctl to get both short and long file names */
88 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
90 #ifndef O_DIRECTORY
91 # define O_DIRECTORY 0200000 /* must be directory */
92 #endif
94 #ifdef __i386__
96 typedef struct
98 ULONG64 d_ino;
99 LONG64 d_off;
100 unsigned short d_reclen;
101 unsigned char d_type;
102 char d_name[256];
103 } KERNEL_DIRENT64;
105 static inline int getdents64( int fd, KERNEL_DIRENT64 *de, unsigned int size )
107 int ret;
108 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
109 : "=a" (ret)
110 : "0" (220 /*NR_getdents64*/), "r" (fd), "c" (de), "d" (size)
111 : "memory" );
112 if (ret < 0)
114 errno = -ret;
115 ret = -1;
117 return ret;
119 #define USE_GETDENTS
121 #endif /* i386 */
123 #endif /* linux */
125 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
126 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
128 #define INVALID_NT_CHARS '*','?','<','>','|','"'
129 #define INVALID_DOS_CHARS INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
131 #define MAX_DIR_ENTRY_LEN 255 /* max length of a directory entry in chars */
133 static int show_dir_symlinks = -1;
134 static int show_dot_files;
136 /* at some point we may want to allow Winelib apps to set this */
137 static const int is_case_sensitive = FALSE;
139 static RTL_CRITICAL_SECTION dir_section;
140 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
142 0, 0, &dir_section,
143 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
144 0, 0, { (DWORD_PTR)(__FILE__ ": dir_section") }
146 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
149 /* check if a given Unicode char is OK in a DOS short name */
150 static inline BOOL is_invalid_dos_char( WCHAR ch )
152 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
153 if (ch > 0x7f) return TRUE;
154 return strchrW( invalid_chars, ch ) != NULL;
157 /***********************************************************************
158 * get_default_com_device
160 * Return the default device to use for serial ports.
162 static char *get_default_com_device( int num )
164 char *ret = NULL;
166 if (!num || num > 9) return ret;
167 #ifdef linux
168 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
169 if (ret)
171 strcpy( ret, "/dev/ttyS0" );
172 ret[strlen(ret) - 1] = '0' + num - 1;
174 #else
175 FIXME( "no known default for device com%d\n", num );
176 #endif
177 return ret;
181 /***********************************************************************
182 * get_default_lpt_device
184 * Return the default device to use for parallel ports.
186 static char *get_default_lpt_device( int num )
188 char *ret = NULL;
190 if (!num || num > 9) return ret;
191 #ifdef linux
192 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
193 if (ret)
195 strcpy( ret, "/dev/lp0" );
196 ret[strlen(ret) - 1] = '0' + num - 1;
198 #else
199 FIXME( "no known default for device lpt%d\n", num );
200 #endif
201 return ret;
205 /***********************************************************************
206 * parse_mount_entries
208 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
211 #ifdef sun
212 #include <sys/vfstab.h>
213 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
216 struct vfstab vfs_entry;
217 struct vfstab *entry=&vfs_entry;
218 struct stat st;
219 char *device;
221 while (! getvfsent( f, entry ))
223 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
224 if (!strcmp( entry->vfs_fstype, "nfs" ) ||
225 !strcmp( entry->vfs_fstype, "smbfs" ) ||
226 !strcmp( entry->vfs_fstype, "ncpfs" )) continue;
228 if (stat( entry->vfs_mountp, &st ) == -1) continue;
229 if (st.st_dev != dev || st.st_ino != ino) continue;
230 if (!strcmp( entry->vfs_fstype, "fd" ))
232 if ((device = strstr( entry->vfs_mntopts, "dev=" )))
234 char *p = strchr( device + 4, ',' );
235 if (p) *p = 0;
236 return device + 4;
239 else
240 return entry->vfs_special;
242 return NULL;
244 #endif
246 #ifdef linux
247 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
249 struct mntent *entry;
250 struct stat st;
251 char *device;
253 while ((entry = getmntent( f )))
255 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
256 if (!strcmp( entry->mnt_type, "nfs" ) ||
257 !strcmp( entry->mnt_type, "smbfs" ) ||
258 !strcmp( entry->mnt_type, "ncpfs" )) continue;
260 if (stat( entry->mnt_dir, &st ) == -1) continue;
261 if (st.st_dev != dev || st.st_ino != ino) continue;
262 if (!strcmp( entry->mnt_type, "supermount" ))
264 if ((device = strstr( entry->mnt_opts, "dev=" )))
266 char *p = strchr( device + 4, ',' );
267 if (p) *p = 0;
268 return device + 4;
271 else
272 return entry->mnt_fsname;
274 return NULL;
276 #endif
278 #ifdef __FreeBSD__
279 #include <fstab.h>
280 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
282 struct fstab *entry;
283 struct stat st;
285 while ((entry = getfsent()))
287 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
288 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
289 !strcmp( entry->fs_vfstype, "smbfs" ) ||
290 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
292 if (stat( entry->fs_file, &st ) == -1) continue;
293 if (st.st_dev != dev || st.st_ino != ino) continue;
294 return entry->fs_spec;
296 return NULL;
298 #endif
300 #ifdef sun
301 #include <sys/mnttab.h>
302 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
305 volatile struct mnttab mntentry;
306 struct mnttab *entry=&mntentry;
307 struct stat st;
308 char *device;
311 while (( ! getmntent( f , entry) ))
313 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
314 if (!strcmp( entry->mnt_fstype, "nfs" ) ||
315 !strcmp( entry->mnt_fstype, "smbfs" ) ||
316 !strcmp( entry->mnt_fstype, "ncpfs" )) continue;
318 if (stat( entry->mnt_mountp, &st ) == -1) continue;
319 if (st.st_dev != dev || st.st_ino != ino) continue;
320 if (!strcmp( entry->mnt_fstype, "fd" ))
322 if ((device = strstr( entry->mnt_mntopts, "dev=" )))
324 char *p = strchr( device + 4, ',' );
325 if (p) *p = 0;
326 return device + 4;
329 else
330 return entry->mnt_special;
332 return NULL;
334 #endif
336 /***********************************************************************
337 * get_default_drive_device
339 * Return the default device to use for a given drive mount point.
341 static char *get_default_drive_device( const char *root )
343 char *ret = NULL;
345 #ifdef linux
346 FILE *f;
347 char *device = NULL;
348 int fd, res = -1;
349 struct stat st;
351 /* try to open it first to force it to get mounted */
352 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
354 res = fstat( fd, &st );
355 close( fd );
357 /* now try normal stat just in case */
358 if (res == -1) res = stat( root, &st );
359 if (res == -1) return NULL;
361 RtlEnterCriticalSection( &dir_section );
363 if ((f = fopen( "/etc/mtab", "r" )))
365 device = parse_mount_entries( f, st.st_dev, st.st_ino );
366 endmntent( f );
368 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
369 if (!device && (f = fopen( "/etc/fstab", "r" )))
371 device = parse_mount_entries( f, st.st_dev, st.st_ino );
372 endmntent( f );
374 if (device)
376 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
377 if (ret) strcpy( ret, device );
379 RtlLeaveCriticalSection( &dir_section );
381 #elif defined( __FreeBSD__ )
382 char *device = NULL;
383 int fd, res = -1;
384 struct stat st;
386 /* try to open it first to force it to get mounted */
387 if ((fd = open( root, O_RDONLY )) != -1)
389 res = fstat( fd, &st );
390 close( fd );
392 /* now try normal stat just in case */
393 if (res == -1) res = stat( root, &st );
394 if (res == -1) return NULL;
396 RtlEnterCriticalSection( &dir_section );
398 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
399 * pass NULL. Leave the argument in for symmetry.
401 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
402 if (device)
404 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
405 if (ret) strcpy( ret, device );
407 RtlLeaveCriticalSection( &dir_section );
409 #elif defined( sun )
410 FILE *f;
411 char *device = NULL;
412 int fd, res = -1;
413 struct stat st;
415 /* try to open it first to force it to get mounted */
416 if ((fd = open( root, O_RDONLY )) != -1)
418 res = fstat( fd, &st );
419 close( fd );
421 /* now try normal stat just in case */
422 if (res == -1) res = stat( root, &st );
423 if (res == -1) return NULL;
425 RtlEnterCriticalSection( &dir_section );
427 if ((f = fopen( "/etc/mnttab", "r" )))
429 device = parse_mount_entries( f, st.st_dev, st.st_ino);
430 fclose( f );
432 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
433 if (!device && (f = fopen( "/etc/vfstab", "r" )))
435 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
436 fclose( f );
438 if (device)
440 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
441 if (ret) strcpy( ret, device );
443 RtlLeaveCriticalSection( &dir_section );
445 #elif defined(__APPLE__)
446 struct statfs *mntStat;
447 struct stat st;
448 int i;
449 int mntSize;
450 dev_t dev;
451 ino_t ino;
452 static const char path_bsd_device[] = "/dev/disk";
453 int res;
455 res = stat( root, &st );
456 if (res == -1) return NULL;
458 dev = st.st_dev;
459 ino = st.st_ino;
461 RtlEnterCriticalSection( &dir_section );
463 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
465 for (i = 0; i < mntSize && !ret; i++)
467 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
468 if (st.st_dev != dev || st.st_ino != ino) continue;
470 /* FIXME add support for mounted network drive */
471 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
473 /* set return value to the corresponding raw BSD node */
474 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
475 if (ret)
477 strcpy(ret, "/dev/r");
478 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
482 RtlLeaveCriticalSection( &dir_section );
483 #else
484 static int warned;
485 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
486 #endif
487 return ret;
491 /***********************************************************************
492 * init_options
494 * Initialize the show_dir_symlinks and show_dot_files options.
496 static void init_options(void)
498 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
499 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
500 static const WCHAR ShowDirSymlinksW[] = {'S','h','o','w','D','i','r','S','y','m','l','i','n','k','s',0};
501 char tmp[80];
502 HANDLE root, hkey;
503 DWORD dummy;
504 OBJECT_ATTRIBUTES attr;
505 UNICODE_STRING nameW;
507 show_dot_files = show_dir_symlinks = 0;
509 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
510 attr.Length = sizeof(attr);
511 attr.RootDirectory = root;
512 attr.ObjectName = &nameW;
513 attr.Attributes = 0;
514 attr.SecurityDescriptor = NULL;
515 attr.SecurityQualityOfService = NULL;
516 RtlInitUnicodeString( &nameW, WineW );
518 /* @@ Wine registry key: HKCU\Software\Wine */
519 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
521 RtlInitUnicodeString( &nameW, ShowDotFilesW );
522 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
524 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
525 show_dot_files = IS_OPTION_TRUE( str[0] );
527 RtlInitUnicodeString( &nameW, ShowDirSymlinksW );
528 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
530 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
531 show_dir_symlinks = IS_OPTION_TRUE( str[0] );
533 NtClose( hkey );
535 NtClose( root );
539 /***********************************************************************
540 * DIR_is_hidden_file
542 * Check if the specified file should be hidden based on its name and the show dot files option.
544 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
546 WCHAR *p, *end;
548 if (show_dir_symlinks == -1) init_options();
549 if (show_dot_files) return FALSE;
551 end = p = name->Buffer + name->Length/sizeof(WCHAR);
552 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
553 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
554 if (p == end || *p != '.') return FALSE;
555 /* make sure it isn't '.' or '..' */
556 if (p + 1 == end) return FALSE;
557 if (p[1] == '.' && p + 2 == end) return FALSE;
558 return TRUE;
562 /***********************************************************************
563 * hash_short_file_name
565 * Transform a Unix file name into a hashed DOS name. If the name is a valid
566 * DOS name, it is converted to upper-case; otherwise it is replaced by a
567 * hashed version that fits in 8.3 format.
568 * 'buffer' must be at least 12 characters long.
569 * Returns length of short name in bytes; short name is NOT null-terminated.
571 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
573 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
575 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
576 LPWSTR dst;
577 unsigned short hash;
578 int i;
580 /* Compute the hash code of the file name */
581 /* If you know something about hash functions, feel free to */
582 /* insert a better algorithm here... */
583 if (!is_case_sensitive)
585 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
586 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
587 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
589 else
591 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
592 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
593 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
596 /* Find last dot for start of the extension */
597 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
599 /* Copy first 4 chars, replacing invalid chars with '_' */
600 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
602 if (p == end || p == ext) break;
603 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
605 /* Pad to 5 chars with '~' */
606 while (i-- >= 0) *dst++ = '~';
608 /* Insert hash code converted to 3 ASCII chars */
609 *dst++ = hash_chars[(hash >> 10) & 0x1f];
610 *dst++ = hash_chars[(hash >> 5) & 0x1f];
611 *dst++ = hash_chars[hash & 0x1f];
613 /* Copy the first 3 chars of the extension (if any) */
614 if (ext)
616 *dst++ = '.';
617 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
618 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
620 return dst - buffer;
624 /***********************************************************************
625 * match_filename
627 * Check a long file name against a mask.
629 * Tests (done in W95 DOS shell - case insensitive):
630 * *.txt test1.test.txt *
631 * *st1* test1.txt *
632 * *.t??????.t* test1.ta.tornado.txt *
633 * *tornado* test1.ta.tornado.txt *
634 * t*t test1.ta.tornado.txt *
635 * ?est* test1.txt *
636 * ?est??? test1.txt -
637 * *test1.txt* test1.txt *
638 * h?l?o*t.dat hellothisisatest.dat *
640 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
642 int mismatch;
643 const WCHAR *name = name_str->Buffer;
644 const WCHAR *mask = mask_str->Buffer;
645 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
646 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
647 const WCHAR *lastjoker = NULL;
648 const WCHAR *next_to_retry = NULL;
650 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
652 while (name < name_end && mask < mask_end)
654 switch(*mask)
656 case '*':
657 mask++;
658 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
659 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
660 lastjoker = mask;
662 /* skip to the next match after the joker(s) */
663 if (is_case_sensitive)
664 while (name < name_end && (*name != *mask)) name++;
665 else
666 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
667 next_to_retry = name;
668 break;
669 case '?':
670 mask++;
671 name++;
672 break;
673 default:
674 if (is_case_sensitive) mismatch = (*mask != *name);
675 else mismatch = (toupperW(*mask) != toupperW(*name));
677 if (!mismatch)
679 mask++;
680 name++;
681 if (mask == mask_end)
683 if (name == name_end) return TRUE;
684 if (lastjoker) mask = lastjoker;
687 else /* mismatch ! */
689 if (lastjoker) /* we had an '*', so we can try unlimitedly */
691 mask = lastjoker;
693 /* this scan sequence was a mismatch, so restart
694 * 1 char after the first char we checked last time */
695 next_to_retry++;
696 name = next_to_retry;
698 else return FALSE; /* bad luck */
700 break;
703 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
704 mask++; /* Ignore trailing '.' or '*' in mask */
705 return (name == name_end && mask == mask_end);
709 /***********************************************************************
710 * append_entry
712 * helper for NtQueryDirectoryFile
714 static FILE_BOTH_DIR_INFORMATION *append_entry( void *info_ptr, ULONG_PTR *pos, ULONG max_length,
715 const char *long_name, const char *short_name,
716 const UNICODE_STRING *mask )
718 FILE_BOTH_DIR_INFORMATION *info;
719 int i, long_len, short_len, total_len;
720 struct stat st;
721 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
722 WCHAR short_nameW[12];
723 UNICODE_STRING str;
725 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
726 if (long_len == -1) return NULL;
728 str.Buffer = long_nameW;
729 str.Length = long_len * sizeof(WCHAR);
730 str.MaximumLength = sizeof(long_nameW);
732 if (short_name)
734 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
735 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
736 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
738 else /* generate a short name if necessary */
740 BOOLEAN spaces;
742 short_len = 0;
743 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
744 short_len = hash_short_file_name( &str, short_nameW );
747 TRACE( "long %s short %s mask %s\n",
748 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
750 if (mask && !match_filename( &str, mask ))
752 if (!short_len) return NULL; /* no short name to match */
753 str.Buffer = short_nameW;
754 str.Length = short_len * sizeof(WCHAR);
755 str.MaximumLength = sizeof(short_nameW);
756 if (!match_filename( &str, mask )) return NULL;
759 total_len = (sizeof(*info) - sizeof(info->FileName) + long_len*sizeof(WCHAR) + 3) & ~3;
760 info = (FILE_BOTH_DIR_INFORMATION *)((char *)info_ptr + *pos);
762 if (*pos + total_len > max_length) total_len = max_length - *pos;
764 info->FileAttributes = 0;
765 if (lstat( long_name, &st ) == -1) return NULL;
766 if (S_ISLNK( st.st_mode ))
768 if (stat( long_name, &st ) == -1) return NULL;
769 if (S_ISDIR( st.st_mode ))
771 if (!show_dir_symlinks) return NULL;
772 info->FileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT;
776 info->NextEntryOffset = total_len;
777 info->FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
779 RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
780 RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
781 RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
782 RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
784 if (S_ISDIR(st.st_mode))
786 info->EndOfFile.QuadPart = info->AllocationSize.QuadPart = 0;
787 info->FileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
789 else
791 info->EndOfFile.QuadPart = st.st_size;
792 info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
793 info->FileAttributes |= FILE_ATTRIBUTE_ARCHIVE;
796 if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
797 info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
799 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
800 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
802 info->EaSize = 0; /* FIXME */
803 info->ShortNameLength = short_len * sizeof(WCHAR);
804 for (i = 0; i < short_len; i++) info->ShortName[i] = toupperW(short_nameW[i]);
805 info->FileNameLength = long_len * sizeof(WCHAR);
806 memcpy( info->FileName, long_nameW,
807 min( info->FileNameLength, total_len-sizeof(*info)+sizeof(info->FileName) ));
809 *pos += total_len;
810 return info;
814 /***********************************************************************
815 * read_directory_vfat
817 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
819 #ifdef VFAT_IOCTL_READDIR_BOTH
820 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
821 BOOLEAN single_entry, const UNICODE_STRING *mask,
822 BOOLEAN restart_scan )
825 int res;
826 KERNEL_DIRENT de[2];
827 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
828 static const unsigned int max_dir_info_size = sizeof(*info) + (MAX_DIR_ENTRY_LEN-1) * sizeof(WCHAR);
830 io->u.Status = STATUS_SUCCESS;
832 if (restart_scan) lseek( fd, 0, SEEK_SET );
834 if (length < max_dir_info_size) /* we may have to return a partial entry here */
836 off_t old_pos = lseek( fd, 0, SEEK_CUR );
838 /* Set d_reclen to 65535 to work around an AFS kernel bug */
839 de[0].d_reclen = 65535;
840 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
841 if (res == -1 && errno != ENOENT) return -1; /* VFAT ioctl probably not supported */
842 if (!res && de[0].d_reclen == 65535) return -1; /* AFS bug */
844 while (res != -1)
846 if (!de[0].d_reclen) break;
847 if (de[1].d_name[0])
848 info = append_entry( buffer, &io->Information, length,
849 de[1].d_name, de[0].d_name, mask );
850 else
851 info = append_entry( buffer, &io->Information, length,
852 de[0].d_name, NULL, mask );
853 if (info)
855 last_info = info;
856 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
858 io->u.Status = STATUS_BUFFER_OVERFLOW;
859 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
861 break;
863 old_pos = lseek( fd, 0, SEEK_CUR );
864 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
867 else /* we'll only return full entries, no need to worry about overflow */
869 /* Set d_reclen to 65535 to work around an AFS kernel bug */
870 de[0].d_reclen = 65535;
871 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
872 if (res == -1 && errno != ENOENT) return -1; /* VFAT ioctl probably not supported */
873 if (!res && de[0].d_reclen == 65535) return -1; /* AFS bug */
875 while (res != -1)
877 if (!de[0].d_reclen) break;
878 if (de[1].d_name[0])
879 info = append_entry( buffer, &io->Information, length,
880 de[1].d_name, de[0].d_name, mask );
881 else
882 info = append_entry( buffer, &io->Information, length,
883 de[0].d_name, NULL, mask );
884 if (info)
886 last_info = info;
887 if (single_entry) break;
888 /* check if we still have enough space for the largest possible entry */
889 if (io->Information + max_dir_info_size > length) break;
891 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
895 if (last_info) last_info->NextEntryOffset = 0;
896 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
897 return 0;
899 #endif /* VFAT_IOCTL_READDIR_BOTH */
902 /***********************************************************************
903 * read_directory_getdents
905 * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
907 #ifdef USE_GETDENTS
908 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
909 BOOLEAN single_entry, const UNICODE_STRING *mask,
910 BOOLEAN restart_scan )
912 off_t old_pos = 0;
913 size_t size = length;
914 int res;
915 char local_buffer[8192];
916 KERNEL_DIRENT64 *data, *de;
917 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
918 static const unsigned int max_dir_info_size = sizeof(*info) + (MAX_DIR_ENTRY_LEN-1) * sizeof(WCHAR);
920 if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
922 size = sizeof(local_buffer);
923 data = (KERNEL_DIRENT64 *)local_buffer;
926 if (restart_scan) lseek( fd, 0, SEEK_SET );
927 else if (length < max_dir_info_size) /* we may have to return a partial entry here */
929 old_pos = lseek( fd, 0, SEEK_CUR );
930 if (old_pos == -1 && errno == ENOENT)
932 io->u.Status = STATUS_NO_MORE_FILES;
933 res = 0;
934 goto done;
938 io->u.Status = STATUS_SUCCESS;
940 res = getdents64( fd, data, size );
941 if (res == -1)
943 if (errno != ENOSYS)
945 io->u.Status = FILE_GetNtStatus();
946 res = 0;
948 goto done;
951 de = data;
953 while (res > 0)
955 res -= de->d_reclen;
956 info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask );
957 if (info)
959 last_info = info;
960 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
962 io->u.Status = STATUS_BUFFER_OVERFLOW;
963 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
964 break;
966 /* check if we still have enough space for the largest possible entry */
967 if (single_entry || io->Information + max_dir_info_size > length)
969 if (res > 0) lseek( fd, de->d_off, SEEK_SET ); /* set pos to next entry */
970 break;
973 old_pos = de->d_off;
974 /* move on to the next entry */
975 if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
976 else
978 res = getdents64( fd, data, size );
979 de = data;
983 if (last_info) last_info->NextEntryOffset = 0;
984 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
985 res = 0;
986 done:
987 if ((char *)data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
988 return res;
990 #endif /* USE_GETDENTS */
993 /***********************************************************************
994 * read_directory_readdir
996 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
998 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
999 BOOLEAN single_entry, const UNICODE_STRING *mask,
1000 BOOLEAN restart_scan )
1002 DIR *dir;
1003 off_t i, old_pos = 0;
1004 struct dirent *de;
1005 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
1006 static const unsigned int max_dir_info_size = sizeof(*info) + (MAX_DIR_ENTRY_LEN-1) * sizeof(WCHAR);
1008 if (!(dir = opendir( "." )))
1010 io->u.Status = FILE_GetNtStatus();
1011 return;
1014 if (!restart_scan)
1016 old_pos = lseek( fd, 0, SEEK_CUR );
1017 /* skip the right number of entries */
1018 for (i = 0; i < old_pos; i++)
1020 if (!readdir( dir ))
1022 closedir( dir );
1023 io->u.Status = STATUS_NO_MORE_FILES;
1024 return;
1028 io->u.Status = STATUS_SUCCESS;
1030 while ((de = readdir( dir )))
1032 old_pos++;
1033 info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask );
1034 if (info)
1036 last_info = info;
1037 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1039 io->u.Status = STATUS_BUFFER_OVERFLOW;
1040 old_pos--; /* restore pos to previous entry */
1041 break;
1043 if (single_entry) break;
1044 /* check if we still have enough space for the largest possible entry */
1045 if (io->Information + max_dir_info_size > length) break;
1049 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
1050 closedir( dir );
1052 if (last_info) last_info->NextEntryOffset = 0;
1053 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1057 /******************************************************************************
1058 * NtQueryDirectoryFile [NTDLL.@]
1059 * ZwQueryDirectoryFile [NTDLL.@]
1061 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
1062 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
1063 PIO_STATUS_BLOCK io,
1064 PVOID buffer, ULONG length,
1065 FILE_INFORMATION_CLASS info_class,
1066 BOOLEAN single_entry,
1067 PUNICODE_STRING mask,
1068 BOOLEAN restart_scan )
1070 int cwd, fd;
1072 TRACE("(%p %p %p %p %p %p 0x%08lx 0x%08x 0x%08x %s 0x%08x\n",
1073 handle, event, apc_routine, apc_context, io, buffer,
1074 length, info_class, single_entry, debugstr_us(mask),
1075 restart_scan);
1077 if (length < sizeof(FILE_BOTH_DIR_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
1079 if (event || apc_routine)
1081 FIXME( "Unsupported yet option\n" );
1082 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1084 if (info_class != FileBothDirectoryInformation)
1086 FIXME( "Unsupported file info class %d\n", info_class );
1087 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1090 if ((io->u.Status = wine_server_handle_to_fd( handle, GENERIC_READ, &fd, NULL )) != STATUS_SUCCESS)
1091 return io->u.Status;
1093 io->Information = 0;
1095 RtlEnterCriticalSection( &dir_section );
1097 if (show_dir_symlinks == -1) init_options();
1099 if ((cwd = open(".", O_RDONLY)) != -1 && fchdir( fd ) != -1)
1101 #ifdef VFAT_IOCTL_READDIR_BOTH
1102 if ((read_directory_vfat( fd, io, buffer, length, single_entry, mask, restart_scan )) == -1)
1103 #endif
1104 #ifdef USE_GETDENTS
1105 if ((read_directory_getdents( fd, io, buffer, length, single_entry, mask, restart_scan )) == -1)
1106 #endif
1107 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan );
1109 if (fchdir( cwd ) == -1) chdir( "/" );
1111 else io->u.Status = FILE_GetNtStatus();
1113 RtlLeaveCriticalSection( &dir_section );
1115 wine_server_release_fd( handle, fd );
1116 if (cwd != -1) close( cwd );
1117 TRACE( "=> %lx (%ld)\n", io->u.Status, io->Information );
1118 return io->u.Status;
1122 /***********************************************************************
1123 * find_file_in_dir
1125 * Find a file in a directory the hard way, by doing a case-insensitive search.
1126 * The file found is appended to unix_name at pos.
1127 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
1129 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
1130 int check_case )
1132 WCHAR buffer[MAX_DIR_ENTRY_LEN];
1133 UNICODE_STRING str;
1134 BOOLEAN spaces;
1135 DIR *dir;
1136 struct dirent *de;
1137 struct stat st;
1138 int ret, used_default, is_name_8_dot_3;
1140 /* try a shortcut for this directory */
1142 unix_name[pos++] = '/';
1143 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
1144 NULL, &used_default );
1145 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
1146 /* so it cannot match the file we are looking for */
1147 if (ret >= 0 && !used_default)
1149 unix_name[pos + ret] = 0;
1150 if (!stat( unix_name, &st )) return STATUS_SUCCESS;
1152 if (check_case) goto not_found; /* we want an exact match */
1154 if (pos > 1) unix_name[pos - 1] = 0;
1155 else unix_name[1] = 0; /* keep the initial slash */
1157 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
1159 str.Buffer = (WCHAR *)name;
1160 str.Length = length * sizeof(WCHAR);
1161 str.MaximumLength = str.Length;
1162 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
1164 /* now look for it through the directory */
1166 #ifdef VFAT_IOCTL_READDIR_BOTH
1167 if (is_name_8_dot_3)
1169 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
1170 if (fd != -1)
1172 KERNEL_DIRENT de[2];
1174 /* Set d_reclen to 65535 to work around an AFS kernel bug */
1175 de[0].d_reclen = 65535;
1176 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) != -1 &&
1177 de[0].d_reclen != 65535)
1179 unix_name[pos - 1] = '/';
1180 for (;;)
1182 if (!de[0].d_reclen) break;
1184 if (de[1].d_name[0])
1186 ret = ntdll_umbstowcs( 0, de[1].d_name, strlen(de[1].d_name),
1187 buffer, MAX_DIR_ENTRY_LEN );
1188 if (ret == length && !memicmpW( buffer, name, length))
1190 strcpy( unix_name + pos, de[1].d_name );
1191 close( fd );
1192 return STATUS_SUCCESS;
1195 ret = ntdll_umbstowcs( 0, de[0].d_name, strlen(de[0].d_name),
1196 buffer, MAX_DIR_ENTRY_LEN );
1197 if (ret == length && !memicmpW( buffer, name, length))
1199 strcpy( unix_name + pos,
1200 de[1].d_name[0] ? de[1].d_name : de[0].d_name );
1201 close( fd );
1202 return STATUS_SUCCESS;
1204 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1)
1206 close( fd );
1207 goto not_found;
1211 close( fd );
1213 /* fall through to normal handling */
1215 #endif /* VFAT_IOCTL_READDIR_BOTH */
1217 if (!(dir = opendir( unix_name )))
1219 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
1220 else return FILE_GetNtStatus();
1222 unix_name[pos - 1] = '/';
1223 str.Buffer = buffer;
1224 str.MaximumLength = sizeof(buffer);
1225 while ((de = readdir( dir )))
1227 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
1228 if (ret == length && !memicmpW( buffer, name, length ))
1230 strcpy( unix_name + pos, de->d_name );
1231 closedir( dir );
1232 return STATUS_SUCCESS;
1235 if (!is_name_8_dot_3) continue;
1237 str.Length = ret * sizeof(WCHAR);
1238 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1240 WCHAR short_nameW[12];
1241 ret = hash_short_file_name( &str, short_nameW );
1242 if (ret == length && !memicmpW( short_nameW, name, length ))
1244 strcpy( unix_name + pos, de->d_name );
1245 closedir( dir );
1246 return STATUS_SUCCESS;
1250 closedir( dir );
1251 goto not_found; /* avoid warning */
1253 not_found:
1254 unix_name[pos - 1] = 0;
1255 return STATUS_OBJECT_PATH_NOT_FOUND;
1259 /******************************************************************************
1260 * get_dos_device
1262 * Get the Unix path of a DOS device.
1264 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
1266 const char *config_dir = wine_get_config_dir();
1267 struct stat st;
1268 char *unix_name, *new_name, *dev;
1269 unsigned int i;
1270 int unix_len;
1272 /* make sure the device name is ASCII */
1273 for (i = 0; i < name_len; i++)
1274 if (name[i] <= 32 || name[i] >= 127) return STATUS_OBJECT_NAME_NOT_FOUND;
1276 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
1278 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1279 return STATUS_NO_MEMORY;
1281 strcpy( unix_name, config_dir );
1282 strcat( unix_name, "/dosdevices/" );
1283 dev = unix_name + strlen(unix_name);
1285 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
1286 dev[i] = 0;
1288 /* special case for drive devices */
1289 if (name_len == 2 && dev[1] == ':')
1291 dev[i++] = ':';
1292 dev[i] = 0;
1295 for (;;)
1297 if (!stat( unix_name, &st ))
1299 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
1300 unix_name_ret->Buffer = unix_name;
1301 unix_name_ret->Length = strlen(unix_name);
1302 unix_name_ret->MaximumLength = unix_len;
1303 return STATUS_SUCCESS;
1305 if (!dev) break;
1307 /* now try some defaults for it */
1308 if (!strcmp( dev, "aux" ))
1310 strcpy( dev, "com1" );
1311 continue;
1313 if (!strcmp( dev, "prn" ))
1315 strcpy( dev, "lpt1" );
1316 continue;
1318 if (!strcmp( dev, "nul" ))
1320 strcpy( unix_name, "/dev/null" );
1321 dev = NULL; /* last try */
1322 continue;
1325 new_name = NULL;
1326 if (dev[1] == ':' && dev[2] == ':') /* drive device */
1328 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
1329 new_name = get_default_drive_device( unix_name );
1331 else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( dev[3] - '0' );
1332 else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( dev[3] - '0' );
1334 if (!new_name) break;
1336 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1337 unix_name = new_name;
1338 unix_len = strlen(unix_name) + 1;
1339 dev = NULL; /* last try */
1341 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1342 return STATUS_OBJECT_NAME_NOT_FOUND;
1346 /* return the length of the DOS namespace prefix if any */
1347 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
1349 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
1350 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
1352 if (name->Length > sizeof(nt_prefixW) &&
1353 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
1354 return sizeof(nt_prefixW) / sizeof(WCHAR);
1356 if (name->Length > sizeof(dosdev_prefixW) &&
1357 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
1358 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
1360 return 0;
1364 /******************************************************************************
1365 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
1367 * Convert a file name from NT namespace to Unix namespace.
1369 * If disposition is not FILE_OPEN or FILE_OVERWRITTE, the last path
1370 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
1371 * returned, but the unix name is still filled in properly.
1373 NTSTATUS wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
1374 UINT disposition, BOOLEAN check_case )
1376 static const WCHAR uncW[] = {'U','N','C','\\'};
1377 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
1379 NTSTATUS status = STATUS_SUCCESS;
1380 const char *config_dir = wine_get_config_dir();
1381 const WCHAR *name, *p;
1382 struct stat st;
1383 char *unix_name;
1384 int pos, ret, name_len, unix_len, used_default;
1386 name = nameW->Buffer;
1387 name_len = nameW->Length / sizeof(WCHAR);
1389 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
1391 if ((pos = get_dos_prefix_len( nameW )))
1393 BOOLEAN is_unc = FALSE;
1395 name += pos;
1396 name_len -= pos;
1398 /* check for UNC prefix */
1399 if (name_len > 4 && !memicmpW( name, uncW, 4 ))
1401 name += 3;
1402 name_len -= 3;
1403 is_unc = TRUE;
1405 else
1407 /* check for a drive letter with path */
1408 if (name_len < 3 || !isalphaW(name[0]) || name[1] != ':' || !IS_SEPARATOR(name[2]))
1410 /* not a drive with path, try other DOS devices */
1411 return get_dos_device( name, name_len, unix_name_ret );
1413 name += 2; /* skip drive letter */
1414 name_len -= 2;
1417 /* check for invalid characters */
1418 for (p = name; p < name + name_len; p++)
1419 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
1421 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1422 unix_len += MAX_DIR_ENTRY_LEN + 3;
1423 unix_len += strlen(config_dir) + sizeof("/dosdevices/") + 3;
1424 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1425 return STATUS_NO_MEMORY;
1426 strcpy( unix_name, config_dir );
1427 strcat( unix_name, "/dosdevices/" );
1428 pos = strlen(unix_name);
1429 if (is_unc)
1431 strcpy( unix_name + pos, "unc" );
1432 pos += 3;
1434 else
1436 unix_name[pos++] = tolowerW( name[-2] );
1437 unix_name[pos++] = ':';
1438 unix_name[pos] = 0;
1441 else /* no DOS prefix, assume NT native name, map directly to Unix */
1443 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_NAME_INVALID;
1444 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1445 unix_len += MAX_DIR_ENTRY_LEN + 3;
1446 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1447 return STATUS_NO_MEMORY;
1448 pos = 0;
1451 /* try a shortcut first */
1453 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
1454 NULL, &used_default );
1456 while (name_len && IS_SEPARATOR(*name))
1458 name++;
1459 name_len--;
1462 if (ret > 0 && !used_default) /* if we used the default char the name didn't convert properly */
1464 char *p;
1465 unix_name[pos + ret] = 0;
1466 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
1467 if (!stat( unix_name, &st ))
1469 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
1470 if (disposition == FILE_CREATE)
1471 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
1472 goto done;
1476 if (!name_len) /* empty name -> drive root doesn't exist */
1478 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1479 return STATUS_OBJECT_PATH_NOT_FOUND;
1481 if (check_case && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
1483 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1484 return STATUS_OBJECT_NAME_NOT_FOUND;
1487 /* now do it component by component */
1489 while (name_len)
1491 const WCHAR *end, *next;
1493 end = name;
1494 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
1495 next = end;
1496 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
1497 name_len -= next - name;
1499 /* grow the buffer if needed */
1501 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
1503 char *new_name;
1504 unix_len += 2 * MAX_DIR_ENTRY_LEN;
1505 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
1507 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1508 return STATUS_NO_MEMORY;
1510 unix_name = new_name;
1513 status = find_file_in_dir( unix_name, pos, name, end - name, check_case );
1515 /* if this is the last element, not finding it is not necessarily fatal */
1516 if (!name_len)
1518 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
1520 status = STATUS_OBJECT_NAME_NOT_FOUND;
1521 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
1523 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
1524 MAX_DIR_ENTRY_LEN, NULL, &used_default );
1525 if (ret > 0 && !used_default)
1527 unix_name[pos] = '/';
1528 unix_name[pos + 1 + ret] = 0;
1529 status = STATUS_NO_SUCH_FILE;
1530 break;
1534 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
1536 status = STATUS_OBJECT_NAME_COLLISION;
1540 if (status != STATUS_SUCCESS)
1542 /* couldn't find it at all, fail */
1543 WARN( "%s not found in %s\n", debugstr_w(name), unix_name );
1544 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1545 return status;
1548 pos += strlen( unix_name + pos );
1549 name = next;
1552 WARN( "%s -> %s required a case-insensitive search\n",
1553 debugstr_us(nameW), debugstr_a(unix_name) );
1555 done:
1556 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
1557 unix_name_ret->Buffer = unix_name;
1558 unix_name_ret->Length = strlen(unix_name);
1559 unix_name_ret->MaximumLength = unix_len;
1560 return status;
1564 /******************************************************************
1565 * RtlDoesFileExists_U (NTDLL.@)
1567 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
1569 UNICODE_STRING nt_name;
1570 ANSI_STRING unix_name;
1571 BOOLEAN ret;
1573 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
1574 ret = (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ) == STATUS_SUCCESS);
1575 if (ret) RtlFreeAnsiString( &unix_name );
1576 RtlFreeUnicodeString( &nt_name );
1577 return ret;
1581 /******************************************************************************
1582 * DIR_get_unix_cwd
1584 * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
1585 * Returned value must be freed by caller.
1587 NTSTATUS DIR_get_unix_cwd( char **cwd )
1589 int old_cwd, unix_fd;
1590 CURDIR *curdir;
1591 HANDLE handle;
1592 NTSTATUS status;
1594 RtlAcquirePebLock();
1596 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1597 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
1598 else
1599 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
1601 if (!(handle = curdir->Handle))
1603 UNICODE_STRING dirW;
1604 OBJECT_ATTRIBUTES attr;
1605 IO_STATUS_BLOCK io;
1607 if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
1609 status = STATUS_OBJECT_NAME_INVALID;
1610 goto done;
1612 attr.Length = sizeof(attr);
1613 attr.RootDirectory = 0;
1614 attr.Attributes = OBJ_CASE_INSENSITIVE;
1615 attr.ObjectName = &dirW;
1616 attr.SecurityDescriptor = NULL;
1617 attr.SecurityQualityOfService = NULL;
1619 status = NtOpenFile( &handle, 0, &attr, &io, 0,
1620 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1621 RtlFreeUnicodeString( &dirW );
1622 if (status != STATUS_SUCCESS) goto done;
1625 if ((status = wine_server_handle_to_fd( handle, 0, &unix_fd, NULL )) == STATUS_SUCCESS)
1627 RtlEnterCriticalSection( &dir_section );
1629 if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
1631 unsigned int size = 512;
1633 for (;;)
1635 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1637 status = STATUS_NO_MEMORY;
1638 break;
1640 if (getcwd( *cwd, size )) break;
1641 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
1642 if (errno != ERANGE)
1644 status = STATUS_OBJECT_PATH_INVALID;
1645 break;
1647 size *= 2;
1649 if (fchdir( old_cwd ) == -1) chdir( "/" );
1651 else status = FILE_GetNtStatus();
1653 RtlLeaveCriticalSection( &dir_section );
1654 wine_server_release_fd( handle, unix_fd );
1656 if (!curdir->Handle) NtClose( handle );
1658 done:
1659 RtlReleasePebLock();
1660 return status;