winejoystick: Fix a crash on accessing a CFArray past its end due to an off-by-one...
[wine/multimedia.git] / dlls / ntdll / directory.c
blobcbfc022be8055e7c6499d745ca8d2b68591e8575
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include "config.h"
24 #include "wine/port.h"
26 #include <assert.h>
27 #include <sys/types.h>
28 #ifdef HAVE_DIRENT_H
29 # include <dirent.h>
30 #endif
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <stdarg.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <limits.h>
38 #ifdef HAVE_MNTENT_H
39 #include <mntent.h>
40 #endif
41 #ifdef HAVE_SYS_STAT_H
42 # include <sys/stat.h>
43 #endif
44 #ifdef HAVE_SYS_SYSCALL_H
45 # include <sys/syscall.h>
46 #endif
47 #ifdef HAVE_SYS_ATTR_H
48 #include <sys/attr.h>
49 #endif
50 #ifdef HAVE_SYS_IOCTL_H
51 #include <sys/ioctl.h>
52 #endif
53 #ifdef HAVE_LINUX_IOCTL_H
54 #include <linux/ioctl.h>
55 #endif
56 #ifdef HAVE_LINUX_MAJOR_H
57 # include <linux/major.h>
58 #endif
59 #ifdef HAVE_SYS_PARAM_H
60 #include <sys/param.h>
61 #endif
62 #ifdef HAVE_SYS_MOUNT_H
63 #include <sys/mount.h>
64 #endif
65 #ifdef HAVE_SYS_STATFS_H
66 #include <sys/statfs.h>
67 #endif
68 #include <time.h>
69 #ifdef HAVE_UNISTD_H
70 # include <unistd.h>
71 #endif
73 #include "ntstatus.h"
74 #define WIN32_NO_STATUS
75 #define NONAMELESSUNION
76 #include "windef.h"
77 #include "winnt.h"
78 #include "winternl.h"
79 #include "ddk/wdm.h"
80 #include "ntdll_misc.h"
81 #include "wine/unicode.h"
82 #include "wine/server.h"
83 #include "wine/list.h"
84 #include "wine/library.h"
85 #include "wine/debug.h"
87 WINE_DEFAULT_DEBUG_CHANNEL(file);
89 /* just in case... */
90 #undef VFAT_IOCTL_READDIR_BOTH
91 #undef USE_GETDENTS
93 #ifdef linux
95 /* We want the real kernel dirent structure, not the libc one */
96 typedef struct
98 long d_ino;
99 long d_off;
100 unsigned short d_reclen;
101 char d_name[256];
102 } KERNEL_DIRENT;
104 /* Define the VFAT ioctl to get both short and long file names */
105 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
107 #ifndef O_DIRECTORY
108 # define O_DIRECTORY 0200000 /* must be directory */
109 #endif
111 #ifdef __NR_getdents64
112 typedef struct
114 ULONG64 d_ino;
115 LONG64 d_off;
116 unsigned short d_reclen;
117 unsigned char d_type;
118 char d_name[256];
119 } KERNEL_DIRENT64;
121 #undef getdents64
122 static inline int getdents64( int fd, char *de, unsigned int size )
124 return syscall( __NR_getdents64, fd, de, size );
126 #define USE_GETDENTS
127 #endif
129 #endif /* linux */
131 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
132 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
134 #define INVALID_NT_CHARS '*','?','<','>','|','"'
135 #define INVALID_DOS_CHARS INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
137 #define MAX_DIR_ENTRY_LEN 255 /* max length of a directory entry in chars */
139 #define MAX_IGNORED_FILES 4
141 struct file_identity
143 dev_t dev;
144 ino_t ino;
147 static struct file_identity ignored_files[MAX_IGNORED_FILES];
148 static unsigned int ignored_files_count;
150 union file_directory_info
152 ULONG next;
153 FILE_DIRECTORY_INFORMATION dir;
154 FILE_BOTH_DIRECTORY_INFORMATION both;
155 FILE_FULL_DIRECTORY_INFORMATION full;
156 FILE_ID_BOTH_DIRECTORY_INFORMATION id_both;
157 FILE_ID_FULL_DIRECTORY_INFORMATION id_full;
160 static BOOL show_dot_files;
161 static RTL_RUN_ONCE init_once = RTL_RUN_ONCE_INIT;
163 /* at some point we may want to allow Winelib apps to set this */
164 static const BOOL is_case_sensitive = FALSE;
166 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
168 static struct file_identity curdir;
169 static struct file_identity windir;
171 static RTL_CRITICAL_SECTION dir_section;
172 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
174 0, 0, &dir_section,
175 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
176 0, 0, { (DWORD_PTR)(__FILE__ ": dir_section") }
178 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
181 /* check if a given Unicode char is OK in a DOS short name */
182 static inline BOOL is_invalid_dos_char( WCHAR ch )
184 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
185 if (ch > 0x7f) return TRUE;
186 return strchrW( invalid_chars, ch ) != NULL;
189 /* check if the device can be a mounted volume */
190 static inline BOOL is_valid_mounted_device( const struct stat *st )
192 #if defined(linux) || defined(__sun__)
193 return S_ISBLK( st->st_mode );
194 #else
195 /* disks are char devices on *BSD */
196 return S_ISCHR( st->st_mode );
197 #endif
200 static inline void ignore_file( const char *name )
202 struct stat st;
203 assert( ignored_files_count < MAX_IGNORED_FILES );
204 if (!stat( name, &st ))
206 ignored_files[ignored_files_count].dev = st.st_dev;
207 ignored_files[ignored_files_count].ino = st.st_ino;
208 ignored_files_count++;
212 static inline BOOL is_same_file( const struct file_identity *file, const struct stat *st )
214 return st->st_dev == file->dev && st->st_ino == file->ino;
217 static inline BOOL is_ignored_file( const struct stat *st )
219 unsigned int i;
221 for (i = 0; i < ignored_files_count; i++)
222 if (is_same_file( &ignored_files[i], st )) return TRUE;
223 return FALSE;
226 static inline unsigned int dir_info_size( FILE_INFORMATION_CLASS class, unsigned int len )
228 switch (class)
230 case FileDirectoryInformation:
231 return (FIELD_OFFSET( FILE_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
232 case FileBothDirectoryInformation:
233 return (FIELD_OFFSET( FILE_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
234 case FileFullDirectoryInformation:
235 return (FIELD_OFFSET( FILE_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
236 case FileIdBothDirectoryInformation:
237 return (FIELD_OFFSET( FILE_ID_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
238 case FileIdFullDirectoryInformation:
239 return (FIELD_OFFSET( FILE_ID_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
240 default:
241 assert(0);
242 return 0;
246 static inline unsigned int max_dir_info_size( FILE_INFORMATION_CLASS class )
248 return dir_info_size( class, MAX_DIR_ENTRY_LEN );
251 static inline BOOL has_wildcard( const UNICODE_STRING *mask )
253 return (!mask ||
254 memchrW( mask->Buffer, '*', mask->Length / sizeof(WCHAR) ) ||
255 memchrW( mask->Buffer, '?', mask->Length / sizeof(WCHAR) ));
259 /* support for a directory queue for filesystem searches */
261 struct dir_name
263 struct list entry;
264 char name[1];
267 static struct list dir_queue = LIST_INIT( dir_queue );
269 static NTSTATUS add_dir_to_queue( const char *name )
271 int len = strlen( name ) + 1;
272 struct dir_name *dir = RtlAllocateHeap( GetProcessHeap(), 0,
273 FIELD_OFFSET( struct dir_name, name[len] ));
274 if (!dir) return STATUS_NO_MEMORY;
275 strcpy( dir->name, name );
276 list_add_tail( &dir_queue, &dir->entry );
277 return STATUS_SUCCESS;
280 static NTSTATUS next_dir_in_queue( char *name )
282 struct list *head = list_head( &dir_queue );
283 if (head)
285 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
286 strcpy( name, dir->name );
287 list_remove( &dir->entry );
288 RtlFreeHeap( GetProcessHeap(), 0, dir );
289 return STATUS_SUCCESS;
291 return STATUS_OBJECT_NAME_NOT_FOUND;
294 static void flush_dir_queue(void)
296 struct list *head;
298 while ((head = list_head( &dir_queue )))
300 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
301 list_remove( &dir->entry );
302 RtlFreeHeap( GetProcessHeap(), 0, dir );
307 /***********************************************************************
308 * get_default_com_device
310 * Return the default device to use for serial ports.
312 static char *get_default_com_device( int num )
314 char *ret = NULL;
316 if (!num || num > 9) return ret;
317 #ifdef linux
318 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
319 if (ret)
321 strcpy( ret, "/dev/ttyS0" );
322 ret[strlen(ret) - 1] = '0' + num - 1;
324 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
325 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuau0") );
326 if (ret)
328 strcpy( ret, "/dev/cuau0" );
329 ret[strlen(ret) - 1] = '0' + num - 1;
331 #elif defined(__DragonFly__)
332 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuaa0") );
333 if (ret)
335 strcpy( ret, "/dev/cuaa0" );
336 ret[strlen(ret) - 1] = '0' + num - 1;
338 #else
339 FIXME( "no known default for device com%d\n", num );
340 #endif
341 return ret;
345 /***********************************************************************
346 * get_default_lpt_device
348 * Return the default device to use for parallel ports.
350 static char *get_default_lpt_device( int num )
352 char *ret = NULL;
354 if (!num || num > 9) return ret;
355 #ifdef linux
356 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
357 if (ret)
359 strcpy( ret, "/dev/lp0" );
360 ret[strlen(ret) - 1] = '0' + num - 1;
362 #else
363 FIXME( "no known default for device lpt%d\n", num );
364 #endif
365 return ret;
368 #ifdef __ANDROID__
370 static char *unescape_field( char *str )
372 char *in, *out;
374 for (in = out = str; *in; in++, out++)
376 *out = *in;
377 if (in[0] == '\\')
379 if (in[1] == '\\')
381 out[0] = '\\';
382 in++;
384 else if (in[1] == '0' && in[2] == '4' && in[3] == '0')
386 out[0] = ' ';
387 in += 3;
389 else if (in[1] == '0' && in[2] == '1' && in[3] == '1')
391 out[0] = '\t';
392 in += 3;
394 else if (in[1] == '0' && in[2] == '1' && in[3] == '2')
396 out[0] = '\n';
397 in += 3;
399 else if (in[1] == '1' && in[2] == '3' && in[3] == '4')
401 out[0] = '\\';
402 in += 3;
406 *out = '\0';
408 return str;
411 static inline char *get_field( char **str )
413 char *ret;
415 ret = strsep( str, " \t" );
416 if (*str) *str += strspn( *str, " \t" );
418 return ret;
420 /************************************************************************
421 * getmntent_replacement
423 * getmntent replacement for Android.
425 * NB returned static buffer is not thread safe; protect with dir_section.
427 static struct mntent *getmntent_replacement( FILE *f )
429 static struct mntent entry;
430 static char buf[4096];
431 char *p, *start;
435 if (!fgets( buf, sizeof(buf), f )) return NULL;
436 p = strchr( buf, '\n' );
437 if (p) *p = '\0';
438 else /* Partially unread line, move file ptr to end */
440 char tmp[1024];
441 while (fgets( tmp, sizeof(tmp), f ))
442 if (strchr( tmp, '\n' )) break;
444 start = buf + strspn( buf, " \t" );
445 } while (start[0] == '\0' || start[0] == '#');
447 p = get_field( &start );
448 entry.mnt_fsname = p ? unescape_field( p ) : (char *)"";
450 p = get_field( &start );
451 entry.mnt_dir = p ? unescape_field( p ) : (char *)"";
453 p = get_field( &start );
454 entry.mnt_type = p ? unescape_field( p ) : (char *)"";
456 p = get_field( &start );
457 entry.mnt_opts = p ? unescape_field( p ) : (char *)"";
459 p = get_field( &start );
460 entry.mnt_freq = p ? atoi(p) : 0;
462 p = get_field( &start );
463 entry.mnt_passno = p ? atoi(p) : 0;
465 return &entry;
467 #define getmntent getmntent_replacement
468 #endif
470 /***********************************************************************
471 * DIR_get_drives_info
473 * Retrieve device/inode number for all the drives. Helper for find_drive_root.
475 unsigned int DIR_get_drives_info( struct drive_info info[MAX_DOS_DRIVES] )
477 static struct drive_info cache[MAX_DOS_DRIVES];
478 static time_t last_update;
479 static unsigned int nb_drives;
480 unsigned int ret;
481 time_t now = time(NULL);
483 RtlEnterCriticalSection( &dir_section );
484 if (now != last_update)
486 const char *config_dir = wine_get_config_dir();
487 char *buffer, *p;
488 struct stat st;
489 unsigned int i;
491 if ((buffer = RtlAllocateHeap( GetProcessHeap(), 0,
492 strlen(config_dir) + sizeof("/dosdevices/a:") )))
494 strcpy( buffer, config_dir );
495 strcat( buffer, "/dosdevices/a:" );
496 p = buffer + strlen(buffer) - 2;
498 for (i = nb_drives = 0; i < MAX_DOS_DRIVES; i++)
500 *p = 'a' + i;
501 if (!stat( buffer, &st ))
503 cache[i].dev = st.st_dev;
504 cache[i].ino = st.st_ino;
505 nb_drives++;
507 else
509 cache[i].dev = 0;
510 cache[i].ino = 0;
513 RtlFreeHeap( GetProcessHeap(), 0, buffer );
515 last_update = now;
517 memcpy( info, cache, sizeof(cache) );
518 ret = nb_drives;
519 RtlLeaveCriticalSection( &dir_section );
520 return ret;
524 /***********************************************************************
525 * parse_mount_entries
527 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
530 #ifdef sun
531 #include <sys/vfstab.h>
532 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
534 struct vfstab entry;
535 struct stat st;
536 char *device;
538 while (! getvfsent( f, &entry ))
540 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
541 if (!strcmp( entry.vfs_fstype, "nfs" ) ||
542 !strcmp( entry.vfs_fstype, "smbfs" ) ||
543 !strcmp( entry.vfs_fstype, "ncpfs" )) continue;
545 if (stat( entry.vfs_mountp, &st ) == -1) continue;
546 if (st.st_dev != dev || st.st_ino != ino) continue;
547 if (!strcmp( entry.vfs_fstype, "fd" ))
549 if ((device = strstr( entry.vfs_mntopts, "dev=" )))
551 char *p = strchr( device + 4, ',' );
552 if (p) *p = 0;
553 return device + 4;
556 else
557 return entry.vfs_special;
559 return NULL;
561 #endif
563 #ifdef linux
564 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
566 struct mntent *entry;
567 struct stat st;
568 char *device;
570 while ((entry = getmntent( f )))
572 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
573 if (!strcmp( entry->mnt_type, "nfs" ) ||
574 !strcmp( entry->mnt_type, "smbfs" ) ||
575 !strcmp( entry->mnt_type, "ncpfs" )) continue;
577 if (stat( entry->mnt_dir, &st ) == -1) continue;
578 if (st.st_dev != dev || st.st_ino != ino) continue;
579 if (!strcmp( entry->mnt_type, "supermount" ))
581 if ((device = strstr( entry->mnt_opts, "dev=" )))
583 char *p = strchr( device + 4, ',' );
584 if (p) *p = 0;
585 return device + 4;
588 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
590 /* if device is a regular file check for a loop mount */
591 if ((device = strstr( entry->mnt_opts, "loop=" )))
593 char *p = strchr( device + 5, ',' );
594 if (p) *p = 0;
595 return device + 5;
598 else
599 return entry->mnt_fsname;
601 return NULL;
603 #endif
605 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
606 #include <fstab.h>
607 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
609 struct fstab *entry;
610 struct stat st;
612 while ((entry = getfsent()))
614 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
615 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
616 !strcmp( entry->fs_vfstype, "smbfs" ) ||
617 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
619 if (stat( entry->fs_file, &st ) == -1) continue;
620 if (st.st_dev != dev || st.st_ino != ino) continue;
621 return entry->fs_spec;
623 return NULL;
625 #endif
627 #ifdef sun
628 #include <sys/mnttab.h>
629 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
631 struct mnttab entry;
632 struct stat st;
633 char *device;
636 while (( ! getmntent( f, &entry) ))
638 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
639 if (!strcmp( entry.mnt_fstype, "nfs" ) ||
640 !strcmp( entry.mnt_fstype, "smbfs" ) ||
641 !strcmp( entry.mnt_fstype, "ncpfs" )) continue;
643 if (stat( entry.mnt_mountp, &st ) == -1) continue;
644 if (st.st_dev != dev || st.st_ino != ino) continue;
645 if (!strcmp( entry.mnt_fstype, "fd" ))
647 if ((device = strstr( entry.mnt_mntopts, "dev=" )))
649 char *p = strchr( device + 4, ',' );
650 if (p) *p = 0;
651 return device + 4;
654 else
655 return entry.mnt_special;
657 return NULL;
659 #endif
661 /***********************************************************************
662 * get_default_drive_device
664 * Return the default device to use for a given drive mount point.
666 static char *get_default_drive_device( const char *root )
668 char *ret = NULL;
670 #ifdef linux
671 FILE *f;
672 char *device = NULL;
673 int fd, res = -1;
674 struct stat st;
676 /* try to open it first to force it to get mounted */
677 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
679 res = fstat( fd, &st );
680 close( fd );
682 /* now try normal stat just in case */
683 if (res == -1) res = stat( root, &st );
684 if (res == -1) return NULL;
686 RtlEnterCriticalSection( &dir_section );
688 #ifdef __ANDROID__
689 if ((f = fopen( "/proc/mounts", "r" )))
691 device = parse_mount_entries( f, st.st_dev, st.st_ino );
692 fclose( f );
694 #else
695 if ((f = fopen( "/etc/mtab", "r" )))
697 device = parse_mount_entries( f, st.st_dev, st.st_ino );
698 fclose( f );
700 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
701 if (!device && (f = fopen( "/etc/fstab", "r" )))
703 device = parse_mount_entries( f, st.st_dev, st.st_ino );
704 fclose( f );
706 #endif
707 if (device)
709 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
710 if (ret) strcpy( ret, device );
712 RtlLeaveCriticalSection( &dir_section );
714 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ ) || defined(__DragonFly__)
715 char *device = NULL;
716 int fd, res = -1;
717 struct stat st;
719 /* try to open it first to force it to get mounted */
720 if ((fd = open( root, O_RDONLY )) != -1)
722 res = fstat( fd, &st );
723 close( fd );
725 /* now try normal stat just in case */
726 if (res == -1) res = stat( root, &st );
727 if (res == -1) return NULL;
729 RtlEnterCriticalSection( &dir_section );
731 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
732 * pass NULL. Leave the argument in for symmetry.
734 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
735 if (device)
737 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
738 if (ret) strcpy( ret, device );
740 RtlLeaveCriticalSection( &dir_section );
742 #elif defined( sun )
743 FILE *f;
744 char *device = NULL;
745 int fd, res = -1;
746 struct stat st;
748 /* try to open it first to force it to get mounted */
749 if ((fd = open( root, O_RDONLY )) != -1)
751 res = fstat( fd, &st );
752 close( fd );
754 /* now try normal stat just in case */
755 if (res == -1) res = stat( root, &st );
756 if (res == -1) return NULL;
758 RtlEnterCriticalSection( &dir_section );
760 if ((f = fopen( "/etc/mnttab", "r" )))
762 device = parse_mount_entries( f, st.st_dev, st.st_ino);
763 fclose( f );
765 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
766 if (!device && (f = fopen( "/etc/vfstab", "r" )))
768 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
769 fclose( f );
771 if (device)
773 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
774 if (ret) strcpy( ret, device );
776 RtlLeaveCriticalSection( &dir_section );
778 #elif defined(__APPLE__)
779 struct statfs *mntStat;
780 struct stat st;
781 int i;
782 int mntSize;
783 dev_t dev;
784 ino_t ino;
785 static const char path_bsd_device[] = "/dev/disk";
786 int res;
788 res = stat( root, &st );
789 if (res == -1) return NULL;
791 dev = st.st_dev;
792 ino = st.st_ino;
794 RtlEnterCriticalSection( &dir_section );
796 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
798 for (i = 0; i < mntSize && !ret; i++)
800 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
801 if (st.st_dev != dev || st.st_ino != ino) continue;
803 /* FIXME add support for mounted network drive */
804 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
806 /* set return value to the corresponding raw BSD node */
807 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
808 if (ret)
810 strcpy(ret, "/dev/r");
811 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
815 RtlLeaveCriticalSection( &dir_section );
816 #else
817 static int warned;
818 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
819 #endif
820 return ret;
824 /***********************************************************************
825 * get_device_mount_point
827 * Return the current mount point for a device.
829 static char *get_device_mount_point( dev_t dev )
831 char *ret = NULL;
833 #ifdef linux
834 FILE *f;
836 RtlEnterCriticalSection( &dir_section );
838 #ifdef __ANDROID__
839 if ((f = fopen( "/proc/mounts", "r" )))
840 #else
841 if ((f = fopen( "/etc/mtab", "r" )))
842 #endif
844 struct mntent *entry;
845 struct stat st;
846 char *p, *device;
848 while ((entry = getmntent( f )))
850 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
851 if (!strcmp( entry->mnt_type, "nfs" ) ||
852 !strcmp( entry->mnt_type, "smbfs" ) ||
853 !strcmp( entry->mnt_type, "ncpfs" )) continue;
855 if (!strcmp( entry->mnt_type, "supermount" ))
857 if ((device = strstr( entry->mnt_opts, "dev=" )))
859 device += 4;
860 if ((p = strchr( device, ',' ))) *p = 0;
863 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
865 /* if device is a regular file check for a loop mount */
866 if ((device = strstr( entry->mnt_opts, "loop=" )))
868 device += 5;
869 if ((p = strchr( device, ',' ))) *p = 0;
872 else device = entry->mnt_fsname;
874 if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
876 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
877 if (ret) strcpy( ret, entry->mnt_dir );
878 break;
881 fclose( f );
883 RtlLeaveCriticalSection( &dir_section );
884 #elif defined(__APPLE__)
885 struct statfs *entry;
886 struct stat st;
887 int i, size;
889 RtlEnterCriticalSection( &dir_section );
891 size = getmntinfo( &entry, MNT_NOWAIT );
892 for (i = 0; i < size; i++)
894 if (stat( entry[i].f_mntfromname, &st ) == -1) continue;
895 if (S_ISBLK(st.st_mode) && st.st_rdev == dev)
897 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry[i].f_mntonname) + 1 );
898 if (ret) strcpy( ret, entry[i].f_mntonname );
899 break;
902 RtlLeaveCriticalSection( &dir_section );
903 #else
904 static int warned;
905 if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
906 #endif
907 return ret;
911 #if defined(HAVE_GETATTRLIST) && defined(ATTR_VOL_CAPABILITIES) && \
912 defined(VOL_CAPABILITIES_FORMAT) && defined(VOL_CAP_FMT_CASE_SENSITIVE)
914 struct get_fsid
916 ULONG size;
917 dev_t dev;
918 fsid_t fsid;
921 struct fs_cache
923 dev_t dev;
924 fsid_t fsid;
925 BOOLEAN case_sensitive;
926 } fs_cache[64];
928 struct vol_caps
930 ULONG size;
931 vol_capabilities_attr_t caps;
934 /***********************************************************************
935 * look_up_fs_cache
937 * Checks if the specified file system is in the cache.
939 static struct fs_cache *look_up_fs_cache( dev_t dev )
941 int i;
942 for (i = 0; i < sizeof(fs_cache)/sizeof(fs_cache[0]); i++)
943 if (fs_cache[i].dev == dev)
944 return fs_cache+i;
945 return NULL;
948 /***********************************************************************
949 * add_fs_cache
951 * Adds the specified file system to the cache.
953 static void add_fs_cache( dev_t dev, fsid_t fsid, BOOLEAN case_sensitive )
955 int i;
956 struct fs_cache *entry = look_up_fs_cache( dev );
957 static int once = 0;
958 if (entry)
960 /* Update the cache */
961 entry->fsid = fsid;
962 entry->case_sensitive = case_sensitive;
963 return;
966 /* Add a new entry */
967 for (i = 0; i < sizeof(fs_cache)/sizeof(fs_cache[0]); i++)
968 if (fs_cache[i].dev == 0)
970 /* This entry is empty, use it */
971 fs_cache[i].dev = dev;
972 fs_cache[i].fsid = fsid;
973 fs_cache[i].case_sensitive = case_sensitive;
974 return;
977 /* Cache is out of space, warn */
978 if (!once++)
979 WARN( "FS cache is out of space, expect performance problems\n" );
982 /***********************************************************************
983 * get_dir_case_sensitivity_attr
985 * Checks if the volume containing the specified directory is case
986 * sensitive or not. Uses getattrlist(2).
988 static int get_dir_case_sensitivity_attr( const char *dir )
990 char *mntpoint = NULL;
991 struct attrlist attr;
992 struct vol_caps caps;
993 struct get_fsid get_fsid;
994 struct fs_cache *entry;
996 /* First get the FS ID of the volume */
997 attr.bitmapcount = ATTR_BIT_MAP_COUNT;
998 attr.reserved = 0;
999 attr.commonattr = ATTR_CMN_DEVID|ATTR_CMN_FSID;
1000 attr.volattr = attr.dirattr = attr.fileattr = attr.forkattr = 0;
1001 get_fsid.size = 0;
1002 if (getattrlist( dir, &attr, &get_fsid, sizeof(get_fsid), 0 ) != 0 ||
1003 get_fsid.size != sizeof(get_fsid))
1004 return -1;
1005 /* Try to look it up in the cache */
1006 entry = look_up_fs_cache( get_fsid.dev );
1007 if (entry && !memcmp( &entry->fsid, &get_fsid.fsid, sizeof(fsid_t) ))
1008 /* Cache lookup succeeded */
1009 return entry->case_sensitive;
1010 /* Cache is stale at this point, we have to update it */
1012 mntpoint = get_device_mount_point( get_fsid.dev );
1013 /* Now look up the case-sensitivity */
1014 attr.commonattr = 0;
1015 attr.volattr = ATTR_VOL_INFO|ATTR_VOL_CAPABILITIES;
1016 if (getattrlist( mntpoint, &attr, &caps, sizeof(caps), 0 ) < 0)
1018 RtlFreeHeap( GetProcessHeap(), 0, mntpoint );
1019 add_fs_cache( get_fsid.dev, get_fsid.fsid, TRUE );
1020 return TRUE;
1022 RtlFreeHeap( GetProcessHeap(), 0, mntpoint );
1023 if (caps.size == sizeof(caps) &&
1024 (caps.caps.valid[VOL_CAPABILITIES_FORMAT] &
1025 (VOL_CAP_FMT_CASE_SENSITIVE | VOL_CAP_FMT_CASE_PRESERVING)) ==
1026 (VOL_CAP_FMT_CASE_SENSITIVE | VOL_CAP_FMT_CASE_PRESERVING))
1028 BOOLEAN ret;
1030 if ((caps.caps.capabilities[VOL_CAPABILITIES_FORMAT] &
1031 VOL_CAP_FMT_CASE_SENSITIVE) != VOL_CAP_FMT_CASE_SENSITIVE)
1032 ret = FALSE;
1033 else
1034 ret = TRUE;
1035 /* Update the cache */
1036 add_fs_cache( get_fsid.dev, get_fsid.fsid, ret );
1037 return ret;
1039 return FALSE;
1041 #endif
1043 /***********************************************************************
1044 * get_dir_case_sensitivity_stat
1046 * Checks if the volume containing the specified directory is case
1047 * sensitive or not. Uses statfs(2) or statvfs(2).
1049 static BOOLEAN get_dir_case_sensitivity_stat( const char *dir )
1051 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1052 struct statfs stfs;
1054 if (statfs( dir, &stfs ) == -1) return FALSE;
1055 /* Assume these file systems are always case insensitive on Mac OS.
1056 * For FreeBSD, only assume CIOPFS is case insensitive (AFAIK, Mac OS
1057 * is the only UNIX that supports case-insensitive lookup).
1059 if (!strcmp( stfs.f_fstypename, "fusefs" ) &&
1060 !strncmp( stfs.f_mntfromname, "ciopfs", 5 ))
1061 return FALSE;
1062 #ifdef __APPLE__
1063 if (!strcmp( stfs.f_fstypename, "msdos" ) ||
1064 !strcmp( stfs.f_fstypename, "cd9660" ) ||
1065 !strcmp( stfs.f_fstypename, "udf" ) ||
1066 !strcmp( stfs.f_fstypename, "ntfs" ) ||
1067 !strcmp( stfs.f_fstypename, "smbfs" ))
1068 return FALSE;
1069 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1070 if (!strcmp( stfs.f_fstypename, "hfs" ) && (stfs.f_fssubtype == 0 ||
1071 stfs.f_fssubtype == 1 ||
1072 stfs.f_fssubtype == 128))
1073 return FALSE;
1074 #else
1075 /* The field says "reserved", but a quick look at the kernel source
1076 * tells us that this "reserved" field is really the same as the
1077 * "fssubtype" field from the inode64 structure (see munge_statfs()
1078 * in <xnu-source>/bsd/vfs/vfs_syscalls.c).
1080 if (!strcmp( stfs.f_fstypename, "hfs" ) && (stfs.f_reserved1 == 0 ||
1081 stfs.f_reserved1 == 1 ||
1082 stfs.f_reserved1 == 128))
1083 return FALSE;
1084 #endif
1085 #endif
1086 return TRUE;
1088 #elif defined(__NetBSD__)
1089 struct statvfs stfs;
1091 if (statvfs( dir, &stfs ) == -1) return FALSE;
1092 /* Only assume CIOPFS is case insensitive. */
1093 if (strcmp( stfs.f_fstypename, "fusefs" ) ||
1094 strncmp( stfs.f_mntfromname, "ciopfs", 5 ))
1095 return TRUE;
1096 return FALSE;
1098 #elif defined(__linux__)
1099 struct statfs stfs;
1100 struct stat st;
1101 char *cifile;
1103 /* Only assume CIOPFS is case insensitive. */
1104 if (statfs( dir, &stfs ) == -1) return FALSE;
1105 if (stfs.f_type != 0x65735546 /* FUSE_SUPER_MAGIC */)
1106 return TRUE;
1107 /* Normally, we'd have to parse the mtab to find out exactly what
1108 * kind of FUSE FS this is. But, someone on wine-devel suggested
1109 * a shortcut. We'll stat a special file in the directory. If it's
1110 * there, we'll assume it's a CIOPFS, else not.
1111 * This will break if somebody puts a file named ".ciopfs" in a non-
1112 * CIOPFS directory.
1114 cifile = RtlAllocateHeap( GetProcessHeap(), 0, strlen( dir )+sizeof("/.ciopfs") );
1115 if (!cifile) return TRUE;
1116 strcpy( cifile, dir );
1117 strcat( cifile, "/.ciopfs" );
1118 if (stat( cifile, &st ) == 0)
1120 RtlFreeHeap( GetProcessHeap(), 0, cifile );
1121 return FALSE;
1123 RtlFreeHeap( GetProcessHeap(), 0, cifile );
1124 return TRUE;
1125 #else
1126 return TRUE;
1127 #endif
1131 /***********************************************************************
1132 * get_dir_case_sensitivity
1134 * Checks if the volume containing the specified directory is case
1135 * sensitive or not. Uses statfs(2) or statvfs(2).
1137 static BOOLEAN get_dir_case_sensitivity( const char *dir )
1139 #if defined(HAVE_GETATTRLIST) && defined(ATTR_VOL_CAPABILITIES) && \
1140 defined(VOL_CAPABILITIES_FORMAT) && defined(VOL_CAP_FMT_CASE_SENSITIVE)
1141 int case_sensitive = get_dir_case_sensitivity_attr( dir );
1142 if (case_sensitive != -1) return case_sensitive;
1143 #endif
1144 return get_dir_case_sensitivity_stat( dir );
1148 /***********************************************************************
1149 * init_options
1151 * Initialize the show_dot_files options.
1153 static DWORD WINAPI init_options( RTL_RUN_ONCE *once, void *param, void **context )
1155 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
1156 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
1157 char tmp[80];
1158 HANDLE root, hkey;
1159 DWORD dummy;
1160 OBJECT_ATTRIBUTES attr;
1161 UNICODE_STRING nameW;
1163 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
1164 attr.Length = sizeof(attr);
1165 attr.RootDirectory = root;
1166 attr.ObjectName = &nameW;
1167 attr.Attributes = 0;
1168 attr.SecurityDescriptor = NULL;
1169 attr.SecurityQualityOfService = NULL;
1170 RtlInitUnicodeString( &nameW, WineW );
1172 /* @@ Wine registry key: HKCU\Software\Wine */
1173 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
1175 RtlInitUnicodeString( &nameW, ShowDotFilesW );
1176 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
1178 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
1179 show_dot_files = IS_OPTION_TRUE( str[0] );
1181 NtClose( hkey );
1183 NtClose( root );
1185 /* a couple of directories that we don't want to return in directory searches */
1186 ignore_file( wine_get_config_dir() );
1187 ignore_file( "/dev" );
1188 ignore_file( "/proc" );
1189 #ifdef linux
1190 ignore_file( "/sys" );
1191 #endif
1192 return TRUE;
1196 /***********************************************************************
1197 * DIR_is_hidden_file
1199 * Check if the specified file should be hidden based on its name and the show dot files option.
1201 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
1203 WCHAR *p, *end;
1205 RtlRunOnceExecuteOnce( &init_once, init_options, NULL, NULL );
1207 if (show_dot_files) return FALSE;
1209 end = p = name->Buffer + name->Length/sizeof(WCHAR);
1210 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
1211 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
1212 if (p == end || *p != '.') return FALSE;
1213 /* make sure it isn't '.' or '..' */
1214 if (p + 1 == end) return FALSE;
1215 if (p[1] == '.' && p + 2 == end) return FALSE;
1216 return TRUE;
1220 /***********************************************************************
1221 * hash_short_file_name
1223 * Transform a Unix file name into a hashed DOS name. If the name is a valid
1224 * DOS name, it is converted to upper-case; otherwise it is replaced by a
1225 * hashed version that fits in 8.3 format.
1226 * 'buffer' must be at least 12 characters long.
1227 * Returns length of short name in bytes; short name is NOT null-terminated.
1229 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
1231 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
1233 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
1234 LPWSTR dst;
1235 unsigned short hash;
1236 int i;
1238 /* Compute the hash code of the file name */
1239 /* If you know something about hash functions, feel free to */
1240 /* insert a better algorithm here... */
1241 if (!is_case_sensitive)
1243 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
1244 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
1245 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
1247 else
1249 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
1250 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
1251 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
1254 /* Find last dot for start of the extension */
1255 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
1257 /* Copy first 4 chars, replacing invalid chars with '_' */
1258 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
1260 if (p == end || p == ext) break;
1261 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
1263 /* Pad to 5 chars with '~' */
1264 while (i-- >= 0) *dst++ = '~';
1266 /* Insert hash code converted to 3 ASCII chars */
1267 *dst++ = hash_chars[(hash >> 10) & 0x1f];
1268 *dst++ = hash_chars[(hash >> 5) & 0x1f];
1269 *dst++ = hash_chars[hash & 0x1f];
1271 /* Copy the first 3 chars of the extension (if any) */
1272 if (ext)
1274 *dst++ = '.';
1275 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
1276 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
1278 return dst - buffer;
1282 /***********************************************************************
1283 * match_filename
1285 * Check a long file name against a mask.
1287 * Tests (done in W95 DOS shell - case insensitive):
1288 * *.txt test1.test.txt *
1289 * *st1* test1.txt *
1290 * *.t??????.t* test1.ta.tornado.txt *
1291 * *tornado* test1.ta.tornado.txt *
1292 * t*t test1.ta.tornado.txt *
1293 * ?est* test1.txt *
1294 * ?est??? test1.txt -
1295 * *test1.txt* test1.txt *
1296 * h?l?o*t.dat hellothisisatest.dat *
1298 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
1300 BOOL mismatch;
1301 const WCHAR *name = name_str->Buffer;
1302 const WCHAR *mask = mask_str->Buffer;
1303 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
1304 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
1305 const WCHAR *lastjoker = NULL;
1306 const WCHAR *next_to_retry = NULL;
1308 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
1310 while (name < name_end && mask < mask_end)
1312 switch(*mask)
1314 case '*':
1315 mask++;
1316 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
1317 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
1318 lastjoker = mask;
1320 /* skip to the next match after the joker(s) */
1321 if (is_case_sensitive)
1322 while (name < name_end && (*name != *mask)) name++;
1323 else
1324 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
1325 next_to_retry = name;
1326 break;
1327 case '?':
1328 mask++;
1329 name++;
1330 break;
1331 default:
1332 if (is_case_sensitive) mismatch = (*mask != *name);
1333 else mismatch = (toupperW(*mask) != toupperW(*name));
1335 if (!mismatch)
1337 mask++;
1338 name++;
1339 if (mask == mask_end)
1341 if (name == name_end) return TRUE;
1342 if (lastjoker) mask = lastjoker;
1345 else /* mismatch ! */
1347 if (lastjoker) /* we had an '*', so we can try unlimitedly */
1349 mask = lastjoker;
1351 /* this scan sequence was a mismatch, so restart
1352 * 1 char after the first char we checked last time */
1353 next_to_retry++;
1354 name = next_to_retry;
1356 else return FALSE; /* bad luck */
1358 break;
1361 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
1362 mask++; /* Ignore trailing '.' or '*' in mask */
1363 return (name == name_end && mask == mask_end);
1367 /***********************************************************************
1368 * append_entry
1370 * helper for NtQueryDirectoryFile
1372 static union file_directory_info *append_entry( void *info_ptr, IO_STATUS_BLOCK *io, ULONG max_length,
1373 const char *long_name, const char *short_name,
1374 const UNICODE_STRING *mask, FILE_INFORMATION_CLASS class )
1376 union file_directory_info *info;
1377 int i, long_len, short_len, total_len;
1378 struct stat st;
1379 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
1380 WCHAR short_nameW[12];
1381 WCHAR *filename;
1382 UNICODE_STRING str;
1383 ULONG attributes;
1385 io->u.Status = STATUS_SUCCESS;
1386 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
1387 if (long_len == -1) return NULL;
1389 str.Buffer = long_nameW;
1390 str.Length = long_len * sizeof(WCHAR);
1391 str.MaximumLength = sizeof(long_nameW);
1393 if (short_name)
1395 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
1396 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
1397 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
1399 else /* generate a short name if necessary */
1401 BOOLEAN spaces;
1403 short_len = 0;
1404 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1405 short_len = hash_short_file_name( &str, short_nameW );
1408 TRACE( "long %s short %s mask %s\n",
1409 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
1411 if (mask && !match_filename( &str, mask ))
1413 if (!short_len) return NULL; /* no short name to match */
1414 str.Buffer = short_nameW;
1415 str.Length = short_len * sizeof(WCHAR);
1416 str.MaximumLength = sizeof(short_nameW);
1417 if (!match_filename( &str, mask )) return NULL;
1420 if (get_file_info( long_name, &st, &attributes ) == -1) return NULL;
1421 if (is_ignored_file( &st ))
1423 TRACE( "ignoring file %s\n", long_name );
1424 return NULL;
1426 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
1427 attributes |= FILE_ATTRIBUTE_HIDDEN;
1429 total_len = dir_info_size( class, long_len );
1430 if (io->Information + total_len > max_length)
1432 total_len = max_length - io->Information;
1433 io->u.Status = STATUS_BUFFER_OVERFLOW;
1435 info = (union file_directory_info *)((char *)info_ptr + io->Information);
1436 if (st.st_dev != curdir.dev) st.st_ino = 0; /* ignore inode if on a different device */
1437 /* all the structures start with a FileDirectoryInformation layout */
1438 fill_file_info( &st, attributes, info, class );
1439 info->dir.NextEntryOffset = total_len;
1440 info->dir.FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
1442 switch (class)
1444 case FileDirectoryInformation:
1445 info->dir.FileNameLength = long_len * sizeof(WCHAR);
1446 filename = info->dir.FileName;
1447 break;
1449 case FileFullDirectoryInformation:
1450 info->full.EaSize = 0; /* FIXME */
1451 info->full.FileNameLength = long_len * sizeof(WCHAR);
1452 filename = info->full.FileName;
1453 break;
1455 case FileIdFullDirectoryInformation:
1456 info->id_full.EaSize = 0; /* FIXME */
1457 info->id_full.FileNameLength = long_len * sizeof(WCHAR);
1458 filename = info->id_full.FileName;
1459 break;
1461 case FileBothDirectoryInformation:
1462 info->both.EaSize = 0; /* FIXME */
1463 info->both.ShortNameLength = short_len * sizeof(WCHAR);
1464 for (i = 0; i < short_len; i++) info->both.ShortName[i] = toupperW(short_nameW[i]);
1465 info->both.FileNameLength = long_len * sizeof(WCHAR);
1466 filename = info->both.FileName;
1467 break;
1469 case FileIdBothDirectoryInformation:
1470 info->id_both.EaSize = 0; /* FIXME */
1471 info->id_both.ShortNameLength = short_len * sizeof(WCHAR);
1472 for (i = 0; i < short_len; i++) info->id_both.ShortName[i] = toupperW(short_nameW[i]);
1473 info->id_both.FileNameLength = long_len * sizeof(WCHAR);
1474 filename = info->id_both.FileName;
1475 break;
1477 default:
1478 assert(0);
1479 return NULL;
1481 memcpy( filename, long_nameW, long_len * sizeof(WCHAR) );
1482 io->Information += total_len;
1483 return info;
1487 #ifdef VFAT_IOCTL_READDIR_BOTH
1489 /***********************************************************************
1490 * start_vfat_ioctl
1492 * Wrapper for the VFAT ioctl to work around various kernel bugs.
1493 * dir_section must be held by caller.
1495 static KERNEL_DIRENT *start_vfat_ioctl( int fd )
1497 static KERNEL_DIRENT *de;
1498 int res;
1500 if (!de)
1502 SIZE_T size = 2 * sizeof(*de) + page_size;
1503 void *addr = NULL;
1505 if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_RESERVE, PAGE_READWRITE ))
1506 return NULL;
1507 /* commit only the size needed for the dir entries */
1508 /* this leaves an extra unaccessible page, which should make the kernel */
1509 /* fail with -EFAULT before it stomps all over our memory */
1510 de = addr;
1511 size = 2 * sizeof(*de);
1512 NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_COMMIT, PAGE_READWRITE );
1515 /* set d_reclen to 65535 to work around an AFS kernel bug */
1516 de[0].d_reclen = 65535;
1517 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
1518 if (res == -1)
1520 if (errno != ENOENT) return NULL; /* VFAT ioctl probably not supported */
1521 de[0].d_reclen = 0; /* eof */
1523 else if (!res && de[0].d_reclen == 65535) return NULL; /* AFS bug */
1525 return de;
1529 /***********************************************************************
1530 * read_directory_vfat
1532 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
1534 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1535 BOOLEAN single_entry, const UNICODE_STRING *mask,
1536 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1539 size_t len;
1540 KERNEL_DIRENT *de;
1541 union file_directory_info *info, *last_info = NULL;
1543 io->u.Status = STATUS_SUCCESS;
1545 if (restart_scan) lseek( fd, 0, SEEK_SET );
1547 if (length < max_dir_info_size(class)) /* we may have to return a partial entry here */
1549 off_t old_pos = lseek( fd, 0, SEEK_CUR );
1551 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1553 while (de[0].d_reclen)
1555 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1556 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1557 de[0].d_name[len] = 0;
1558 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1559 de[1].d_name[len] = 0;
1561 if (de[1].d_name[0])
1562 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1563 else
1564 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1565 if (info)
1567 last_info = info;
1568 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1569 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1570 break;
1572 old_pos = lseek( fd, 0, SEEK_CUR );
1573 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1576 else /* we'll only return full entries, no need to worry about overflow */
1578 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1580 while (de[0].d_reclen)
1582 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1583 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1584 de[0].d_name[len] = 0;
1585 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1586 de[1].d_name[len] = 0;
1588 if (de[1].d_name[0])
1589 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1590 else
1591 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1592 if (info)
1594 last_info = info;
1595 if (single_entry) break;
1596 /* check if we still have enough space for the largest possible entry */
1597 if (io->Information + max_dir_info_size(class) > length) break;
1599 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1603 if (last_info) last_info->next = 0;
1604 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1605 return 0;
1607 #endif /* VFAT_IOCTL_READDIR_BOTH */
1610 #ifdef USE_GETDENTS
1611 /***********************************************************************
1612 * read_first_dent_name
1614 * reads name of first or second dentry (if they have inodes).
1616 static char *read_first_dent_name( int which, int fd, off_t second_offs, KERNEL_DIRENT64 *de_first_two,
1617 char *buffer, size_t size, BOOL *buffer_changed )
1619 KERNEL_DIRENT64 *de;
1620 int res;
1622 de = de_first_two;
1623 if (de != NULL)
1625 if (which == 1)
1626 de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1628 return de->d_ino ? de->d_name : NULL;
1631 *buffer_changed = TRUE;
1632 lseek( fd, which == 1 ? second_offs : 0, SEEK_SET );
1633 res = getdents64( fd, buffer, size );
1634 if (res <= 0)
1635 return NULL;
1637 de = (KERNEL_DIRENT64 *)buffer;
1638 return de->d_ino ? de->d_name : NULL;
1641 /***********************************************************************
1642 * read_directory_getdents
1644 * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
1646 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1647 BOOLEAN single_entry, const UNICODE_STRING *mask,
1648 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1650 static off_t second_entry_pos;
1651 static struct file_identity last_dir_id;
1652 off_t old_pos = 0, next_pos;
1653 size_t size = length;
1654 char *data, local_buffer[8192];
1655 KERNEL_DIRENT64 *de, *de_first_two = NULL;
1656 union file_directory_info *info, *last_info = NULL;
1657 const char *filename;
1658 BOOL data_buffer_changed;
1659 int res, swap_to;
1661 if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1663 size = sizeof(local_buffer);
1664 data = local_buffer;
1667 if (restart_scan) lseek( fd, 0, SEEK_SET );
1668 else
1670 old_pos = lseek( fd, 0, SEEK_CUR );
1671 if (old_pos == -1)
1673 io->u.Status = (errno == ENOENT) ? STATUS_NO_MORE_FILES : FILE_GetNtStatus();
1674 res = 0;
1675 goto done;
1679 io->u.Status = STATUS_SUCCESS;
1680 de = (KERNEL_DIRENT64 *)data;
1682 /* if old_pos is not 0 we don't know how many entries have been returned already,
1683 * so maintain second_entry_pos to know when to return '..' */
1684 if (old_pos != 0 && (last_dir_id.dev != curdir.dev || last_dir_id.ino != curdir.ino))
1686 lseek( fd, 0, SEEK_SET );
1687 res = getdents64( fd, data, size );
1688 if (res > 0)
1690 second_entry_pos = de->d_off;
1691 last_dir_id = curdir;
1693 lseek( fd, old_pos, SEEK_SET );
1696 res = getdents64( fd, data, size );
1697 if (res == -1)
1699 if (errno != ENOSYS)
1701 io->u.Status = FILE_GetNtStatus();
1702 res = 0;
1704 goto done;
1707 if (old_pos == 0 && res > 0)
1709 second_entry_pos = de->d_off;
1710 last_dir_id = curdir;
1711 if (res > de->d_reclen)
1712 de_first_two = de;
1715 while (res > 0)
1717 res -= de->d_reclen;
1718 next_pos = de->d_off;
1719 filename = NULL;
1721 /* we must return first 2 entries as "." and "..", but getdents64()
1722 * can return them anywhere, so swap first entries with "." and ".." */
1723 if (old_pos == 0)
1724 filename = ".";
1725 else if (old_pos == second_entry_pos)
1726 filename = "..";
1727 else if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))
1729 swap_to = !strcmp( de->d_name, "." ) ? 0 : 1;
1730 data_buffer_changed = FALSE;
1732 filename = read_first_dent_name( swap_to, fd, second_entry_pos, de_first_two,
1733 data, size, &data_buffer_changed );
1734 if (filename != NULL && (!strcmp( filename, "." ) || !strcmp( filename, ".." )))
1735 filename = read_first_dent_name( swap_to ^ 1, fd, second_entry_pos, NULL,
1736 data, size, &data_buffer_changed );
1737 if (data_buffer_changed)
1739 lseek( fd, next_pos, SEEK_SET );
1740 res = 0;
1743 else if (de->d_ino)
1744 filename = de->d_name;
1746 if (filename && (info = append_entry( buffer, io, length, filename, NULL, mask, class )))
1748 last_info = info;
1749 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1751 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1752 break;
1754 /* check if we still have enough space for the largest possible entry */
1755 if (single_entry || io->Information + max_dir_info_size(class) > length)
1757 if (res > 0) lseek( fd, next_pos, SEEK_SET ); /* set pos to next entry */
1758 break;
1761 old_pos = next_pos;
1762 /* move on to the next entry */
1763 if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1764 else
1766 res = getdents64( fd, data, size );
1767 de = (KERNEL_DIRENT64 *)data;
1768 de_first_two = NULL;
1772 if (last_info) last_info->next = 0;
1773 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1774 res = 0;
1775 done:
1776 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1777 return res;
1780 #elif defined HAVE_GETDIRENTRIES
1782 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1784 /* Darwin doesn't provide a version of getdirentries with support for 64-bit
1785 * inodes. When 64-bit inodes are enabled, the getdirentries symbol is mapped
1786 * to _getdirentries_is_not_available_when_64_bit_inodes_are_in_effect so that
1787 * we get link errors if we try to use it. We still need getdirentries, but we
1788 * don't need it to support 64-bit inodes. So, we use the legacy getdirentries
1789 * with 32-bit inodes. We have to be careful to use a corresponding dirent
1790 * structure, too.
1792 int darwin_legacy_getdirentries(int, char *, int, long *) __asm("_getdirentries");
1793 #define getdirentries darwin_legacy_getdirentries
1795 struct darwin_legacy_dirent {
1796 __uint32_t d_ino;
1797 __uint16_t d_reclen;
1798 __uint8_t d_type;
1799 __uint8_t d_namlen;
1800 char d_name[__DARWIN_MAXNAMLEN + 1];
1802 #define dirent darwin_legacy_dirent
1804 #endif
1806 /***********************************************************************
1807 * wine_getdirentries
1809 * Wrapper for the BSD getdirentries system call to fix a bug in the
1810 * Mac OS X version. For some file systems (at least Apple Filing
1811 * Protocol a.k.a. AFP), getdirentries resets the file position to 0
1812 * when it's about to return 0 (no more entries). So, a subsequent
1813 * getdirentries call starts over at the beginning again, causing an
1814 * infinite loop.
1816 static inline int wine_getdirentries(int fd, char *buf, int nbytes, long *basep)
1818 int res = getdirentries(fd, buf, nbytes, basep);
1819 #ifdef __APPLE__
1820 if (res == 0)
1821 lseek(fd, *basep, SEEK_SET);
1822 #endif
1823 return res;
1826 static inline int dir_reclen(struct dirent *de)
1828 #ifdef HAVE_STRUCT_DIRENT_D_RECLEN
1829 return de->d_reclen;
1830 #else
1831 return _DIRENT_RECLEN(de->d_namlen);
1832 #endif
1835 /***********************************************************************
1836 * read_directory_getdirentries
1838 * Read a directory using the BSD getdirentries system call; helper for NtQueryDirectoryFile.
1840 static int read_directory_getdirentries( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1841 BOOLEAN single_entry, const UNICODE_STRING *mask,
1842 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1844 long restart_pos;
1845 ULONG_PTR restart_info_pos = 0;
1846 size_t size, initial_size = length;
1847 int res, fake_dot_dot = 1;
1848 char *data, local_buffer[8192];
1849 struct dirent *de;
1850 union file_directory_info *info, *last_info = NULL, *restart_last_info = NULL;
1852 size = initial_size;
1853 data = local_buffer;
1854 if (size > sizeof(local_buffer) && !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1856 io->u.Status = STATUS_NO_MEMORY;
1857 return io->u.Status;
1860 if (restart_scan) lseek( fd, 0, SEEK_SET );
1862 io->u.Status = STATUS_SUCCESS;
1864 /* FIXME: should make sure size is larger than filesystem block size */
1865 res = wine_getdirentries( fd, data, size, &restart_pos );
1866 if (res == -1)
1868 io->u.Status = FILE_GetNtStatus();
1869 res = 0;
1870 goto done;
1873 de = (struct dirent *)data;
1875 if (restart_scan)
1877 /* check if we got . and .. from getdirentries */
1878 if (res > 0)
1880 if (!strcmp( de->d_name, "." ) && res > dir_reclen(de))
1882 struct dirent *next_de = (struct dirent *)(data + dir_reclen(de));
1883 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1886 /* make sure we have enough room for both entries */
1887 if (fake_dot_dot)
1889 const ULONG min_info_size = dir_info_size( class, 1 ) + dir_info_size( class, 2 );
1890 if (length < min_info_size || single_entry)
1892 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1893 fake_dot_dot = 0;
1897 if (fake_dot_dot)
1899 if ((info = append_entry( buffer, io, length, ".", NULL, mask, class )))
1900 last_info = info;
1901 if ((info = append_entry( buffer, io, length, "..", NULL, mask, class )))
1902 last_info = info;
1904 restart_last_info = last_info;
1905 restart_info_pos = io->Information;
1907 /* check if we still have enough space for the largest possible entry */
1908 if (last_info && io->Information + max_dir_info_size(class) > length)
1910 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1911 res = 0;
1916 while (res > 0)
1918 res -= dir_reclen(de);
1919 if (de->d_fileno &&
1920 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1921 ((info = append_entry( buffer, io, length, de->d_name, NULL, mask, class ))))
1923 last_info = info;
1924 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1926 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1927 if (restart_info_pos) /* if we have a complete read already, return it */
1929 io->u.Status = STATUS_SUCCESS;
1930 io->Information = restart_info_pos;
1931 last_info = restart_last_info;
1932 break;
1934 /* otherwise restart from the start with a smaller size */
1935 size = (char *)de - data;
1936 if (!size) break;
1937 io->Information = 0;
1938 last_info = NULL;
1939 goto restart;
1941 if (!has_wildcard( mask )) break;
1942 /* if we have to return but the buffer contains more data, restart with a smaller size */
1943 if (res > 0 && (single_entry || io->Information + max_dir_info_size(class) > length))
1945 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1946 size = (char *)de + dir_reclen(de) - data;
1947 io->Information = restart_info_pos;
1948 last_info = restart_last_info;
1949 goto restart;
1952 /* move on to the next entry */
1953 if (res > 0)
1955 de = (struct dirent *)((char *)de + dir_reclen(de));
1956 continue;
1958 if (size < initial_size) break; /* already restarted once, give up now */
1959 restart_last_info = last_info;
1960 restart_info_pos = io->Information;
1961 restart:
1962 res = wine_getdirentries( fd, data, size, &restart_pos );
1963 de = (struct dirent *)data;
1966 if (last_info) last_info->next = 0;
1967 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1968 res = 0;
1969 done:
1970 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1971 return res;
1974 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1975 #undef getdirentries
1976 #undef dirent
1977 #endif
1979 #endif /* HAVE_GETDIRENTRIES */
1982 /***********************************************************************
1983 * read_directory_readdir
1985 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1987 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1988 BOOLEAN single_entry, const UNICODE_STRING *mask,
1989 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1991 DIR *dir;
1992 off_t i, old_pos = 0;
1993 struct dirent *de;
1994 union file_directory_info *info, *last_info = NULL;
1996 if (!(dir = opendir( "." )))
1998 io->u.Status = FILE_GetNtStatus();
1999 return;
2002 if (!restart_scan)
2004 old_pos = lseek( fd, 0, SEEK_CUR );
2005 /* skip the right number of entries */
2006 for (i = 0; i < old_pos - 2; i++)
2008 if (!readdir( dir ))
2010 closedir( dir );
2011 io->u.Status = STATUS_NO_MORE_FILES;
2012 return;
2016 io->u.Status = STATUS_SUCCESS;
2018 for (;;)
2020 if (old_pos == 0)
2021 info = append_entry( buffer, io, length, ".", NULL, mask, class );
2022 else if (old_pos == 1)
2023 info = append_entry( buffer, io, length, "..", NULL, mask, class );
2024 else if ((de = readdir( dir )))
2026 if (strcmp( de->d_name, "." ) && strcmp( de->d_name, ".." ))
2027 info = append_entry( buffer, io, length, de->d_name, NULL, mask, class );
2028 else
2029 info = NULL;
2031 else
2032 break;
2033 old_pos++;
2034 if (info)
2036 last_info = info;
2037 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
2039 old_pos--; /* restore pos to previous entry */
2040 break;
2042 if (single_entry) break;
2043 /* check if we still have enough space for the largest possible entry */
2044 if (io->Information + max_dir_info_size(class) > length) break;
2048 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
2049 closedir( dir );
2051 if (last_info) last_info->next = 0;
2052 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
2055 /***********************************************************************
2056 * read_directory_stat
2058 * Read a single file from a directory by determining whether the file
2059 * identified by mask exists using stat.
2061 static int read_directory_stat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
2062 BOOLEAN single_entry, const UNICODE_STRING *mask,
2063 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
2065 int unix_len, ret, used_default;
2066 char *unix_name;
2067 struct stat st;
2069 TRACE("trying optimisation for file %s\n", debugstr_us( mask ));
2071 unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
2072 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
2074 io->u.Status = STATUS_NO_MEMORY;
2075 return 0;
2077 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
2078 NULL, &used_default );
2079 if (ret > 0 && !used_default)
2081 unix_name[ret] = 0;
2082 if (restart_scan)
2084 lseek( fd, 0, SEEK_SET );
2086 else if (lseek( fd, 0, SEEK_CUR ) != 0)
2088 io->u.Status = STATUS_NO_MORE_FILES;
2089 ret = 0;
2090 goto done;
2093 ret = stat( unix_name, &st );
2094 if (!ret)
2096 union file_directory_info *info = append_entry( buffer, io, length, unix_name, NULL, NULL, class );
2097 if (info)
2099 info->next = 0;
2100 if (io->u.Status != STATUS_BUFFER_OVERFLOW) lseek( fd, 1, SEEK_CUR );
2102 else io->u.Status = STATUS_NO_MORE_FILES;
2105 else ret = -1;
2107 done:
2108 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2110 TRACE("returning %d\n", ret);
2112 return ret;
2116 /******************************************************************************
2117 * NtQueryDirectoryFile [NTDLL.@]
2118 * ZwQueryDirectoryFile [NTDLL.@]
2120 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
2121 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
2122 PIO_STATUS_BLOCK io,
2123 PVOID buffer, ULONG length,
2124 FILE_INFORMATION_CLASS info_class,
2125 BOOLEAN single_entry,
2126 PUNICODE_STRING mask,
2127 BOOLEAN restart_scan )
2129 int cwd, fd, needs_close;
2131 TRACE("(%p %p %p %p %p %p 0x%08x 0x%08x 0x%08x %s 0x%08x\n",
2132 handle, event, apc_routine, apc_context, io, buffer,
2133 length, info_class, single_entry, debugstr_us(mask),
2134 restart_scan);
2136 if (event || apc_routine)
2138 FIXME( "Unsupported yet option\n" );
2139 return io->u.Status = STATUS_NOT_IMPLEMENTED;
2141 switch (info_class)
2143 case FileDirectoryInformation:
2144 case FileBothDirectoryInformation:
2145 case FileFullDirectoryInformation:
2146 case FileIdBothDirectoryInformation:
2147 case FileIdFullDirectoryInformation:
2148 if (length < dir_info_size( info_class, 1 )) return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
2149 if (!buffer) return io->u.Status = STATUS_ACCESS_VIOLATION;
2150 break;
2151 default:
2152 FIXME( "Unsupported file info class %d\n", info_class );
2153 return io->u.Status = STATUS_NOT_IMPLEMENTED;
2156 if ((io->u.Status = server_get_unix_fd( handle, FILE_LIST_DIRECTORY, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
2157 return io->u.Status;
2159 io->Information = 0;
2161 RtlRunOnceExecuteOnce( &init_once, init_options, NULL, NULL );
2163 RtlEnterCriticalSection( &dir_section );
2165 cwd = open( ".", O_RDONLY );
2166 if (fchdir( fd ) != -1)
2168 struct stat st;
2169 fstat( fd, &st );
2170 curdir.dev = st.st_dev;
2171 curdir.ino = st.st_ino;
2172 #ifdef VFAT_IOCTL_READDIR_BOTH
2173 if ((read_directory_vfat( fd, io, buffer, length, single_entry,
2174 mask, restart_scan, info_class )) != -1) goto done;
2175 #endif
2176 if (!has_wildcard( mask ) &&
2177 read_directory_stat( fd, io, buffer, length, single_entry,
2178 mask, restart_scan, info_class ) != -1) goto done;
2179 #ifdef USE_GETDENTS
2180 if ((read_directory_getdents( fd, io, buffer, length, single_entry,
2181 mask, restart_scan, info_class )) != -1) goto done;
2182 #elif defined HAVE_GETDIRENTRIES
2183 if ((read_directory_getdirentries( fd, io, buffer, length, single_entry,
2184 mask, restart_scan, info_class )) != -1) goto done;
2185 #endif
2186 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan, info_class );
2188 done:
2189 if (cwd == -1 || fchdir( cwd ) == -1) chdir( "/" );
2191 else io->u.Status = FILE_GetNtStatus();
2193 RtlLeaveCriticalSection( &dir_section );
2195 if (needs_close) close( fd );
2196 if (cwd != -1) close( cwd );
2197 TRACE( "=> %x (%ld)\n", io->u.Status, io->Information );
2198 return io->u.Status;
2202 /***********************************************************************
2203 * find_file_in_dir
2205 * Find a file in a directory the hard way, by doing a case-insensitive search.
2206 * The file found is appended to unix_name at pos.
2207 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
2209 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
2210 BOOLEAN check_case, BOOLEAN *is_win_dir )
2212 WCHAR buffer[MAX_DIR_ENTRY_LEN];
2213 UNICODE_STRING str;
2214 BOOLEAN spaces, is_name_8_dot_3;
2215 DIR *dir;
2216 struct dirent *de;
2217 struct stat st;
2218 int ret, used_default;
2220 /* try a shortcut for this directory */
2222 unix_name[pos++] = '/';
2223 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
2224 NULL, &used_default );
2225 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
2226 /* so it cannot match the file we are looking for */
2227 if (ret >= 0 && !used_default)
2229 unix_name[pos + ret] = 0;
2230 if (!stat( unix_name, &st ))
2232 if (is_win_dir) *is_win_dir = is_same_file( &windir, &st );
2233 return STATUS_SUCCESS;
2236 if (check_case) goto not_found; /* we want an exact match */
2238 if (pos > 1) unix_name[pos - 1] = 0;
2239 else unix_name[1] = 0; /* keep the initial slash */
2241 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
2243 str.Buffer = (WCHAR *)name;
2244 str.Length = length * sizeof(WCHAR);
2245 str.MaximumLength = str.Length;
2246 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
2247 #ifndef VFAT_IOCTL_READDIR_BOTH
2248 is_name_8_dot_3 = is_name_8_dot_3 && length >= 8 && name[4] == '~';
2249 #endif
2251 if (!is_name_8_dot_3 && !get_dir_case_sensitivity( unix_name )) goto not_found;
2253 /* now look for it through the directory */
2255 #ifdef VFAT_IOCTL_READDIR_BOTH
2256 if (is_name_8_dot_3)
2258 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
2259 if (fd != -1)
2261 KERNEL_DIRENT *kde;
2263 RtlEnterCriticalSection( &dir_section );
2264 if ((kde = start_vfat_ioctl( fd )))
2266 unix_name[pos - 1] = '/';
2267 while (kde[0].d_reclen)
2269 /* make sure names are null-terminated to work around an x86-64 kernel bug */
2270 size_t len = min(kde[0].d_reclen, sizeof(kde[0].d_name) - 1 );
2271 kde[0].d_name[len] = 0;
2272 len = min(kde[1].d_reclen, sizeof(kde[1].d_name) - 1 );
2273 kde[1].d_name[len] = 0;
2275 if (kde[1].d_name[0])
2277 ret = ntdll_umbstowcs( 0, kde[1].d_name, strlen(kde[1].d_name),
2278 buffer, MAX_DIR_ENTRY_LEN );
2279 if (ret == length && !memicmpW( buffer, name, length))
2281 strcpy( unix_name + pos, kde[1].d_name );
2282 RtlLeaveCriticalSection( &dir_section );
2283 close( fd );
2284 goto success;
2287 ret = ntdll_umbstowcs( 0, kde[0].d_name, strlen(kde[0].d_name),
2288 buffer, MAX_DIR_ENTRY_LEN );
2289 if (ret == length && !memicmpW( buffer, name, length))
2291 strcpy( unix_name + pos,
2292 kde[1].d_name[0] ? kde[1].d_name : kde[0].d_name );
2293 RtlLeaveCriticalSection( &dir_section );
2294 close( fd );
2295 goto success;
2297 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)kde ) == -1)
2299 RtlLeaveCriticalSection( &dir_section );
2300 close( fd );
2301 goto not_found;
2305 RtlLeaveCriticalSection( &dir_section );
2306 close( fd );
2308 /* fall through to normal handling */
2310 #endif /* VFAT_IOCTL_READDIR_BOTH */
2312 if (!(dir = opendir( unix_name )))
2314 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
2315 else return FILE_GetNtStatus();
2317 unix_name[pos - 1] = '/';
2318 str.Buffer = buffer;
2319 str.MaximumLength = sizeof(buffer);
2320 while ((de = readdir( dir )))
2322 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
2323 if (ret == length && !memicmpW( buffer, name, length ))
2325 strcpy( unix_name + pos, de->d_name );
2326 closedir( dir );
2327 goto success;
2330 if (!is_name_8_dot_3) continue;
2332 str.Length = ret * sizeof(WCHAR);
2333 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
2335 WCHAR short_nameW[12];
2336 ret = hash_short_file_name( &str, short_nameW );
2337 if (ret == length && !memicmpW( short_nameW, name, length ))
2339 strcpy( unix_name + pos, de->d_name );
2340 closedir( dir );
2341 goto success;
2345 closedir( dir );
2347 not_found:
2348 unix_name[pos - 1] = 0;
2349 return STATUS_OBJECT_PATH_NOT_FOUND;
2351 success:
2352 if (is_win_dir && !stat( unix_name, &st )) *is_win_dir = is_same_file( &windir, &st );
2353 return STATUS_SUCCESS;
2357 #ifndef _WIN64
2359 static const WCHAR catrootW[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t',0};
2360 static const WCHAR catroot2W[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t','2',0};
2361 static const WCHAR driversstoreW[] = {'s','y','s','t','e','m','3','2','\\','d','r','i','v','e','r','s','s','t','o','r','e',0};
2362 static const WCHAR driversetcW[] = {'s','y','s','t','e','m','3','2','\\','d','r','i','v','e','r','s','\\','e','t','c',0};
2363 static const WCHAR logfilesW[] = {'s','y','s','t','e','m','3','2','\\','l','o','g','f','i','l','e','s',0};
2364 static const WCHAR spoolW[] = {'s','y','s','t','e','m','3','2','\\','s','p','o','o','l',0};
2365 static const WCHAR system32W[] = {'s','y','s','t','e','m','3','2',0};
2366 static const WCHAR syswow64W[] = {'s','y','s','w','o','w','6','4',0};
2367 static const WCHAR sysnativeW[] = {'s','y','s','n','a','t','i','v','e',0};
2368 static const WCHAR regeditW[] = {'r','e','g','e','d','i','t','.','e','x','e',0};
2369 static const WCHAR wow_regeditW[] = {'s','y','s','w','o','w','6','4','\\','r','e','g','e','d','i','t','.','e','x','e',0};
2371 static struct
2373 const WCHAR *source;
2374 const WCHAR *dos_target;
2375 const char *unix_target;
2376 } redirects[] =
2378 { catrootW, NULL, NULL },
2379 { catroot2W, NULL, NULL },
2380 { driversstoreW, NULL, NULL },
2381 { driversetcW, NULL, NULL },
2382 { logfilesW, NULL, NULL },
2383 { spoolW, NULL, NULL },
2384 { system32W, syswow64W, NULL },
2385 { sysnativeW, system32W, NULL },
2386 { regeditW, wow_regeditW, NULL }
2389 static unsigned int nb_redirects;
2392 /***********************************************************************
2393 * get_redirect_target
2395 * Find the target unix name for a redirected dir.
2397 static const char *get_redirect_target( const char *windows_dir, const WCHAR *name )
2399 int used_default, len, pos, win_len = strlen( windows_dir );
2400 char *unix_name, *unix_target = NULL;
2401 NTSTATUS status;
2403 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, win_len + MAX_DIR_ENTRY_LEN + 2 )))
2404 return NULL;
2405 memcpy( unix_name, windows_dir, win_len );
2406 pos = win_len;
2408 while (*name)
2410 const WCHAR *end, *next;
2412 for (end = name; *end; end++) if (IS_SEPARATOR(*end)) break;
2413 for (next = end; *next; next++) if (!IS_SEPARATOR(*next)) break;
2415 status = find_file_in_dir( unix_name, pos, name, end - name, FALSE, NULL );
2416 if (status == STATUS_OBJECT_PATH_NOT_FOUND && !*next) /* not finding last element is ok */
2418 len = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2419 MAX_DIR_ENTRY_LEN - (pos - win_len), NULL, &used_default );
2420 if (len > 0 && !used_default)
2422 unix_name[pos] = '/';
2423 pos += len + 1;
2424 unix_name[pos] = 0;
2425 break;
2428 if (status) goto done;
2429 pos += strlen( unix_name + pos );
2430 name = next;
2433 if ((unix_target = RtlAllocateHeap( GetProcessHeap(), 0, pos - win_len )))
2434 memcpy( unix_target, unix_name + win_len + 1, pos - win_len );
2436 done:
2437 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2438 return unix_target;
2442 /***********************************************************************
2443 * init_redirects
2445 static void init_redirects(void)
2447 UNICODE_STRING nt_name;
2448 ANSI_STRING unix_name;
2449 NTSTATUS status;
2450 struct stat st;
2451 unsigned int i;
2453 if (!RtlDosPathNameToNtPathName_U( user_shared_data->NtSystemRoot, &nt_name, NULL, NULL ))
2455 ERR( "can't convert %s\n", debugstr_w(user_shared_data->NtSystemRoot) );
2456 return;
2458 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
2459 RtlFreeUnicodeString( &nt_name );
2460 if (status)
2462 ERR( "cannot open %s (%x)\n", debugstr_w(user_shared_data->NtSystemRoot), status );
2463 return;
2465 if (!stat( unix_name.Buffer, &st ))
2467 windir.dev = st.st_dev;
2468 windir.ino = st.st_ino;
2469 nb_redirects = sizeof(redirects) / sizeof(redirects[0]);
2470 for (i = 0; i < nb_redirects; i++)
2472 if (!redirects[i].dos_target) continue;
2473 redirects[i].unix_target = get_redirect_target( unix_name.Buffer, redirects[i].dos_target );
2474 TRACE( "%s -> %s\n", debugstr_w(redirects[i].source), redirects[i].unix_target );
2477 RtlFreeAnsiString( &unix_name );
2482 /***********************************************************************
2483 * match_redirect
2485 * Check if path matches a redirect name. If yes, return matched length.
2487 static int match_redirect( const WCHAR *path, int len, const WCHAR *redir, BOOLEAN check_case )
2489 int i = 0;
2491 while (i < len && *redir)
2493 if (IS_SEPARATOR(path[i]))
2495 if (*redir++ != '\\') return 0;
2496 while (i < len && IS_SEPARATOR(path[i])) i++;
2497 continue; /* move on to next path component */
2499 else if (check_case)
2501 if (path[i] != *redir) return 0;
2503 else
2505 if (tolowerW(path[i]) != tolowerW(*redir)) return 0;
2507 i++;
2508 redir++;
2510 if (*redir) return 0;
2511 if (i < len && !IS_SEPARATOR(path[i])) return 0;
2512 while (i < len && IS_SEPARATOR(path[i])) i++;
2513 return i;
2517 /***********************************************************************
2518 * get_redirect_path
2520 * Retrieve the Unix path corresponding to a redirected path if any.
2522 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, BOOLEAN check_case )
2524 unsigned int i;
2525 int len;
2527 for (i = 0; i < nb_redirects; i++)
2529 if ((len = match_redirect( name, length, redirects[i].source, check_case )))
2531 if (!redirects[i].unix_target) break;
2532 unix_name[pos++] = '/';
2533 strcpy( unix_name + pos, redirects[i].unix_target );
2534 return len;
2537 return 0;
2540 #else /* _WIN64 */
2542 /* there are no redirects on 64-bit */
2544 static const unsigned int nb_redirects = 0;
2546 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, BOOLEAN check_case )
2548 return 0;
2551 #endif
2553 /***********************************************************************
2554 * DIR_init_windows_dir
2556 void DIR_init_windows_dir( const WCHAR *win, const WCHAR *sys )
2558 /* FIXME: should probably store paths as NT file names */
2560 RtlCreateUnicodeString( &system_dir, sys );
2562 #ifndef _WIN64
2563 if (is_wow64) init_redirects();
2564 #endif
2568 /******************************************************************************
2569 * get_dos_device
2571 * Get the Unix path of a DOS device.
2573 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
2575 const char *config_dir = wine_get_config_dir();
2576 struct stat st;
2577 char *unix_name, *new_name, *dev;
2578 unsigned int i;
2579 int unix_len;
2581 /* make sure the device name is ASCII */
2582 for (i = 0; i < name_len; i++)
2583 if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
2585 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
2587 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2588 return STATUS_NO_MEMORY;
2590 strcpy( unix_name, config_dir );
2591 strcat( unix_name, "/dosdevices/" );
2592 dev = unix_name + strlen(unix_name);
2594 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
2595 dev[i] = 0;
2597 /* special case for drive devices */
2598 if (name_len == 2 && dev[1] == ':')
2600 dev[i++] = ':';
2601 dev[i] = 0;
2604 for (;;)
2606 if (!stat( unix_name, &st ))
2608 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
2609 unix_name_ret->Buffer = unix_name;
2610 unix_name_ret->Length = strlen(unix_name);
2611 unix_name_ret->MaximumLength = unix_len;
2612 return STATUS_SUCCESS;
2614 if (!dev) break;
2616 /* now try some defaults for it */
2617 if (!strcmp( dev, "aux" ))
2619 strcpy( dev, "com1" );
2620 continue;
2622 if (!strcmp( dev, "prn" ))
2624 strcpy( dev, "lpt1" );
2625 continue;
2627 if (!strcmp( dev, "nul" ))
2629 strcpy( unix_name, "/dev/null" );
2630 dev = NULL; /* last try */
2631 continue;
2634 new_name = NULL;
2635 if (dev[1] == ':' && dev[2] == ':') /* drive device */
2637 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
2638 new_name = get_default_drive_device( unix_name );
2640 else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( atoi(dev + 3 ));
2641 else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( atoi(dev + 3 ));
2643 if (!new_name) break;
2645 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2646 unix_name = new_name;
2647 unix_len = strlen(unix_name) + 1;
2648 dev = NULL; /* last try */
2650 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2651 return STATUS_BAD_DEVICE_TYPE;
2655 /* return the length of the DOS namespace prefix if any */
2656 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
2658 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
2659 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
2661 if (name->Length > sizeof(nt_prefixW) &&
2662 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
2663 return sizeof(nt_prefixW) / sizeof(WCHAR);
2665 if (name->Length > sizeof(dosdev_prefixW) &&
2666 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
2667 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
2669 return 0;
2673 /******************************************************************************
2674 * find_file_id
2676 * Recursively search directories from the dir queue for a given inode.
2678 static NTSTATUS find_file_id( ANSI_STRING *unix_name, ULONGLONG file_id, dev_t dev )
2680 unsigned int pos;
2681 DIR *dir;
2682 struct dirent *de;
2683 NTSTATUS status;
2684 struct stat st;
2686 while (!(status = next_dir_in_queue( unix_name->Buffer )))
2688 if (!(dir = opendir( unix_name->Buffer ))) continue;
2689 TRACE( "searching %s for %s\n", unix_name->Buffer, wine_dbgstr_longlong(file_id) );
2690 pos = strlen( unix_name->Buffer );
2691 if (pos + MAX_DIR_ENTRY_LEN >= unix_name->MaximumLength/sizeof(WCHAR))
2693 char *new = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name->Buffer,
2694 unix_name->MaximumLength * 2 );
2695 if (!new)
2697 closedir( dir );
2698 return STATUS_NO_MEMORY;
2700 unix_name->MaximumLength *= 2;
2701 unix_name->Buffer = new;
2703 unix_name->Buffer[pos++] = '/';
2704 while ((de = readdir( dir )))
2706 if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
2707 strcpy( unix_name->Buffer + pos, de->d_name );
2708 if (lstat( unix_name->Buffer, &st ) == -1) continue;
2709 if (st.st_dev != dev) continue;
2710 if (st.st_ino == file_id)
2712 closedir( dir );
2713 return STATUS_SUCCESS;
2715 if (!S_ISDIR( st.st_mode )) continue;
2716 if ((status = add_dir_to_queue( unix_name->Buffer )) != STATUS_SUCCESS)
2718 closedir( dir );
2719 return status;
2722 closedir( dir );
2724 return status;
2728 /******************************************************************************
2729 * file_id_to_unix_file_name
2731 * Lookup a file from its file id instead of its name.
2733 NTSTATUS file_id_to_unix_file_name( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name )
2735 enum server_fd_type type;
2736 int old_cwd, root_fd, needs_close;
2737 NTSTATUS status;
2738 ULONGLONG file_id;
2739 struct stat st, root_st;
2741 if (attr->ObjectName->Length != sizeof(ULONGLONG)) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2742 if (!attr->RootDirectory) return STATUS_INVALID_PARAMETER;
2743 memcpy( &file_id, attr->ObjectName->Buffer, sizeof(file_id) );
2745 unix_name->MaximumLength = 2 * MAX_DIR_ENTRY_LEN + 4;
2746 if (!(unix_name->Buffer = RtlAllocateHeap( GetProcessHeap(), 0, unix_name->MaximumLength )))
2747 return STATUS_NO_MEMORY;
2748 strcpy( unix_name->Buffer, "." );
2750 if ((status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
2751 goto done;
2753 if (type != FD_TYPE_DIR)
2755 status = STATUS_OBJECT_TYPE_MISMATCH;
2756 goto done;
2759 fstat( root_fd, &root_st );
2760 if (root_st.st_ino == file_id) /* shortcut for "." */
2762 status = STATUS_SUCCESS;
2763 goto done;
2766 RtlEnterCriticalSection( &dir_section );
2767 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2769 /* shortcut for ".." */
2770 if (!stat( "..", &st ) && st.st_dev == root_st.st_dev && st.st_ino == file_id)
2772 strcpy( unix_name->Buffer, ".." );
2773 status = STATUS_SUCCESS;
2775 else
2777 status = add_dir_to_queue( "." );
2778 if (!status)
2779 status = find_file_id( unix_name, file_id, root_st.st_dev );
2780 if (!status) /* get rid of "./" prefix */
2781 memmove( unix_name->Buffer, unix_name->Buffer + 2, strlen(unix_name->Buffer) - 1 );
2782 flush_dir_queue();
2784 if (fchdir( old_cwd ) == -1) chdir( "/" );
2786 else status = FILE_GetNtStatus();
2787 RtlLeaveCriticalSection( &dir_section );
2788 if (old_cwd != -1) close( old_cwd );
2790 done:
2791 if (status == STATUS_SUCCESS)
2793 TRACE( "%s -> %s\n", wine_dbgstr_longlong(file_id), debugstr_a(unix_name->Buffer) );
2794 unix_name->Length = strlen( unix_name->Buffer );
2796 else
2798 TRACE( "%s not found in dir %p\n", wine_dbgstr_longlong(file_id), attr->RootDirectory );
2799 RtlFreeHeap( GetProcessHeap(), 0, unix_name->Buffer );
2801 if (needs_close) close( root_fd );
2802 return status;
2806 /******************************************************************************
2807 * lookup_unix_name
2809 * Helper for nt_to_unix_file_name
2811 static NTSTATUS lookup_unix_name( const WCHAR *name, int name_len, char **buffer, int unix_len, int pos,
2812 UINT disposition, BOOLEAN check_case )
2814 NTSTATUS status;
2815 int ret, used_default, len;
2816 struct stat st;
2817 char *unix_name = *buffer;
2818 const BOOL redirect = nb_redirects && ntdll_get_thread_data()->wow64_redir;
2820 /* try a shortcut first */
2822 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
2823 NULL, &used_default );
2825 while (name_len && IS_SEPARATOR(*name))
2827 name++;
2828 name_len--;
2831 if (ret >= 0 && !used_default) /* if we used the default char the name didn't convert properly */
2833 char *p;
2834 unix_name[pos + ret] = 0;
2835 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
2836 if (!redirect || (!strstr( unix_name, "/windows/") && strncmp( unix_name, "windows/", 8 )))
2838 if (!stat( unix_name, &st ))
2840 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
2841 if (disposition == FILE_CREATE)
2842 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
2843 return STATUS_SUCCESS;
2848 if (!name_len) /* empty name -> drive root doesn't exist */
2849 return STATUS_OBJECT_PATH_NOT_FOUND;
2850 if (check_case && !redirect && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
2851 return STATUS_OBJECT_NAME_NOT_FOUND;
2853 /* now do it component by component */
2855 while (name_len)
2857 const WCHAR *end, *next;
2858 BOOLEAN is_win_dir = FALSE;
2860 end = name;
2861 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
2862 next = end;
2863 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
2864 name_len -= next - name;
2866 /* grow the buffer if needed */
2868 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
2870 char *new_name;
2871 unix_len += 2 * MAX_DIR_ENTRY_LEN;
2872 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
2873 return STATUS_NO_MEMORY;
2874 unix_name = *buffer = new_name;
2877 status = find_file_in_dir( unix_name, pos, name, end - name,
2878 check_case, redirect ? &is_win_dir : NULL );
2880 /* if this is the last element, not finding it is not necessarily fatal */
2881 if (!name_len)
2883 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
2885 status = STATUS_OBJECT_NAME_NOT_FOUND;
2886 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
2888 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2889 MAX_DIR_ENTRY_LEN, NULL, &used_default );
2890 if (ret > 0 && !used_default)
2892 unix_name[pos] = '/';
2893 unix_name[pos + 1 + ret] = 0;
2894 status = STATUS_NO_SUCH_FILE;
2895 break;
2899 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
2901 status = STATUS_OBJECT_NAME_COLLISION;
2905 if (status != STATUS_SUCCESS) break;
2907 pos += strlen( unix_name + pos );
2908 name = next;
2910 if (is_win_dir && (len = get_redirect_path( unix_name, pos, name, name_len, check_case )))
2912 name += len;
2913 name_len -= len;
2914 pos += strlen( unix_name + pos );
2915 TRACE( "redirecting -> %s + %s\n", debugstr_a(unix_name), debugstr_w(name) );
2919 return status;
2923 /******************************************************************************
2924 * nt_to_unix_file_name_attr
2926 NTSTATUS nt_to_unix_file_name_attr( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name_ret,
2927 UINT disposition )
2929 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2930 enum server_fd_type type;
2931 int old_cwd, root_fd, needs_close;
2932 const WCHAR *name, *p;
2933 char *unix_name;
2934 int name_len, unix_len;
2935 NTSTATUS status;
2936 BOOLEAN check_case = !(attr->Attributes & OBJ_CASE_INSENSITIVE);
2938 if (!attr->RootDirectory) /* without root dir fall back to normal lookup */
2939 return wine_nt_to_unix_file_name( attr->ObjectName, unix_name_ret, disposition, check_case );
2941 name = attr->ObjectName->Buffer;
2942 name_len = attr->ObjectName->Length / sizeof(WCHAR);
2944 if (name_len && IS_SEPARATOR(name[0])) return STATUS_INVALID_PARAMETER;
2946 /* check for invalid characters */
2947 for (p = name; p < name + name_len; p++)
2948 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2950 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
2951 unix_len += MAX_DIR_ENTRY_LEN + 3;
2952 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2953 return STATUS_NO_MEMORY;
2954 unix_name[0] = '.';
2956 if (!(status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
2958 if (type != FD_TYPE_DIR)
2960 if (needs_close) close( root_fd );
2961 status = STATUS_BAD_DEVICE_TYPE;
2963 else
2965 RtlEnterCriticalSection( &dir_section );
2966 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2968 status = lookup_unix_name( name, name_len, &unix_name, unix_len, 1,
2969 disposition, check_case );
2970 if (fchdir( old_cwd ) == -1) chdir( "/" );
2972 else status = FILE_GetNtStatus();
2973 RtlLeaveCriticalSection( &dir_section );
2974 if (old_cwd != -1) close( old_cwd );
2975 if (needs_close) close( root_fd );
2978 else if (status == STATUS_OBJECT_TYPE_MISMATCH) status = STATUS_BAD_DEVICE_TYPE;
2980 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
2982 TRACE( "%s -> %s\n", debugstr_us(attr->ObjectName), debugstr_a(unix_name) );
2983 unix_name_ret->Buffer = unix_name;
2984 unix_name_ret->Length = strlen(unix_name);
2985 unix_name_ret->MaximumLength = unix_len;
2987 else
2989 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
2990 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2992 return status;
2996 /******************************************************************************
2997 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
2999 * Convert a file name from NT namespace to Unix namespace.
3001 * If disposition is not FILE_OPEN or FILE_OVERWRITE, the last path
3002 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
3003 * returned, but the unix name is still filled in properly.
3005 NTSTATUS CDECL wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
3006 UINT disposition, BOOLEAN check_case )
3008 static const WCHAR unixW[] = {'u','n','i','x'};
3009 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
3011 NTSTATUS status = STATUS_SUCCESS;
3012 const char *config_dir = wine_get_config_dir();
3013 const WCHAR *name, *p;
3014 struct stat st;
3015 char *unix_name;
3016 int pos, ret, name_len, unix_len, prefix_len, used_default;
3017 WCHAR prefix[MAX_DIR_ENTRY_LEN];
3018 BOOLEAN is_unix = FALSE;
3020 name = nameW->Buffer;
3021 name_len = nameW->Length / sizeof(WCHAR);
3023 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
3025 if (!(pos = get_dos_prefix_len( nameW )))
3026 return STATUS_BAD_DEVICE_TYPE; /* no DOS prefix, assume NT native name */
3028 name += pos;
3029 name_len -= pos;
3031 /* check for sub-directory */
3032 for (pos = 0; pos < name_len; pos++)
3034 if (IS_SEPARATOR(name[pos])) break;
3035 if (name[pos] < 32 || strchrW( invalid_charsW, name[pos] ))
3036 return STATUS_OBJECT_NAME_INVALID;
3038 if (pos > MAX_DIR_ENTRY_LEN)
3039 return STATUS_OBJECT_NAME_INVALID;
3041 if (pos == name_len) /* no subdir, plain DOS device */
3042 return get_dos_device( name, name_len, unix_name_ret );
3044 for (prefix_len = 0; prefix_len < pos; prefix_len++)
3045 prefix[prefix_len] = tolowerW(name[prefix_len]);
3047 name += prefix_len;
3048 name_len -= prefix_len;
3050 /* check for invalid characters (all chars except 0 are valid for unix) */
3051 is_unix = (prefix_len == 4 && !memcmp( prefix, unixW, sizeof(unixW) ));
3052 if (is_unix)
3054 for (p = name; p < name + name_len; p++)
3055 if (!*p) return STATUS_OBJECT_NAME_INVALID;
3056 check_case = TRUE;
3058 else
3060 for (p = name; p < name + name_len; p++)
3061 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
3064 unix_len = ntdll_wcstoumbs( 0, prefix, prefix_len, NULL, 0, NULL, NULL );
3065 unix_len += ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
3066 unix_len += MAX_DIR_ENTRY_LEN + 3;
3067 unix_len += strlen(config_dir) + sizeof("/dosdevices/");
3068 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
3069 return STATUS_NO_MEMORY;
3070 strcpy( unix_name, config_dir );
3071 strcat( unix_name, "/dosdevices/" );
3072 pos = strlen(unix_name);
3074 ret = ntdll_wcstoumbs( 0, prefix, prefix_len, unix_name + pos, unix_len - pos - 1,
3075 NULL, &used_default );
3076 if (!ret || used_default)
3078 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3079 return STATUS_OBJECT_NAME_INVALID;
3081 pos += ret;
3083 /* check if prefix exists (except for DOS drives to avoid extra stat calls) */
3085 if (prefix_len != 2 || prefix[1] != ':')
3087 unix_name[pos] = 0;
3088 if (lstat( unix_name, &st ) == -1 && errno == ENOENT)
3090 if (!is_unix)
3092 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3093 return STATUS_BAD_DEVICE_TYPE;
3095 pos = 0; /* fall back to unix root */
3099 status = lookup_unix_name( name, name_len, &unix_name, unix_len, pos, disposition, check_case );
3100 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
3102 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
3103 unix_name_ret->Buffer = unix_name;
3104 unix_name_ret->Length = strlen(unix_name);
3105 unix_name_ret->MaximumLength = unix_len;
3107 else
3109 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
3110 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3112 return status;
3116 /******************************************************************
3117 * RtlWow64EnableFsRedirection (NTDLL.@)
3119 NTSTATUS WINAPI RtlWow64EnableFsRedirection( BOOLEAN enable )
3121 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
3122 ntdll_get_thread_data()->wow64_redir = enable;
3123 return STATUS_SUCCESS;
3127 /******************************************************************
3128 * RtlWow64EnableFsRedirectionEx (NTDLL.@)
3130 NTSTATUS WINAPI RtlWow64EnableFsRedirectionEx( ULONG disable, ULONG *old_value )
3132 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
3133 if (((ULONG_PTR)old_value >> 16) == 0) return STATUS_ACCESS_VIOLATION;
3135 *old_value = !ntdll_get_thread_data()->wow64_redir;
3136 ntdll_get_thread_data()->wow64_redir = !disable;
3137 return STATUS_SUCCESS;
3141 /******************************************************************
3142 * RtlDoesFileExists_U (NTDLL.@)
3144 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
3146 UNICODE_STRING nt_name;
3147 FILE_BASIC_INFORMATION basic_info;
3148 OBJECT_ATTRIBUTES attr;
3149 BOOLEAN ret;
3151 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
3153 attr.Length = sizeof(attr);
3154 attr.RootDirectory = 0;
3155 attr.ObjectName = &nt_name;
3156 attr.Attributes = OBJ_CASE_INSENSITIVE;
3157 attr.SecurityDescriptor = NULL;
3158 attr.SecurityQualityOfService = NULL;
3160 ret = NtQueryAttributesFile(&attr, &basic_info) == STATUS_SUCCESS;
3162 RtlFreeUnicodeString( &nt_name );
3163 return ret;
3167 /***********************************************************************
3168 * DIR_unmount_device
3170 * Unmount the specified device.
3172 NTSTATUS DIR_unmount_device( HANDLE handle )
3174 NTSTATUS status;
3175 int unix_fd, needs_close;
3177 if (!(status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )))
3179 struct stat st;
3180 char *mount_point = NULL;
3182 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
3183 status = STATUS_INVALID_PARAMETER;
3184 else
3186 if ((mount_point = get_device_mount_point( st.st_rdev )))
3188 #ifdef __APPLE__
3189 static const char umount[] = "diskutil unmount >/dev/null 2>&1 ";
3190 #else
3191 static const char umount[] = "umount >/dev/null 2>&1 ";
3192 #endif
3193 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
3194 if (cmd)
3196 strcpy( cmd, umount );
3197 strcat( cmd, mount_point );
3198 system( cmd );
3199 RtlFreeHeap( GetProcessHeap(), 0, cmd );
3200 #ifdef linux
3201 /* umount will fail to release the loop device since we still have
3202 a handle to it, so we release it here */
3203 if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
3204 #endif
3206 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
3209 if (needs_close) close( unix_fd );
3211 return status;
3215 /******************************************************************************
3216 * DIR_get_unix_cwd
3218 * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
3219 * Returned value must be freed by caller.
3221 NTSTATUS DIR_get_unix_cwd( char **cwd )
3223 int old_cwd, unix_fd, needs_close;
3224 CURDIR *curdir;
3225 HANDLE handle;
3226 NTSTATUS status;
3228 RtlAcquirePebLock();
3230 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
3231 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
3232 else
3233 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
3235 if (!(handle = curdir->Handle))
3237 UNICODE_STRING dirW;
3238 OBJECT_ATTRIBUTES attr;
3239 IO_STATUS_BLOCK io;
3241 if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
3243 status = STATUS_OBJECT_NAME_INVALID;
3244 goto done;
3246 attr.Length = sizeof(attr);
3247 attr.RootDirectory = 0;
3248 attr.Attributes = OBJ_CASE_INSENSITIVE;
3249 attr.ObjectName = &dirW;
3250 attr.SecurityDescriptor = NULL;
3251 attr.SecurityQualityOfService = NULL;
3253 status = NtOpenFile( &handle, 0, &attr, &io, 0,
3254 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
3255 RtlFreeUnicodeString( &dirW );
3256 if (status != STATUS_SUCCESS) goto done;
3259 if ((status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )) == STATUS_SUCCESS)
3261 RtlEnterCriticalSection( &dir_section );
3263 if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
3265 unsigned int size = 512;
3267 for (;;)
3269 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
3271 status = STATUS_NO_MEMORY;
3272 break;
3274 if (getcwd( *cwd, size )) break;
3275 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
3276 if (errno != ERANGE)
3278 status = STATUS_OBJECT_PATH_INVALID;
3279 break;
3281 size *= 2;
3283 if (fchdir( old_cwd ) == -1) chdir( "/" );
3285 else status = FILE_GetNtStatus();
3287 RtlLeaveCriticalSection( &dir_section );
3288 if (old_cwd != -1) close( old_cwd );
3289 if (needs_close) close( unix_fd );
3291 if (!curdir->Handle) NtClose( handle );
3293 done:
3294 RtlReleasePebLock();
3295 return status;