vbscript: Implemented Tan.
[wine.git] / dlls / ntdll / directory.c
bloba2796b204e7a457f832b248d02bb8a03e53cb7dd
1 /*
2 * NTDLL directory functions
4 * Copyright 1993 Erik Bos
5 * Copyright 2003 Eric Pouech
6 * Copyright 1996, 2004 Alexandre Julliard
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include "config.h"
24 #include "wine/port.h"
26 #include <assert.h>
27 #include <sys/types.h>
28 #ifdef HAVE_DIRENT_H
29 # include <dirent.h>
30 #endif
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <stdarg.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <limits.h>
38 #ifdef HAVE_MNTENT_H
39 #include <mntent.h>
40 #endif
41 #ifdef HAVE_SYS_STAT_H
42 # include <sys/stat.h>
43 #endif
44 #ifdef HAVE_SYS_SYSCALL_H
45 # include <sys/syscall.h>
46 #endif
47 #ifdef HAVE_SYS_ATTR_H
48 #include <sys/attr.h>
49 #endif
50 #ifdef HAVE_SYS_IOCTL_H
51 #include <sys/ioctl.h>
52 #endif
53 #ifdef HAVE_LINUX_IOCTL_H
54 #include <linux/ioctl.h>
55 #endif
56 #ifdef HAVE_LINUX_MAJOR_H
57 # include <linux/major.h>
58 #endif
59 #ifdef HAVE_SYS_PARAM_H
60 #include <sys/param.h>
61 #endif
62 #ifdef HAVE_SYS_MOUNT_H
63 #include <sys/mount.h>
64 #endif
65 #ifdef HAVE_SYS_STATFS_H
66 #include <sys/statfs.h>
67 #endif
68 #include <time.h>
69 #ifdef HAVE_UNISTD_H
70 # include <unistd.h>
71 #endif
73 #define NONAMELESSUNION
74 #define NONAMELESSSTRUCT
75 #include "ntstatus.h"
76 #define WIN32_NO_STATUS
77 #include "windef.h"
78 #include "winnt.h"
79 #include "winternl.h"
80 #include "ddk/wdm.h"
81 #include "ntdll_misc.h"
82 #include "wine/unicode.h"
83 #include "wine/server.h"
84 #include "wine/list.h"
85 #include "wine/library.h"
86 #include "wine/debug.h"
88 WINE_DEFAULT_DEBUG_CHANNEL(file);
90 /* just in case... */
91 #undef VFAT_IOCTL_READDIR_BOTH
92 #undef USE_GETDENTS
94 #ifdef linux
96 /* We want the real kernel dirent structure, not the libc one */
97 typedef struct
99 long d_ino;
100 long d_off;
101 unsigned short d_reclen;
102 char d_name[256];
103 } KERNEL_DIRENT;
105 /* Define the VFAT ioctl to get both short and long file names */
106 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
108 #ifndef O_DIRECTORY
109 # define O_DIRECTORY 0200000 /* must be directory */
110 #endif
112 #ifdef __NR_getdents64
113 typedef struct
115 ULONG64 d_ino;
116 LONG64 d_off;
117 unsigned short d_reclen;
118 unsigned char d_type;
119 char d_name[256];
120 } KERNEL_DIRENT64;
122 static inline int getdents64( int fd, char *de, unsigned int size )
124 return syscall( __NR_getdents64, fd, de, size );
126 #define USE_GETDENTS
127 #endif
129 #endif /* linux */
131 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
132 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
134 #define INVALID_NT_CHARS '*','?','<','>','|','"'
135 #define INVALID_DOS_CHARS INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
137 #define MAX_DIR_ENTRY_LEN 255 /* max length of a directory entry in chars */
139 #define MAX_IGNORED_FILES 4
141 struct file_identity
143 dev_t dev;
144 ino_t ino;
147 static struct file_identity ignored_files[MAX_IGNORED_FILES];
148 static unsigned int ignored_files_count;
150 union file_directory_info
152 ULONG next;
153 FILE_DIRECTORY_INFORMATION dir;
154 FILE_BOTH_DIRECTORY_INFORMATION both;
155 FILE_FULL_DIRECTORY_INFORMATION full;
156 FILE_ID_BOTH_DIRECTORY_INFORMATION id_both;
157 FILE_ID_FULL_DIRECTORY_INFORMATION id_full;
160 static BOOL show_dot_files;
161 static RTL_RUN_ONCE init_once = RTL_RUN_ONCE_INIT;
163 /* at some point we may want to allow Winelib apps to set this */
164 static const BOOL is_case_sensitive = FALSE;
166 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
168 static struct file_identity curdir;
169 static struct file_identity windir;
171 static RTL_CRITICAL_SECTION dir_section;
172 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
174 0, 0, &dir_section,
175 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
176 0, 0, { (DWORD_PTR)(__FILE__ ": dir_section") }
178 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
181 /* check if a given Unicode char is OK in a DOS short name */
182 static inline BOOL is_invalid_dos_char( WCHAR ch )
184 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
185 if (ch > 0x7f) return TRUE;
186 return strchrW( invalid_chars, ch ) != NULL;
189 /* check if the device can be a mounted volume */
190 static inline BOOL is_valid_mounted_device( const struct stat *st )
192 #if defined(linux) || defined(__sun__)
193 return S_ISBLK( st->st_mode );
194 #else
195 /* disks are char devices on *BSD */
196 return S_ISCHR( st->st_mode );
197 #endif
200 static inline void ignore_file( const char *name )
202 struct stat st;
203 assert( ignored_files_count < MAX_IGNORED_FILES );
204 if (!stat( name, &st ))
206 ignored_files[ignored_files_count].dev = st.st_dev;
207 ignored_files[ignored_files_count].ino = st.st_ino;
208 ignored_files_count++;
212 static inline BOOL is_same_file( const struct file_identity *file, const struct stat *st )
214 return st->st_dev == file->dev && st->st_ino == file->ino;
217 static inline BOOL is_ignored_file( const struct stat *st )
219 unsigned int i;
221 for (i = 0; i < ignored_files_count; i++)
222 if (is_same_file( &ignored_files[i], st )) return TRUE;
223 return FALSE;
226 static inline unsigned int dir_info_size( FILE_INFORMATION_CLASS class, unsigned int len )
228 switch (class)
230 case FileDirectoryInformation:
231 return (FIELD_OFFSET( FILE_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
232 case FileBothDirectoryInformation:
233 return (FIELD_OFFSET( FILE_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
234 case FileFullDirectoryInformation:
235 return (FIELD_OFFSET( FILE_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
236 case FileIdBothDirectoryInformation:
237 return (FIELD_OFFSET( FILE_ID_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
238 case FileIdFullDirectoryInformation:
239 return (FIELD_OFFSET( FILE_ID_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
240 default:
241 assert(0);
242 return 0;
246 static inline unsigned int max_dir_info_size( FILE_INFORMATION_CLASS class )
248 return dir_info_size( class, MAX_DIR_ENTRY_LEN );
251 static inline BOOL has_wildcard( const UNICODE_STRING *mask )
253 return (!mask ||
254 memchrW( mask->Buffer, '*', mask->Length / sizeof(WCHAR) ) ||
255 memchrW( mask->Buffer, '?', mask->Length / sizeof(WCHAR) ));
259 /* support for a directory queue for filesystem searches */
261 struct dir_name
263 struct list entry;
264 char name[1];
267 static struct list dir_queue = LIST_INIT( dir_queue );
269 static NTSTATUS add_dir_to_queue( const char *name )
271 int len = strlen( name ) + 1;
272 struct dir_name *dir = RtlAllocateHeap( GetProcessHeap(), 0,
273 FIELD_OFFSET( struct dir_name, name[len] ));
274 if (!dir) return STATUS_NO_MEMORY;
275 strcpy( dir->name, name );
276 list_add_tail( &dir_queue, &dir->entry );
277 return STATUS_SUCCESS;
280 static NTSTATUS next_dir_in_queue( char *name )
282 struct list *head = list_head( &dir_queue );
283 if (head)
285 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
286 strcpy( name, dir->name );
287 list_remove( &dir->entry );
288 RtlFreeHeap( GetProcessHeap(), 0, dir );
289 return STATUS_SUCCESS;
291 return STATUS_OBJECT_NAME_NOT_FOUND;
294 static void flush_dir_queue(void)
296 struct list *head;
298 while ((head = list_head( &dir_queue )))
300 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
301 list_remove( &dir->entry );
302 RtlFreeHeap( GetProcessHeap(), 0, dir );
307 /***********************************************************************
308 * get_default_com_device
310 * Return the default device to use for serial ports.
312 static char *get_default_com_device( int num )
314 char *ret = NULL;
316 if (!num || num > 9) return ret;
317 #ifdef linux
318 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
319 if (ret)
321 strcpy( ret, "/dev/ttyS0" );
322 ret[strlen(ret) - 1] = '0' + num - 1;
324 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
325 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuau0") );
326 if (ret)
328 strcpy( ret, "/dev/cuau0" );
329 ret[strlen(ret) - 1] = '0' + num - 1;
331 #elif defined(__DragonFly__)
332 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuaa0") );
333 if (ret)
335 strcpy( ret, "/dev/cuaa0" );
336 ret[strlen(ret) - 1] = '0' + num - 1;
338 #else
339 FIXME( "no known default for device com%d\n", num );
340 #endif
341 return ret;
345 /***********************************************************************
346 * get_default_lpt_device
348 * Return the default device to use for parallel ports.
350 static char *get_default_lpt_device( int num )
352 char *ret = NULL;
354 if (!num || num > 9) return ret;
355 #ifdef linux
356 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
357 if (ret)
359 strcpy( ret, "/dev/lp0" );
360 ret[strlen(ret) - 1] = '0' + num - 1;
362 #else
363 FIXME( "no known default for device lpt%d\n", num );
364 #endif
365 return ret;
368 #ifdef __ANDROID__
370 static char *unescape_field( char *str )
372 char *in, *out;
374 for (in = out = str; *in; in++, out++)
376 *out = *in;
377 if (in[0] == '\\')
379 if (in[1] == '\\')
381 out[0] = '\\';
382 in++;
384 else if (in[1] == '0' && in[2] == '4' && in[3] == '0')
386 out[0] = ' ';
387 in += 3;
389 else if (in[1] == '0' && in[2] == '1' && in[3] == '1')
391 out[0] = '\t';
392 in += 3;
394 else if (in[1] == '0' && in[2] == '1' && in[3] == '2')
396 out[0] = '\n';
397 in += 3;
399 else if (in[1] == '1' && in[2] == '3' && in[3] == '4')
401 out[0] = '\\';
402 in += 3;
406 *out = '\0';
408 return str;
411 static inline char *get_field( char **str )
413 char *ret;
415 ret = strsep( str, " \t" );
416 if (*str) *str += strspn( *str, " \t" );
418 return ret;
420 /************************************************************************
421 * getmntent_replacement
423 * getmntent replacement for Android.
425 * NB returned static buffer is not thread safe; protect with dir_section.
427 static struct mntent *getmntent_replacement( FILE *f )
429 static struct mntent entry;
430 static char buf[4096];
431 char *p, *start;
435 if (!fgets( buf, sizeof(buf), f )) return NULL;
436 p = strchr( buf, '\n' );
437 if (p) *p = '\0';
438 else /* Partially unread line, move file ptr to end */
440 char tmp[1024];
441 while (fgets( tmp, sizeof(tmp), f ))
442 if (strchr( tmp, '\n' )) break;
444 start = buf + strspn( buf, " \t" );
445 } while (start[0] == '\0' || start[0] == '#');
447 p = get_field( &start );
448 entry.mnt_fsname = p ? unescape_field( p ) : (char *)"";
450 p = get_field( &start );
451 entry.mnt_dir = p ? unescape_field( p ) : (char *)"";
453 p = get_field( &start );
454 entry.mnt_type = p ? unescape_field( p ) : (char *)"";
456 p = get_field( &start );
457 entry.mnt_opts = p ? unescape_field( p ) : (char *)"";
459 p = get_field( &start );
460 entry.mnt_freq = p ? atoi(p) : 0;
462 p = get_field( &start );
463 entry.mnt_passno = p ? atoi(p) : 0;
465 return &entry;
467 #define getmntent getmntent_replacement
468 #endif
470 /***********************************************************************
471 * DIR_get_drives_info
473 * Retrieve device/inode number for all the drives. Helper for find_drive_root.
475 unsigned int DIR_get_drives_info( struct drive_info info[MAX_DOS_DRIVES] )
477 static struct drive_info cache[MAX_DOS_DRIVES];
478 static time_t last_update;
479 static unsigned int nb_drives;
480 unsigned int ret;
481 time_t now = time(NULL);
483 RtlEnterCriticalSection( &dir_section );
484 if (now != last_update)
486 const char *config_dir = wine_get_config_dir();
487 char *buffer, *p;
488 struct stat st;
489 unsigned int i;
491 if ((buffer = RtlAllocateHeap( GetProcessHeap(), 0,
492 strlen(config_dir) + sizeof("/dosdevices/a:") )))
494 strcpy( buffer, config_dir );
495 strcat( buffer, "/dosdevices/a:" );
496 p = buffer + strlen(buffer) - 2;
498 for (i = nb_drives = 0; i < MAX_DOS_DRIVES; i++)
500 *p = 'a' + i;
501 if (!stat( buffer, &st ))
503 cache[i].dev = st.st_dev;
504 cache[i].ino = st.st_ino;
505 nb_drives++;
507 else
509 cache[i].dev = 0;
510 cache[i].ino = 0;
513 RtlFreeHeap( GetProcessHeap(), 0, buffer );
515 last_update = now;
517 memcpy( info, cache, sizeof(cache) );
518 ret = nb_drives;
519 RtlLeaveCriticalSection( &dir_section );
520 return ret;
524 /***********************************************************************
525 * parse_mount_entries
527 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
530 #ifdef sun
531 #include <sys/vfstab.h>
532 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
534 struct vfstab entry;
535 struct stat st;
536 char *device;
538 while (! getvfsent( f, &entry ))
540 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
541 if (!strcmp( entry.vfs_fstype, "nfs" ) ||
542 !strcmp( entry.vfs_fstype, "smbfs" ) ||
543 !strcmp( entry.vfs_fstype, "ncpfs" )) continue;
545 if (stat( entry.vfs_mountp, &st ) == -1) continue;
546 if (st.st_dev != dev || st.st_ino != ino) continue;
547 if (!strcmp( entry.vfs_fstype, "fd" ))
549 if ((device = strstr( entry.vfs_mntopts, "dev=" )))
551 char *p = strchr( device + 4, ',' );
552 if (p) *p = 0;
553 return device + 4;
556 else
557 return entry.vfs_special;
559 return NULL;
561 #endif
563 #ifdef linux
564 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
566 struct mntent *entry;
567 struct stat st;
568 char *device;
570 while ((entry = getmntent( f )))
572 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
573 if (!strcmp( entry->mnt_type, "nfs" ) ||
574 !strcmp( entry->mnt_type, "smbfs" ) ||
575 !strcmp( entry->mnt_type, "ncpfs" )) continue;
577 if (stat( entry->mnt_dir, &st ) == -1) continue;
578 if (st.st_dev != dev || st.st_ino != ino) continue;
579 if (!strcmp( entry->mnt_type, "supermount" ))
581 if ((device = strstr( entry->mnt_opts, "dev=" )))
583 char *p = strchr( device + 4, ',' );
584 if (p) *p = 0;
585 return device + 4;
588 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
590 /* if device is a regular file check for a loop mount */
591 if ((device = strstr( entry->mnt_opts, "loop=" )))
593 char *p = strchr( device + 5, ',' );
594 if (p) *p = 0;
595 return device + 5;
598 else
599 return entry->mnt_fsname;
601 return NULL;
603 #endif
605 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
606 #include <fstab.h>
607 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
609 struct fstab *entry;
610 struct stat st;
612 while ((entry = getfsent()))
614 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
615 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
616 !strcmp( entry->fs_vfstype, "smbfs" ) ||
617 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
619 if (stat( entry->fs_file, &st ) == -1) continue;
620 if (st.st_dev != dev || st.st_ino != ino) continue;
621 return entry->fs_spec;
623 return NULL;
625 #endif
627 #ifdef sun
628 #include <sys/mnttab.h>
629 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
631 struct mnttab entry;
632 struct stat st;
633 char *device;
636 while (( ! getmntent( f, &entry) ))
638 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
639 if (!strcmp( entry.mnt_fstype, "nfs" ) ||
640 !strcmp( entry.mnt_fstype, "smbfs" ) ||
641 !strcmp( entry.mnt_fstype, "ncpfs" )) continue;
643 if (stat( entry.mnt_mountp, &st ) == -1) continue;
644 if (st.st_dev != dev || st.st_ino != ino) continue;
645 if (!strcmp( entry.mnt_fstype, "fd" ))
647 if ((device = strstr( entry.mnt_mntopts, "dev=" )))
649 char *p = strchr( device + 4, ',' );
650 if (p) *p = 0;
651 return device + 4;
654 else
655 return entry.mnt_special;
657 return NULL;
659 #endif
661 /***********************************************************************
662 * get_default_drive_device
664 * Return the default device to use for a given drive mount point.
666 static char *get_default_drive_device( const char *root )
668 char *ret = NULL;
670 #ifdef linux
671 FILE *f;
672 char *device = NULL;
673 int fd, res = -1;
674 struct stat st;
676 /* try to open it first to force it to get mounted */
677 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
679 res = fstat( fd, &st );
680 close( fd );
682 /* now try normal stat just in case */
683 if (res == -1) res = stat( root, &st );
684 if (res == -1) return NULL;
686 RtlEnterCriticalSection( &dir_section );
688 #ifdef __ANDROID__
689 if ((f = fopen( "/proc/mounts", "r" )))
691 device = parse_mount_entries( f, st.st_dev, st.st_ino );
692 fclose( f );
694 #else
695 if ((f = fopen( "/etc/mtab", "r" )))
697 device = parse_mount_entries( f, st.st_dev, st.st_ino );
698 fclose( f );
700 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
701 if (!device && (f = fopen( "/etc/fstab", "r" )))
703 device = parse_mount_entries( f, st.st_dev, st.st_ino );
704 fclose( f );
706 #endif
707 if (device)
709 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
710 if (ret) strcpy( ret, device );
712 RtlLeaveCriticalSection( &dir_section );
714 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ ) || defined(__DragonFly__)
715 char *device = NULL;
716 int fd, res = -1;
717 struct stat st;
719 /* try to open it first to force it to get mounted */
720 if ((fd = open( root, O_RDONLY )) != -1)
722 res = fstat( fd, &st );
723 close( fd );
725 /* now try normal stat just in case */
726 if (res == -1) res = stat( root, &st );
727 if (res == -1) return NULL;
729 RtlEnterCriticalSection( &dir_section );
731 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
732 * pass NULL. Leave the argument in for symmetry.
734 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
735 if (device)
737 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
738 if (ret) strcpy( ret, device );
740 RtlLeaveCriticalSection( &dir_section );
742 #elif defined( sun )
743 FILE *f;
744 char *device = NULL;
745 int fd, res = -1;
746 struct stat st;
748 /* try to open it first to force it to get mounted */
749 if ((fd = open( root, O_RDONLY )) != -1)
751 res = fstat( fd, &st );
752 close( fd );
754 /* now try normal stat just in case */
755 if (res == -1) res = stat( root, &st );
756 if (res == -1) return NULL;
758 RtlEnterCriticalSection( &dir_section );
760 if ((f = fopen( "/etc/mnttab", "r" )))
762 device = parse_mount_entries( f, st.st_dev, st.st_ino);
763 fclose( f );
765 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
766 if (!device && (f = fopen( "/etc/vfstab", "r" )))
768 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
769 fclose( f );
771 if (device)
773 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
774 if (ret) strcpy( ret, device );
776 RtlLeaveCriticalSection( &dir_section );
778 #elif defined(__APPLE__)
779 struct statfs *mntStat;
780 struct stat st;
781 int i;
782 int mntSize;
783 dev_t dev;
784 ino_t ino;
785 static const char path_bsd_device[] = "/dev/disk";
786 int res;
788 res = stat( root, &st );
789 if (res == -1) return NULL;
791 dev = st.st_dev;
792 ino = st.st_ino;
794 RtlEnterCriticalSection( &dir_section );
796 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
798 for (i = 0; i < mntSize && !ret; i++)
800 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
801 if (st.st_dev != dev || st.st_ino != ino) continue;
803 /* FIXME add support for mounted network drive */
804 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
806 /* set return value to the corresponding raw BSD node */
807 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
808 if (ret)
810 strcpy(ret, "/dev/r");
811 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
815 RtlLeaveCriticalSection( &dir_section );
816 #else
817 static int warned;
818 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
819 #endif
820 return ret;
824 /***********************************************************************
825 * get_device_mount_point
827 * Return the current mount point for a device.
829 static char *get_device_mount_point( dev_t dev )
831 char *ret = NULL;
833 #ifdef linux
834 FILE *f;
836 RtlEnterCriticalSection( &dir_section );
838 #ifdef __ANDROID__
839 if ((f = fopen( "/proc/mounts", "r" )))
840 #else
841 if ((f = fopen( "/etc/mtab", "r" )))
842 #endif
844 struct mntent *entry;
845 struct stat st;
846 char *p, *device;
848 while ((entry = getmntent( f )))
850 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
851 if (!strcmp( entry->mnt_type, "nfs" ) ||
852 !strcmp( entry->mnt_type, "smbfs" ) ||
853 !strcmp( entry->mnt_type, "ncpfs" )) continue;
855 if (!strcmp( entry->mnt_type, "supermount" ))
857 if ((device = strstr( entry->mnt_opts, "dev=" )))
859 device += 4;
860 if ((p = strchr( device, ',' ))) *p = 0;
863 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
865 /* if device is a regular file check for a loop mount */
866 if ((device = strstr( entry->mnt_opts, "loop=" )))
868 device += 5;
869 if ((p = strchr( device, ',' ))) *p = 0;
872 else device = entry->mnt_fsname;
874 if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
876 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
877 if (ret) strcpy( ret, entry->mnt_dir );
878 break;
881 fclose( f );
883 RtlLeaveCriticalSection( &dir_section );
884 #elif defined(__APPLE__)
885 struct statfs *entry;
886 struct stat st;
887 int i, size;
889 RtlEnterCriticalSection( &dir_section );
891 size = getmntinfo( &entry, MNT_NOWAIT );
892 for (i = 0; i < size; i++)
894 if (stat( entry[i].f_mntfromname, &st ) == -1) continue;
895 if (S_ISBLK(st.st_mode) && st.st_rdev == dev)
897 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry[i].f_mntonname) + 1 );
898 if (ret) strcpy( ret, entry[i].f_mntonname );
899 break;
902 RtlLeaveCriticalSection( &dir_section );
903 #else
904 static int warned;
905 if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
906 #endif
907 return ret;
911 #if defined(HAVE_GETATTRLIST) && defined(ATTR_VOL_CAPABILITIES) && \
912 defined(VOL_CAPABILITIES_FORMAT) && defined(VOL_CAP_FMT_CASE_SENSITIVE)
914 struct get_fsid
916 ULONG size;
917 dev_t dev;
918 fsid_t fsid;
921 struct fs_cache
923 dev_t dev;
924 fsid_t fsid;
925 BOOLEAN case_sensitive;
926 } fs_cache[64];
928 struct vol_caps
930 ULONG size;
931 vol_capabilities_attr_t caps;
934 /***********************************************************************
935 * look_up_fs_cache
937 * Checks if the specified file system is in the cache.
939 static struct fs_cache *look_up_fs_cache( dev_t dev )
941 int i;
942 for (i = 0; i < sizeof(fs_cache)/sizeof(fs_cache[0]); i++)
943 if (fs_cache[i].dev == dev)
944 return fs_cache+i;
945 return NULL;
948 /***********************************************************************
949 * add_fs_cache
951 * Adds the specified file system to the cache.
953 static void add_fs_cache( dev_t dev, fsid_t fsid, BOOLEAN case_sensitive )
955 int i;
956 struct fs_cache *entry = look_up_fs_cache( dev );
957 static int once = 0;
958 if (entry)
960 /* Update the cache */
961 entry->fsid = fsid;
962 entry->case_sensitive = case_sensitive;
963 return;
966 /* Add a new entry */
967 for (i = 0; i < sizeof(fs_cache)/sizeof(fs_cache[0]); i++)
968 if (fs_cache[i].dev == 0)
970 /* This entry is empty, use it */
971 fs_cache[i].dev = dev;
972 fs_cache[i].fsid = fsid;
973 fs_cache[i].case_sensitive = case_sensitive;
974 return;
977 /* Cache is out of space, warn */
978 if (!once++)
979 WARN( "FS cache is out of space, expect performance problems\n" );
982 /***********************************************************************
983 * get_dir_case_sensitivity_attr
985 * Checks if the volume containing the specified directory is case
986 * sensitive or not. Uses getattrlist(2).
988 static int get_dir_case_sensitivity_attr( const char *dir )
990 char *mntpoint = NULL;
991 struct attrlist attr;
992 struct vol_caps caps;
993 struct get_fsid get_fsid;
994 struct fs_cache *entry;
996 /* First get the FS ID of the volume */
997 attr.bitmapcount = ATTR_BIT_MAP_COUNT;
998 attr.reserved = 0;
999 attr.commonattr = ATTR_CMN_DEVID|ATTR_CMN_FSID;
1000 attr.volattr = attr.dirattr = attr.fileattr = attr.forkattr = 0;
1001 get_fsid.size = 0;
1002 if (getattrlist( dir, &attr, &get_fsid, sizeof(get_fsid), 0 ) != 0 ||
1003 get_fsid.size != sizeof(get_fsid))
1004 return -1;
1005 /* Try to look it up in the cache */
1006 entry = look_up_fs_cache( get_fsid.dev );
1007 if (entry && !memcmp( &entry->fsid, &get_fsid.fsid, sizeof(fsid_t) ))
1008 /* Cache lookup succeeded */
1009 return entry->case_sensitive;
1010 /* Cache is stale at this point, we have to update it */
1012 mntpoint = get_device_mount_point( get_fsid.dev );
1013 /* Now look up the case-sensitivity */
1014 attr.commonattr = 0;
1015 attr.volattr = ATTR_VOL_INFO|ATTR_VOL_CAPABILITIES;
1016 if (getattrlist( mntpoint, &attr, &caps, sizeof(caps), 0 ) < 0)
1018 RtlFreeHeap( GetProcessHeap(), 0, mntpoint );
1019 add_fs_cache( get_fsid.dev, get_fsid.fsid, TRUE );
1020 return TRUE;
1022 RtlFreeHeap( GetProcessHeap(), 0, mntpoint );
1023 if (caps.size == sizeof(caps) &&
1024 (caps.caps.valid[VOL_CAPABILITIES_FORMAT] &
1025 (VOL_CAP_FMT_CASE_SENSITIVE | VOL_CAP_FMT_CASE_PRESERVING)) ==
1026 (VOL_CAP_FMT_CASE_SENSITIVE | VOL_CAP_FMT_CASE_PRESERVING))
1028 BOOLEAN ret;
1030 if ((caps.caps.capabilities[VOL_CAPABILITIES_FORMAT] &
1031 VOL_CAP_FMT_CASE_SENSITIVE) != VOL_CAP_FMT_CASE_SENSITIVE)
1032 ret = FALSE;
1033 else
1034 ret = TRUE;
1035 /* Update the cache */
1036 add_fs_cache( get_fsid.dev, get_fsid.fsid, ret );
1037 return ret;
1039 return FALSE;
1041 #endif
1043 /***********************************************************************
1044 * get_dir_case_sensitivity_stat
1046 * Checks if the volume containing the specified directory is case
1047 * sensitive or not. Uses statfs(2) or statvfs(2).
1049 static BOOLEAN get_dir_case_sensitivity_stat( const char *dir )
1051 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1052 struct statfs stfs;
1054 if (statfs( dir, &stfs ) == -1) return FALSE;
1055 /* Assume these file systems are always case insensitive on Mac OS.
1056 * For FreeBSD, only assume CIOPFS is case insensitive (AFAIK, Mac OS
1057 * is the only UNIX that supports case-insensitive lookup).
1059 if (!strcmp( stfs.f_fstypename, "fusefs" ) &&
1060 !strncmp( stfs.f_mntfromname, "ciopfs", 5 ))
1061 return FALSE;
1062 #ifdef __APPLE__
1063 if (!strcmp( stfs.f_fstypename, "msdos" ) ||
1064 !strcmp( stfs.f_fstypename, "cd9660" ) ||
1065 !strcmp( stfs.f_fstypename, "udf" ) ||
1066 !strcmp( stfs.f_fstypename, "ntfs" ) ||
1067 !strcmp( stfs.f_fstypename, "smbfs" ))
1068 return FALSE;
1069 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1070 if (!strcmp( stfs.f_fstypename, "hfs" ) && (stfs.f_fssubtype == 0 ||
1071 stfs.f_fssubtype == 1 ||
1072 stfs.f_fssubtype == 128))
1073 return FALSE;
1074 #else
1075 /* The field says "reserved", but a quick look at the kernel source
1076 * tells us that this "reserved" field is really the same as the
1077 * "fssubtype" field from the inode64 structure (see munge_statfs()
1078 * in <xnu-source>/bsd/vfs/vfs_syscalls.c).
1080 if (!strcmp( stfs.f_fstypename, "hfs" ) && (stfs.f_reserved1 == 0 ||
1081 stfs.f_reserved1 == 1 ||
1082 stfs.f_reserved1 == 128))
1083 return FALSE;
1084 #endif
1085 #endif
1086 return TRUE;
1088 #elif defined(__NetBSD__)
1089 struct statvfs stfs;
1091 if (statvfs( dir, &stfs ) == -1) return FALSE;
1092 /* Only assume CIOPFS is case insensitive. */
1093 if (strcmp( stfs.f_fstypename, "fusefs" ) ||
1094 strncmp( stfs.f_mntfromname, "ciopfs", 5 ))
1095 return TRUE;
1096 return FALSE;
1098 #elif defined(__linux__)
1099 struct statfs stfs;
1100 struct stat st;
1101 char *cifile;
1103 /* Only assume CIOPFS is case insensitive. */
1104 if (statfs( dir, &stfs ) == -1) return FALSE;
1105 if (stfs.f_type != 0x65735546 /* FUSE_SUPER_MAGIC */)
1106 return TRUE;
1107 /* Normally, we'd have to parse the mtab to find out exactly what
1108 * kind of FUSE FS this is. But, someone on wine-devel suggested
1109 * a shortcut. We'll stat a special file in the directory. If it's
1110 * there, we'll assume it's a CIOPFS, else not.
1111 * This will break if somebody puts a file named ".ciopfs" in a non-
1112 * CIOPFS directory.
1114 cifile = RtlAllocateHeap( GetProcessHeap(), 0, strlen( dir )+sizeof("/.ciopfs") );
1115 if (!cifile) return TRUE;
1116 strcpy( cifile, dir );
1117 strcat( cifile, "/.ciopfs" );
1118 if (stat( cifile, &st ) == 0)
1120 RtlFreeHeap( GetProcessHeap(), 0, cifile );
1121 return FALSE;
1123 RtlFreeHeap( GetProcessHeap(), 0, cifile );
1124 return TRUE;
1125 #else
1126 return TRUE;
1127 #endif
1131 /***********************************************************************
1132 * get_dir_case_sensitivity
1134 * Checks if the volume containing the specified directory is case
1135 * sensitive or not. Uses statfs(2) or statvfs(2).
1137 static BOOLEAN get_dir_case_sensitivity( const char *dir )
1139 #if defined(HAVE_GETATTRLIST) && defined(ATTR_VOL_CAPABILITIES) && \
1140 defined(VOL_CAPABILITIES_FORMAT) && defined(VOL_CAP_FMT_CASE_SENSITIVE)
1141 int case_sensitive = get_dir_case_sensitivity_attr( dir );
1142 if (case_sensitive != -1) return case_sensitive;
1143 #endif
1144 return get_dir_case_sensitivity_stat( dir );
1148 /***********************************************************************
1149 * init_options
1151 * Initialize the show_dot_files options.
1153 static DWORD WINAPI init_options( RTL_RUN_ONCE *once, void *param, void **context )
1155 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
1156 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
1157 char tmp[80];
1158 HANDLE root, hkey;
1159 DWORD dummy;
1160 OBJECT_ATTRIBUTES attr;
1161 UNICODE_STRING nameW;
1163 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
1164 attr.Length = sizeof(attr);
1165 attr.RootDirectory = root;
1166 attr.ObjectName = &nameW;
1167 attr.Attributes = 0;
1168 attr.SecurityDescriptor = NULL;
1169 attr.SecurityQualityOfService = NULL;
1170 RtlInitUnicodeString( &nameW, WineW );
1172 /* @@ Wine registry key: HKCU\Software\Wine */
1173 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
1175 RtlInitUnicodeString( &nameW, ShowDotFilesW );
1176 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
1178 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
1179 show_dot_files = IS_OPTION_TRUE( str[0] );
1181 NtClose( hkey );
1183 NtClose( root );
1185 /* a couple of directories that we don't want to return in directory searches */
1186 ignore_file( wine_get_config_dir() );
1187 ignore_file( "/dev" );
1188 ignore_file( "/proc" );
1189 #ifdef linux
1190 ignore_file( "/sys" );
1191 #endif
1192 return TRUE;
1196 /***********************************************************************
1197 * DIR_is_hidden_file
1199 * Check if the specified file should be hidden based on its name and the show dot files option.
1201 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
1203 WCHAR *p, *end;
1205 RtlRunOnceExecuteOnce( &init_once, init_options, NULL, NULL );
1207 if (show_dot_files) return FALSE;
1209 end = p = name->Buffer + name->Length/sizeof(WCHAR);
1210 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
1211 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
1212 if (p == end || *p != '.') return FALSE;
1213 /* make sure it isn't '.' or '..' */
1214 if (p + 1 == end) return FALSE;
1215 if (p[1] == '.' && p + 2 == end) return FALSE;
1216 return TRUE;
1220 /***********************************************************************
1221 * hash_short_file_name
1223 * Transform a Unix file name into a hashed DOS name. If the name is a valid
1224 * DOS name, it is converted to upper-case; otherwise it is replaced by a
1225 * hashed version that fits in 8.3 format.
1226 * 'buffer' must be at least 12 characters long.
1227 * Returns length of short name in bytes; short name is NOT null-terminated.
1229 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
1231 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
1233 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
1234 LPWSTR dst;
1235 unsigned short hash;
1236 int i;
1238 /* Compute the hash code of the file name */
1239 /* If you know something about hash functions, feel free to */
1240 /* insert a better algorithm here... */
1241 if (!is_case_sensitive)
1243 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
1244 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
1245 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
1247 else
1249 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
1250 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
1251 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
1254 /* Find last dot for start of the extension */
1255 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
1257 /* Copy first 4 chars, replacing invalid chars with '_' */
1258 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
1260 if (p == end || p == ext) break;
1261 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
1263 /* Pad to 5 chars with '~' */
1264 while (i-- >= 0) *dst++ = '~';
1266 /* Insert hash code converted to 3 ASCII chars */
1267 *dst++ = hash_chars[(hash >> 10) & 0x1f];
1268 *dst++ = hash_chars[(hash >> 5) & 0x1f];
1269 *dst++ = hash_chars[hash & 0x1f];
1271 /* Copy the first 3 chars of the extension (if any) */
1272 if (ext)
1274 *dst++ = '.';
1275 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
1276 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
1278 return dst - buffer;
1282 /***********************************************************************
1283 * match_filename
1285 * Check a long file name against a mask.
1287 * Tests (done in W95 DOS shell - case insensitive):
1288 * *.txt test1.test.txt *
1289 * *st1* test1.txt *
1290 * *.t??????.t* test1.ta.tornado.txt *
1291 * *tornado* test1.ta.tornado.txt *
1292 * t*t test1.ta.tornado.txt *
1293 * ?est* test1.txt *
1294 * ?est??? test1.txt -
1295 * *test1.txt* test1.txt *
1296 * h?l?o*t.dat hellothisisatest.dat *
1298 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
1300 BOOL mismatch;
1301 const WCHAR *name = name_str->Buffer;
1302 const WCHAR *mask = mask_str->Buffer;
1303 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
1304 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
1305 const WCHAR *lastjoker = NULL;
1306 const WCHAR *next_to_retry = NULL;
1308 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
1310 while (name < name_end && mask < mask_end)
1312 switch(*mask)
1314 case '*':
1315 mask++;
1316 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
1317 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
1318 lastjoker = mask;
1320 /* skip to the next match after the joker(s) */
1321 if (is_case_sensitive)
1322 while (name < name_end && (*name != *mask)) name++;
1323 else
1324 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
1325 next_to_retry = name;
1326 break;
1327 case '?':
1328 mask++;
1329 name++;
1330 break;
1331 default:
1332 if (is_case_sensitive) mismatch = (*mask != *name);
1333 else mismatch = (toupperW(*mask) != toupperW(*name));
1335 if (!mismatch)
1337 mask++;
1338 name++;
1339 if (mask == mask_end)
1341 if (name == name_end) return TRUE;
1342 if (lastjoker) mask = lastjoker;
1345 else /* mismatch ! */
1347 if (lastjoker) /* we had an '*', so we can try unlimitedly */
1349 mask = lastjoker;
1351 /* this scan sequence was a mismatch, so restart
1352 * 1 char after the first char we checked last time */
1353 next_to_retry++;
1354 name = next_to_retry;
1356 else return FALSE; /* bad luck */
1358 break;
1361 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
1362 mask++; /* Ignore trailing '.' or '*' in mask */
1363 return (name == name_end && mask == mask_end);
1367 /***********************************************************************
1368 * append_entry
1370 * helper for NtQueryDirectoryFile
1372 static union file_directory_info *append_entry( void *info_ptr, IO_STATUS_BLOCK *io, ULONG max_length,
1373 const char *long_name, const char *short_name,
1374 const UNICODE_STRING *mask, FILE_INFORMATION_CLASS class )
1376 union file_directory_info *info;
1377 int i, long_len, short_len, total_len;
1378 struct stat st;
1379 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
1380 WCHAR short_nameW[12];
1381 WCHAR *filename;
1382 UNICODE_STRING str;
1383 ULONG attributes = 0;
1385 io->u.Status = STATUS_SUCCESS;
1386 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
1387 if (long_len == -1) return NULL;
1389 str.Buffer = long_nameW;
1390 str.Length = long_len * sizeof(WCHAR);
1391 str.MaximumLength = sizeof(long_nameW);
1393 if (short_name)
1395 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
1396 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
1397 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
1399 else /* generate a short name if necessary */
1401 BOOLEAN spaces;
1403 short_len = 0;
1404 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1405 short_len = hash_short_file_name( &str, short_nameW );
1408 TRACE( "long %s short %s mask %s\n",
1409 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
1411 if (mask && !match_filename( &str, mask ))
1413 if (!short_len) return NULL; /* no short name to match */
1414 str.Buffer = short_nameW;
1415 str.Length = short_len * sizeof(WCHAR);
1416 str.MaximumLength = sizeof(short_nameW);
1417 if (!match_filename( &str, mask )) return NULL;
1420 if (lstat( long_name, &st ) == -1) return NULL;
1421 if (S_ISLNK( st.st_mode ))
1423 if (stat( long_name, &st ) == -1) return NULL;
1424 if (S_ISDIR( st.st_mode )) attributes |= FILE_ATTRIBUTE_REPARSE_POINT;
1426 if (is_ignored_file( &st ))
1428 TRACE( "ignoring file %s\n", long_name );
1429 return NULL;
1431 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
1432 attributes |= FILE_ATTRIBUTE_HIDDEN;
1434 total_len = dir_info_size( class, long_len );
1435 if (io->Information + total_len > max_length)
1437 total_len = max_length - io->Information;
1438 io->u.Status = STATUS_BUFFER_OVERFLOW;
1440 info = (union file_directory_info *)((char *)info_ptr + io->Information);
1441 if (st.st_dev != curdir.dev) st.st_ino = 0; /* ignore inode if on a different device */
1442 /* all the structures start with a FileDirectoryInformation layout */
1443 fill_stat_info( &st, info, class );
1444 info->dir.NextEntryOffset = total_len;
1445 info->dir.FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
1446 info->dir.FileAttributes |= attributes;
1448 switch (class)
1450 case FileDirectoryInformation:
1451 info->dir.FileNameLength = long_len * sizeof(WCHAR);
1452 filename = info->dir.FileName;
1453 break;
1455 case FileFullDirectoryInformation:
1456 info->full.EaSize = 0; /* FIXME */
1457 info->full.FileNameLength = long_len * sizeof(WCHAR);
1458 filename = info->full.FileName;
1459 break;
1461 case FileIdFullDirectoryInformation:
1462 info->id_full.EaSize = 0; /* FIXME */
1463 info->id_full.FileNameLength = long_len * sizeof(WCHAR);
1464 filename = info->id_full.FileName;
1465 break;
1467 case FileBothDirectoryInformation:
1468 info->both.EaSize = 0; /* FIXME */
1469 info->both.ShortNameLength = short_len * sizeof(WCHAR);
1470 for (i = 0; i < short_len; i++) info->both.ShortName[i] = toupperW(short_nameW[i]);
1471 info->both.FileNameLength = long_len * sizeof(WCHAR);
1472 filename = info->both.FileName;
1473 break;
1475 case FileIdBothDirectoryInformation:
1476 info->id_both.EaSize = 0; /* FIXME */
1477 info->id_both.ShortNameLength = short_len * sizeof(WCHAR);
1478 for (i = 0; i < short_len; i++) info->id_both.ShortName[i] = toupperW(short_nameW[i]);
1479 info->id_both.FileNameLength = long_len * sizeof(WCHAR);
1480 filename = info->id_both.FileName;
1481 break;
1483 default:
1484 assert(0);
1485 return NULL;
1487 memcpy( filename, long_nameW, long_len * sizeof(WCHAR) );
1488 io->Information += total_len;
1489 return info;
1493 #ifdef VFAT_IOCTL_READDIR_BOTH
1495 /***********************************************************************
1496 * start_vfat_ioctl
1498 * Wrapper for the VFAT ioctl to work around various kernel bugs.
1499 * dir_section must be held by caller.
1501 static KERNEL_DIRENT *start_vfat_ioctl( int fd )
1503 static KERNEL_DIRENT *de;
1504 int res;
1506 if (!de)
1508 SIZE_T size = 2 * sizeof(*de) + page_size;
1509 void *addr = NULL;
1511 if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_RESERVE, PAGE_READWRITE ))
1512 return NULL;
1513 /* commit only the size needed for the dir entries */
1514 /* this leaves an extra unaccessible page, which should make the kernel */
1515 /* fail with -EFAULT before it stomps all over our memory */
1516 de = addr;
1517 size = 2 * sizeof(*de);
1518 NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_COMMIT, PAGE_READWRITE );
1521 /* set d_reclen to 65535 to work around an AFS kernel bug */
1522 de[0].d_reclen = 65535;
1523 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
1524 if (res == -1)
1526 if (errno != ENOENT) return NULL; /* VFAT ioctl probably not supported */
1527 de[0].d_reclen = 0; /* eof */
1529 else if (!res && de[0].d_reclen == 65535) return NULL; /* AFS bug */
1531 return de;
1535 /***********************************************************************
1536 * read_directory_vfat
1538 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
1540 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1541 BOOLEAN single_entry, const UNICODE_STRING *mask,
1542 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1545 size_t len;
1546 KERNEL_DIRENT *de;
1547 union file_directory_info *info, *last_info = NULL;
1549 io->u.Status = STATUS_SUCCESS;
1551 if (restart_scan) lseek( fd, 0, SEEK_SET );
1553 if (length < max_dir_info_size(class)) /* we may have to return a partial entry here */
1555 off_t old_pos = lseek( fd, 0, SEEK_CUR );
1557 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1559 while (de[0].d_reclen)
1561 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1562 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1563 de[0].d_name[len] = 0;
1564 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1565 de[1].d_name[len] = 0;
1567 if (de[1].d_name[0])
1568 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1569 else
1570 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1571 if (info)
1573 last_info = info;
1574 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1575 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1576 break;
1578 old_pos = lseek( fd, 0, SEEK_CUR );
1579 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1582 else /* we'll only return full entries, no need to worry about overflow */
1584 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1586 while (de[0].d_reclen)
1588 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1589 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1590 de[0].d_name[len] = 0;
1591 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1592 de[1].d_name[len] = 0;
1594 if (de[1].d_name[0])
1595 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1596 else
1597 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1598 if (info)
1600 last_info = info;
1601 if (single_entry) break;
1602 /* check if we still have enough space for the largest possible entry */
1603 if (io->Information + max_dir_info_size(class) > length) break;
1605 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1609 if (last_info) last_info->next = 0;
1610 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1611 return 0;
1613 #endif /* VFAT_IOCTL_READDIR_BOTH */
1616 #ifdef USE_GETDENTS
1617 /***********************************************************************
1618 * read_first_dent_name
1620 * reads name of first or second dentry (if they have inodes).
1622 static char *read_first_dent_name( int which, int fd, off_t second_offs, KERNEL_DIRENT64 *de_first_two,
1623 char *buffer, size_t size, BOOL *buffer_changed )
1625 KERNEL_DIRENT64 *de;
1626 int res;
1628 de = de_first_two;
1629 if (de != NULL)
1631 if (which == 1)
1632 de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1634 return de->d_ino ? de->d_name : NULL;
1637 *buffer_changed = TRUE;
1638 lseek( fd, which == 1 ? second_offs : 0, SEEK_SET );
1639 res = getdents64( fd, buffer, size );
1640 if (res <= 0)
1641 return NULL;
1643 de = (KERNEL_DIRENT64 *)buffer;
1644 return de->d_ino ? de->d_name : NULL;
1647 /***********************************************************************
1648 * read_directory_getdents
1650 * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
1652 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1653 BOOLEAN single_entry, const UNICODE_STRING *mask,
1654 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1656 static off_t second_entry_pos;
1657 static struct file_identity last_dir_id;
1658 off_t old_pos = 0, next_pos;
1659 size_t size = length;
1660 char *data, local_buffer[8192];
1661 KERNEL_DIRENT64 *de, *de_first_two = NULL;
1662 union file_directory_info *info, *last_info = NULL;
1663 const char *filename;
1664 BOOL data_buffer_changed;
1665 int res, swap_to;
1667 if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1669 size = sizeof(local_buffer);
1670 data = local_buffer;
1673 if (restart_scan) lseek( fd, 0, SEEK_SET );
1674 else
1676 old_pos = lseek( fd, 0, SEEK_CUR );
1677 if (old_pos == -1)
1679 io->u.Status = (errno == ENOENT) ? STATUS_NO_MORE_FILES : FILE_GetNtStatus();
1680 res = 0;
1681 goto done;
1685 io->u.Status = STATUS_SUCCESS;
1686 de = (KERNEL_DIRENT64 *)data;
1688 /* if old_pos is not 0 we don't know how many entries have been returned already,
1689 * so maintain second_entry_pos to know when to return '..' */
1690 if (old_pos != 0 && (last_dir_id.dev != curdir.dev || last_dir_id.ino != curdir.ino))
1692 lseek( fd, 0, SEEK_SET );
1693 res = getdents64( fd, data, size );
1694 if (res > 0)
1696 second_entry_pos = de->d_off;
1697 last_dir_id = curdir;
1699 lseek( fd, old_pos, SEEK_SET );
1702 res = getdents64( fd, data, size );
1703 if (res == -1)
1705 if (errno != ENOSYS)
1707 io->u.Status = FILE_GetNtStatus();
1708 res = 0;
1710 goto done;
1713 if (old_pos == 0 && res > 0)
1715 second_entry_pos = de->d_off;
1716 last_dir_id = curdir;
1717 if (res > de->d_reclen)
1718 de_first_two = de;
1721 while (res > 0)
1723 res -= de->d_reclen;
1724 next_pos = de->d_off;
1725 filename = NULL;
1727 /* we must return first 2 entries as "." and "..", but getdents64()
1728 * can return them anywhere, so swap first entries with "." and ".." */
1729 if (old_pos == 0)
1730 filename = ".";
1731 else if (old_pos == second_entry_pos)
1732 filename = "..";
1733 else if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))
1735 swap_to = !strcmp( de->d_name, "." ) ? 0 : 1;
1736 data_buffer_changed = FALSE;
1738 filename = read_first_dent_name( swap_to, fd, second_entry_pos, de_first_two,
1739 data, size, &data_buffer_changed );
1740 if (filename != NULL && (!strcmp( filename, "." ) || !strcmp( filename, ".." )))
1741 filename = read_first_dent_name( swap_to ^ 1, fd, second_entry_pos, NULL,
1742 data, size, &data_buffer_changed );
1743 if (data_buffer_changed)
1745 lseek( fd, next_pos, SEEK_SET );
1746 res = 0;
1749 else if (de->d_ino)
1750 filename = de->d_name;
1752 if (filename && (info = append_entry( buffer, io, length, filename, NULL, mask, class )))
1754 last_info = info;
1755 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1757 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1758 break;
1760 /* check if we still have enough space for the largest possible entry */
1761 if (single_entry || io->Information + max_dir_info_size(class) > length)
1763 if (res > 0) lseek( fd, next_pos, SEEK_SET ); /* set pos to next entry */
1764 break;
1767 old_pos = next_pos;
1768 /* move on to the next entry */
1769 if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1770 else
1772 res = getdents64( fd, data, size );
1773 de = (KERNEL_DIRENT64 *)data;
1774 de_first_two = NULL;
1778 if (last_info) last_info->next = 0;
1779 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1780 res = 0;
1781 done:
1782 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1783 return res;
1786 #elif defined HAVE_GETDIRENTRIES
1788 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1790 /* Darwin doesn't provide a version of getdirentries with support for 64-bit
1791 * inodes. When 64-bit inodes are enabled, the getdirentries symbol is mapped
1792 * to _getdirentries_is_not_available_when_64_bit_inodes_are_in_effect so that
1793 * we get link errors if we try to use it. We still need getdirentries, but we
1794 * don't need it to support 64-bit inodes. So, we use the legacy getdirentries
1795 * with 32-bit inodes. We have to be careful to use a corresponding dirent
1796 * structure, too.
1798 int darwin_legacy_getdirentries(int, char *, int, long *) __asm("_getdirentries");
1799 #define getdirentries darwin_legacy_getdirentries
1801 struct darwin_legacy_dirent {
1802 __uint32_t d_ino;
1803 __uint16_t d_reclen;
1804 __uint8_t d_type;
1805 __uint8_t d_namlen;
1806 char d_name[__DARWIN_MAXNAMLEN + 1];
1808 #define dirent darwin_legacy_dirent
1810 #endif
1812 /***********************************************************************
1813 * wine_getdirentries
1815 * Wrapper for the BSD getdirentries system call to fix a bug in the
1816 * Mac OS X version. For some file systems (at least Apple Filing
1817 * Protocol a.k.a. AFP), getdirentries resets the file position to 0
1818 * when it's about to return 0 (no more entries). So, a subsequent
1819 * getdirentries call starts over at the beginning again, causing an
1820 * infinite loop.
1822 static inline int wine_getdirentries(int fd, char *buf, int nbytes, long *basep)
1824 int res = getdirentries(fd, buf, nbytes, basep);
1825 #ifdef __APPLE__
1826 if (res == 0)
1827 lseek(fd, *basep, SEEK_SET);
1828 #endif
1829 return res;
1832 static inline int dir_reclen(struct dirent *de)
1834 #ifdef HAVE_STRUCT_DIRENT_D_RECLEN
1835 return de->d_reclen;
1836 #else
1837 return _DIRENT_RECLEN(de->d_namlen);
1838 #endif
1841 /***********************************************************************
1842 * read_directory_getdirentries
1844 * Read a directory using the BSD getdirentries system call; helper for NtQueryDirectoryFile.
1846 static int read_directory_getdirentries( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1847 BOOLEAN single_entry, const UNICODE_STRING *mask,
1848 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1850 long restart_pos;
1851 ULONG_PTR restart_info_pos = 0;
1852 size_t size, initial_size = length;
1853 int res, fake_dot_dot = 1;
1854 char *data, local_buffer[8192];
1855 struct dirent *de;
1856 union file_directory_info *info, *last_info = NULL, *restart_last_info = NULL;
1858 size = initial_size;
1859 data = local_buffer;
1860 if (size > sizeof(local_buffer) && !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1862 io->u.Status = STATUS_NO_MEMORY;
1863 return io->u.Status;
1866 if (restart_scan) lseek( fd, 0, SEEK_SET );
1868 io->u.Status = STATUS_SUCCESS;
1870 /* FIXME: should make sure size is larger than filesystem block size */
1871 res = wine_getdirentries( fd, data, size, &restart_pos );
1872 if (res == -1)
1874 io->u.Status = FILE_GetNtStatus();
1875 res = 0;
1876 goto done;
1879 de = (struct dirent *)data;
1881 if (restart_scan)
1883 /* check if we got . and .. from getdirentries */
1884 if (res > 0)
1886 if (!strcmp( de->d_name, "." ) && res > dir_reclen(de))
1888 struct dirent *next_de = (struct dirent *)(data + dir_reclen(de));
1889 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1892 /* make sure we have enough room for both entries */
1893 if (fake_dot_dot)
1895 const ULONG min_info_size = dir_info_size( class, 1 ) + dir_info_size( class, 2 );
1896 if (length < min_info_size || single_entry)
1898 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1899 fake_dot_dot = 0;
1903 if (fake_dot_dot)
1905 if ((info = append_entry( buffer, io, length, ".", NULL, mask, class )))
1906 last_info = info;
1907 if ((info = append_entry( buffer, io, length, "..", NULL, mask, class )))
1908 last_info = info;
1910 restart_last_info = last_info;
1911 restart_info_pos = io->Information;
1913 /* check if we still have enough space for the largest possible entry */
1914 if (last_info && io->Information + max_dir_info_size(class) > length)
1916 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1917 res = 0;
1922 while (res > 0)
1924 res -= dir_reclen(de);
1925 if (de->d_fileno &&
1926 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1927 ((info = append_entry( buffer, io, length, de->d_name, NULL, mask, class ))))
1929 last_info = info;
1930 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1932 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1933 if (restart_info_pos) /* if we have a complete read already, return it */
1935 io->u.Status = STATUS_SUCCESS;
1936 io->Information = restart_info_pos;
1937 last_info = restart_last_info;
1938 break;
1940 /* otherwise restart from the start with a smaller size */
1941 size = (char *)de - data;
1942 if (!size) break;
1943 io->Information = 0;
1944 last_info = NULL;
1945 goto restart;
1947 if (!has_wildcard( mask )) break;
1948 /* if we have to return but the buffer contains more data, restart with a smaller size */
1949 if (res > 0 && (single_entry || io->Information + max_dir_info_size(class) > length))
1951 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1952 size = (char *)de + dir_reclen(de) - data;
1953 io->Information = restart_info_pos;
1954 last_info = restart_last_info;
1955 goto restart;
1958 /* move on to the next entry */
1959 if (res > 0)
1961 de = (struct dirent *)((char *)de + dir_reclen(de));
1962 continue;
1964 if (size < initial_size) break; /* already restarted once, give up now */
1965 restart_last_info = last_info;
1966 restart_info_pos = io->Information;
1967 restart:
1968 res = wine_getdirentries( fd, data, size, &restart_pos );
1969 de = (struct dirent *)data;
1972 if (last_info) last_info->next = 0;
1973 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1974 res = 0;
1975 done:
1976 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1977 return res;
1980 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1981 #undef getdirentries
1982 #undef dirent
1983 #endif
1985 #endif /* HAVE_GETDIRENTRIES */
1988 /***********************************************************************
1989 * read_directory_readdir
1991 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1993 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1994 BOOLEAN single_entry, const UNICODE_STRING *mask,
1995 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1997 DIR *dir;
1998 off_t i, old_pos = 0;
1999 struct dirent *de;
2000 union file_directory_info *info, *last_info = NULL;
2002 if (!(dir = opendir( "." )))
2004 io->u.Status = FILE_GetNtStatus();
2005 return;
2008 if (!restart_scan)
2010 old_pos = lseek( fd, 0, SEEK_CUR );
2011 /* skip the right number of entries */
2012 for (i = 0; i < old_pos - 2; i++)
2014 if (!readdir( dir ))
2016 closedir( dir );
2017 io->u.Status = STATUS_NO_MORE_FILES;
2018 return;
2022 io->u.Status = STATUS_SUCCESS;
2024 for (;;)
2026 if (old_pos == 0)
2027 info = append_entry( buffer, io, length, ".", NULL, mask, class );
2028 else if (old_pos == 1)
2029 info = append_entry( buffer, io, length, "..", NULL, mask, class );
2030 else if ((de = readdir( dir )))
2032 if (strcmp( de->d_name, "." ) && strcmp( de->d_name, ".." ))
2033 info = append_entry( buffer, io, length, de->d_name, NULL, mask, class );
2034 else
2035 info = NULL;
2037 else
2038 break;
2039 old_pos++;
2040 if (info)
2042 last_info = info;
2043 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
2045 old_pos--; /* restore pos to previous entry */
2046 break;
2048 if (single_entry) break;
2049 /* check if we still have enough space for the largest possible entry */
2050 if (io->Information + max_dir_info_size(class) > length) break;
2054 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
2055 closedir( dir );
2057 if (last_info) last_info->next = 0;
2058 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
2061 /***********************************************************************
2062 * read_directory_stat
2064 * Read a single file from a directory by determining whether the file
2065 * identified by mask exists using stat.
2067 static int read_directory_stat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
2068 BOOLEAN single_entry, const UNICODE_STRING *mask,
2069 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
2071 int unix_len, ret, used_default;
2072 char *unix_name;
2073 struct stat st;
2075 TRACE("trying optimisation for file %s\n", debugstr_us( mask ));
2077 unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
2078 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
2080 io->u.Status = STATUS_NO_MEMORY;
2081 return 0;
2083 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
2084 NULL, &used_default );
2085 if (ret > 0 && !used_default)
2087 unix_name[ret] = 0;
2088 if (restart_scan)
2090 lseek( fd, 0, SEEK_SET );
2092 else if (lseek( fd, 0, SEEK_CUR ) != 0)
2094 io->u.Status = STATUS_NO_MORE_FILES;
2095 ret = 0;
2096 goto done;
2099 ret = stat( unix_name, &st );
2100 if (!ret)
2102 union file_directory_info *info = append_entry( buffer, io, length, unix_name, NULL, NULL, class );
2103 if (info)
2105 info->next = 0;
2106 if (io->u.Status != STATUS_BUFFER_OVERFLOW) lseek( fd, 1, SEEK_CUR );
2108 else io->u.Status = STATUS_NO_MORE_FILES;
2111 else ret = -1;
2113 done:
2114 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2116 TRACE("returning %d\n", ret);
2118 return ret;
2122 /******************************************************************************
2123 * NtQueryDirectoryFile [NTDLL.@]
2124 * ZwQueryDirectoryFile [NTDLL.@]
2126 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
2127 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
2128 PIO_STATUS_BLOCK io,
2129 PVOID buffer, ULONG length,
2130 FILE_INFORMATION_CLASS info_class,
2131 BOOLEAN single_entry,
2132 PUNICODE_STRING mask,
2133 BOOLEAN restart_scan )
2135 int cwd, fd, needs_close;
2137 TRACE("(%p %p %p %p %p %p 0x%08x 0x%08x 0x%08x %s 0x%08x\n",
2138 handle, event, apc_routine, apc_context, io, buffer,
2139 length, info_class, single_entry, debugstr_us(mask),
2140 restart_scan);
2142 if (event || apc_routine)
2144 FIXME( "Unsupported yet option\n" );
2145 return io->u.Status = STATUS_NOT_IMPLEMENTED;
2147 switch (info_class)
2149 case FileDirectoryInformation:
2150 case FileBothDirectoryInformation:
2151 case FileFullDirectoryInformation:
2152 case FileIdBothDirectoryInformation:
2153 case FileIdFullDirectoryInformation:
2154 if (length < dir_info_size( info_class, 1 )) return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
2155 if (!buffer) return io->u.Status = STATUS_ACCESS_VIOLATION;
2156 break;
2157 default:
2158 FIXME( "Unsupported file info class %d\n", info_class );
2159 return io->u.Status = STATUS_NOT_IMPLEMENTED;
2162 if ((io->u.Status = server_get_unix_fd( handle, FILE_LIST_DIRECTORY, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
2163 return io->u.Status;
2165 io->Information = 0;
2167 RtlRunOnceExecuteOnce( &init_once, init_options, NULL, NULL );
2169 RtlEnterCriticalSection( &dir_section );
2171 cwd = open( ".", O_RDONLY );
2172 if (fchdir( fd ) != -1)
2174 struct stat st;
2175 fstat( fd, &st );
2176 curdir.dev = st.st_dev;
2177 curdir.ino = st.st_ino;
2178 #ifdef VFAT_IOCTL_READDIR_BOTH
2179 if ((read_directory_vfat( fd, io, buffer, length, single_entry,
2180 mask, restart_scan, info_class )) != -1) goto done;
2181 #endif
2182 if (!has_wildcard( mask ) &&
2183 read_directory_stat( fd, io, buffer, length, single_entry,
2184 mask, restart_scan, info_class ) != -1) goto done;
2185 #ifdef USE_GETDENTS
2186 if ((read_directory_getdents( fd, io, buffer, length, single_entry,
2187 mask, restart_scan, info_class )) != -1) goto done;
2188 #elif defined HAVE_GETDIRENTRIES
2189 if ((read_directory_getdirentries( fd, io, buffer, length, single_entry,
2190 mask, restart_scan, info_class )) != -1) goto done;
2191 #endif
2192 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan, info_class );
2194 done:
2195 if (cwd == -1 || fchdir( cwd ) == -1) chdir( "/" );
2197 else io->u.Status = FILE_GetNtStatus();
2199 RtlLeaveCriticalSection( &dir_section );
2201 if (needs_close) close( fd );
2202 if (cwd != -1) close( cwd );
2203 TRACE( "=> %x (%ld)\n", io->u.Status, io->Information );
2204 return io->u.Status;
2208 /***********************************************************************
2209 * find_file_in_dir
2211 * Find a file in a directory the hard way, by doing a case-insensitive search.
2212 * The file found is appended to unix_name at pos.
2213 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
2215 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
2216 BOOLEAN check_case, BOOLEAN *is_win_dir )
2218 WCHAR buffer[MAX_DIR_ENTRY_LEN];
2219 UNICODE_STRING str;
2220 BOOLEAN spaces, is_name_8_dot_3;
2221 DIR *dir;
2222 struct dirent *de;
2223 struct stat st;
2224 int ret, used_default;
2226 /* try a shortcut for this directory */
2228 unix_name[pos++] = '/';
2229 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
2230 NULL, &used_default );
2231 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
2232 /* so it cannot match the file we are looking for */
2233 if (ret >= 0 && !used_default)
2235 unix_name[pos + ret] = 0;
2236 if (!stat( unix_name, &st ))
2238 if (is_win_dir) *is_win_dir = is_same_file( &windir, &st );
2239 return STATUS_SUCCESS;
2242 if (check_case) goto not_found; /* we want an exact match */
2244 if (pos > 1) unix_name[pos - 1] = 0;
2245 else unix_name[1] = 0; /* keep the initial slash */
2247 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
2249 str.Buffer = (WCHAR *)name;
2250 str.Length = length * sizeof(WCHAR);
2251 str.MaximumLength = str.Length;
2252 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
2253 #ifndef VFAT_IOCTL_READDIR_BOTH
2254 is_name_8_dot_3 = is_name_8_dot_3 && length >= 8 && name[4] == '~';
2255 #endif
2257 if (!is_name_8_dot_3 && !get_dir_case_sensitivity( unix_name )) goto not_found;
2259 /* now look for it through the directory */
2261 #ifdef VFAT_IOCTL_READDIR_BOTH
2262 if (is_name_8_dot_3)
2264 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
2265 if (fd != -1)
2267 KERNEL_DIRENT *kde;
2269 RtlEnterCriticalSection( &dir_section );
2270 if ((kde = start_vfat_ioctl( fd )))
2272 unix_name[pos - 1] = '/';
2273 while (kde[0].d_reclen)
2275 /* make sure names are null-terminated to work around an x86-64 kernel bug */
2276 size_t len = min(kde[0].d_reclen, sizeof(kde[0].d_name) - 1 );
2277 kde[0].d_name[len] = 0;
2278 len = min(kde[1].d_reclen, sizeof(kde[1].d_name) - 1 );
2279 kde[1].d_name[len] = 0;
2281 if (kde[1].d_name[0])
2283 ret = ntdll_umbstowcs( 0, kde[1].d_name, strlen(kde[1].d_name),
2284 buffer, MAX_DIR_ENTRY_LEN );
2285 if (ret == length && !memicmpW( buffer, name, length))
2287 strcpy( unix_name + pos, kde[1].d_name );
2288 RtlLeaveCriticalSection( &dir_section );
2289 close( fd );
2290 goto success;
2293 ret = ntdll_umbstowcs( 0, kde[0].d_name, strlen(kde[0].d_name),
2294 buffer, MAX_DIR_ENTRY_LEN );
2295 if (ret == length && !memicmpW( buffer, name, length))
2297 strcpy( unix_name + pos,
2298 kde[1].d_name[0] ? kde[1].d_name : kde[0].d_name );
2299 RtlLeaveCriticalSection( &dir_section );
2300 close( fd );
2301 goto success;
2303 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)kde ) == -1)
2305 RtlLeaveCriticalSection( &dir_section );
2306 close( fd );
2307 goto not_found;
2311 RtlLeaveCriticalSection( &dir_section );
2312 close( fd );
2314 /* fall through to normal handling */
2316 #endif /* VFAT_IOCTL_READDIR_BOTH */
2318 if (!(dir = opendir( unix_name )))
2320 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
2321 else return FILE_GetNtStatus();
2323 unix_name[pos - 1] = '/';
2324 str.Buffer = buffer;
2325 str.MaximumLength = sizeof(buffer);
2326 while ((de = readdir( dir )))
2328 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
2329 if (ret == length && !memicmpW( buffer, name, length ))
2331 strcpy( unix_name + pos, de->d_name );
2332 closedir( dir );
2333 goto success;
2336 if (!is_name_8_dot_3) continue;
2338 str.Length = ret * sizeof(WCHAR);
2339 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
2341 WCHAR short_nameW[12];
2342 ret = hash_short_file_name( &str, short_nameW );
2343 if (ret == length && !memicmpW( short_nameW, name, length ))
2345 strcpy( unix_name + pos, de->d_name );
2346 closedir( dir );
2347 goto success;
2351 closedir( dir );
2353 not_found:
2354 unix_name[pos - 1] = 0;
2355 return STATUS_OBJECT_PATH_NOT_FOUND;
2357 success:
2358 if (is_win_dir && !stat( unix_name, &st )) *is_win_dir = is_same_file( &windir, &st );
2359 return STATUS_SUCCESS;
2363 #ifndef _WIN64
2365 static const WCHAR catrootW[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t',0};
2366 static const WCHAR catroot2W[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t','2',0};
2367 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};
2368 static const WCHAR driversetcW[] = {'s','y','s','t','e','m','3','2','\\','d','r','i','v','e','r','s','\\','e','t','c',0};
2369 static const WCHAR logfilesW[] = {'s','y','s','t','e','m','3','2','\\','l','o','g','f','i','l','e','s',0};
2370 static const WCHAR spoolW[] = {'s','y','s','t','e','m','3','2','\\','s','p','o','o','l',0};
2371 static const WCHAR system32W[] = {'s','y','s','t','e','m','3','2',0};
2372 static const WCHAR syswow64W[] = {'s','y','s','w','o','w','6','4',0};
2373 static const WCHAR sysnativeW[] = {'s','y','s','n','a','t','i','v','e',0};
2374 static const WCHAR regeditW[] = {'r','e','g','e','d','i','t','.','e','x','e',0};
2375 static const WCHAR wow_regeditW[] = {'s','y','s','w','o','w','6','4','\\','r','e','g','e','d','i','t','.','e','x','e',0};
2377 static struct
2379 const WCHAR *source;
2380 const WCHAR *dos_target;
2381 const char *unix_target;
2382 } redirects[] =
2384 { catrootW, NULL, NULL },
2385 { catroot2W, NULL, NULL },
2386 { driversstoreW, NULL, NULL },
2387 { driversetcW, NULL, NULL },
2388 { logfilesW, NULL, NULL },
2389 { spoolW, NULL, NULL },
2390 { system32W, syswow64W, NULL },
2391 { sysnativeW, system32W, NULL },
2392 { regeditW, wow_regeditW, NULL }
2395 static unsigned int nb_redirects;
2398 /***********************************************************************
2399 * get_redirect_target
2401 * Find the target unix name for a redirected dir.
2403 static const char *get_redirect_target( const char *windows_dir, const WCHAR *name )
2405 int used_default, len, pos, win_len = strlen( windows_dir );
2406 char *unix_name, *unix_target = NULL;
2407 NTSTATUS status;
2409 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, win_len + MAX_DIR_ENTRY_LEN + 2 )))
2410 return NULL;
2411 memcpy( unix_name, windows_dir, win_len );
2412 pos = win_len;
2414 while (*name)
2416 const WCHAR *end, *next;
2418 for (end = name; *end; end++) if (IS_SEPARATOR(*end)) break;
2419 for (next = end; *next; next++) if (!IS_SEPARATOR(*next)) break;
2421 status = find_file_in_dir( unix_name, pos, name, end - name, FALSE, NULL );
2422 if (status == STATUS_OBJECT_PATH_NOT_FOUND && !*next) /* not finding last element is ok */
2424 len = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2425 MAX_DIR_ENTRY_LEN - (pos - win_len), NULL, &used_default );
2426 if (len > 0 && !used_default)
2428 unix_name[pos] = '/';
2429 pos += len + 1;
2430 unix_name[pos] = 0;
2431 break;
2434 if (status) goto done;
2435 pos += strlen( unix_name + pos );
2436 name = next;
2439 if ((unix_target = RtlAllocateHeap( GetProcessHeap(), 0, pos - win_len )))
2440 memcpy( unix_target, unix_name + win_len + 1, pos - win_len );
2442 done:
2443 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2444 return unix_target;
2448 /***********************************************************************
2449 * init_redirects
2451 static void init_redirects(void)
2453 UNICODE_STRING nt_name;
2454 ANSI_STRING unix_name;
2455 NTSTATUS status;
2456 struct stat st;
2457 unsigned int i;
2459 if (!RtlDosPathNameToNtPathName_U( user_shared_data->NtSystemRoot, &nt_name, NULL, NULL ))
2461 ERR( "can't convert %s\n", debugstr_w(user_shared_data->NtSystemRoot) );
2462 return;
2464 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
2465 RtlFreeUnicodeString( &nt_name );
2466 if (status)
2468 ERR( "cannot open %s (%x)\n", debugstr_w(user_shared_data->NtSystemRoot), status );
2469 return;
2471 if (!stat( unix_name.Buffer, &st ))
2473 windir.dev = st.st_dev;
2474 windir.ino = st.st_ino;
2475 nb_redirects = sizeof(redirects) / sizeof(redirects[0]);
2476 for (i = 0; i < nb_redirects; i++)
2478 if (!redirects[i].dos_target) continue;
2479 redirects[i].unix_target = get_redirect_target( unix_name.Buffer, redirects[i].dos_target );
2480 TRACE( "%s -> %s\n", debugstr_w(redirects[i].source), redirects[i].unix_target );
2483 RtlFreeAnsiString( &unix_name );
2488 /***********************************************************************
2489 * match_redirect
2491 * Check if path matches a redirect name. If yes, return matched length.
2493 static int match_redirect( const WCHAR *path, int len, const WCHAR *redir, BOOLEAN check_case )
2495 int i = 0;
2497 while (i < len && *redir)
2499 if (IS_SEPARATOR(path[i]))
2501 if (*redir++ != '\\') return 0;
2502 while (i < len && IS_SEPARATOR(path[i])) i++;
2503 continue; /* move on to next path component */
2505 else if (check_case)
2507 if (path[i] != *redir) return 0;
2509 else
2511 if (tolowerW(path[i]) != tolowerW(*redir)) return 0;
2513 i++;
2514 redir++;
2516 if (*redir) return 0;
2517 if (i < len && !IS_SEPARATOR(path[i])) return 0;
2518 while (i < len && IS_SEPARATOR(path[i])) i++;
2519 return i;
2523 /***********************************************************************
2524 * get_redirect_path
2526 * Retrieve the Unix path corresponding to a redirected path if any.
2528 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, BOOLEAN check_case )
2530 unsigned int i;
2531 int len;
2533 for (i = 0; i < nb_redirects; i++)
2535 if ((len = match_redirect( name, length, redirects[i].source, check_case )))
2537 if (!redirects[i].unix_target) break;
2538 unix_name[pos++] = '/';
2539 strcpy( unix_name + pos, redirects[i].unix_target );
2540 return len;
2543 return 0;
2546 #else /* _WIN64 */
2548 /* there are no redirects on 64-bit */
2550 static const unsigned int nb_redirects = 0;
2552 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, BOOLEAN check_case )
2554 return 0;
2557 #endif
2559 /***********************************************************************
2560 * DIR_init_windows_dir
2562 void DIR_init_windows_dir( const WCHAR *win, const WCHAR *sys )
2564 /* FIXME: should probably store paths as NT file names */
2566 RtlCreateUnicodeString( &system_dir, sys );
2568 #ifndef _WIN64
2569 if (is_wow64) init_redirects();
2570 #endif
2574 /******************************************************************************
2575 * get_dos_device
2577 * Get the Unix path of a DOS device.
2579 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
2581 const char *config_dir = wine_get_config_dir();
2582 struct stat st;
2583 char *unix_name, *new_name, *dev;
2584 unsigned int i;
2585 int unix_len;
2587 /* make sure the device name is ASCII */
2588 for (i = 0; i < name_len; i++)
2589 if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
2591 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
2593 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2594 return STATUS_NO_MEMORY;
2596 strcpy( unix_name, config_dir );
2597 strcat( unix_name, "/dosdevices/" );
2598 dev = unix_name + strlen(unix_name);
2600 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
2601 dev[i] = 0;
2603 /* special case for drive devices */
2604 if (name_len == 2 && dev[1] == ':')
2606 dev[i++] = ':';
2607 dev[i] = 0;
2610 for (;;)
2612 if (!stat( unix_name, &st ))
2614 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
2615 unix_name_ret->Buffer = unix_name;
2616 unix_name_ret->Length = strlen(unix_name);
2617 unix_name_ret->MaximumLength = unix_len;
2618 return STATUS_SUCCESS;
2620 if (!dev) break;
2622 /* now try some defaults for it */
2623 if (!strcmp( dev, "aux" ))
2625 strcpy( dev, "com1" );
2626 continue;
2628 if (!strcmp( dev, "prn" ))
2630 strcpy( dev, "lpt1" );
2631 continue;
2633 if (!strcmp( dev, "nul" ))
2635 strcpy( unix_name, "/dev/null" );
2636 dev = NULL; /* last try */
2637 continue;
2640 new_name = NULL;
2641 if (dev[1] == ':' && dev[2] == ':') /* drive device */
2643 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
2644 new_name = get_default_drive_device( unix_name );
2646 else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( atoi(dev + 3 ));
2647 else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( atoi(dev + 3 ));
2649 if (!new_name) break;
2651 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2652 unix_name = new_name;
2653 unix_len = strlen(unix_name) + 1;
2654 dev = NULL; /* last try */
2656 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2657 return STATUS_BAD_DEVICE_TYPE;
2661 /* return the length of the DOS namespace prefix if any */
2662 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
2664 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
2665 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
2667 if (name->Length > sizeof(nt_prefixW) &&
2668 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
2669 return sizeof(nt_prefixW) / sizeof(WCHAR);
2671 if (name->Length > sizeof(dosdev_prefixW) &&
2672 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
2673 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
2675 return 0;
2679 /******************************************************************************
2680 * find_file_id
2682 * Recursively search directories from the dir queue for a given inode.
2684 static NTSTATUS find_file_id( ANSI_STRING *unix_name, ULONGLONG file_id, dev_t dev )
2686 unsigned int pos;
2687 DIR *dir;
2688 struct dirent *de;
2689 NTSTATUS status;
2690 struct stat st;
2692 while (!(status = next_dir_in_queue( unix_name->Buffer )))
2694 if (!(dir = opendir( unix_name->Buffer ))) continue;
2695 TRACE( "searching %s for %s\n", unix_name->Buffer, wine_dbgstr_longlong(file_id) );
2696 pos = strlen( unix_name->Buffer );
2697 if (pos + MAX_DIR_ENTRY_LEN >= unix_name->MaximumLength/sizeof(WCHAR))
2699 char *new = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name->Buffer,
2700 unix_name->MaximumLength * 2 );
2701 if (!new)
2703 closedir( dir );
2704 return STATUS_NO_MEMORY;
2706 unix_name->MaximumLength *= 2;
2707 unix_name->Buffer = new;
2709 unix_name->Buffer[pos++] = '/';
2710 while ((de = readdir( dir )))
2712 if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
2713 strcpy( unix_name->Buffer + pos, de->d_name );
2714 if (lstat( unix_name->Buffer, &st ) == -1) continue;
2715 if (st.st_dev != dev) continue;
2716 if (st.st_ino == file_id)
2718 closedir( dir );
2719 return STATUS_SUCCESS;
2721 if (!S_ISDIR( st.st_mode )) continue;
2722 if ((status = add_dir_to_queue( unix_name->Buffer )) != STATUS_SUCCESS)
2724 closedir( dir );
2725 return status;
2728 closedir( dir );
2730 return status;
2734 /******************************************************************************
2735 * file_id_to_unix_file_name
2737 * Lookup a file from its file id instead of its name.
2739 NTSTATUS file_id_to_unix_file_name( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name )
2741 enum server_fd_type type;
2742 int old_cwd, root_fd, needs_close;
2743 NTSTATUS status;
2744 ULONGLONG file_id;
2745 struct stat st, root_st;
2747 if (attr->ObjectName->Length != sizeof(ULONGLONG)) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2748 if (!attr->RootDirectory) return STATUS_INVALID_PARAMETER;
2749 memcpy( &file_id, attr->ObjectName->Buffer, sizeof(file_id) );
2751 unix_name->MaximumLength = 2 * MAX_DIR_ENTRY_LEN + 4;
2752 if (!(unix_name->Buffer = RtlAllocateHeap( GetProcessHeap(), 0, unix_name->MaximumLength )))
2753 return STATUS_NO_MEMORY;
2754 strcpy( unix_name->Buffer, "." );
2756 if ((status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
2757 goto done;
2759 if (type != FD_TYPE_DIR)
2761 status = STATUS_OBJECT_TYPE_MISMATCH;
2762 goto done;
2765 fstat( root_fd, &root_st );
2766 if (root_st.st_ino == file_id) /* shortcut for "." */
2768 status = STATUS_SUCCESS;
2769 goto done;
2772 RtlEnterCriticalSection( &dir_section );
2773 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2775 /* shortcut for ".." */
2776 if (!stat( "..", &st ) && st.st_dev == root_st.st_dev && st.st_ino == file_id)
2778 strcpy( unix_name->Buffer, ".." );
2779 status = STATUS_SUCCESS;
2781 else
2783 status = add_dir_to_queue( "." );
2784 if (!status)
2785 status = find_file_id( unix_name, file_id, root_st.st_dev );
2786 if (!status) /* get rid of "./" prefix */
2787 memmove( unix_name->Buffer, unix_name->Buffer + 2, strlen(unix_name->Buffer) - 1 );
2788 flush_dir_queue();
2790 if (fchdir( old_cwd ) == -1) chdir( "/" );
2792 else status = FILE_GetNtStatus();
2793 RtlLeaveCriticalSection( &dir_section );
2794 if (old_cwd != -1) close( old_cwd );
2796 done:
2797 if (status == STATUS_SUCCESS)
2799 TRACE( "%s -> %s\n", wine_dbgstr_longlong(file_id), debugstr_a(unix_name->Buffer) );
2800 unix_name->Length = strlen( unix_name->Buffer );
2802 else
2804 TRACE( "%s not found in dir %p\n", wine_dbgstr_longlong(file_id), attr->RootDirectory );
2805 RtlFreeHeap( GetProcessHeap(), 0, unix_name->Buffer );
2807 if (needs_close) close( root_fd );
2808 return status;
2812 /******************************************************************************
2813 * lookup_unix_name
2815 * Helper for nt_to_unix_file_name
2817 static NTSTATUS lookup_unix_name( const WCHAR *name, int name_len, char **buffer, int unix_len, int pos,
2818 UINT disposition, BOOLEAN check_case )
2820 NTSTATUS status;
2821 int ret, used_default, len;
2822 struct stat st;
2823 char *unix_name = *buffer;
2824 const BOOL redirect = nb_redirects && ntdll_get_thread_data()->wow64_redir;
2826 /* try a shortcut first */
2828 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
2829 NULL, &used_default );
2831 while (name_len && IS_SEPARATOR(*name))
2833 name++;
2834 name_len--;
2837 if (ret >= 0 && !used_default) /* if we used the default char the name didn't convert properly */
2839 char *p;
2840 unix_name[pos + ret] = 0;
2841 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
2842 if (!redirect || (!strstr( unix_name, "/windows/") && strncmp( unix_name, "windows/", 8 )))
2844 if (!stat( unix_name, &st ))
2846 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
2847 if (disposition == FILE_CREATE)
2848 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
2849 return STATUS_SUCCESS;
2854 if (!name_len) /* empty name -> drive root doesn't exist */
2855 return STATUS_OBJECT_PATH_NOT_FOUND;
2856 if (check_case && !redirect && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
2857 return STATUS_OBJECT_NAME_NOT_FOUND;
2859 /* now do it component by component */
2861 while (name_len)
2863 const WCHAR *end, *next;
2864 BOOLEAN is_win_dir = FALSE;
2866 end = name;
2867 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
2868 next = end;
2869 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
2870 name_len -= next - name;
2872 /* grow the buffer if needed */
2874 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
2876 char *new_name;
2877 unix_len += 2 * MAX_DIR_ENTRY_LEN;
2878 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
2879 return STATUS_NO_MEMORY;
2880 unix_name = *buffer = new_name;
2883 status = find_file_in_dir( unix_name, pos, name, end - name,
2884 check_case, redirect ? &is_win_dir : NULL );
2886 /* if this is the last element, not finding it is not necessarily fatal */
2887 if (!name_len)
2889 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
2891 status = STATUS_OBJECT_NAME_NOT_FOUND;
2892 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
2894 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2895 MAX_DIR_ENTRY_LEN, NULL, &used_default );
2896 if (ret > 0 && !used_default)
2898 unix_name[pos] = '/';
2899 unix_name[pos + 1 + ret] = 0;
2900 status = STATUS_NO_SUCH_FILE;
2901 break;
2905 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
2907 status = STATUS_OBJECT_NAME_COLLISION;
2911 if (status != STATUS_SUCCESS) break;
2913 pos += strlen( unix_name + pos );
2914 name = next;
2916 if (is_win_dir && (len = get_redirect_path( unix_name, pos, name, name_len, check_case )))
2918 name += len;
2919 name_len -= len;
2920 pos += strlen( unix_name + pos );
2921 TRACE( "redirecting -> %s + %s\n", debugstr_a(unix_name), debugstr_w(name) );
2925 return status;
2929 /******************************************************************************
2930 * nt_to_unix_file_name_attr
2932 NTSTATUS nt_to_unix_file_name_attr( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name_ret,
2933 UINT disposition )
2935 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2936 enum server_fd_type type;
2937 int old_cwd, root_fd, needs_close;
2938 const WCHAR *name, *p;
2939 char *unix_name;
2940 int name_len, unix_len;
2941 NTSTATUS status;
2942 BOOLEAN check_case = !(attr->Attributes & OBJ_CASE_INSENSITIVE);
2944 if (!attr->RootDirectory) /* without root dir fall back to normal lookup */
2945 return wine_nt_to_unix_file_name( attr->ObjectName, unix_name_ret, disposition, check_case );
2947 name = attr->ObjectName->Buffer;
2948 name_len = attr->ObjectName->Length / sizeof(WCHAR);
2950 if (name_len && IS_SEPARATOR(name[0])) return STATUS_INVALID_PARAMETER;
2952 /* check for invalid characters */
2953 for (p = name; p < name + name_len; p++)
2954 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2956 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
2957 unix_len += MAX_DIR_ENTRY_LEN + 3;
2958 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2959 return STATUS_NO_MEMORY;
2960 unix_name[0] = '.';
2962 if (!(status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
2964 if (type != FD_TYPE_DIR)
2966 if (needs_close) close( root_fd );
2967 status = STATUS_BAD_DEVICE_TYPE;
2969 else
2971 RtlEnterCriticalSection( &dir_section );
2972 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2974 status = lookup_unix_name( name, name_len, &unix_name, unix_len, 1,
2975 disposition, check_case );
2976 if (fchdir( old_cwd ) == -1) chdir( "/" );
2978 else status = FILE_GetNtStatus();
2979 RtlLeaveCriticalSection( &dir_section );
2980 if (old_cwd != -1) close( old_cwd );
2981 if (needs_close) close( root_fd );
2984 else if (status == STATUS_OBJECT_TYPE_MISMATCH) status = STATUS_BAD_DEVICE_TYPE;
2986 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
2988 TRACE( "%s -> %s\n", debugstr_us(attr->ObjectName), debugstr_a(unix_name) );
2989 unix_name_ret->Buffer = unix_name;
2990 unix_name_ret->Length = strlen(unix_name);
2991 unix_name_ret->MaximumLength = unix_len;
2993 else
2995 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
2996 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2998 return status;
3002 /******************************************************************************
3003 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
3005 * Convert a file name from NT namespace to Unix namespace.
3007 * If disposition is not FILE_OPEN or FILE_OVERWRITE, the last path
3008 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
3009 * returned, but the unix name is still filled in properly.
3011 NTSTATUS CDECL wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
3012 UINT disposition, BOOLEAN check_case )
3014 static const WCHAR unixW[] = {'u','n','i','x'};
3015 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
3017 NTSTATUS status = STATUS_SUCCESS;
3018 const char *config_dir = wine_get_config_dir();
3019 const WCHAR *name, *p;
3020 struct stat st;
3021 char *unix_name;
3022 int pos, ret, name_len, unix_len, prefix_len, used_default;
3023 WCHAR prefix[MAX_DIR_ENTRY_LEN];
3024 BOOLEAN is_unix = FALSE;
3026 name = nameW->Buffer;
3027 name_len = nameW->Length / sizeof(WCHAR);
3029 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
3031 if (!(pos = get_dos_prefix_len( nameW )))
3032 return STATUS_BAD_DEVICE_TYPE; /* no DOS prefix, assume NT native name */
3034 name += pos;
3035 name_len -= pos;
3037 /* check for sub-directory */
3038 for (pos = 0; pos < name_len; pos++)
3040 if (IS_SEPARATOR(name[pos])) break;
3041 if (name[pos] < 32 || strchrW( invalid_charsW, name[pos] ))
3042 return STATUS_OBJECT_NAME_INVALID;
3044 if (pos > MAX_DIR_ENTRY_LEN)
3045 return STATUS_OBJECT_NAME_INVALID;
3047 if (pos == name_len) /* no subdir, plain DOS device */
3048 return get_dos_device( name, name_len, unix_name_ret );
3050 for (prefix_len = 0; prefix_len < pos; prefix_len++)
3051 prefix[prefix_len] = tolowerW(name[prefix_len]);
3053 name += prefix_len;
3054 name_len -= prefix_len;
3056 /* check for invalid characters (all chars except 0 are valid for unix) */
3057 is_unix = (prefix_len == 4 && !memcmp( prefix, unixW, sizeof(unixW) ));
3058 if (is_unix)
3060 for (p = name; p < name + name_len; p++)
3061 if (!*p) return STATUS_OBJECT_NAME_INVALID;
3062 check_case = TRUE;
3064 else
3066 for (p = name; p < name + name_len; p++)
3067 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
3070 unix_len = ntdll_wcstoumbs( 0, prefix, prefix_len, NULL, 0, NULL, NULL );
3071 unix_len += ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
3072 unix_len += MAX_DIR_ENTRY_LEN + 3;
3073 unix_len += strlen(config_dir) + sizeof("/dosdevices/");
3074 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
3075 return STATUS_NO_MEMORY;
3076 strcpy( unix_name, config_dir );
3077 strcat( unix_name, "/dosdevices/" );
3078 pos = strlen(unix_name);
3080 ret = ntdll_wcstoumbs( 0, prefix, prefix_len, unix_name + pos, unix_len - pos - 1,
3081 NULL, &used_default );
3082 if (!ret || used_default)
3084 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3085 return STATUS_OBJECT_NAME_INVALID;
3087 pos += ret;
3089 /* check if prefix exists (except for DOS drives to avoid extra stat calls) */
3091 if (prefix_len != 2 || prefix[1] != ':')
3093 unix_name[pos] = 0;
3094 if (lstat( unix_name, &st ) == -1 && errno == ENOENT)
3096 if (!is_unix)
3098 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3099 return STATUS_BAD_DEVICE_TYPE;
3101 pos = 0; /* fall back to unix root */
3105 status = lookup_unix_name( name, name_len, &unix_name, unix_len, pos, disposition, check_case );
3106 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
3108 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
3109 unix_name_ret->Buffer = unix_name;
3110 unix_name_ret->Length = strlen(unix_name);
3111 unix_name_ret->MaximumLength = unix_len;
3113 else
3115 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
3116 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3118 return status;
3122 /******************************************************************
3123 * RtlWow64EnableFsRedirection (NTDLL.@)
3125 NTSTATUS WINAPI RtlWow64EnableFsRedirection( BOOLEAN enable )
3127 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
3128 ntdll_get_thread_data()->wow64_redir = enable;
3129 return STATUS_SUCCESS;
3133 /******************************************************************
3134 * RtlWow64EnableFsRedirectionEx (NTDLL.@)
3136 NTSTATUS WINAPI RtlWow64EnableFsRedirectionEx( ULONG disable, ULONG *old_value )
3138 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
3139 if (((ULONG_PTR)old_value >> 16) == 0) return STATUS_ACCESS_VIOLATION;
3141 *old_value = !ntdll_get_thread_data()->wow64_redir;
3142 ntdll_get_thread_data()->wow64_redir = !disable;
3143 return STATUS_SUCCESS;
3147 /******************************************************************
3148 * RtlDoesFileExists_U (NTDLL.@)
3150 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
3152 UNICODE_STRING nt_name;
3153 FILE_BASIC_INFORMATION basic_info;
3154 OBJECT_ATTRIBUTES attr;
3155 BOOLEAN ret;
3157 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
3159 attr.Length = sizeof(attr);
3160 attr.RootDirectory = 0;
3161 attr.ObjectName = &nt_name;
3162 attr.Attributes = OBJ_CASE_INSENSITIVE;
3163 attr.SecurityDescriptor = NULL;
3164 attr.SecurityQualityOfService = NULL;
3166 ret = NtQueryAttributesFile(&attr, &basic_info) == STATUS_SUCCESS;
3168 RtlFreeUnicodeString( &nt_name );
3169 return ret;
3173 /***********************************************************************
3174 * DIR_unmount_device
3176 * Unmount the specified device.
3178 NTSTATUS DIR_unmount_device( HANDLE handle )
3180 NTSTATUS status;
3181 int unix_fd, needs_close;
3183 if (!(status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )))
3185 struct stat st;
3186 char *mount_point = NULL;
3188 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
3189 status = STATUS_INVALID_PARAMETER;
3190 else
3192 if ((mount_point = get_device_mount_point( st.st_rdev )))
3194 #ifdef __APPLE__
3195 static const char umount[] = "diskutil unmount >/dev/null 2>&1 ";
3196 #else
3197 static const char umount[] = "umount >/dev/null 2>&1 ";
3198 #endif
3199 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
3200 if (cmd)
3202 strcpy( cmd, umount );
3203 strcat( cmd, mount_point );
3204 system( cmd );
3205 RtlFreeHeap( GetProcessHeap(), 0, cmd );
3206 #ifdef linux
3207 /* umount will fail to release the loop device since we still have
3208 a handle to it, so we release it here */
3209 if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
3210 #endif
3212 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
3215 if (needs_close) close( unix_fd );
3217 return status;
3221 /******************************************************************************
3222 * DIR_get_unix_cwd
3224 * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
3225 * Returned value must be freed by caller.
3227 NTSTATUS DIR_get_unix_cwd( char **cwd )
3229 int old_cwd, unix_fd, needs_close;
3230 CURDIR *curdir;
3231 HANDLE handle;
3232 NTSTATUS status;
3234 RtlAcquirePebLock();
3236 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
3237 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
3238 else
3239 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
3241 if (!(handle = curdir->Handle))
3243 UNICODE_STRING dirW;
3244 OBJECT_ATTRIBUTES attr;
3245 IO_STATUS_BLOCK io;
3247 if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
3249 status = STATUS_OBJECT_NAME_INVALID;
3250 goto done;
3252 attr.Length = sizeof(attr);
3253 attr.RootDirectory = 0;
3254 attr.Attributes = OBJ_CASE_INSENSITIVE;
3255 attr.ObjectName = &dirW;
3256 attr.SecurityDescriptor = NULL;
3257 attr.SecurityQualityOfService = NULL;
3259 status = NtOpenFile( &handle, 0, &attr, &io, 0,
3260 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
3261 RtlFreeUnicodeString( &dirW );
3262 if (status != STATUS_SUCCESS) goto done;
3265 if ((status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )) == STATUS_SUCCESS)
3267 RtlEnterCriticalSection( &dir_section );
3269 if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
3271 unsigned int size = 512;
3273 for (;;)
3275 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
3277 status = STATUS_NO_MEMORY;
3278 break;
3280 if (getcwd( *cwd, size )) break;
3281 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
3282 if (errno != ERANGE)
3284 status = STATUS_OBJECT_PATH_INVALID;
3285 break;
3287 size *= 2;
3289 if (fchdir( old_cwd ) == -1) chdir( "/" );
3291 else status = FILE_GetNtStatus();
3293 RtlLeaveCriticalSection( &dir_section );
3294 if (old_cwd != -1) close( old_cwd );
3295 if (needs_close) close( unix_fd );
3297 if (!curdir->Handle) NtClose( handle );
3299 done:
3300 RtlReleasePebLock();
3301 return status;
3304 struct read_changes_info
3306 HANDLE FileHandle;
3307 PVOID Buffer;
3308 ULONG BufferSize;
3309 PIO_APC_ROUTINE apc;
3310 void *apc_arg;
3313 /* callback for ioctl user APC */
3314 static void WINAPI read_changes_user_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
3316 struct read_changes_info *info = arg;
3317 if (info->apc) info->apc( info->apc_arg, io, reserved );
3318 RtlFreeHeap( GetProcessHeap(), 0, info );
3321 static NTSTATUS read_changes_apc( void *user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
3323 struct read_changes_info *info = user;
3324 char data[PATH_MAX];
3325 NTSTATUS ret;
3326 int size;
3328 SERVER_START_REQ( read_change )
3330 req->handle = wine_server_obj_handle( info->FileHandle );
3331 wine_server_set_reply( req, data, PATH_MAX );
3332 ret = wine_server_call( req );
3333 size = wine_server_reply_size( reply );
3335 SERVER_END_REQ;
3337 if (ret == STATUS_SUCCESS && info->Buffer)
3339 PFILE_NOTIFY_INFORMATION pfni = info->Buffer;
3340 int i, left = info->BufferSize;
3341 DWORD *last_entry_offset = NULL;
3342 struct filesystem_event *event = (struct filesystem_event*)data;
3344 while (size && left >= sizeof(*pfni))
3346 /* convert to an NT style path */
3347 for (i=0; i<event->len; i++)
3348 if (event->name[i] == '/')
3349 event->name[i] = '\\';
3351 pfni->Action = event->action;
3352 pfni->FileNameLength = ntdll_umbstowcs( 0, event->name, event->len, pfni->FileName,
3353 (left - offsetof(FILE_NOTIFY_INFORMATION, FileName)) / sizeof(WCHAR));
3354 last_entry_offset = &pfni->NextEntryOffset;
3356 if(pfni->FileNameLength == -1 || pfni->FileNameLength == -2)
3357 break;
3359 i = offsetof(FILE_NOTIFY_INFORMATION, FileName[pfni->FileNameLength]);
3360 pfni->FileNameLength *= sizeof(WCHAR);
3361 pfni->NextEntryOffset = i;
3362 pfni = (FILE_NOTIFY_INFORMATION*)((char*)pfni + i);
3363 left -= i;
3365 i = (offsetof(struct filesystem_event, name[event->len])
3366 + sizeof(int)-1) / sizeof(int) * sizeof(int);
3367 event = (struct filesystem_event*)((char*)event + i);
3368 size -= i;
3371 if (size)
3373 ret = STATUS_NOTIFY_ENUM_DIR;
3374 size = 0;
3376 else
3378 *last_entry_offset = 0;
3379 size = info->BufferSize - left;
3382 else
3384 ret = STATUS_NOTIFY_ENUM_DIR;
3385 size = 0;
3388 iosb->u.Status = ret;
3389 iosb->Information = size;
3390 *apc = read_changes_user_apc;
3391 return ret;
3394 #define FILE_NOTIFY_ALL ( \
3395 FILE_NOTIFY_CHANGE_FILE_NAME | \
3396 FILE_NOTIFY_CHANGE_DIR_NAME | \
3397 FILE_NOTIFY_CHANGE_ATTRIBUTES | \
3398 FILE_NOTIFY_CHANGE_SIZE | \
3399 FILE_NOTIFY_CHANGE_LAST_WRITE | \
3400 FILE_NOTIFY_CHANGE_LAST_ACCESS | \
3401 FILE_NOTIFY_CHANGE_CREATION | \
3402 FILE_NOTIFY_CHANGE_SECURITY )
3404 /******************************************************************************
3405 * NtNotifyChangeDirectoryFile [NTDLL.@]
3407 NTSTATUS WINAPI
3408 NtNotifyChangeDirectoryFile( HANDLE FileHandle, HANDLE Event,
3409 PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext,
3410 PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer,
3411 ULONG BufferSize, ULONG CompletionFilter, BOOLEAN WatchTree )
3413 struct read_changes_info *info;
3414 NTSTATUS status;
3415 ULONG_PTR cvalue = ApcRoutine ? 0 : (ULONG_PTR)ApcContext;
3417 TRACE("%p %p %p %p %p %p %u %u %d\n",
3418 FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock,
3419 Buffer, BufferSize, CompletionFilter, WatchTree );
3421 if (!IoStatusBlock)
3422 return STATUS_ACCESS_VIOLATION;
3424 if (CompletionFilter == 0 || (CompletionFilter & ~FILE_NOTIFY_ALL))
3425 return STATUS_INVALID_PARAMETER;
3427 info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof *info );
3428 if (!info)
3429 return STATUS_NO_MEMORY;
3431 info->FileHandle = FileHandle;
3432 info->Buffer = Buffer;
3433 info->BufferSize = BufferSize;
3434 info->apc = ApcRoutine;
3435 info->apc_arg = ApcContext;
3437 SERVER_START_REQ( read_directory_changes )
3439 req->filter = CompletionFilter;
3440 req->want_data = (Buffer != NULL);
3441 req->subtree = WatchTree;
3442 req->async.handle = wine_server_obj_handle( FileHandle );
3443 req->async.callback = wine_server_client_ptr( read_changes_apc );
3444 req->async.iosb = wine_server_client_ptr( IoStatusBlock );
3445 req->async.arg = wine_server_client_ptr( info );
3446 req->async.event = wine_server_obj_handle( Event );
3447 req->async.cvalue = cvalue;
3448 status = wine_server_call( req );
3450 SERVER_END_REQ;
3452 if (status != STATUS_PENDING)
3453 RtlFreeHeap( GetProcessHeap(), 0, info );
3455 return status;