ntdll: Add tests for buffer overflows in NtQueryDirectoryFile.
[wine.git] / dlls / ntdll / directory.c
blob41e7115ec51813baa7e929dfd7fab24e5629846b
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 MAJOR_IN_MKDEV
51 # include <sys/mkdev.h>
52 #elif defined(MAJOR_IN_SYSMACROS)
53 # include <sys/sysmacros.h>
54 #endif
55 #ifdef HAVE_SYS_VNODE_H
56 /* Work around a conflict with Solaris' system list defined in sys/list.h. */
57 #define list SYSLIST
58 #define list_next SYSLIST_NEXT
59 #define list_prev SYSLIST_PREV
60 #define list_head SYSLIST_HEAD
61 #define list_tail SYSLIST_TAIL
62 #define list_move_tail SYSLIST_MOVE_TAIL
63 #define list_remove SYSLIST_REMOVE
64 #include <sys/vnode.h>
65 #undef list
66 #undef list_next
67 #undef list_prev
68 #undef list_head
69 #undef list_tail
70 #undef list_move_tail
71 #undef list_remove
72 #endif
73 #ifdef HAVE_SYS_IOCTL_H
74 #include <sys/ioctl.h>
75 #endif
76 #ifdef HAVE_LINUX_IOCTL_H
77 #include <linux/ioctl.h>
78 #endif
79 #ifdef HAVE_LINUX_MAJOR_H
80 # include <linux/major.h>
81 #endif
82 #ifdef HAVE_SYS_PARAM_H
83 #include <sys/param.h>
84 #endif
85 #ifdef HAVE_SYS_MOUNT_H
86 #include <sys/mount.h>
87 #endif
88 #ifdef HAVE_SYS_STATFS_H
89 #include <sys/statfs.h>
90 #endif
91 #include <time.h>
92 #ifdef HAVE_UNISTD_H
93 # include <unistd.h>
94 #endif
96 #include "ntstatus.h"
97 #define WIN32_NO_STATUS
98 #define NONAMELESSUNION
99 #include "windef.h"
100 #include "winnt.h"
101 #include "winternl.h"
102 #include "ddk/wdm.h"
103 #include "ntdll_misc.h"
104 #include "wine/unicode.h"
105 #include "wine/server.h"
106 #include "wine/list.h"
107 #include "wine/library.h"
108 #include "wine/debug.h"
110 WINE_DEFAULT_DEBUG_CHANNEL(file);
112 /* just in case... */
113 #undef VFAT_IOCTL_READDIR_BOTH
114 #undef USE_GETDENTS
116 #ifdef linux
118 /* We want the real kernel dirent structure, not the libc one */
119 typedef struct
121 long d_ino;
122 long d_off;
123 unsigned short d_reclen;
124 char d_name[256];
125 } KERNEL_DIRENT;
127 /* Define the VFAT ioctl to get both short and long file names */
128 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
130 #ifndef O_DIRECTORY
131 # define O_DIRECTORY 0200000 /* must be directory */
132 #endif
134 #ifdef __NR_getdents64
135 typedef struct
137 ULONG64 d_ino;
138 LONG64 d_off;
139 unsigned short d_reclen;
140 unsigned char d_type;
141 char d_name[256];
142 } KERNEL_DIRENT64;
144 #undef getdents64
145 static inline int getdents64( int fd, char *de, unsigned int size )
147 return syscall( __NR_getdents64, fd, de, size );
149 #define USE_GETDENTS
150 #endif
152 #endif /* linux */
154 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
155 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
157 #define INVALID_NT_CHARS '*','?','<','>','|','"'
158 #define INVALID_DOS_CHARS INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
160 #define MAX_DIR_ENTRY_LEN 255 /* max length of a directory entry in chars */
162 #define MAX_IGNORED_FILES 4
164 struct file_identity
166 dev_t dev;
167 ino_t ino;
170 static struct file_identity ignored_files[MAX_IGNORED_FILES];
171 static unsigned int ignored_files_count;
173 union file_directory_info
175 ULONG next;
176 FILE_DIRECTORY_INFORMATION dir;
177 FILE_BOTH_DIRECTORY_INFORMATION both;
178 FILE_FULL_DIRECTORY_INFORMATION full;
179 FILE_ID_BOTH_DIRECTORY_INFORMATION id_both;
180 FILE_ID_FULL_DIRECTORY_INFORMATION id_full;
183 static BOOL show_dot_files;
184 static RTL_RUN_ONCE init_once = RTL_RUN_ONCE_INIT;
186 /* at some point we may want to allow Winelib apps to set this */
187 static const BOOL is_case_sensitive = FALSE;
189 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
191 static struct file_identity curdir;
192 static struct file_identity windir;
194 static RTL_CRITICAL_SECTION dir_section;
195 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
197 0, 0, &dir_section,
198 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
199 0, 0, { (DWORD_PTR)(__FILE__ ": dir_section") }
201 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
204 /* check if a given Unicode char is OK in a DOS short name */
205 static inline BOOL is_invalid_dos_char( WCHAR ch )
207 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
208 if (ch > 0x7f) return TRUE;
209 return strchrW( invalid_chars, ch ) != NULL;
212 /* check if the device can be a mounted volume */
213 static inline BOOL is_valid_mounted_device( const struct stat *st )
215 #if defined(linux) || defined(__sun__)
216 return S_ISBLK( st->st_mode );
217 #else
218 /* disks are char devices on *BSD */
219 return S_ISCHR( st->st_mode );
220 #endif
223 static inline void ignore_file( const char *name )
225 struct stat st;
226 assert( ignored_files_count < MAX_IGNORED_FILES );
227 if (!stat( name, &st ))
229 ignored_files[ignored_files_count].dev = st.st_dev;
230 ignored_files[ignored_files_count].ino = st.st_ino;
231 ignored_files_count++;
235 static inline BOOL is_same_file( const struct file_identity *file, const struct stat *st )
237 return st->st_dev == file->dev && st->st_ino == file->ino;
240 static inline BOOL is_ignored_file( const struct stat *st )
242 unsigned int i;
244 for (i = 0; i < ignored_files_count; i++)
245 if (is_same_file( &ignored_files[i], st )) return TRUE;
246 return FALSE;
249 static inline unsigned int dir_info_size( FILE_INFORMATION_CLASS class, unsigned int len )
251 switch (class)
253 case FileDirectoryInformation:
254 return (FIELD_OFFSET( FILE_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
255 case FileBothDirectoryInformation:
256 return (FIELD_OFFSET( FILE_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
257 case FileFullDirectoryInformation:
258 return (FIELD_OFFSET( FILE_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
259 case FileIdBothDirectoryInformation:
260 return (FIELD_OFFSET( FILE_ID_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
261 case FileIdFullDirectoryInformation:
262 return (FIELD_OFFSET( FILE_ID_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
263 default:
264 assert(0);
265 return 0;
269 static inline unsigned int max_dir_info_size( FILE_INFORMATION_CLASS class )
271 return dir_info_size( class, MAX_DIR_ENTRY_LEN );
274 static inline BOOL has_wildcard( const UNICODE_STRING *mask )
276 return (!mask ||
277 memchrW( mask->Buffer, '*', mask->Length / sizeof(WCHAR) ) ||
278 memchrW( mask->Buffer, '?', mask->Length / sizeof(WCHAR) ));
282 /* support for a directory queue for filesystem searches */
284 struct dir_name
286 struct list entry;
287 char name[1];
290 static struct list dir_queue = LIST_INIT( dir_queue );
292 static NTSTATUS add_dir_to_queue( const char *name )
294 int len = strlen( name ) + 1;
295 struct dir_name *dir = RtlAllocateHeap( GetProcessHeap(), 0,
296 FIELD_OFFSET( struct dir_name, name[len] ));
297 if (!dir) return STATUS_NO_MEMORY;
298 strcpy( dir->name, name );
299 list_add_tail( &dir_queue, &dir->entry );
300 return STATUS_SUCCESS;
303 static NTSTATUS next_dir_in_queue( char *name )
305 struct list *head = list_head( &dir_queue );
306 if (head)
308 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
309 strcpy( name, dir->name );
310 list_remove( &dir->entry );
311 RtlFreeHeap( GetProcessHeap(), 0, dir );
312 return STATUS_SUCCESS;
314 return STATUS_OBJECT_NAME_NOT_FOUND;
317 static void flush_dir_queue(void)
319 struct list *head;
321 while ((head = list_head( &dir_queue )))
323 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
324 list_remove( &dir->entry );
325 RtlFreeHeap( GetProcessHeap(), 0, dir );
330 /***********************************************************************
331 * get_default_com_device
333 * Return the default device to use for serial ports.
335 static char *get_default_com_device( int num )
337 char *ret = NULL;
339 if (num < 1 || num > 256) return NULL;
340 #ifdef linux
341 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS256") );
342 if (!ret) return NULL;
343 sprintf( ret, "/dev/ttyS%d", num - 1 );
344 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
345 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuau256") );
346 if (!ret) return NULL;
347 sprintf( ret, "/dev/cuau%d", num - 1 );
348 #elif defined(__DragonFly__)
349 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuaa256") );
350 if (!ret) return NULL;
351 sprintf( ret, "/dev/cuaa%d", num - 1 );
352 #else
353 FIXME( "no known default for device com%d\n", num );
354 #endif
355 return ret;
359 /***********************************************************************
360 * get_default_lpt_device
362 * Return the default device to use for parallel ports.
364 static char *get_default_lpt_device( int num )
366 char *ret = NULL;
368 if (num < 1 || num > 256) return NULL;
369 #ifdef linux
370 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp256") );
371 if (!ret) return NULL;
372 sprintf( ret, "/dev/lp%d", num - 1 );
373 #else
374 FIXME( "no known default for device lpt%d\n", num );
375 #endif
376 return ret;
379 #ifdef __ANDROID__
381 static char *unescape_field( char *str )
383 char *in, *out;
385 for (in = out = str; *in; in++, out++)
387 *out = *in;
388 if (in[0] == '\\')
390 if (in[1] == '\\')
392 out[0] = '\\';
393 in++;
395 else if (in[1] == '0' && in[2] == '4' && in[3] == '0')
397 out[0] = ' ';
398 in += 3;
400 else if (in[1] == '0' && in[2] == '1' && in[3] == '1')
402 out[0] = '\t';
403 in += 3;
405 else if (in[1] == '0' && in[2] == '1' && in[3] == '2')
407 out[0] = '\n';
408 in += 3;
410 else if (in[1] == '1' && in[2] == '3' && in[3] == '4')
412 out[0] = '\\';
413 in += 3;
417 *out = '\0';
419 return str;
422 static inline char *get_field( char **str )
424 char *ret;
426 ret = strsep( str, " \t" );
427 if (*str) *str += strspn( *str, " \t" );
429 return ret;
431 /************************************************************************
432 * getmntent_replacement
434 * getmntent replacement for Android.
436 * NB returned static buffer is not thread safe; protect with dir_section.
438 static struct mntent *getmntent_replacement( FILE *f )
440 static struct mntent entry;
441 static char buf[4096];
442 char *p, *start;
446 if (!fgets( buf, sizeof(buf), f )) return NULL;
447 p = strchr( buf, '\n' );
448 if (p) *p = '\0';
449 else /* Partially unread line, move file ptr to end */
451 char tmp[1024];
452 while (fgets( tmp, sizeof(tmp), f ))
453 if (strchr( tmp, '\n' )) break;
455 start = buf + strspn( buf, " \t" );
456 } while (start[0] == '\0' || start[0] == '#');
458 p = get_field( &start );
459 entry.mnt_fsname = p ? unescape_field( p ) : (char *)"";
461 p = get_field( &start );
462 entry.mnt_dir = p ? unescape_field( p ) : (char *)"";
464 p = get_field( &start );
465 entry.mnt_type = p ? unescape_field( p ) : (char *)"";
467 p = get_field( &start );
468 entry.mnt_opts = p ? unescape_field( p ) : (char *)"";
470 p = get_field( &start );
471 entry.mnt_freq = p ? atoi(p) : 0;
473 p = get_field( &start );
474 entry.mnt_passno = p ? atoi(p) : 0;
476 return &entry;
478 #define getmntent getmntent_replacement
479 #endif
481 /***********************************************************************
482 * DIR_get_drives_info
484 * Retrieve device/inode number for all the drives. Helper for find_drive_root.
486 unsigned int DIR_get_drives_info( struct drive_info info[MAX_DOS_DRIVES] )
488 static struct drive_info cache[MAX_DOS_DRIVES];
489 static time_t last_update;
490 static unsigned int nb_drives;
491 unsigned int ret;
492 time_t now = time(NULL);
494 RtlEnterCriticalSection( &dir_section );
495 if (now != last_update)
497 const char *config_dir = wine_get_config_dir();
498 char *buffer, *p;
499 struct stat st;
500 unsigned int i;
502 if ((buffer = RtlAllocateHeap( GetProcessHeap(), 0,
503 strlen(config_dir) + sizeof("/dosdevices/a:") )))
505 strcpy( buffer, config_dir );
506 strcat( buffer, "/dosdevices/a:" );
507 p = buffer + strlen(buffer) - 2;
509 for (i = nb_drives = 0; i < MAX_DOS_DRIVES; i++)
511 *p = 'a' + i;
512 if (!stat( buffer, &st ))
514 cache[i].dev = st.st_dev;
515 cache[i].ino = st.st_ino;
516 nb_drives++;
518 else
520 cache[i].dev = 0;
521 cache[i].ino = 0;
524 RtlFreeHeap( GetProcessHeap(), 0, buffer );
526 last_update = now;
528 memcpy( info, cache, sizeof(cache) );
529 ret = nb_drives;
530 RtlLeaveCriticalSection( &dir_section );
531 return ret;
535 /***********************************************************************
536 * parse_mount_entries
538 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
541 #ifdef sun
542 #include <sys/vfstab.h>
543 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
545 struct vfstab entry;
546 struct stat st;
547 char *device;
549 while (! getvfsent( f, &entry ))
551 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
552 if (!strcmp( entry.vfs_fstype, "nfs" ) ||
553 !strcmp( entry.vfs_fstype, "smbfs" ) ||
554 !strcmp( entry.vfs_fstype, "ncpfs" )) continue;
556 if (stat( entry.vfs_mountp, &st ) == -1) continue;
557 if (st.st_dev != dev || st.st_ino != ino) continue;
558 if (!strcmp( entry.vfs_fstype, "fd" ))
560 if ((device = strstr( entry.vfs_mntopts, "dev=" )))
562 char *p = strchr( device + 4, ',' );
563 if (p) *p = 0;
564 return device + 4;
567 else
568 return entry.vfs_special;
570 return NULL;
572 #endif
574 #ifdef linux
575 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
577 struct mntent *entry;
578 struct stat st;
579 char *device;
581 while ((entry = getmntent( f )))
583 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
584 if (!strcmp( entry->mnt_type, "nfs" ) ||
585 !strcmp( entry->mnt_type, "smbfs" ) ||
586 !strcmp( entry->mnt_type, "ncpfs" )) continue;
588 if (stat( entry->mnt_dir, &st ) == -1) continue;
589 if (st.st_dev != dev || st.st_ino != ino) continue;
590 if (!strcmp( entry->mnt_type, "supermount" ))
592 if ((device = strstr( entry->mnt_opts, "dev=" )))
594 char *p = strchr( device + 4, ',' );
595 if (p) *p = 0;
596 return device + 4;
599 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
601 /* if device is a regular file check for a loop mount */
602 if ((device = strstr( entry->mnt_opts, "loop=" )))
604 char *p = strchr( device + 5, ',' );
605 if (p) *p = 0;
606 return device + 5;
609 else
610 return entry->mnt_fsname;
612 return NULL;
614 #endif
616 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
617 #include <fstab.h>
618 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
620 struct fstab *entry;
621 struct stat st;
623 while ((entry = getfsent()))
625 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
626 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
627 !strcmp( entry->fs_vfstype, "smbfs" ) ||
628 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
630 if (stat( entry->fs_file, &st ) == -1) continue;
631 if (st.st_dev != dev || st.st_ino != ino) continue;
632 return entry->fs_spec;
634 return NULL;
636 #endif
638 #ifdef sun
639 #include <sys/mnttab.h>
640 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
642 struct mnttab entry;
643 struct stat st;
644 char *device;
647 while (( ! getmntent( f, &entry) ))
649 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
650 if (!strcmp( entry.mnt_fstype, "nfs" ) ||
651 !strcmp( entry.mnt_fstype, "smbfs" ) ||
652 !strcmp( entry.mnt_fstype, "ncpfs" )) continue;
654 if (stat( entry.mnt_mountp, &st ) == -1) continue;
655 if (st.st_dev != dev || st.st_ino != ino) continue;
656 if (!strcmp( entry.mnt_fstype, "fd" ))
658 if ((device = strstr( entry.mnt_mntopts, "dev=" )))
660 char *p = strchr( device + 4, ',' );
661 if (p) *p = 0;
662 return device + 4;
665 else
666 return entry.mnt_special;
668 return NULL;
670 #endif
672 /***********************************************************************
673 * get_default_drive_device
675 * Return the default device to use for a given drive mount point.
677 static char *get_default_drive_device( const char *root )
679 char *ret = NULL;
681 #ifdef linux
682 FILE *f;
683 char *device = NULL;
684 int fd, res = -1;
685 struct stat st;
687 /* try to open it first to force it to get mounted */
688 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
690 res = fstat( fd, &st );
691 close( fd );
693 /* now try normal stat just in case */
694 if (res == -1) res = stat( root, &st );
695 if (res == -1) return NULL;
697 RtlEnterCriticalSection( &dir_section );
699 #ifdef __ANDROID__
700 if ((f = fopen( "/proc/mounts", "r" )))
702 device = parse_mount_entries( f, st.st_dev, st.st_ino );
703 fclose( f );
705 #else
706 if ((f = fopen( "/etc/mtab", "r" )))
708 device = parse_mount_entries( f, st.st_dev, st.st_ino );
709 fclose( f );
711 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
712 if (!device && (f = fopen( "/etc/fstab", "r" )))
714 device = parse_mount_entries( f, st.st_dev, st.st_ino );
715 fclose( f );
717 #endif
718 if (device)
720 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
721 if (ret) strcpy( ret, device );
723 RtlLeaveCriticalSection( &dir_section );
725 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ ) || defined(__DragonFly__)
726 char *device = NULL;
727 int fd, res = -1;
728 struct stat st;
730 /* try to open it first to force it to get mounted */
731 if ((fd = open( root, O_RDONLY )) != -1)
733 res = fstat( fd, &st );
734 close( fd );
736 /* now try normal stat just in case */
737 if (res == -1) res = stat( root, &st );
738 if (res == -1) return NULL;
740 RtlEnterCriticalSection( &dir_section );
742 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
743 * pass NULL. Leave the argument in for symmetry.
745 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
746 if (device)
748 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
749 if (ret) strcpy( ret, device );
751 RtlLeaveCriticalSection( &dir_section );
753 #elif defined( sun )
754 FILE *f;
755 char *device = NULL;
756 int fd, res = -1;
757 struct stat st;
759 /* try to open it first to force it to get mounted */
760 if ((fd = open( root, O_RDONLY )) != -1)
762 res = fstat( fd, &st );
763 close( fd );
765 /* now try normal stat just in case */
766 if (res == -1) res = stat( root, &st );
767 if (res == -1) return NULL;
769 RtlEnterCriticalSection( &dir_section );
771 if ((f = fopen( "/etc/mnttab", "r" )))
773 device = parse_mount_entries( f, st.st_dev, st.st_ino);
774 fclose( f );
776 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
777 if (!device && (f = fopen( "/etc/vfstab", "r" )))
779 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
780 fclose( f );
782 if (device)
784 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
785 if (ret) strcpy( ret, device );
787 RtlLeaveCriticalSection( &dir_section );
789 #elif defined(__APPLE__)
790 struct statfs *mntStat;
791 struct stat st;
792 int i;
793 int mntSize;
794 dev_t dev;
795 ino_t ino;
796 static const char path_bsd_device[] = "/dev/disk";
797 int res;
799 res = stat( root, &st );
800 if (res == -1) return NULL;
802 dev = st.st_dev;
803 ino = st.st_ino;
805 RtlEnterCriticalSection( &dir_section );
807 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
809 for (i = 0; i < mntSize && !ret; i++)
811 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
812 if (st.st_dev != dev || st.st_ino != ino) continue;
814 /* FIXME add support for mounted network drive */
815 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
817 /* set return value to the corresponding raw BSD node */
818 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
819 if (ret)
821 strcpy(ret, "/dev/r");
822 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
826 RtlLeaveCriticalSection( &dir_section );
827 #else
828 static int warned;
829 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
830 #endif
831 return ret;
835 /***********************************************************************
836 * get_device_mount_point
838 * Return the current mount point for a device.
840 static char *get_device_mount_point( dev_t dev )
842 char *ret = NULL;
844 #ifdef linux
845 FILE *f;
847 RtlEnterCriticalSection( &dir_section );
849 #ifdef __ANDROID__
850 if ((f = fopen( "/proc/mounts", "r" )))
851 #else
852 if ((f = fopen( "/etc/mtab", "r" )))
853 #endif
855 struct mntent *entry;
856 struct stat st;
857 char *p, *device;
859 while ((entry = getmntent( f )))
861 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
862 if (!strcmp( entry->mnt_type, "nfs" ) ||
863 !strcmp( entry->mnt_type, "smbfs" ) ||
864 !strcmp( entry->mnt_type, "ncpfs" )) continue;
866 if (!strcmp( entry->mnt_type, "supermount" ))
868 if ((device = strstr( entry->mnt_opts, "dev=" )))
870 device += 4;
871 if ((p = strchr( device, ',' ))) *p = 0;
874 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
876 /* if device is a regular file check for a loop mount */
877 if ((device = strstr( entry->mnt_opts, "loop=" )))
879 device += 5;
880 if ((p = strchr( device, ',' ))) *p = 0;
883 else device = entry->mnt_fsname;
885 if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
887 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
888 if (ret) strcpy( ret, entry->mnt_dir );
889 break;
892 fclose( f );
894 RtlLeaveCriticalSection( &dir_section );
895 #elif defined(__APPLE__)
896 struct statfs *entry;
897 struct stat st;
898 int i, size;
900 RtlEnterCriticalSection( &dir_section );
902 size = getmntinfo( &entry, MNT_NOWAIT );
903 for (i = 0; i < size; i++)
905 if (stat( entry[i].f_mntfromname, &st ) == -1) continue;
906 if (S_ISBLK(st.st_mode) && st.st_rdev == dev)
908 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry[i].f_mntonname) + 1 );
909 if (ret) strcpy( ret, entry[i].f_mntonname );
910 break;
913 RtlLeaveCriticalSection( &dir_section );
914 #else
915 static int warned;
916 if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
917 #endif
918 return ret;
922 #if defined(HAVE_GETATTRLIST) && defined(ATTR_VOL_CAPABILITIES) && \
923 defined(VOL_CAPABILITIES_FORMAT) && defined(VOL_CAP_FMT_CASE_SENSITIVE)
925 struct get_fsid
927 ULONG size;
928 dev_t dev;
929 fsid_t fsid;
932 struct fs_cache
934 dev_t dev;
935 fsid_t fsid;
936 BOOLEAN case_sensitive;
937 } fs_cache[64];
939 struct vol_caps
941 ULONG size;
942 vol_capabilities_attr_t caps;
945 /***********************************************************************
946 * look_up_fs_cache
948 * Checks if the specified file system is in the cache.
950 static struct fs_cache *look_up_fs_cache( dev_t dev )
952 int i;
953 for (i = 0; i < sizeof(fs_cache)/sizeof(fs_cache[0]); i++)
954 if (fs_cache[i].dev == dev)
955 return fs_cache+i;
956 return NULL;
959 /***********************************************************************
960 * add_fs_cache
962 * Adds the specified file system to the cache.
964 static void add_fs_cache( dev_t dev, fsid_t fsid, BOOLEAN case_sensitive )
966 int i;
967 struct fs_cache *entry = look_up_fs_cache( dev );
968 static int once = 0;
969 if (entry)
971 /* Update the cache */
972 entry->fsid = fsid;
973 entry->case_sensitive = case_sensitive;
974 return;
977 /* Add a new entry */
978 for (i = 0; i < sizeof(fs_cache)/sizeof(fs_cache[0]); i++)
979 if (fs_cache[i].dev == 0)
981 /* This entry is empty, use it */
982 fs_cache[i].dev = dev;
983 fs_cache[i].fsid = fsid;
984 fs_cache[i].case_sensitive = case_sensitive;
985 return;
988 /* Cache is out of space, warn */
989 if (!once++)
990 WARN( "FS cache is out of space, expect performance problems\n" );
993 /***********************************************************************
994 * get_dir_case_sensitivity_attr
996 * Checks if the volume containing the specified directory is case
997 * sensitive or not. Uses getattrlist(2).
999 static int get_dir_case_sensitivity_attr( const char *dir )
1001 char *mntpoint;
1002 struct attrlist attr;
1003 struct vol_caps caps;
1004 struct get_fsid get_fsid;
1005 struct fs_cache *entry;
1007 /* First get the FS ID of the volume */
1008 attr.bitmapcount = ATTR_BIT_MAP_COUNT;
1009 attr.reserved = 0;
1010 attr.commonattr = ATTR_CMN_DEVID|ATTR_CMN_FSID;
1011 attr.volattr = attr.dirattr = attr.fileattr = attr.forkattr = 0;
1012 get_fsid.size = 0;
1013 if (getattrlist( dir, &attr, &get_fsid, sizeof(get_fsid), 0 ) != 0 ||
1014 get_fsid.size != sizeof(get_fsid))
1015 return -1;
1016 /* Try to look it up in the cache */
1017 entry = look_up_fs_cache( get_fsid.dev );
1018 if (entry && !memcmp( &entry->fsid, &get_fsid.fsid, sizeof(fsid_t) ))
1019 /* Cache lookup succeeded */
1020 return entry->case_sensitive;
1021 /* Cache is stale at this point, we have to update it */
1023 mntpoint = get_device_mount_point( get_fsid.dev );
1024 /* Now look up the case-sensitivity */
1025 attr.commonattr = 0;
1026 attr.volattr = ATTR_VOL_INFO|ATTR_VOL_CAPABILITIES;
1027 if (getattrlist( mntpoint, &attr, &caps, sizeof(caps), 0 ) < 0)
1029 RtlFreeHeap( GetProcessHeap(), 0, mntpoint );
1030 add_fs_cache( get_fsid.dev, get_fsid.fsid, TRUE );
1031 return TRUE;
1033 RtlFreeHeap( GetProcessHeap(), 0, mntpoint );
1034 if (caps.size == sizeof(caps) &&
1035 (caps.caps.valid[VOL_CAPABILITIES_FORMAT] &
1036 (VOL_CAP_FMT_CASE_SENSITIVE | VOL_CAP_FMT_CASE_PRESERVING)) ==
1037 (VOL_CAP_FMT_CASE_SENSITIVE | VOL_CAP_FMT_CASE_PRESERVING))
1039 BOOLEAN ret;
1041 if ((caps.caps.capabilities[VOL_CAPABILITIES_FORMAT] &
1042 VOL_CAP_FMT_CASE_SENSITIVE) != VOL_CAP_FMT_CASE_SENSITIVE)
1043 ret = FALSE;
1044 else
1045 ret = TRUE;
1046 /* Update the cache */
1047 add_fs_cache( get_fsid.dev, get_fsid.fsid, ret );
1048 return ret;
1050 return FALSE;
1052 #endif
1054 /***********************************************************************
1055 * get_dir_case_sensitivity_stat
1057 * Checks if the volume containing the specified directory is case
1058 * sensitive or not. Uses statfs(2) or statvfs(2).
1060 static BOOLEAN get_dir_case_sensitivity_stat( const char *dir )
1062 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1063 struct statfs stfs;
1065 if (statfs( dir, &stfs ) == -1) return FALSE;
1066 /* Assume these file systems are always case insensitive on Mac OS.
1067 * For FreeBSD, only assume CIOPFS is case insensitive (AFAIK, Mac OS
1068 * is the only UNIX that supports case-insensitive lookup).
1070 if (!strcmp( stfs.f_fstypename, "fusefs" ) &&
1071 !strncmp( stfs.f_mntfromname, "ciopfs", 5 ))
1072 return FALSE;
1073 #ifdef __APPLE__
1074 if (!strcmp( stfs.f_fstypename, "msdos" ) ||
1075 !strcmp( stfs.f_fstypename, "cd9660" ) ||
1076 !strcmp( stfs.f_fstypename, "udf" ) ||
1077 !strcmp( stfs.f_fstypename, "ntfs" ) ||
1078 !strcmp( stfs.f_fstypename, "smbfs" ))
1079 return FALSE;
1080 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1081 if (!strcmp( stfs.f_fstypename, "hfs" ) && (stfs.f_fssubtype == 0 ||
1082 stfs.f_fssubtype == 1 ||
1083 stfs.f_fssubtype == 128))
1084 return FALSE;
1085 #else
1086 /* The field says "reserved", but a quick look at the kernel source
1087 * tells us that this "reserved" field is really the same as the
1088 * "fssubtype" field from the inode64 structure (see munge_statfs()
1089 * in <xnu-source>/bsd/vfs/vfs_syscalls.c).
1091 if (!strcmp( stfs.f_fstypename, "hfs" ) && (stfs.f_reserved1 == 0 ||
1092 stfs.f_reserved1 == 1 ||
1093 stfs.f_reserved1 == 128))
1094 return FALSE;
1095 #endif
1096 #endif
1097 return TRUE;
1099 #elif defined(__NetBSD__)
1100 struct statvfs stfs;
1102 if (statvfs( dir, &stfs ) == -1) return FALSE;
1103 /* Only assume CIOPFS is case insensitive. */
1104 if (strcmp( stfs.f_fstypename, "fusefs" ) ||
1105 strncmp( stfs.f_mntfromname, "ciopfs", 5 ))
1106 return TRUE;
1107 return FALSE;
1109 #elif defined(__linux__)
1110 struct statfs stfs;
1111 struct stat st;
1112 char *cifile;
1114 /* Only assume CIOPFS is case insensitive. */
1115 if (statfs( dir, &stfs ) == -1) return FALSE;
1116 if (stfs.f_type != 0x65735546 /* FUSE_SUPER_MAGIC */)
1117 return TRUE;
1118 /* Normally, we'd have to parse the mtab to find out exactly what
1119 * kind of FUSE FS this is. But, someone on wine-devel suggested
1120 * a shortcut. We'll stat a special file in the directory. If it's
1121 * there, we'll assume it's a CIOPFS, else not.
1122 * This will break if somebody puts a file named ".ciopfs" in a non-
1123 * CIOPFS directory.
1125 cifile = RtlAllocateHeap( GetProcessHeap(), 0, strlen( dir )+sizeof("/.ciopfs") );
1126 if (!cifile) return TRUE;
1127 strcpy( cifile, dir );
1128 strcat( cifile, "/.ciopfs" );
1129 if (stat( cifile, &st ) == 0)
1131 RtlFreeHeap( GetProcessHeap(), 0, cifile );
1132 return FALSE;
1134 RtlFreeHeap( GetProcessHeap(), 0, cifile );
1135 return TRUE;
1136 #else
1137 return TRUE;
1138 #endif
1142 /***********************************************************************
1143 * get_dir_case_sensitivity
1145 * Checks if the volume containing the specified directory is case
1146 * sensitive or not. Uses statfs(2) or statvfs(2).
1148 static BOOLEAN get_dir_case_sensitivity( const char *dir )
1150 #if defined(HAVE_GETATTRLIST) && defined(ATTR_VOL_CAPABILITIES) && \
1151 defined(VOL_CAPABILITIES_FORMAT) && defined(VOL_CAP_FMT_CASE_SENSITIVE)
1152 int case_sensitive = get_dir_case_sensitivity_attr( dir );
1153 if (case_sensitive != -1) return case_sensitive;
1154 #endif
1155 return get_dir_case_sensitivity_stat( dir );
1159 /***********************************************************************
1160 * init_options
1162 * Initialize the show_dot_files options.
1164 static DWORD WINAPI init_options( RTL_RUN_ONCE *once, void *param, void **context )
1166 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
1167 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
1168 char tmp[80];
1169 HANDLE root, hkey;
1170 DWORD dummy;
1171 OBJECT_ATTRIBUTES attr;
1172 UNICODE_STRING nameW;
1174 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
1175 attr.Length = sizeof(attr);
1176 attr.RootDirectory = root;
1177 attr.ObjectName = &nameW;
1178 attr.Attributes = 0;
1179 attr.SecurityDescriptor = NULL;
1180 attr.SecurityQualityOfService = NULL;
1181 RtlInitUnicodeString( &nameW, WineW );
1183 /* @@ Wine registry key: HKCU\Software\Wine */
1184 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
1186 RtlInitUnicodeString( &nameW, ShowDotFilesW );
1187 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
1189 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
1190 show_dot_files = IS_OPTION_TRUE( str[0] );
1192 NtClose( hkey );
1194 NtClose( root );
1196 /* a couple of directories that we don't want to return in directory searches */
1197 ignore_file( wine_get_config_dir() );
1198 ignore_file( "/dev" );
1199 ignore_file( "/proc" );
1200 #ifdef linux
1201 ignore_file( "/sys" );
1202 #endif
1203 return TRUE;
1207 /***********************************************************************
1208 * DIR_is_hidden_file
1210 * Check if the specified file should be hidden based on its name and the show dot files option.
1212 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
1214 WCHAR *p, *end;
1216 RtlRunOnceExecuteOnce( &init_once, init_options, NULL, NULL );
1218 if (show_dot_files) return FALSE;
1220 end = p = name->Buffer + name->Length/sizeof(WCHAR);
1221 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
1222 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
1223 if (p == end || *p != '.') return FALSE;
1224 /* make sure it isn't '.' or '..' */
1225 if (p + 1 == end) return FALSE;
1226 if (p[1] == '.' && p + 2 == end) return FALSE;
1227 return TRUE;
1231 /***********************************************************************
1232 * hash_short_file_name
1234 * Transform a Unix file name into a hashed DOS name. If the name is a valid
1235 * DOS name, it is converted to upper-case; otherwise it is replaced by a
1236 * hashed version that fits in 8.3 format.
1237 * 'buffer' must be at least 12 characters long.
1238 * Returns length of short name in bytes; short name is NOT null-terminated.
1240 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
1242 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
1244 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
1245 LPWSTR dst;
1246 unsigned short hash;
1247 int i;
1249 /* Compute the hash code of the file name */
1250 /* If you know something about hash functions, feel free to */
1251 /* insert a better algorithm here... */
1252 if (!is_case_sensitive)
1254 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
1255 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
1256 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
1258 else
1260 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
1261 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
1262 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
1265 /* Find last dot for start of the extension */
1266 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
1268 /* Copy first 4 chars, replacing invalid chars with '_' */
1269 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
1271 if (p == end || p == ext) break;
1272 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
1274 /* Pad to 5 chars with '~' */
1275 while (i-- >= 0) *dst++ = '~';
1277 /* Insert hash code converted to 3 ASCII chars */
1278 *dst++ = hash_chars[(hash >> 10) & 0x1f];
1279 *dst++ = hash_chars[(hash >> 5) & 0x1f];
1280 *dst++ = hash_chars[hash & 0x1f];
1282 /* Copy the first 3 chars of the extension (if any) */
1283 if (ext)
1285 *dst++ = '.';
1286 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
1287 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
1289 return dst - buffer;
1293 /***********************************************************************
1294 * match_filename
1296 * Check a long file name against a mask.
1298 * Tests (done in W95 DOS shell - case insensitive):
1299 * *.txt test1.test.txt *
1300 * *st1* test1.txt *
1301 * *.t??????.t* test1.ta.tornado.txt *
1302 * *tornado* test1.ta.tornado.txt *
1303 * t*t test1.ta.tornado.txt *
1304 * ?est* test1.txt *
1305 * ?est??? test1.txt -
1306 * *test1.txt* test1.txt *
1307 * h?l?o*t.dat hellothisisatest.dat *
1309 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
1311 BOOL mismatch;
1312 const WCHAR *name = name_str->Buffer;
1313 const WCHAR *mask = mask_str->Buffer;
1314 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
1315 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
1316 const WCHAR *lastjoker = NULL;
1317 const WCHAR *next_to_retry = NULL;
1319 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
1321 while (name < name_end && mask < mask_end)
1323 switch(*mask)
1325 case '*':
1326 mask++;
1327 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
1328 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
1329 lastjoker = mask;
1331 /* skip to the next match after the joker(s) */
1332 if (is_case_sensitive)
1333 while (name < name_end && (*name != *mask)) name++;
1334 else
1335 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
1336 next_to_retry = name;
1337 break;
1338 case '?':
1339 mask++;
1340 name++;
1341 break;
1342 default:
1343 if (is_case_sensitive) mismatch = (*mask != *name);
1344 else mismatch = (toupperW(*mask) != toupperW(*name));
1346 if (!mismatch)
1348 mask++;
1349 name++;
1350 if (mask == mask_end)
1352 if (name == name_end) return TRUE;
1353 if (lastjoker) mask = lastjoker;
1356 else /* mismatch ! */
1358 if (lastjoker) /* we had an '*', so we can try unlimitedly */
1360 mask = lastjoker;
1362 /* this scan sequence was a mismatch, so restart
1363 * 1 char after the first char we checked last time */
1364 next_to_retry++;
1365 name = next_to_retry;
1367 else return FALSE; /* bad luck */
1369 break;
1372 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
1373 mask++; /* Ignore trailing '.' or '*' in mask */
1374 return (name == name_end && mask == mask_end);
1378 /***********************************************************************
1379 * append_entry
1381 * helper for NtQueryDirectoryFile
1383 static union file_directory_info *append_entry( void *info_ptr, IO_STATUS_BLOCK *io, ULONG max_length,
1384 const char *long_name, const char *short_name,
1385 const UNICODE_STRING *mask, FILE_INFORMATION_CLASS class )
1387 union file_directory_info *info;
1388 int i, long_len, short_len, total_len;
1389 struct stat st;
1390 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
1391 WCHAR short_nameW[12];
1392 WCHAR *filename;
1393 UNICODE_STRING str;
1394 ULONG attributes;
1396 io->u.Status = STATUS_SUCCESS;
1397 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
1398 if (long_len == -1) return NULL;
1400 str.Buffer = long_nameW;
1401 str.Length = long_len * sizeof(WCHAR);
1402 str.MaximumLength = sizeof(long_nameW);
1404 if (short_name)
1406 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
1407 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
1408 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
1410 else /* generate a short name if necessary */
1412 BOOLEAN spaces;
1414 short_len = 0;
1415 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1416 short_len = hash_short_file_name( &str, short_nameW );
1419 TRACE( "long %s short %s mask %s\n",
1420 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
1422 if (mask && !match_filename( &str, mask ))
1424 if (!short_len) return NULL; /* no short name to match */
1425 str.Buffer = short_nameW;
1426 str.Length = short_len * sizeof(WCHAR);
1427 str.MaximumLength = sizeof(short_nameW);
1428 if (!match_filename( &str, mask )) return NULL;
1431 if (get_file_info( long_name, &st, &attributes ) == -1) return NULL;
1432 if (is_ignored_file( &st ))
1434 TRACE( "ignoring file %s\n", long_name );
1435 return NULL;
1437 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
1438 attributes |= FILE_ATTRIBUTE_HIDDEN;
1440 total_len = dir_info_size( class, long_len );
1441 if (io->Information + total_len > max_length)
1443 total_len = max_length - io->Information;
1444 io->u.Status = STATUS_BUFFER_OVERFLOW;
1446 info = (union file_directory_info *)((char *)info_ptr + io->Information);
1447 if (st.st_dev != curdir.dev) st.st_ino = 0; /* ignore inode if on a different device */
1448 /* all the structures start with a FileDirectoryInformation layout */
1449 fill_file_info( &st, attributes, info, class );
1450 info->dir.NextEntryOffset = total_len;
1451 info->dir.FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
1453 switch (class)
1455 case FileDirectoryInformation:
1456 info->dir.FileNameLength = long_len * sizeof(WCHAR);
1457 filename = info->dir.FileName;
1458 break;
1460 case FileFullDirectoryInformation:
1461 info->full.EaSize = 0; /* FIXME */
1462 info->full.FileNameLength = long_len * sizeof(WCHAR);
1463 filename = info->full.FileName;
1464 break;
1466 case FileIdFullDirectoryInformation:
1467 info->id_full.EaSize = 0; /* FIXME */
1468 info->id_full.FileNameLength = long_len * sizeof(WCHAR);
1469 filename = info->id_full.FileName;
1470 break;
1472 case FileBothDirectoryInformation:
1473 info->both.EaSize = 0; /* FIXME */
1474 info->both.ShortNameLength = short_len * sizeof(WCHAR);
1475 for (i = 0; i < short_len; i++) info->both.ShortName[i] = toupperW(short_nameW[i]);
1476 info->both.FileNameLength = long_len * sizeof(WCHAR);
1477 filename = info->both.FileName;
1478 break;
1480 case FileIdBothDirectoryInformation:
1481 info->id_both.EaSize = 0; /* FIXME */
1482 info->id_both.ShortNameLength = short_len * sizeof(WCHAR);
1483 for (i = 0; i < short_len; i++) info->id_both.ShortName[i] = toupperW(short_nameW[i]);
1484 info->id_both.FileNameLength = long_len * sizeof(WCHAR);
1485 filename = info->id_both.FileName;
1486 break;
1488 default:
1489 assert(0);
1490 return NULL;
1492 memcpy( filename, long_nameW, long_len * sizeof(WCHAR) );
1493 io->Information += total_len;
1494 return info;
1498 #ifdef VFAT_IOCTL_READDIR_BOTH
1500 /***********************************************************************
1501 * start_vfat_ioctl
1503 * Wrapper for the VFAT ioctl to work around various kernel bugs.
1504 * dir_section must be held by caller.
1506 static KERNEL_DIRENT *start_vfat_ioctl( int fd )
1508 static KERNEL_DIRENT *de;
1509 int res;
1511 if (!de)
1513 SIZE_T size = 2 * sizeof(*de) + page_size;
1514 void *addr = NULL;
1516 if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_RESERVE, PAGE_READWRITE ))
1517 return NULL;
1518 /* commit only the size needed for the dir entries */
1519 /* this leaves an extra unaccessible page, which should make the kernel */
1520 /* fail with -EFAULT before it stomps all over our memory */
1521 de = addr;
1522 size = 2 * sizeof(*de);
1523 NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_COMMIT, PAGE_READWRITE );
1526 /* set d_reclen to 65535 to work around an AFS kernel bug */
1527 de[0].d_reclen = 65535;
1528 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
1529 if (res == -1)
1531 if (errno != ENOENT) return NULL; /* VFAT ioctl probably not supported */
1532 de[0].d_reclen = 0; /* eof */
1534 else if (!res && de[0].d_reclen == 65535) return NULL; /* AFS bug */
1536 return de;
1540 /***********************************************************************
1541 * read_directory_vfat
1543 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
1545 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1546 BOOLEAN single_entry, const UNICODE_STRING *mask,
1547 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1550 size_t len;
1551 KERNEL_DIRENT *de;
1552 union file_directory_info *info, *last_info = NULL;
1554 io->u.Status = STATUS_SUCCESS;
1556 if (restart_scan) lseek( fd, 0, SEEK_SET );
1558 if (length < max_dir_info_size(class)) /* we may have to return a partial entry here */
1560 off_t old_pos = lseek( fd, 0, SEEK_CUR );
1562 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1564 while (de[0].d_reclen)
1566 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1567 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1568 de[0].d_name[len] = 0;
1569 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1570 de[1].d_name[len] = 0;
1572 if (de[1].d_name[0])
1573 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1574 else
1575 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1576 if (info)
1578 last_info = info;
1579 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1580 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1581 break;
1583 old_pos = lseek( fd, 0, SEEK_CUR );
1584 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1587 else /* we'll only return full entries, no need to worry about overflow */
1589 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1591 while (de[0].d_reclen)
1593 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1594 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1595 de[0].d_name[len] = 0;
1596 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1597 de[1].d_name[len] = 0;
1599 if (de[1].d_name[0])
1600 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1601 else
1602 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1603 if (info)
1605 last_info = info;
1606 if (single_entry) break;
1607 /* check if we still have enough space for the largest possible entry */
1608 if (io->Information + max_dir_info_size(class) > length) break;
1610 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1614 if (last_info) last_info->next = 0;
1615 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1616 return 0;
1618 #endif /* VFAT_IOCTL_READDIR_BOTH */
1621 #ifdef USE_GETDENTS
1622 /***********************************************************************
1623 * read_first_dent_name
1625 * reads name of first or second dentry (if they have inodes).
1627 static char *read_first_dent_name( int which, int fd, off_t second_offs, KERNEL_DIRENT64 *de_first_two,
1628 char *buffer, size_t size, BOOL *buffer_changed )
1630 KERNEL_DIRENT64 *de;
1631 int res;
1633 de = de_first_two;
1634 if (de != NULL)
1636 if (which == 1)
1637 de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1639 return de->d_ino ? de->d_name : NULL;
1642 *buffer_changed = TRUE;
1643 lseek( fd, which == 1 ? second_offs : 0, SEEK_SET );
1644 res = getdents64( fd, buffer, size );
1645 if (res <= 0)
1646 return NULL;
1648 de = (KERNEL_DIRENT64 *)buffer;
1649 return de->d_ino ? de->d_name : NULL;
1652 /***********************************************************************
1653 * read_directory_getdents
1655 * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
1657 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1658 BOOLEAN single_entry, const UNICODE_STRING *mask,
1659 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1661 static off_t second_entry_pos;
1662 static struct file_identity last_dir_id;
1663 off_t old_pos = 0, next_pos;
1664 size_t size = length;
1665 char *data, local_buffer[8192];
1666 KERNEL_DIRENT64 *de, *de_first_two = NULL;
1667 union file_directory_info *info, *last_info = NULL;
1668 const char *filename;
1669 BOOL data_buffer_changed;
1670 int res, swap_to;
1672 if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1674 size = sizeof(local_buffer);
1675 data = local_buffer;
1678 if (restart_scan) lseek( fd, 0, SEEK_SET );
1679 else
1681 old_pos = lseek( fd, 0, SEEK_CUR );
1682 if (old_pos == -1)
1684 io->u.Status = (errno == ENOENT) ? STATUS_NO_MORE_FILES : FILE_GetNtStatus();
1685 res = 0;
1686 goto done;
1690 io->u.Status = STATUS_SUCCESS;
1691 de = (KERNEL_DIRENT64 *)data;
1693 /* if old_pos is not 0 we don't know how many entries have been returned already,
1694 * so maintain second_entry_pos to know when to return '..' */
1695 if (old_pos != 0 && (last_dir_id.dev != curdir.dev || last_dir_id.ino != curdir.ino))
1697 lseek( fd, 0, SEEK_SET );
1698 res = getdents64( fd, data, size );
1699 if (res > 0)
1701 second_entry_pos = de->d_off;
1702 last_dir_id = curdir;
1704 lseek( fd, old_pos, SEEK_SET );
1707 res = getdents64( fd, data, size );
1708 if (res == -1)
1710 if (errno != ENOSYS)
1712 io->u.Status = FILE_GetNtStatus();
1713 res = 0;
1715 goto done;
1718 if (old_pos == 0 && res > 0)
1720 second_entry_pos = de->d_off;
1721 last_dir_id = curdir;
1722 if (res > de->d_reclen)
1723 de_first_two = de;
1726 while (res > 0)
1728 res -= de->d_reclen;
1729 next_pos = de->d_off;
1730 filename = NULL;
1732 /* we must return first 2 entries as "." and "..", but getdents64()
1733 * can return them anywhere, so swap first entries with "." and ".." */
1734 if (old_pos == 0)
1735 filename = ".";
1736 else if (old_pos == second_entry_pos)
1737 filename = "..";
1738 else if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))
1740 swap_to = !strcmp( de->d_name, "." ) ? 0 : 1;
1741 data_buffer_changed = FALSE;
1743 filename = read_first_dent_name( swap_to, fd, second_entry_pos, de_first_two,
1744 data, size, &data_buffer_changed );
1745 if (filename != NULL && (!strcmp( filename, "." ) || !strcmp( filename, ".." )))
1746 filename = read_first_dent_name( swap_to ^ 1, fd, second_entry_pos, NULL,
1747 data, size, &data_buffer_changed );
1748 if (data_buffer_changed)
1750 lseek( fd, next_pos, SEEK_SET );
1751 res = 0;
1754 else if (de->d_ino)
1755 filename = de->d_name;
1757 if (filename && (info = append_entry( buffer, io, length, filename, NULL, mask, class )))
1759 last_info = info;
1760 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1762 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1763 break;
1765 /* check if we still have enough space for the largest possible entry */
1766 if (single_entry || io->Information + max_dir_info_size(class) > length)
1768 if (res > 0) lseek( fd, next_pos, SEEK_SET ); /* set pos to next entry */
1769 break;
1772 old_pos = next_pos;
1773 /* move on to the next entry */
1774 if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1775 else
1777 res = getdents64( fd, data, size );
1778 de = (KERNEL_DIRENT64 *)data;
1779 de_first_two = NULL;
1783 if (last_info) last_info->next = 0;
1784 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1785 res = 0;
1786 done:
1787 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1788 return res;
1791 #elif defined HAVE_GETDIRENTRIES
1793 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1795 /* Darwin doesn't provide a version of getdirentries with support for 64-bit
1796 * inodes. When 64-bit inodes are enabled, the getdirentries symbol is mapped
1797 * to _getdirentries_is_not_available_when_64_bit_inodes_are_in_effect so that
1798 * we get link errors if we try to use it. We still need getdirentries, but we
1799 * don't need it to support 64-bit inodes. So, we use the legacy getdirentries
1800 * with 32-bit inodes. We have to be careful to use a corresponding dirent
1801 * structure, too.
1803 int darwin_legacy_getdirentries(int, char *, int, long *) __asm("_getdirentries");
1804 #define getdirentries darwin_legacy_getdirentries
1806 struct darwin_legacy_dirent {
1807 __uint32_t d_ino;
1808 __uint16_t d_reclen;
1809 __uint8_t d_type;
1810 __uint8_t d_namlen;
1811 char d_name[__DARWIN_MAXNAMLEN + 1];
1813 #define dirent darwin_legacy_dirent
1815 #endif
1817 /***********************************************************************
1818 * wine_getdirentries
1820 * Wrapper for the BSD getdirentries system call to fix a bug in the
1821 * Mac OS X version. For some file systems (at least Apple Filing
1822 * Protocol a.k.a. AFP), getdirentries resets the file position to 0
1823 * when it's about to return 0 (no more entries). So, a subsequent
1824 * getdirentries call starts over at the beginning again, causing an
1825 * infinite loop.
1827 static inline int wine_getdirentries(int fd, char *buf, int nbytes, long *basep)
1829 int res = getdirentries(fd, buf, nbytes, basep);
1830 #ifdef __APPLE__
1831 if (res == 0)
1832 lseek(fd, *basep, SEEK_SET);
1833 #endif
1834 return res;
1837 static inline int dir_reclen(struct dirent *de)
1839 #ifdef HAVE_STRUCT_DIRENT_D_RECLEN
1840 return de->d_reclen;
1841 #else
1842 return _DIRENT_RECLEN(de->d_namlen);
1843 #endif
1846 /***********************************************************************
1847 * read_directory_getdirentries
1849 * Read a directory using the BSD getdirentries system call; helper for NtQueryDirectoryFile.
1851 static int read_directory_getdirentries( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1852 BOOLEAN single_entry, const UNICODE_STRING *mask,
1853 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1855 long restart_pos;
1856 ULONG_PTR restart_info_pos = 0;
1857 size_t size, initial_size = length;
1858 int res, fake_dot_dot = 1;
1859 char *data, local_buffer[8192];
1860 struct dirent *de;
1861 union file_directory_info *info, *last_info = NULL, *restart_last_info = NULL;
1863 size = initial_size;
1864 data = local_buffer;
1865 if (size > sizeof(local_buffer) && !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1867 io->u.Status = STATUS_NO_MEMORY;
1868 return io->u.Status;
1871 if (restart_scan) lseek( fd, 0, SEEK_SET );
1873 io->u.Status = STATUS_SUCCESS;
1875 /* FIXME: should make sure size is larger than filesystem block size */
1876 res = wine_getdirentries( fd, data, size, &restart_pos );
1877 if (res == -1)
1879 io->u.Status = FILE_GetNtStatus();
1880 res = 0;
1881 goto done;
1884 de = (struct dirent *)data;
1886 if (restart_scan)
1888 /* check if we got . and .. from getdirentries */
1889 if (res > 0)
1891 if (!strcmp( de->d_name, "." ) && res > dir_reclen(de))
1893 struct dirent *next_de = (struct dirent *)(data + dir_reclen(de));
1894 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1897 /* make sure we have enough room for both entries */
1898 if (fake_dot_dot)
1900 const ULONG min_info_size = dir_info_size( class, 1 ) + dir_info_size( class, 2 );
1901 if (length < min_info_size || single_entry)
1903 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1904 fake_dot_dot = 0;
1908 if (fake_dot_dot)
1910 if ((info = append_entry( buffer, io, length, ".", NULL, mask, class )))
1911 last_info = info;
1912 if ((info = append_entry( buffer, io, length, "..", NULL, mask, class )))
1913 last_info = info;
1915 restart_last_info = last_info;
1916 restart_info_pos = io->Information;
1918 /* check if we still have enough space for the largest possible entry */
1919 if (last_info && io->Information + max_dir_info_size(class) > length)
1921 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1922 res = 0;
1927 while (res > 0)
1929 res -= dir_reclen(de);
1930 if (de->d_fileno &&
1931 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1932 ((info = append_entry( buffer, io, length, de->d_name, NULL, mask, class ))))
1934 last_info = info;
1935 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1937 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1938 if (restart_info_pos) /* if we have a complete read already, return it */
1940 io->u.Status = STATUS_SUCCESS;
1941 io->Information = restart_info_pos;
1942 last_info = restart_last_info;
1943 break;
1945 /* otherwise restart from the start with a smaller size */
1946 size = (char *)de - data;
1947 if (!size) break;
1948 io->Information = 0;
1949 last_info = NULL;
1950 goto restart;
1952 if (!has_wildcard( mask )) break;
1953 /* if we have to return but the buffer contains more data, restart with a smaller size */
1954 if (res > 0 && (single_entry || io->Information + max_dir_info_size(class) > length))
1956 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1957 size = (char *)de + dir_reclen(de) - data;
1958 io->Information = restart_info_pos;
1959 last_info = restart_last_info;
1960 goto restart;
1963 /* move on to the next entry */
1964 if (res > 0)
1966 de = (struct dirent *)((char *)de + dir_reclen(de));
1967 continue;
1969 if (size < initial_size) break; /* already restarted once, give up now */
1970 restart_last_info = last_info;
1971 restart_info_pos = io->Information;
1972 restart:
1973 res = wine_getdirentries( fd, data, size, &restart_pos );
1974 de = (struct dirent *)data;
1977 if (last_info) last_info->next = 0;
1978 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1979 res = 0;
1980 done:
1981 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1982 return res;
1985 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1986 #undef getdirentries
1987 #undef dirent
1988 #endif
1990 #endif /* HAVE_GETDIRENTRIES */
1993 /***********************************************************************
1994 * read_directory_readdir
1996 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1998 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1999 BOOLEAN single_entry, const UNICODE_STRING *mask,
2000 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
2002 DIR *dir;
2003 off_t i, old_pos = 0;
2004 struct dirent *de;
2005 union file_directory_info *info, *last_info = NULL;
2007 if (!(dir = opendir( "." )))
2009 io->u.Status = FILE_GetNtStatus();
2010 return;
2013 if (!restart_scan)
2015 old_pos = lseek( fd, 0, SEEK_CUR );
2016 /* skip the right number of entries */
2017 for (i = 0; i < old_pos - 2; i++)
2019 if (!readdir( dir ))
2021 closedir( dir );
2022 io->u.Status = STATUS_NO_MORE_FILES;
2023 return;
2027 io->u.Status = STATUS_SUCCESS;
2029 for (;;)
2031 if (old_pos == 0)
2032 info = append_entry( buffer, io, length, ".", NULL, mask, class );
2033 else if (old_pos == 1)
2034 info = append_entry( buffer, io, length, "..", NULL, mask, class );
2035 else if ((de = readdir( dir )))
2037 if (strcmp( de->d_name, "." ) && strcmp( de->d_name, ".." ))
2038 info = append_entry( buffer, io, length, de->d_name, NULL, mask, class );
2039 else
2040 info = NULL;
2042 else
2043 break;
2044 old_pos++;
2045 if (info)
2047 last_info = info;
2048 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
2050 old_pos--; /* restore pos to previous entry */
2051 break;
2053 if (single_entry) break;
2054 /* check if we still have enough space for the largest possible entry */
2055 if (io->Information + max_dir_info_size(class) > length) break;
2059 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
2060 closedir( dir );
2062 if (last_info) last_info->next = 0;
2063 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
2066 /***********************************************************************
2067 * read_directory_stat
2069 * Read a single file from a directory by determining whether the file
2070 * identified by mask exists using stat.
2072 static int read_directory_stat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
2073 BOOLEAN single_entry, const UNICODE_STRING *mask,
2074 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
2076 int unix_len, ret, used_default;
2077 char *unix_name;
2078 struct stat st;
2079 BOOL case_sensitive = get_dir_case_sensitivity(".");
2081 TRACE("looking up file %s\n", debugstr_us( mask ));
2083 unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
2084 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
2086 io->u.Status = STATUS_NO_MEMORY;
2087 return 0;
2089 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
2090 NULL, &used_default );
2091 if (ret > 0 && !used_default)
2093 unix_name[ret] = 0;
2094 if (restart_scan)
2096 lseek( fd, 0, SEEK_SET );
2098 else if (lseek( fd, 0, SEEK_CUR ) != 0)
2100 io->u.Status = STATUS_NO_MORE_FILES;
2101 ret = 0;
2102 goto done;
2105 ret = stat( unix_name, &st );
2106 if (case_sensitive && !ret)
2108 union file_directory_info *info = append_entry( buffer, io, length, unix_name, NULL, NULL, class );
2109 if (info)
2111 info->next = 0;
2112 if (io->u.Status != STATUS_BUFFER_OVERFLOW) lseek( fd, 1, SEEK_CUR );
2114 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
2116 else
2118 ret = -1;
2121 else ret = -1;
2123 done:
2124 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2126 TRACE("returning %d\n", ret);
2128 return ret;
2131 #ifdef HAVE_GETATTRLIST
2132 /***********************************************************************
2133 * read_directory_getattrlist
2135 * Read a single file from a directory by determining whether the file
2136 * identified by mask exists using getattrlist.
2138 static int read_directory_getattrlist( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
2139 BOOLEAN single_entry, const UNICODE_STRING *mask,
2140 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
2142 int unix_len, ret, used_default;
2143 char *unix_name;
2144 struct attrlist attrlist;
2145 #include "pshpack4.h"
2146 struct
2148 u_int32_t length;
2149 struct attrreference name_reference;
2150 fsobj_type_t type;
2151 char name[NAME_MAX * 3 + 1];
2152 } attrlist_buffer;
2153 #include "poppack.h"
2155 TRACE("looking up file %s\n", debugstr_us( mask ));
2157 unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
2158 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
2160 io->u.Status = STATUS_NO_MEMORY;
2161 return 0;
2163 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
2164 NULL, &used_default );
2165 if (ret > 0 && !used_default)
2167 unix_name[ret] = 0;
2168 if (restart_scan)
2170 lseek( fd, 0, SEEK_SET );
2172 else if (lseek( fd, 0, SEEK_CUR ) != 0)
2174 io->u.Status = STATUS_NO_MORE_FILES;
2175 ret = 0;
2176 goto done;
2179 memset( &attrlist, 0, sizeof(attrlist) );
2180 attrlist.bitmapcount = ATTR_BIT_MAP_COUNT;
2181 attrlist.commonattr = ATTR_CMN_NAME | ATTR_CMN_OBJTYPE;
2182 ret = getattrlist( unix_name, &attrlist, &attrlist_buffer, sizeof(attrlist_buffer), FSOPT_NOFOLLOW );
2183 /* If unix_name named a symlink, the above may have succeeded even if the symlink is broken.
2184 Check that with another call without FSOPT_NOFOLLOW. We don't ask for any attributes. */
2185 if (!ret && attrlist_buffer.type == VLNK)
2187 u_int32_t dummy;
2188 attrlist.commonattr = 0;
2189 ret = getattrlist( unix_name, &attrlist, &dummy, sizeof(dummy), 0 );
2191 if (!ret)
2193 union file_directory_info *info = append_entry( buffer, io, length, attrlist_buffer.name, NULL, NULL, class );
2194 if (info)
2196 info->next = 0;
2197 if (io->u.Status != STATUS_BUFFER_OVERFLOW) lseek( fd, 1, SEEK_CUR );
2199 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
2202 else ret = -1;
2204 done:
2205 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2207 TRACE("returning %d\n", ret);
2209 return ret;
2211 #endif
2214 /******************************************************************************
2215 * NtQueryDirectoryFile [NTDLL.@]
2216 * ZwQueryDirectoryFile [NTDLL.@]
2218 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
2219 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
2220 PIO_STATUS_BLOCK io,
2221 PVOID buffer, ULONG length,
2222 FILE_INFORMATION_CLASS info_class,
2223 BOOLEAN single_entry,
2224 PUNICODE_STRING mask,
2225 BOOLEAN restart_scan )
2227 int cwd, fd, needs_close;
2228 NTSTATUS status;
2230 TRACE("(%p %p %p %p %p %p 0x%08x 0x%08x 0x%08x %s 0x%08x\n",
2231 handle, event, apc_routine, apc_context, io, buffer,
2232 length, info_class, single_entry, debugstr_us(mask),
2233 restart_scan);
2235 if (event || apc_routine)
2237 FIXME( "Unsupported yet option\n" );
2238 return STATUS_NOT_IMPLEMENTED;
2240 switch (info_class)
2242 case FileDirectoryInformation:
2243 case FileBothDirectoryInformation:
2244 case FileFullDirectoryInformation:
2245 case FileIdBothDirectoryInformation:
2246 case FileIdFullDirectoryInformation:
2247 if (length < dir_info_size( info_class, 1 )) return STATUS_INFO_LENGTH_MISMATCH;
2248 if (!buffer) return STATUS_ACCESS_VIOLATION;
2249 break;
2250 default:
2251 FIXME( "Unsupported file info class %d\n", info_class );
2252 return STATUS_NOT_IMPLEMENTED;
2255 if ((status = server_get_unix_fd( handle, FILE_LIST_DIRECTORY, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
2256 return status;
2258 io->Information = 0;
2260 RtlRunOnceExecuteOnce( &init_once, init_options, NULL, NULL );
2262 RtlEnterCriticalSection( &dir_section );
2264 cwd = open( ".", O_RDONLY );
2265 if (fchdir( fd ) != -1)
2267 struct stat st;
2268 fstat( fd, &st );
2269 curdir.dev = st.st_dev;
2270 curdir.ino = st.st_ino;
2271 #ifdef VFAT_IOCTL_READDIR_BOTH
2272 if ((read_directory_vfat( fd, io, buffer, length, single_entry,
2273 mask, restart_scan, info_class )) != -1) goto done;
2274 #endif
2275 if (!has_wildcard( mask ))
2277 #ifdef HAVE_GETATTRLIST
2278 if (read_directory_getattrlist( fd, io, buffer, length, single_entry,
2279 mask, restart_scan, info_class ) != -1) goto done;
2280 #endif
2281 if (read_directory_stat( fd, io, buffer, length, single_entry,
2282 mask, restart_scan, info_class ) != -1) goto done;
2284 #ifdef USE_GETDENTS
2285 if ((read_directory_getdents( fd, io, buffer, length, single_entry,
2286 mask, restart_scan, info_class )) != -1) goto done;
2287 #elif defined HAVE_GETDIRENTRIES
2288 if ((read_directory_getdirentries( fd, io, buffer, length, single_entry,
2289 mask, restart_scan, info_class )) != -1) goto done;
2290 #endif
2291 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan, info_class );
2293 done:
2294 status = io->u.Status;
2295 if (cwd == -1 || fchdir( cwd ) == -1) chdir( "/" );
2297 else status = FILE_GetNtStatus();
2299 RtlLeaveCriticalSection( &dir_section );
2301 if (needs_close) close( fd );
2302 if (cwd != -1) close( cwd );
2303 TRACE( "=> %x (%ld)\n", status, io->Information );
2304 return status;
2308 /***********************************************************************
2309 * find_file_in_dir
2311 * Find a file in a directory the hard way, by doing a case-insensitive search.
2312 * The file found is appended to unix_name at pos.
2313 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
2315 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
2316 BOOLEAN check_case, BOOLEAN *is_win_dir )
2318 WCHAR buffer[MAX_DIR_ENTRY_LEN];
2319 UNICODE_STRING str;
2320 BOOLEAN spaces, is_name_8_dot_3;
2321 DIR *dir;
2322 struct dirent *de;
2323 struct stat st;
2324 int ret, used_default;
2326 /* try a shortcut for this directory */
2328 unix_name[pos++] = '/';
2329 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
2330 NULL, &used_default );
2331 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
2332 /* so it cannot match the file we are looking for */
2333 if (ret >= 0 && !used_default)
2335 unix_name[pos + ret] = 0;
2336 if (!stat( unix_name, &st ))
2338 if (is_win_dir) *is_win_dir = is_same_file( &windir, &st );
2339 return STATUS_SUCCESS;
2342 if (check_case) goto not_found; /* we want an exact match */
2344 if (pos > 1) unix_name[pos - 1] = 0;
2345 else unix_name[1] = 0; /* keep the initial slash */
2347 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
2349 str.Buffer = (WCHAR *)name;
2350 str.Length = length * sizeof(WCHAR);
2351 str.MaximumLength = str.Length;
2352 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
2353 #ifndef VFAT_IOCTL_READDIR_BOTH
2354 is_name_8_dot_3 = is_name_8_dot_3 && length >= 8 && name[4] == '~';
2355 #endif
2357 if (!is_name_8_dot_3 && !get_dir_case_sensitivity( unix_name )) goto not_found;
2359 /* now look for it through the directory */
2361 #ifdef VFAT_IOCTL_READDIR_BOTH
2362 if (is_name_8_dot_3)
2364 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
2365 if (fd != -1)
2367 KERNEL_DIRENT *kde;
2369 RtlEnterCriticalSection( &dir_section );
2370 if ((kde = start_vfat_ioctl( fd )))
2372 unix_name[pos - 1] = '/';
2373 while (kde[0].d_reclen)
2375 /* make sure names are null-terminated to work around an x86-64 kernel bug */
2376 size_t len = min(kde[0].d_reclen, sizeof(kde[0].d_name) - 1 );
2377 kde[0].d_name[len] = 0;
2378 len = min(kde[1].d_reclen, sizeof(kde[1].d_name) - 1 );
2379 kde[1].d_name[len] = 0;
2381 if (kde[1].d_name[0])
2383 ret = ntdll_umbstowcs( 0, kde[1].d_name, strlen(kde[1].d_name),
2384 buffer, MAX_DIR_ENTRY_LEN );
2385 if (ret == length && !memicmpW( buffer, name, length))
2387 strcpy( unix_name + pos, kde[1].d_name );
2388 RtlLeaveCriticalSection( &dir_section );
2389 close( fd );
2390 goto success;
2393 ret = ntdll_umbstowcs( 0, kde[0].d_name, strlen(kde[0].d_name),
2394 buffer, MAX_DIR_ENTRY_LEN );
2395 if (ret == length && !memicmpW( buffer, name, length))
2397 strcpy( unix_name + pos,
2398 kde[1].d_name[0] ? kde[1].d_name : kde[0].d_name );
2399 RtlLeaveCriticalSection( &dir_section );
2400 close( fd );
2401 goto success;
2403 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)kde ) == -1)
2405 RtlLeaveCriticalSection( &dir_section );
2406 close( fd );
2407 goto not_found;
2411 RtlLeaveCriticalSection( &dir_section );
2412 close( fd );
2414 /* fall through to normal handling */
2416 #endif /* VFAT_IOCTL_READDIR_BOTH */
2418 if (!(dir = opendir( unix_name )))
2420 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
2421 else return FILE_GetNtStatus();
2423 unix_name[pos - 1] = '/';
2424 str.Buffer = buffer;
2425 str.MaximumLength = sizeof(buffer);
2426 while ((de = readdir( dir )))
2428 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
2429 if (ret == length && !memicmpW( buffer, name, length ))
2431 strcpy( unix_name + pos, de->d_name );
2432 closedir( dir );
2433 goto success;
2436 if (!is_name_8_dot_3) continue;
2438 str.Length = ret * sizeof(WCHAR);
2439 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
2441 WCHAR short_nameW[12];
2442 ret = hash_short_file_name( &str, short_nameW );
2443 if (ret == length && !memicmpW( short_nameW, name, length ))
2445 strcpy( unix_name + pos, de->d_name );
2446 closedir( dir );
2447 goto success;
2451 closedir( dir );
2453 not_found:
2454 unix_name[pos - 1] = 0;
2455 return STATUS_OBJECT_PATH_NOT_FOUND;
2457 success:
2458 if (is_win_dir && !stat( unix_name, &st )) *is_win_dir = is_same_file( &windir, &st );
2459 return STATUS_SUCCESS;
2463 #ifndef _WIN64
2465 static const WCHAR catrootW[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t',0};
2466 static const WCHAR catroot2W[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t','2',0};
2467 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};
2468 static const WCHAR driversetcW[] = {'s','y','s','t','e','m','3','2','\\','d','r','i','v','e','r','s','\\','e','t','c',0};
2469 static const WCHAR logfilesW[] = {'s','y','s','t','e','m','3','2','\\','l','o','g','f','i','l','e','s',0};
2470 static const WCHAR spoolW[] = {'s','y','s','t','e','m','3','2','\\','s','p','o','o','l',0};
2471 static const WCHAR system32W[] = {'s','y','s','t','e','m','3','2',0};
2472 static const WCHAR syswow64W[] = {'s','y','s','w','o','w','6','4',0};
2473 static const WCHAR sysnativeW[] = {'s','y','s','n','a','t','i','v','e',0};
2474 static const WCHAR regeditW[] = {'r','e','g','e','d','i','t','.','e','x','e',0};
2475 static const WCHAR wow_regeditW[] = {'s','y','s','w','o','w','6','4','\\','r','e','g','e','d','i','t','.','e','x','e',0};
2477 static struct
2479 const WCHAR *source;
2480 const WCHAR *dos_target;
2481 const char *unix_target;
2482 } redirects[] =
2484 { catrootW, NULL, NULL },
2485 { catroot2W, NULL, NULL },
2486 { driversstoreW, NULL, NULL },
2487 { driversetcW, NULL, NULL },
2488 { logfilesW, NULL, NULL },
2489 { spoolW, NULL, NULL },
2490 { system32W, syswow64W, NULL },
2491 { sysnativeW, system32W, NULL },
2492 { regeditW, wow_regeditW, NULL }
2495 static unsigned int nb_redirects;
2498 /***********************************************************************
2499 * get_redirect_target
2501 * Find the target unix name for a redirected dir.
2503 static const char *get_redirect_target( const char *windows_dir, const WCHAR *name )
2505 int used_default, len, pos, win_len = strlen( windows_dir );
2506 char *unix_name, *unix_target = NULL;
2507 NTSTATUS status;
2509 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, win_len + MAX_DIR_ENTRY_LEN + 2 )))
2510 return NULL;
2511 memcpy( unix_name, windows_dir, win_len );
2512 pos = win_len;
2514 while (*name)
2516 const WCHAR *end, *next;
2518 for (end = name; *end; end++) if (IS_SEPARATOR(*end)) break;
2519 for (next = end; *next; next++) if (!IS_SEPARATOR(*next)) break;
2521 status = find_file_in_dir( unix_name, pos, name, end - name, FALSE, NULL );
2522 if (status == STATUS_OBJECT_PATH_NOT_FOUND && !*next) /* not finding last element is ok */
2524 len = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2525 MAX_DIR_ENTRY_LEN - (pos - win_len), NULL, &used_default );
2526 if (len > 0 && !used_default)
2528 unix_name[pos] = '/';
2529 pos += len + 1;
2530 unix_name[pos] = 0;
2531 break;
2534 if (status) goto done;
2535 pos += strlen( unix_name + pos );
2536 name = next;
2539 if ((unix_target = RtlAllocateHeap( GetProcessHeap(), 0, pos - win_len )))
2540 memcpy( unix_target, unix_name + win_len + 1, pos - win_len );
2542 done:
2543 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2544 return unix_target;
2548 /***********************************************************************
2549 * init_redirects
2551 static void init_redirects(void)
2553 UNICODE_STRING nt_name;
2554 ANSI_STRING unix_name;
2555 NTSTATUS status;
2556 struct stat st;
2557 unsigned int i;
2559 if (!RtlDosPathNameToNtPathName_U( user_shared_data->NtSystemRoot, &nt_name, NULL, NULL ))
2561 ERR( "can't convert %s\n", debugstr_w(user_shared_data->NtSystemRoot) );
2562 return;
2564 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
2565 RtlFreeUnicodeString( &nt_name );
2566 if (status)
2568 ERR( "cannot open %s (%x)\n", debugstr_w(user_shared_data->NtSystemRoot), status );
2569 return;
2571 if (!stat( unix_name.Buffer, &st ))
2573 windir.dev = st.st_dev;
2574 windir.ino = st.st_ino;
2575 nb_redirects = sizeof(redirects) / sizeof(redirects[0]);
2576 for (i = 0; i < nb_redirects; i++)
2578 if (!redirects[i].dos_target) continue;
2579 redirects[i].unix_target = get_redirect_target( unix_name.Buffer, redirects[i].dos_target );
2580 TRACE( "%s -> %s\n", debugstr_w(redirects[i].source), redirects[i].unix_target );
2583 RtlFreeAnsiString( &unix_name );
2588 /***********************************************************************
2589 * match_redirect
2591 * Check if path matches a redirect name. If yes, return matched length.
2593 static int match_redirect( const WCHAR *path, int len, const WCHAR *redir, BOOLEAN check_case )
2595 int i = 0;
2597 while (i < len && *redir)
2599 if (IS_SEPARATOR(path[i]))
2601 if (*redir++ != '\\') return 0;
2602 while (i < len && IS_SEPARATOR(path[i])) i++;
2603 continue; /* move on to next path component */
2605 else if (check_case)
2607 if (path[i] != *redir) return 0;
2609 else
2611 if (tolowerW(path[i]) != tolowerW(*redir)) return 0;
2613 i++;
2614 redir++;
2616 if (*redir) return 0;
2617 if (i < len && !IS_SEPARATOR(path[i])) return 0;
2618 while (i < len && IS_SEPARATOR(path[i])) i++;
2619 return i;
2623 /***********************************************************************
2624 * get_redirect_path
2626 * Retrieve the Unix path corresponding to a redirected path if any.
2628 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, BOOLEAN check_case )
2630 unsigned int i;
2631 int len;
2633 for (i = 0; i < nb_redirects; i++)
2635 if ((len = match_redirect( name, length, redirects[i].source, check_case )))
2637 if (!redirects[i].unix_target) break;
2638 unix_name[pos++] = '/';
2639 strcpy( unix_name + pos, redirects[i].unix_target );
2640 return len;
2643 return 0;
2646 #else /* _WIN64 */
2648 /* there are no redirects on 64-bit */
2650 static const unsigned int nb_redirects = 0;
2652 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, BOOLEAN check_case )
2654 return 0;
2657 #endif
2659 /***********************************************************************
2660 * DIR_init_windows_dir
2662 void DIR_init_windows_dir( const WCHAR *win, const WCHAR *sys )
2664 /* FIXME: should probably store paths as NT file names */
2666 RtlCreateUnicodeString( &system_dir, sys );
2668 #ifndef _WIN64
2669 if (is_wow64) init_redirects();
2670 #endif
2674 /******************************************************************************
2675 * get_dos_device
2677 * Get the Unix path of a DOS device.
2679 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
2681 const char *config_dir = wine_get_config_dir();
2682 struct stat st;
2683 char *unix_name, *new_name, *dev;
2684 unsigned int i;
2685 int unix_len;
2687 /* make sure the device name is ASCII */
2688 for (i = 0; i < name_len; i++)
2689 if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
2691 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
2693 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2694 return STATUS_NO_MEMORY;
2696 strcpy( unix_name, config_dir );
2697 strcat( unix_name, "/dosdevices/" );
2698 dev = unix_name + strlen(unix_name);
2700 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
2701 dev[i] = 0;
2703 /* special case for drive devices */
2704 if (name_len == 2 && dev[1] == ':')
2706 dev[i++] = ':';
2707 dev[i] = 0;
2710 for (;;)
2712 if (!stat( unix_name, &st ))
2714 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
2715 unix_name_ret->Buffer = unix_name;
2716 unix_name_ret->Length = strlen(unix_name);
2717 unix_name_ret->MaximumLength = unix_len;
2718 return STATUS_SUCCESS;
2720 if (!dev) break;
2722 /* now try some defaults for it */
2723 if (!strcmp( dev, "aux" ))
2725 strcpy( dev, "com1" );
2726 continue;
2728 if (!strcmp( dev, "prn" ))
2730 strcpy( dev, "lpt1" );
2731 continue;
2734 new_name = NULL;
2735 if (dev[1] == ':' && dev[2] == ':') /* drive device */
2737 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
2738 new_name = get_default_drive_device( unix_name );
2740 else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( atoi(dev + 3 ));
2741 else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( atoi(dev + 3 ));
2743 if (!new_name) break;
2745 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2746 unix_name = new_name;
2747 unix_len = strlen(unix_name) + 1;
2748 dev = NULL; /* last try */
2750 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2751 return STATUS_BAD_DEVICE_TYPE;
2755 /* return the length of the DOS namespace prefix if any */
2756 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
2758 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
2759 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
2761 if (name->Length >= sizeof(nt_prefixW) &&
2762 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
2763 return sizeof(nt_prefixW) / sizeof(WCHAR);
2765 if (name->Length >= sizeof(dosdev_prefixW) &&
2766 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
2767 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
2769 return 0;
2773 /******************************************************************************
2774 * find_file_id
2776 * Recursively search directories from the dir queue for a given inode.
2778 static NTSTATUS find_file_id( ANSI_STRING *unix_name, ULONGLONG file_id, dev_t dev )
2780 unsigned int pos;
2781 DIR *dir;
2782 struct dirent *de;
2783 NTSTATUS status;
2784 struct stat st;
2786 while (!(status = next_dir_in_queue( unix_name->Buffer )))
2788 if (!(dir = opendir( unix_name->Buffer ))) continue;
2789 TRACE( "searching %s for %s\n", unix_name->Buffer, wine_dbgstr_longlong(file_id) );
2790 pos = strlen( unix_name->Buffer );
2791 if (pos + MAX_DIR_ENTRY_LEN >= unix_name->MaximumLength/sizeof(WCHAR))
2793 char *new = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name->Buffer,
2794 unix_name->MaximumLength * 2 );
2795 if (!new)
2797 closedir( dir );
2798 return STATUS_NO_MEMORY;
2800 unix_name->MaximumLength *= 2;
2801 unix_name->Buffer = new;
2803 unix_name->Buffer[pos++] = '/';
2804 while ((de = readdir( dir )))
2806 if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
2807 strcpy( unix_name->Buffer + pos, de->d_name );
2808 if (lstat( unix_name->Buffer, &st ) == -1) continue;
2809 if (st.st_dev != dev) continue;
2810 if (st.st_ino == file_id)
2812 closedir( dir );
2813 return STATUS_SUCCESS;
2815 if (!S_ISDIR( st.st_mode )) continue;
2816 if ((status = add_dir_to_queue( unix_name->Buffer )) != STATUS_SUCCESS)
2818 closedir( dir );
2819 return status;
2822 closedir( dir );
2824 return status;
2828 /******************************************************************************
2829 * file_id_to_unix_file_name
2831 * Lookup a file from its file id instead of its name.
2833 NTSTATUS file_id_to_unix_file_name( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name )
2835 enum server_fd_type type;
2836 int old_cwd, root_fd, needs_close;
2837 NTSTATUS status;
2838 ULONGLONG file_id;
2839 struct stat st, root_st;
2841 if (attr->ObjectName->Length != sizeof(ULONGLONG)) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2842 if (!attr->RootDirectory) return STATUS_INVALID_PARAMETER;
2843 memcpy( &file_id, attr->ObjectName->Buffer, sizeof(file_id) );
2845 unix_name->MaximumLength = 2 * MAX_DIR_ENTRY_LEN + 4;
2846 if (!(unix_name->Buffer = RtlAllocateHeap( GetProcessHeap(), 0, unix_name->MaximumLength )))
2847 return STATUS_NO_MEMORY;
2848 strcpy( unix_name->Buffer, "." );
2850 if ((status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
2851 goto done;
2853 if (type != FD_TYPE_DIR)
2855 status = STATUS_OBJECT_TYPE_MISMATCH;
2856 goto done;
2859 fstat( root_fd, &root_st );
2860 if (root_st.st_ino == file_id) /* shortcut for "." */
2862 status = STATUS_SUCCESS;
2863 goto done;
2866 RtlEnterCriticalSection( &dir_section );
2867 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2869 /* shortcut for ".." */
2870 if (!stat( "..", &st ) && st.st_dev == root_st.st_dev && st.st_ino == file_id)
2872 strcpy( unix_name->Buffer, ".." );
2873 status = STATUS_SUCCESS;
2875 else
2877 status = add_dir_to_queue( "." );
2878 if (!status)
2879 status = find_file_id( unix_name, file_id, root_st.st_dev );
2880 if (!status) /* get rid of "./" prefix */
2881 memmove( unix_name->Buffer, unix_name->Buffer + 2, strlen(unix_name->Buffer) - 1 );
2882 flush_dir_queue();
2884 if (fchdir( old_cwd ) == -1) chdir( "/" );
2886 else status = FILE_GetNtStatus();
2887 RtlLeaveCriticalSection( &dir_section );
2888 if (old_cwd != -1) close( old_cwd );
2890 done:
2891 if (status == STATUS_SUCCESS)
2893 TRACE( "%s -> %s\n", wine_dbgstr_longlong(file_id), debugstr_a(unix_name->Buffer) );
2894 unix_name->Length = strlen( unix_name->Buffer );
2896 else
2898 TRACE( "%s not found in dir %p\n", wine_dbgstr_longlong(file_id), attr->RootDirectory );
2899 RtlFreeHeap( GetProcessHeap(), 0, unix_name->Buffer );
2901 if (needs_close) close( root_fd );
2902 return status;
2906 /******************************************************************************
2907 * lookup_unix_name
2909 * Helper for nt_to_unix_file_name
2911 static NTSTATUS lookup_unix_name( const WCHAR *name, int name_len, char **buffer, int unix_len, int pos,
2912 UINT disposition, BOOLEAN check_case )
2914 NTSTATUS status;
2915 int ret, used_default, len;
2916 struct stat st;
2917 char *unix_name = *buffer;
2918 const BOOL redirect = nb_redirects && ntdll_get_thread_data()->wow64_redir;
2920 /* try a shortcut first */
2922 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
2923 NULL, &used_default );
2925 while (name_len && IS_SEPARATOR(*name))
2927 name++;
2928 name_len--;
2931 if (ret >= 0 && !used_default) /* if we used the default char the name didn't convert properly */
2933 char *p;
2934 unix_name[pos + ret] = 0;
2935 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
2936 if (!redirect || (!strstr( unix_name, "/windows/") && strncmp( unix_name, "windows/", 8 )))
2938 if (!stat( unix_name, &st ))
2940 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
2941 if (disposition == FILE_CREATE)
2942 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
2943 return STATUS_SUCCESS;
2948 if (!name_len) /* empty name -> drive root doesn't exist */
2949 return STATUS_OBJECT_PATH_NOT_FOUND;
2950 if (check_case && !redirect && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
2951 return STATUS_OBJECT_NAME_NOT_FOUND;
2953 /* now do it component by component */
2955 while (name_len)
2957 const WCHAR *end, *next;
2958 BOOLEAN is_win_dir = FALSE;
2960 end = name;
2961 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
2962 next = end;
2963 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
2964 name_len -= next - name;
2966 /* grow the buffer if needed */
2968 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
2970 char *new_name;
2971 unix_len += 2 * MAX_DIR_ENTRY_LEN;
2972 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
2973 return STATUS_NO_MEMORY;
2974 unix_name = *buffer = new_name;
2977 status = find_file_in_dir( unix_name, pos, name, end - name,
2978 check_case, redirect ? &is_win_dir : NULL );
2980 /* if this is the last element, not finding it is not necessarily fatal */
2981 if (!name_len)
2983 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
2985 status = STATUS_OBJECT_NAME_NOT_FOUND;
2986 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
2988 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2989 MAX_DIR_ENTRY_LEN, NULL, &used_default );
2990 if (ret > 0 && !used_default)
2992 unix_name[pos] = '/';
2993 unix_name[pos + 1 + ret] = 0;
2994 status = STATUS_NO_SUCH_FILE;
2995 break;
2999 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
3001 status = STATUS_OBJECT_NAME_COLLISION;
3005 if (status != STATUS_SUCCESS) break;
3007 pos += strlen( unix_name + pos );
3008 name = next;
3010 if (is_win_dir && (len = get_redirect_path( unix_name, pos, name, name_len, check_case )))
3012 name += len;
3013 name_len -= len;
3014 pos += strlen( unix_name + pos );
3015 TRACE( "redirecting -> %s + %s\n", debugstr_a(unix_name), debugstr_w(name) );
3019 return status;
3023 /******************************************************************************
3024 * nt_to_unix_file_name_attr
3026 NTSTATUS nt_to_unix_file_name_attr( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name_ret,
3027 UINT disposition )
3029 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
3030 enum server_fd_type type;
3031 int old_cwd, root_fd, needs_close;
3032 const WCHAR *name, *p;
3033 char *unix_name;
3034 int name_len, unix_len;
3035 NTSTATUS status;
3036 BOOLEAN check_case = !(attr->Attributes & OBJ_CASE_INSENSITIVE);
3038 if (!attr->RootDirectory) /* without root dir fall back to normal lookup */
3039 return wine_nt_to_unix_file_name( attr->ObjectName, unix_name_ret, disposition, check_case );
3041 name = attr->ObjectName->Buffer;
3042 name_len = attr->ObjectName->Length / sizeof(WCHAR);
3044 if (name_len && IS_SEPARATOR(name[0])) return STATUS_INVALID_PARAMETER;
3046 /* check for invalid characters */
3047 for (p = name; p < name + name_len; p++)
3048 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
3050 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
3051 unix_len += MAX_DIR_ENTRY_LEN + 3;
3052 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
3053 return STATUS_NO_MEMORY;
3054 unix_name[0] = '.';
3056 if (!(status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
3058 if (type != FD_TYPE_DIR)
3060 if (needs_close) close( root_fd );
3061 status = STATUS_BAD_DEVICE_TYPE;
3063 else
3065 RtlEnterCriticalSection( &dir_section );
3066 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
3068 status = lookup_unix_name( name, name_len, &unix_name, unix_len, 1,
3069 disposition, check_case );
3070 if (fchdir( old_cwd ) == -1) chdir( "/" );
3072 else status = FILE_GetNtStatus();
3073 RtlLeaveCriticalSection( &dir_section );
3074 if (old_cwd != -1) close( old_cwd );
3075 if (needs_close) close( root_fd );
3078 else if (status == STATUS_OBJECT_TYPE_MISMATCH) status = STATUS_BAD_DEVICE_TYPE;
3080 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
3082 TRACE( "%s -> %s\n", debugstr_us(attr->ObjectName), debugstr_a(unix_name) );
3083 unix_name_ret->Buffer = unix_name;
3084 unix_name_ret->Length = strlen(unix_name);
3085 unix_name_ret->MaximumLength = unix_len;
3087 else
3089 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
3090 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3092 return status;
3096 /******************************************************************************
3097 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
3099 * Convert a file name from NT namespace to Unix namespace.
3101 * If disposition is not FILE_OPEN or FILE_OVERWRITE, the last path
3102 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
3103 * returned, but the unix name is still filled in properly.
3105 NTSTATUS CDECL wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
3106 UINT disposition, BOOLEAN check_case )
3108 static const WCHAR unixW[] = {'u','n','i','x'};
3109 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
3111 NTSTATUS status = STATUS_SUCCESS;
3112 const char *config_dir = wine_get_config_dir();
3113 const WCHAR *name, *p;
3114 struct stat st;
3115 char *unix_name;
3116 int pos, ret, name_len, unix_len, prefix_len, used_default;
3117 WCHAR prefix[MAX_DIR_ENTRY_LEN];
3118 BOOLEAN is_unix = FALSE;
3120 name = nameW->Buffer;
3121 name_len = nameW->Length / sizeof(WCHAR);
3123 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
3125 if (!(pos = get_dos_prefix_len( nameW )))
3126 return STATUS_BAD_DEVICE_TYPE; /* no DOS prefix, assume NT native name */
3128 name += pos;
3129 name_len -= pos;
3131 if (!name_len) return STATUS_OBJECT_NAME_INVALID;
3133 /* check for sub-directory */
3134 for (pos = 0; pos < name_len; pos++)
3136 if (IS_SEPARATOR(name[pos])) break;
3137 if (name[pos] < 32 || strchrW( invalid_charsW, name[pos] ))
3138 return STATUS_OBJECT_NAME_INVALID;
3140 if (pos > MAX_DIR_ENTRY_LEN)
3141 return STATUS_OBJECT_NAME_INVALID;
3143 if (pos == name_len) /* no subdir, plain DOS device */
3144 return get_dos_device( name, name_len, unix_name_ret );
3146 for (prefix_len = 0; prefix_len < pos; prefix_len++)
3147 prefix[prefix_len] = tolowerW(name[prefix_len]);
3149 name += prefix_len;
3150 name_len -= prefix_len;
3152 /* check for invalid characters (all chars except 0 are valid for unix) */
3153 is_unix = (prefix_len == 4 && !memcmp( prefix, unixW, sizeof(unixW) ));
3154 if (is_unix)
3156 for (p = name; p < name + name_len; p++)
3157 if (!*p) return STATUS_OBJECT_NAME_INVALID;
3158 check_case = TRUE;
3160 else
3162 for (p = name; p < name + name_len; p++)
3163 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
3166 unix_len = ntdll_wcstoumbs( 0, prefix, prefix_len, NULL, 0, NULL, NULL );
3167 unix_len += ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
3168 unix_len += MAX_DIR_ENTRY_LEN + 3;
3169 unix_len += strlen(config_dir) + sizeof("/dosdevices/");
3170 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
3171 return STATUS_NO_MEMORY;
3172 strcpy( unix_name, config_dir );
3173 strcat( unix_name, "/dosdevices/" );
3174 pos = strlen(unix_name);
3176 ret = ntdll_wcstoumbs( 0, prefix, prefix_len, unix_name + pos, unix_len - pos - 1,
3177 NULL, &used_default );
3178 if (!ret || used_default)
3180 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3181 return STATUS_OBJECT_NAME_INVALID;
3183 pos += ret;
3185 /* check if prefix exists (except for DOS drives to avoid extra stat calls) */
3187 if (prefix_len != 2 || prefix[1] != ':')
3189 unix_name[pos] = 0;
3190 if (lstat( unix_name, &st ) == -1 && errno == ENOENT)
3192 if (!is_unix)
3194 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3195 return STATUS_BAD_DEVICE_TYPE;
3197 pos = 0; /* fall back to unix root */
3201 status = lookup_unix_name( name, name_len, &unix_name, unix_len, pos, disposition, check_case );
3202 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
3204 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
3205 unix_name_ret->Buffer = unix_name;
3206 unix_name_ret->Length = strlen(unix_name);
3207 unix_name_ret->MaximumLength = unix_len;
3209 else
3211 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
3212 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3214 return status;
3218 /******************************************************************
3219 * RtlWow64EnableFsRedirection (NTDLL.@)
3221 NTSTATUS WINAPI RtlWow64EnableFsRedirection( BOOLEAN enable )
3223 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
3224 ntdll_get_thread_data()->wow64_redir = enable;
3225 return STATUS_SUCCESS;
3229 /******************************************************************
3230 * RtlWow64EnableFsRedirectionEx (NTDLL.@)
3232 NTSTATUS WINAPI RtlWow64EnableFsRedirectionEx( ULONG disable, ULONG *old_value )
3234 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
3235 if (((ULONG_PTR)old_value >> 16) == 0) return STATUS_ACCESS_VIOLATION;
3237 *old_value = !ntdll_get_thread_data()->wow64_redir;
3238 ntdll_get_thread_data()->wow64_redir = !disable;
3239 return STATUS_SUCCESS;
3243 /******************************************************************
3244 * RtlDoesFileExists_U (NTDLL.@)
3246 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
3248 UNICODE_STRING nt_name;
3249 FILE_BASIC_INFORMATION basic_info;
3250 OBJECT_ATTRIBUTES attr;
3251 BOOLEAN ret;
3253 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
3255 attr.Length = sizeof(attr);
3256 attr.RootDirectory = 0;
3257 attr.ObjectName = &nt_name;
3258 attr.Attributes = OBJ_CASE_INSENSITIVE;
3259 attr.SecurityDescriptor = NULL;
3260 attr.SecurityQualityOfService = NULL;
3262 ret = NtQueryAttributesFile(&attr, &basic_info) == STATUS_SUCCESS;
3264 RtlFreeUnicodeString( &nt_name );
3265 return ret;
3269 /***********************************************************************
3270 * DIR_unmount_device
3272 * Unmount the specified device.
3274 NTSTATUS DIR_unmount_device( HANDLE handle )
3276 NTSTATUS status;
3277 int unix_fd, needs_close;
3279 if (!(status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )))
3281 struct stat st;
3282 char *mount_point = NULL;
3284 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
3285 status = STATUS_INVALID_PARAMETER;
3286 else
3288 if ((mount_point = get_device_mount_point( st.st_rdev )))
3290 #ifdef __APPLE__
3291 static const char umount[] = "diskutil unmount >/dev/null 2>&1 ";
3292 #else
3293 static const char umount[] = "umount >/dev/null 2>&1 ";
3294 #endif
3295 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
3296 if (cmd)
3298 strcpy( cmd, umount );
3299 strcat( cmd, mount_point );
3300 system( cmd );
3301 RtlFreeHeap( GetProcessHeap(), 0, cmd );
3302 #ifdef linux
3303 /* umount will fail to release the loop device since we still have
3304 a handle to it, so we release it here */
3305 if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
3306 #endif
3308 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
3311 if (needs_close) close( unix_fd );
3313 return status;
3317 /******************************************************************************
3318 * DIR_get_unix_cwd
3320 * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
3321 * Returned value must be freed by caller.
3323 NTSTATUS DIR_get_unix_cwd( char **cwd )
3325 int old_cwd, unix_fd, needs_close;
3326 CURDIR *curdir;
3327 HANDLE handle;
3328 NTSTATUS status;
3330 RtlAcquirePebLock();
3332 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
3333 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
3334 else
3335 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
3337 if (!(handle = curdir->Handle))
3339 UNICODE_STRING dirW;
3340 OBJECT_ATTRIBUTES attr;
3341 IO_STATUS_BLOCK io;
3343 if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
3345 status = STATUS_OBJECT_NAME_INVALID;
3346 goto done;
3348 attr.Length = sizeof(attr);
3349 attr.RootDirectory = 0;
3350 attr.Attributes = OBJ_CASE_INSENSITIVE;
3351 attr.ObjectName = &dirW;
3352 attr.SecurityDescriptor = NULL;
3353 attr.SecurityQualityOfService = NULL;
3355 status = NtOpenFile( &handle, SYNCHRONIZE, &attr, &io, 0,
3356 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
3357 RtlFreeUnicodeString( &dirW );
3358 if (status != STATUS_SUCCESS) goto done;
3361 if ((status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )) == STATUS_SUCCESS)
3363 RtlEnterCriticalSection( &dir_section );
3365 if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
3367 unsigned int size = 512;
3369 for (;;)
3371 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
3373 status = STATUS_NO_MEMORY;
3374 break;
3376 if (getcwd( *cwd, size )) break;
3377 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
3378 if (errno != ERANGE)
3380 status = STATUS_OBJECT_PATH_INVALID;
3381 break;
3383 size *= 2;
3385 if (fchdir( old_cwd ) == -1) chdir( "/" );
3387 else status = FILE_GetNtStatus();
3389 RtlLeaveCriticalSection( &dir_section );
3390 if (old_cwd != -1) close( old_cwd );
3391 if (needs_close) close( unix_fd );
3393 if (!curdir->Handle) NtClose( handle );
3395 done:
3396 RtlReleasePebLock();
3397 return status;