ntdll/tests: Dump entire VM_COUNTERS structure.
[wine.git] / dlls / ntdll / directory.c
blob9d5cf92b2aa41481ec9545b607d0716d072c5fac
1 /*
2 * NTDLL directory functions
4 * Copyright 1993 Erik Bos
5 * Copyright 2003 Eric Pouech
6 * Copyright 1996, 2004 Alexandre Julliard
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include "config.h"
24 #include "wine/port.h"
26 #include <assert.h>
27 #include <sys/types.h>
28 #ifdef HAVE_DIRENT_H
29 # include <dirent.h>
30 #endif
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <stdarg.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <limits.h>
38 #ifdef HAVE_MNTENT_H
39 #include <mntent.h>
40 #endif
41 #ifdef HAVE_SYS_STAT_H
42 # include <sys/stat.h>
43 #endif
44 #ifdef HAVE_SYS_SYSCALL_H
45 # include <sys/syscall.h>
46 #endif
47 #ifdef HAVE_SYS_ATTR_H
48 #include <sys/attr.h>
49 #endif
50 #ifdef MAJOR_IN_MKDEV
51 # include <sys/mkdev.h>
52 #elif defined(MAJOR_IN_SYSMACROS)
53 # include <sys/sysmacros.h>
54 #endif
55 #ifdef HAVE_SYS_VNODE_H
56 # ifdef HAVE_STDINT_H
57 # include <stdint.h> /* needed for kfreebsd */
58 # endif
59 /* Work around a conflict with Solaris' system list defined in sys/list.h. */
60 #define list SYSLIST
61 #define list_next SYSLIST_NEXT
62 #define list_prev SYSLIST_PREV
63 #define list_head SYSLIST_HEAD
64 #define list_tail SYSLIST_TAIL
65 #define list_move_tail SYSLIST_MOVE_TAIL
66 #define list_remove SYSLIST_REMOVE
67 #include <sys/vnode.h>
68 #undef list
69 #undef list_next
70 #undef list_prev
71 #undef list_head
72 #undef list_tail
73 #undef list_move_tail
74 #undef list_remove
75 #endif
76 #ifdef HAVE_SYS_IOCTL_H
77 #include <sys/ioctl.h>
78 #endif
79 #ifdef HAVE_LINUX_IOCTL_H
80 #include <linux/ioctl.h>
81 #endif
82 #ifdef HAVE_LINUX_MAJOR_H
83 # include <linux/major.h>
84 #endif
85 #ifdef HAVE_SYS_PARAM_H
86 #include <sys/param.h>
87 #endif
88 #ifdef HAVE_SYS_MOUNT_H
89 #include <sys/mount.h>
90 #endif
91 #ifdef HAVE_SYS_STATFS_H
92 #include <sys/statfs.h>
93 #endif
94 #include <time.h>
95 #ifdef HAVE_UNISTD_H
96 # include <unistd.h>
97 #endif
99 #include "ntstatus.h"
100 #define WIN32_NO_STATUS
101 #define NONAMELESSUNION
102 #include "windef.h"
103 #include "winnt.h"
104 #include "winternl.h"
105 #include "ddk/wdm.h"
106 #include "ntdll_misc.h"
107 #include "wine/unicode.h"
108 #include "wine/server.h"
109 #include "wine/list.h"
110 #include "wine/library.h"
111 #include "wine/debug.h"
112 #include "wine/exception.h"
114 WINE_DEFAULT_DEBUG_CHANNEL(file);
116 /* just in case... */
117 #undef VFAT_IOCTL_READDIR_BOTH
119 #ifdef linux
121 /* We want the real kernel dirent structure, not the libc one */
122 typedef struct
124 long d_ino;
125 long d_off;
126 unsigned short d_reclen;
127 char d_name[256];
128 } KERNEL_DIRENT;
130 /* Define the VFAT ioctl to get both short and long file names */
131 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
133 #ifndef O_DIRECTORY
134 # define O_DIRECTORY 0200000 /* must be directory */
135 #endif
137 #endif /* linux */
139 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
140 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
142 #define INVALID_NT_CHARS '*','?','<','>','|','"'
143 #define INVALID_DOS_CHARS INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
145 #define MAX_DIR_ENTRY_LEN 255 /* max length of a directory entry in chars */
147 #define MAX_IGNORED_FILES 4
149 struct file_identity
151 dev_t dev;
152 ino_t ino;
155 static struct file_identity ignored_files[MAX_IGNORED_FILES];
156 static unsigned int ignored_files_count;
158 union file_directory_info
160 ULONG next;
161 FILE_DIRECTORY_INFORMATION dir;
162 FILE_BOTH_DIRECTORY_INFORMATION both;
163 FILE_FULL_DIRECTORY_INFORMATION full;
164 FILE_ID_BOTH_DIRECTORY_INFORMATION id_both;
165 FILE_ID_FULL_DIRECTORY_INFORMATION id_full;
166 FILE_ID_GLOBAL_TX_DIR_INFORMATION id_tx;
167 FILE_NAMES_INFORMATION names;
170 struct dir_data_buffer
172 struct dir_data_buffer *next; /* next buffer in the list */
173 unsigned int size; /* total size of the buffer */
174 unsigned int pos; /* current position in the buffer */
175 char data[1];
178 struct dir_data_names
180 const WCHAR *long_name; /* long file name in Unicode */
181 const WCHAR *short_name; /* short file name in Unicode */
182 const char *unix_name; /* Unix file name in host encoding */
185 struct dir_data
187 unsigned int size; /* size of the names array */
188 unsigned int count; /* count of used entries in the names array */
189 unsigned int pos; /* current reading position in the names array */
190 struct file_identity id; /* directory file identity */
191 struct dir_data_names *names; /* directory file names */
192 struct dir_data_buffer *buffer; /* head of data buffers list */
195 static const unsigned int dir_data_buffer_initial_size = 4096;
196 static const unsigned int dir_data_cache_initial_size = 256;
197 static const unsigned int dir_data_names_initial_size = 64;
199 static struct dir_data **dir_data_cache;
200 static unsigned int dir_data_cache_size;
202 static BOOL show_dot_files;
203 static RTL_RUN_ONCE init_once = RTL_RUN_ONCE_INIT;
205 /* at some point we may want to allow Winelib apps to set this */
206 static const BOOL is_case_sensitive = FALSE;
208 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
210 static struct file_identity windir;
212 static RTL_CRITICAL_SECTION dir_section;
213 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
215 0, 0, &dir_section,
216 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
217 0, 0, { (DWORD_PTR)(__FILE__ ": dir_section") }
219 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
222 /* check if a given Unicode char is OK in a DOS short name */
223 static inline BOOL is_invalid_dos_char( WCHAR ch )
225 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
226 if (ch > 0x7f) return TRUE;
227 return strchrW( invalid_chars, ch ) != NULL;
230 /* check if the device can be a mounted volume */
231 static inline BOOL is_valid_mounted_device( const struct stat *st )
233 #if defined(linux) || defined(__sun__)
234 return S_ISBLK( st->st_mode );
235 #else
236 /* disks are char devices on *BSD */
237 return S_ISCHR( st->st_mode );
238 #endif
241 static inline void ignore_file( const char *name )
243 struct stat st;
244 assert( ignored_files_count < MAX_IGNORED_FILES );
245 if (!stat( name, &st ))
247 ignored_files[ignored_files_count].dev = st.st_dev;
248 ignored_files[ignored_files_count].ino = st.st_ino;
249 ignored_files_count++;
253 static inline BOOL is_same_file( const struct file_identity *file, const struct stat *st )
255 return st->st_dev == file->dev && st->st_ino == file->ino;
258 static inline BOOL is_ignored_file( const struct stat *st )
260 unsigned int i;
262 for (i = 0; i < ignored_files_count; i++)
263 if (is_same_file( &ignored_files[i], st )) return TRUE;
264 return FALSE;
267 static inline unsigned int dir_info_align( unsigned int len )
269 return (len + 7) & ~7;
272 static inline unsigned int dir_info_size( FILE_INFORMATION_CLASS class, unsigned int len )
274 switch (class)
276 case FileDirectoryInformation:
277 return offsetof( FILE_DIRECTORY_INFORMATION, FileName[len] );
278 case FileBothDirectoryInformation:
279 return offsetof( FILE_BOTH_DIRECTORY_INFORMATION, FileName[len] );
280 case FileFullDirectoryInformation:
281 return offsetof( FILE_FULL_DIRECTORY_INFORMATION, FileName[len] );
282 case FileIdBothDirectoryInformation:
283 return offsetof( FILE_ID_BOTH_DIRECTORY_INFORMATION, FileName[len] );
284 case FileIdFullDirectoryInformation:
285 return offsetof( FILE_ID_FULL_DIRECTORY_INFORMATION, FileName[len] );
286 case FileIdGlobalTxDirectoryInformation:
287 return offsetof( FILE_ID_GLOBAL_TX_DIR_INFORMATION, FileName[len] );
288 case FileNamesInformation:
289 return offsetof( FILE_NAMES_INFORMATION, FileName[len] );
290 default:
291 assert(0);
292 return 0;
296 static inline BOOL has_wildcard( const UNICODE_STRING *mask )
298 return (!mask ||
299 memchrW( mask->Buffer, '*', mask->Length / sizeof(WCHAR) ) ||
300 memchrW( mask->Buffer, '?', mask->Length / sizeof(WCHAR) ));
303 /* get space from the current directory data buffer, allocating a new one if necessary */
304 static void *get_dir_data_space( struct dir_data *data, unsigned int size )
306 struct dir_data_buffer *buffer = data->buffer;
307 void *ret;
309 if (!buffer || size > buffer->size - buffer->pos)
311 unsigned int new_size = buffer ? buffer->size * 2 : dir_data_buffer_initial_size;
312 if (new_size < size) new_size = size;
313 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0,
314 offsetof( struct dir_data_buffer, data[new_size] ) ))) return NULL;
315 buffer->pos = 0;
316 buffer->size = new_size;
317 buffer->next = data->buffer;
318 data->buffer = buffer;
320 ret = buffer->data + buffer->pos;
321 buffer->pos += size;
322 return ret;
325 /* add a string to the directory data buffer */
326 static const char *add_dir_data_nameA( struct dir_data *data, const char *name )
328 /* keep buffer data WCHAR-aligned */
329 char *ptr = get_dir_data_space( data, (strlen( name ) + sizeof(WCHAR)) & ~(sizeof(WCHAR) - 1) );
330 if (ptr) strcpy( ptr, name );
331 return ptr;
334 /* add a Unicode string to the directory data buffer */
335 static const WCHAR *add_dir_data_nameW( struct dir_data *data, const WCHAR *name )
337 WCHAR *ptr = get_dir_data_space( data, (strlenW( name ) + 1) * sizeof(WCHAR) );
338 if (ptr) strcpyW( ptr, name );
339 return ptr;
342 /* add an entry to the directory names array */
343 static BOOL add_dir_data_names( struct dir_data *data, const WCHAR *long_name,
344 const WCHAR *short_name, const char *unix_name )
346 static const WCHAR empty[1];
347 struct dir_data_names *names = data->names;
349 if (data->count >= data->size)
351 unsigned int new_size = max( data->size * 2, dir_data_names_initial_size );
353 if (names) names = RtlReAllocateHeap( GetProcessHeap(), 0, names, new_size * sizeof(*names) );
354 else names = RtlAllocateHeap( GetProcessHeap(), 0, new_size * sizeof(*names) );
355 if (!names) return FALSE;
356 data->size = new_size;
357 data->names = names;
360 if (short_name[0])
362 if (!(names[data->count].short_name = add_dir_data_nameW( data, short_name ))) return FALSE;
364 else names[data->count].short_name = empty;
366 if (!(names[data->count].long_name = add_dir_data_nameW( data, long_name ))) return FALSE;
367 if (!(names[data->count].unix_name = add_dir_data_nameA( data, unix_name ))) return FALSE;
368 data->count++;
369 return TRUE;
372 /* free the complete directory data structure */
373 static void free_dir_data( struct dir_data *data )
375 struct dir_data_buffer *buffer, *next;
377 if (!data) return;
379 for (buffer = data->buffer; buffer; buffer = next)
381 next = buffer->next;
382 RtlFreeHeap( GetProcessHeap(), 0, buffer );
384 RtlFreeHeap( GetProcessHeap(), 0, data->names );
385 RtlFreeHeap( GetProcessHeap(), 0, data );
389 /* support for a directory queue for filesystem searches */
391 struct dir_name
393 struct list entry;
394 char name[1];
397 static struct list dir_queue = LIST_INIT( dir_queue );
399 static NTSTATUS add_dir_to_queue( const char *name )
401 int len = strlen( name ) + 1;
402 struct dir_name *dir = RtlAllocateHeap( GetProcessHeap(), 0,
403 FIELD_OFFSET( struct dir_name, name[len] ));
404 if (!dir) return STATUS_NO_MEMORY;
405 strcpy( dir->name, name );
406 list_add_tail( &dir_queue, &dir->entry );
407 return STATUS_SUCCESS;
410 static NTSTATUS next_dir_in_queue( char *name )
412 struct list *head = list_head( &dir_queue );
413 if (head)
415 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
416 strcpy( name, dir->name );
417 list_remove( &dir->entry );
418 RtlFreeHeap( GetProcessHeap(), 0, dir );
419 return STATUS_SUCCESS;
421 return STATUS_OBJECT_NAME_NOT_FOUND;
424 static void flush_dir_queue(void)
426 struct list *head;
428 while ((head = list_head( &dir_queue )))
430 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
431 list_remove( &dir->entry );
432 RtlFreeHeap( GetProcessHeap(), 0, dir );
437 #ifdef __ANDROID__
439 static char *unescape_field( char *str )
441 char *in, *out;
443 for (in = out = str; *in; in++, out++)
445 *out = *in;
446 if (in[0] == '\\')
448 if (in[1] == '\\')
450 out[0] = '\\';
451 in++;
453 else if (in[1] == '0' && in[2] == '4' && in[3] == '0')
455 out[0] = ' ';
456 in += 3;
458 else if (in[1] == '0' && in[2] == '1' && in[3] == '1')
460 out[0] = '\t';
461 in += 3;
463 else if (in[1] == '0' && in[2] == '1' && in[3] == '2')
465 out[0] = '\n';
466 in += 3;
468 else if (in[1] == '1' && in[2] == '3' && in[3] == '4')
470 out[0] = '\\';
471 in += 3;
475 *out = '\0';
477 return str;
480 static inline char *get_field( char **str )
482 char *ret;
484 ret = strsep( str, " \t" );
485 if (*str) *str += strspn( *str, " \t" );
487 return ret;
489 /************************************************************************
490 * getmntent_replacement
492 * getmntent replacement for Android.
494 * NB returned static buffer is not thread safe; protect with dir_section.
496 static struct mntent *getmntent_replacement( FILE *f )
498 static struct mntent entry;
499 static char buf[4096];
500 char *p, *start;
504 if (!fgets( buf, sizeof(buf), f )) return NULL;
505 p = strchr( buf, '\n' );
506 if (p) *p = '\0';
507 else /* Partially unread line, move file ptr to end */
509 char tmp[1024];
510 while (fgets( tmp, sizeof(tmp), f ))
511 if (strchr( tmp, '\n' )) break;
513 start = buf + strspn( buf, " \t" );
514 } while (start[0] == '\0' || start[0] == '#');
516 p = get_field( &start );
517 entry.mnt_fsname = p ? unescape_field( p ) : (char *)"";
519 p = get_field( &start );
520 entry.mnt_dir = p ? unescape_field( p ) : (char *)"";
522 p = get_field( &start );
523 entry.mnt_type = p ? unescape_field( p ) : (char *)"";
525 p = get_field( &start );
526 entry.mnt_opts = p ? unescape_field( p ) : (char *)"";
528 p = get_field( &start );
529 entry.mnt_freq = p ? atoi(p) : 0;
531 p = get_field( &start );
532 entry.mnt_passno = p ? atoi(p) : 0;
534 return &entry;
536 #define getmntent getmntent_replacement
537 #endif
539 /***********************************************************************
540 * DIR_get_drives_info
542 * Retrieve device/inode number for all the drives. Helper for find_drive_root.
544 unsigned int DIR_get_drives_info( struct drive_info info[MAX_DOS_DRIVES] )
546 static struct drive_info cache[MAX_DOS_DRIVES];
547 static time_t last_update;
548 static unsigned int nb_drives;
549 unsigned int ret;
550 time_t now = time(NULL);
552 RtlEnterCriticalSection( &dir_section );
553 if (now != last_update)
555 const char *config_dir = wine_get_config_dir();
556 char *buffer, *p;
557 struct stat st;
558 unsigned int i;
560 if ((buffer = RtlAllocateHeap( GetProcessHeap(), 0,
561 strlen(config_dir) + sizeof("/dosdevices/a:") )))
563 strcpy( buffer, config_dir );
564 strcat( buffer, "/dosdevices/a:" );
565 p = buffer + strlen(buffer) - 2;
567 for (i = nb_drives = 0; i < MAX_DOS_DRIVES; i++)
569 *p = 'a' + i;
570 if (!stat( buffer, &st ))
572 cache[i].dev = st.st_dev;
573 cache[i].ino = st.st_ino;
574 nb_drives++;
576 else
578 cache[i].dev = 0;
579 cache[i].ino = 0;
582 RtlFreeHeap( GetProcessHeap(), 0, buffer );
584 last_update = now;
586 memcpy( info, cache, sizeof(cache) );
587 ret = nb_drives;
588 RtlLeaveCriticalSection( &dir_section );
589 return ret;
593 /***********************************************************************
594 * parse_mount_entries
596 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
599 #ifdef sun
600 #include <sys/vfstab.h>
601 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
603 struct vfstab entry;
604 struct stat st;
605 char *device;
607 while (! getvfsent( f, &entry ))
609 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
610 if (!strcmp( entry.vfs_fstype, "nfs" ) ||
611 !strcmp( entry.vfs_fstype, "smbfs" ) ||
612 !strcmp( entry.vfs_fstype, "ncpfs" )) continue;
614 if (stat( entry.vfs_mountp, &st ) == -1) continue;
615 if (st.st_dev != dev || st.st_ino != ino) continue;
616 if (!strcmp( entry.vfs_fstype, "fd" ))
618 if ((device = strstr( entry.vfs_mntopts, "dev=" )))
620 char *p = strchr( device + 4, ',' );
621 if (p) *p = 0;
622 return device + 4;
625 else
626 return entry.vfs_special;
628 return NULL;
630 #endif
632 #ifdef linux
633 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
635 struct mntent *entry;
636 struct stat st;
637 char *device;
639 while ((entry = getmntent( f )))
641 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
642 if (!strcmp( entry->mnt_type, "nfs" ) ||
643 !strcmp( entry->mnt_type, "smbfs" ) ||
644 !strcmp( entry->mnt_type, "ncpfs" )) continue;
646 if (stat( entry->mnt_dir, &st ) == -1) continue;
647 if (st.st_dev != dev || st.st_ino != ino) continue;
648 if (!strcmp( entry->mnt_type, "supermount" ))
650 if ((device = strstr( entry->mnt_opts, "dev=" )))
652 char *p = strchr( device + 4, ',' );
653 if (p) *p = 0;
654 return device + 4;
657 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
659 /* if device is a regular file check for a loop mount */
660 if ((device = strstr( entry->mnt_opts, "loop=" )))
662 char *p = strchr( device + 5, ',' );
663 if (p) *p = 0;
664 return device + 5;
667 else
668 return entry->mnt_fsname;
670 return NULL;
672 #endif
674 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
675 #include <fstab.h>
676 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
678 struct fstab *entry;
679 struct stat st;
681 while ((entry = getfsent()))
683 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
684 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
685 !strcmp( entry->fs_vfstype, "smbfs" ) ||
686 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
688 if (stat( entry->fs_file, &st ) == -1) continue;
689 if (st.st_dev != dev || st.st_ino != ino) continue;
690 return entry->fs_spec;
692 return NULL;
694 #endif
696 #ifdef sun
697 #include <sys/mnttab.h>
698 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
700 struct mnttab entry;
701 struct stat st;
702 char *device;
705 while (( ! getmntent( f, &entry) ))
707 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
708 if (!strcmp( entry.mnt_fstype, "nfs" ) ||
709 !strcmp( entry.mnt_fstype, "smbfs" ) ||
710 !strcmp( entry.mnt_fstype, "ncpfs" )) continue;
712 if (stat( entry.mnt_mountp, &st ) == -1) continue;
713 if (st.st_dev != dev || st.st_ino != ino) continue;
714 if (!strcmp( entry.mnt_fstype, "fd" ))
716 if ((device = strstr( entry.mnt_mntopts, "dev=" )))
718 char *p = strchr( device + 4, ',' );
719 if (p) *p = 0;
720 return device + 4;
723 else
724 return entry.mnt_special;
726 return NULL;
728 #endif
730 /***********************************************************************
731 * get_default_drive_device
733 * Return the default device to use for a given drive mount point.
735 static char *get_default_drive_device( const char *root )
737 char *ret = NULL;
739 #ifdef linux
740 FILE *f;
741 char *device = NULL;
742 int fd, res = -1;
743 struct stat st;
745 /* try to open it first to force it to get mounted */
746 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
748 res = fstat( fd, &st );
749 close( fd );
751 /* now try normal stat just in case */
752 if (res == -1) res = stat( root, &st );
753 if (res == -1) return NULL;
755 RtlEnterCriticalSection( &dir_section );
757 #ifdef __ANDROID__
758 if ((f = fopen( "/proc/mounts", "r" )))
760 device = parse_mount_entries( f, st.st_dev, st.st_ino );
761 fclose( f );
763 #else
764 if ((f = fopen( "/etc/mtab", "r" )))
766 device = parse_mount_entries( f, st.st_dev, st.st_ino );
767 fclose( f );
769 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
770 if (!device && (f = fopen( "/etc/fstab", "r" )))
772 device = parse_mount_entries( f, st.st_dev, st.st_ino );
773 fclose( f );
775 #endif
776 if (device)
778 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
779 if (ret) strcpy( ret, device );
781 RtlLeaveCriticalSection( &dir_section );
783 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ ) || defined(__DragonFly__)
784 char *device = NULL;
785 int fd, res = -1;
786 struct stat st;
788 /* try to open it first to force it to get mounted */
789 if ((fd = open( root, O_RDONLY )) != -1)
791 res = fstat( fd, &st );
792 close( fd );
794 /* now try normal stat just in case */
795 if (res == -1) res = stat( root, &st );
796 if (res == -1) return NULL;
798 RtlEnterCriticalSection( &dir_section );
800 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
801 * pass NULL. Leave the argument in for symmetry.
803 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
804 if (device)
806 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
807 if (ret) strcpy( ret, device );
809 RtlLeaveCriticalSection( &dir_section );
811 #elif defined( sun )
812 FILE *f;
813 char *device = NULL;
814 int fd, res = -1;
815 struct stat st;
817 /* try to open it first to force it to get mounted */
818 if ((fd = open( root, O_RDONLY )) != -1)
820 res = fstat( fd, &st );
821 close( fd );
823 /* now try normal stat just in case */
824 if (res == -1) res = stat( root, &st );
825 if (res == -1) return NULL;
827 RtlEnterCriticalSection( &dir_section );
829 if ((f = fopen( "/etc/mnttab", "r" )))
831 device = parse_mount_entries( f, st.st_dev, st.st_ino);
832 fclose( f );
834 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
835 if (!device && (f = fopen( "/etc/vfstab", "r" )))
837 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
838 fclose( f );
840 if (device)
842 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
843 if (ret) strcpy( ret, device );
845 RtlLeaveCriticalSection( &dir_section );
847 #elif defined(__APPLE__)
848 struct statfs *mntStat;
849 struct stat st;
850 int i;
851 int mntSize;
852 dev_t dev;
853 ino_t ino;
854 static const char path_bsd_device[] = "/dev/disk";
855 int res;
857 res = stat( root, &st );
858 if (res == -1) return NULL;
860 dev = st.st_dev;
861 ino = st.st_ino;
863 RtlEnterCriticalSection( &dir_section );
865 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
867 for (i = 0; i < mntSize && !ret; i++)
869 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
870 if (st.st_dev != dev || st.st_ino != ino) continue;
872 /* FIXME add support for mounted network drive */
873 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
875 /* set return value to the corresponding raw BSD node */
876 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
877 if (ret)
879 strcpy(ret, "/dev/r");
880 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
884 RtlLeaveCriticalSection( &dir_section );
885 #else
886 static int warned;
887 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
888 #endif
889 return ret;
893 /***********************************************************************
894 * get_device_mount_point
896 * Return the current mount point for a device.
898 static char *get_device_mount_point( dev_t dev )
900 char *ret = NULL;
902 #ifdef linux
903 FILE *f;
905 RtlEnterCriticalSection( &dir_section );
907 #ifdef __ANDROID__
908 if ((f = fopen( "/proc/mounts", "r" )))
909 #else
910 if ((f = fopen( "/etc/mtab", "r" )))
911 #endif
913 struct mntent *entry;
914 struct stat st;
915 char *p, *device;
917 while ((entry = getmntent( f )))
919 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
920 if (!strcmp( entry->mnt_type, "nfs" ) ||
921 !strcmp( entry->mnt_type, "smbfs" ) ||
922 !strcmp( entry->mnt_type, "ncpfs" )) continue;
924 if (!strcmp( entry->mnt_type, "supermount" ))
926 if ((device = strstr( entry->mnt_opts, "dev=" )))
928 device += 4;
929 if ((p = strchr( device, ',' ))) *p = 0;
932 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
934 /* if device is a regular file check for a loop mount */
935 if ((device = strstr( entry->mnt_opts, "loop=" )))
937 device += 5;
938 if ((p = strchr( device, ',' ))) *p = 0;
941 else device = entry->mnt_fsname;
943 if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
945 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
946 if (ret) strcpy( ret, entry->mnt_dir );
947 break;
950 fclose( f );
952 RtlLeaveCriticalSection( &dir_section );
953 #elif defined(__APPLE__)
954 struct statfs *entry;
955 struct stat st;
956 int i, size;
958 RtlEnterCriticalSection( &dir_section );
960 size = getmntinfo( &entry, MNT_NOWAIT );
961 for (i = 0; i < size; i++)
963 if (stat( entry[i].f_mntfromname, &st ) == -1) continue;
964 if (S_ISBLK(st.st_mode) && st.st_rdev == dev)
966 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry[i].f_mntonname) + 1 );
967 if (ret) strcpy( ret, entry[i].f_mntonname );
968 break;
971 RtlLeaveCriticalSection( &dir_section );
972 #else
973 static int warned;
974 if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
975 #endif
976 return ret;
980 #if defined(HAVE_GETATTRLIST) && defined(ATTR_VOL_CAPABILITIES) && \
981 defined(VOL_CAPABILITIES_FORMAT) && defined(VOL_CAP_FMT_CASE_SENSITIVE)
983 struct get_fsid
985 ULONG size;
986 dev_t dev;
987 fsid_t fsid;
990 struct fs_cache
992 dev_t dev;
993 fsid_t fsid;
994 BOOLEAN case_sensitive;
995 } fs_cache[64];
997 struct vol_caps
999 ULONG size;
1000 vol_capabilities_attr_t caps;
1003 /***********************************************************************
1004 * look_up_fs_cache
1006 * Checks if the specified file system is in the cache.
1008 static struct fs_cache *look_up_fs_cache( dev_t dev )
1010 int i;
1011 for (i = 0; i < sizeof(fs_cache)/sizeof(fs_cache[0]); i++)
1012 if (fs_cache[i].dev == dev)
1013 return fs_cache+i;
1014 return NULL;
1017 /***********************************************************************
1018 * add_fs_cache
1020 * Adds the specified file system to the cache.
1022 static void add_fs_cache( dev_t dev, fsid_t fsid, BOOLEAN case_sensitive )
1024 int i;
1025 struct fs_cache *entry = look_up_fs_cache( dev );
1026 static int once = 0;
1027 if (entry)
1029 /* Update the cache */
1030 entry->fsid = fsid;
1031 entry->case_sensitive = case_sensitive;
1032 return;
1035 /* Add a new entry */
1036 for (i = 0; i < sizeof(fs_cache)/sizeof(fs_cache[0]); i++)
1037 if (fs_cache[i].dev == 0)
1039 /* This entry is empty, use it */
1040 fs_cache[i].dev = dev;
1041 fs_cache[i].fsid = fsid;
1042 fs_cache[i].case_sensitive = case_sensitive;
1043 return;
1046 /* Cache is out of space, warn */
1047 if (!once++)
1048 WARN( "FS cache is out of space, expect performance problems\n" );
1051 /***********************************************************************
1052 * get_dir_case_sensitivity_attr
1054 * Checks if the volume containing the specified directory is case
1055 * sensitive or not. Uses getattrlist(2).
1057 static int get_dir_case_sensitivity_attr( const char *dir )
1059 char *mntpoint;
1060 struct attrlist attr;
1061 struct vol_caps caps;
1062 struct get_fsid get_fsid;
1063 struct fs_cache *entry;
1065 /* First get the FS ID of the volume */
1066 attr.bitmapcount = ATTR_BIT_MAP_COUNT;
1067 attr.reserved = 0;
1068 attr.commonattr = ATTR_CMN_DEVID|ATTR_CMN_FSID;
1069 attr.volattr = attr.dirattr = attr.fileattr = attr.forkattr = 0;
1070 get_fsid.size = 0;
1071 if (getattrlist( dir, &attr, &get_fsid, sizeof(get_fsid), 0 ) != 0 ||
1072 get_fsid.size != sizeof(get_fsid))
1073 return -1;
1074 /* Try to look it up in the cache */
1075 entry = look_up_fs_cache( get_fsid.dev );
1076 if (entry && !memcmp( &entry->fsid, &get_fsid.fsid, sizeof(fsid_t) ))
1077 /* Cache lookup succeeded */
1078 return entry->case_sensitive;
1079 /* Cache is stale at this point, we have to update it */
1081 mntpoint = get_device_mount_point( get_fsid.dev );
1082 /* Now look up the case-sensitivity */
1083 attr.commonattr = 0;
1084 attr.volattr = ATTR_VOL_INFO|ATTR_VOL_CAPABILITIES;
1085 if (getattrlist( mntpoint, &attr, &caps, sizeof(caps), 0 ) < 0)
1087 RtlFreeHeap( GetProcessHeap(), 0, mntpoint );
1088 add_fs_cache( get_fsid.dev, get_fsid.fsid, TRUE );
1089 return TRUE;
1091 RtlFreeHeap( GetProcessHeap(), 0, mntpoint );
1092 if (caps.size == sizeof(caps) &&
1093 (caps.caps.valid[VOL_CAPABILITIES_FORMAT] &
1094 (VOL_CAP_FMT_CASE_SENSITIVE | VOL_CAP_FMT_CASE_PRESERVING)) ==
1095 (VOL_CAP_FMT_CASE_SENSITIVE | VOL_CAP_FMT_CASE_PRESERVING))
1097 BOOLEAN ret;
1099 if ((caps.caps.capabilities[VOL_CAPABILITIES_FORMAT] &
1100 VOL_CAP_FMT_CASE_SENSITIVE) != VOL_CAP_FMT_CASE_SENSITIVE)
1101 ret = FALSE;
1102 else
1103 ret = TRUE;
1104 /* Update the cache */
1105 add_fs_cache( get_fsid.dev, get_fsid.fsid, ret );
1106 return ret;
1108 return FALSE;
1110 #endif
1112 /***********************************************************************
1113 * get_dir_case_sensitivity_stat
1115 * Checks if the volume containing the specified directory is case
1116 * sensitive or not. Uses statfs(2) or statvfs(2).
1118 static BOOLEAN get_dir_case_sensitivity_stat( const char *dir )
1120 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1121 struct statfs stfs;
1123 if (statfs( dir, &stfs ) == -1) return FALSE;
1124 /* Assume these file systems are always case insensitive on Mac OS.
1125 * For FreeBSD, only assume CIOPFS is case insensitive (AFAIK, Mac OS
1126 * is the only UNIX that supports case-insensitive lookup).
1128 if (!strcmp( stfs.f_fstypename, "fusefs" ) &&
1129 !strncmp( stfs.f_mntfromname, "ciopfs", 5 ))
1130 return FALSE;
1131 #ifdef __APPLE__
1132 if (!strcmp( stfs.f_fstypename, "msdos" ) ||
1133 !strcmp( stfs.f_fstypename, "cd9660" ) ||
1134 !strcmp( stfs.f_fstypename, "udf" ) ||
1135 !strcmp( stfs.f_fstypename, "ntfs" ) ||
1136 !strcmp( stfs.f_fstypename, "smbfs" ))
1137 return FALSE;
1138 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1139 if (!strcmp( stfs.f_fstypename, "hfs" ) && (stfs.f_fssubtype == 0 ||
1140 stfs.f_fssubtype == 1 ||
1141 stfs.f_fssubtype == 128))
1142 return FALSE;
1143 #else
1144 /* The field says "reserved", but a quick look at the kernel source
1145 * tells us that this "reserved" field is really the same as the
1146 * "fssubtype" field from the inode64 structure (see munge_statfs()
1147 * in <xnu-source>/bsd/vfs/vfs_syscalls.c).
1149 if (!strcmp( stfs.f_fstypename, "hfs" ) && (stfs.f_reserved1 == 0 ||
1150 stfs.f_reserved1 == 1 ||
1151 stfs.f_reserved1 == 128))
1152 return FALSE;
1153 #endif
1154 #endif
1155 return TRUE;
1157 #elif defined(__NetBSD__)
1158 struct statvfs stfs;
1160 if (statvfs( dir, &stfs ) == -1) return FALSE;
1161 /* Only assume CIOPFS is case insensitive. */
1162 if (strcmp( stfs.f_fstypename, "fusefs" ) ||
1163 strncmp( stfs.f_mntfromname, "ciopfs", 5 ))
1164 return TRUE;
1165 return FALSE;
1167 #elif defined(__linux__)
1168 struct statfs stfs;
1169 struct stat st;
1170 char *cifile;
1172 /* Only assume CIOPFS is case insensitive. */
1173 if (statfs( dir, &stfs ) == -1) return FALSE;
1174 if (stfs.f_type != 0x65735546 /* FUSE_SUPER_MAGIC */)
1175 return TRUE;
1176 /* Normally, we'd have to parse the mtab to find out exactly what
1177 * kind of FUSE FS this is. But, someone on wine-devel suggested
1178 * a shortcut. We'll stat a special file in the directory. If it's
1179 * there, we'll assume it's a CIOPFS, else not.
1180 * This will break if somebody puts a file named ".ciopfs" in a non-
1181 * CIOPFS directory.
1183 cifile = RtlAllocateHeap( GetProcessHeap(), 0, strlen( dir )+sizeof("/.ciopfs") );
1184 if (!cifile) return TRUE;
1185 strcpy( cifile, dir );
1186 strcat( cifile, "/.ciopfs" );
1187 if (stat( cifile, &st ) == 0)
1189 RtlFreeHeap( GetProcessHeap(), 0, cifile );
1190 return FALSE;
1192 RtlFreeHeap( GetProcessHeap(), 0, cifile );
1193 return TRUE;
1194 #else
1195 return TRUE;
1196 #endif
1200 /***********************************************************************
1201 * get_dir_case_sensitivity
1203 * Checks if the volume containing the specified directory is case
1204 * sensitive or not. Uses statfs(2) or statvfs(2).
1206 static BOOLEAN get_dir_case_sensitivity( const char *dir )
1208 #if defined(HAVE_GETATTRLIST) && defined(ATTR_VOL_CAPABILITIES) && \
1209 defined(VOL_CAPABILITIES_FORMAT) && defined(VOL_CAP_FMT_CASE_SENSITIVE)
1210 int case_sensitive = get_dir_case_sensitivity_attr( dir );
1211 if (case_sensitive != -1) return case_sensitive;
1212 #endif
1213 return get_dir_case_sensitivity_stat( dir );
1217 /***********************************************************************
1218 * init_options
1220 * Initialize the show_dot_files options.
1222 static DWORD WINAPI init_options( RTL_RUN_ONCE *once, void *param, void **context )
1224 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
1225 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
1226 char tmp[80];
1227 HANDLE root, hkey;
1228 DWORD dummy;
1229 OBJECT_ATTRIBUTES attr;
1230 UNICODE_STRING nameW;
1232 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
1233 attr.Length = sizeof(attr);
1234 attr.RootDirectory = root;
1235 attr.ObjectName = &nameW;
1236 attr.Attributes = 0;
1237 attr.SecurityDescriptor = NULL;
1238 attr.SecurityQualityOfService = NULL;
1239 RtlInitUnicodeString( &nameW, WineW );
1241 /* @@ Wine registry key: HKCU\Software\Wine */
1242 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
1244 RtlInitUnicodeString( &nameW, ShowDotFilesW );
1245 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
1247 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
1248 show_dot_files = IS_OPTION_TRUE( str[0] );
1250 NtClose( hkey );
1252 NtClose( root );
1254 /* a couple of directories that we don't want to return in directory searches */
1255 ignore_file( wine_get_config_dir() );
1256 ignore_file( "/dev" );
1257 ignore_file( "/proc" );
1258 #ifdef linux
1259 ignore_file( "/sys" );
1260 #endif
1261 return TRUE;
1265 /***********************************************************************
1266 * DIR_is_hidden_file
1268 * Check if the specified file should be hidden based on its name and the show dot files option.
1270 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
1272 WCHAR *p, *end;
1274 RtlRunOnceExecuteOnce( &init_once, init_options, NULL, NULL );
1276 if (show_dot_files) return FALSE;
1278 end = p = name->Buffer + name->Length/sizeof(WCHAR);
1279 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
1280 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
1281 if (p == end || *p != '.') return FALSE;
1282 /* make sure it isn't '.' or '..' */
1283 if (p + 1 == end) return FALSE;
1284 if (p[1] == '.' && p + 2 == end) return FALSE;
1285 return TRUE;
1289 /***********************************************************************
1290 * hash_short_file_name
1292 * Transform a Unix file name into a hashed DOS name. If the name is a valid
1293 * DOS name, it is converted to upper-case; otherwise it is replaced by a
1294 * hashed version that fits in 8.3 format.
1295 * 'buffer' must be at least 12 characters long.
1296 * Returns length of short name in bytes; short name is NOT null-terminated.
1298 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
1300 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
1302 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
1303 LPWSTR dst;
1304 unsigned short hash;
1305 int i;
1307 /* Compute the hash code of the file name */
1308 /* If you know something about hash functions, feel free to */
1309 /* insert a better algorithm here... */
1310 if (!is_case_sensitive)
1312 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
1313 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
1314 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
1316 else
1318 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
1319 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
1320 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
1323 /* Find last dot for start of the extension */
1324 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
1326 /* Copy first 4 chars, replacing invalid chars with '_' */
1327 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
1329 if (p == end || p == ext) break;
1330 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
1332 /* Pad to 5 chars with '~' */
1333 while (i-- >= 0) *dst++ = '~';
1335 /* Insert hash code converted to 3 ASCII chars */
1336 *dst++ = hash_chars[(hash >> 10) & 0x1f];
1337 *dst++ = hash_chars[(hash >> 5) & 0x1f];
1338 *dst++ = hash_chars[hash & 0x1f];
1340 /* Copy the first 3 chars of the extension (if any) */
1341 if (ext)
1343 *dst++ = '.';
1344 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
1345 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
1347 return dst - buffer;
1351 /***********************************************************************
1352 * match_filename
1354 * Check a long file name against a mask.
1356 * Tests (done in W95 DOS shell - case insensitive):
1357 * *.txt test1.test.txt *
1358 * *st1* test1.txt *
1359 * *.t??????.t* test1.ta.tornado.txt *
1360 * *tornado* test1.ta.tornado.txt *
1361 * t*t test1.ta.tornado.txt *
1362 * ?est* test1.txt *
1363 * ?est??? test1.txt -
1364 * *test1.txt* test1.txt *
1365 * h?l?o*t.dat hellothisisatest.dat *
1367 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
1369 BOOL mismatch;
1370 const WCHAR *name = name_str->Buffer;
1371 const WCHAR *mask = mask_str->Buffer;
1372 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
1373 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
1374 const WCHAR *lastjoker = NULL;
1375 const WCHAR *next_to_retry = NULL;
1377 while (name < name_end && mask < mask_end)
1379 switch(*mask)
1381 case '*':
1382 mask++;
1383 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
1384 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
1385 lastjoker = mask;
1387 /* skip to the next match after the joker(s) */
1388 if (is_case_sensitive)
1389 while (name < name_end && (*name != *mask)) name++;
1390 else
1391 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
1392 next_to_retry = name;
1393 break;
1394 case '?':
1395 mask++;
1396 name++;
1397 break;
1398 default:
1399 if (is_case_sensitive) mismatch = (*mask != *name);
1400 else mismatch = (toupperW(*mask) != toupperW(*name));
1402 if (!mismatch)
1404 mask++;
1405 name++;
1406 if (mask == mask_end)
1408 if (name == name_end) return TRUE;
1409 if (lastjoker) mask = lastjoker;
1412 else /* mismatch ! */
1414 if (lastjoker) /* we had an '*', so we can try unlimitedly */
1416 mask = lastjoker;
1418 /* this scan sequence was a mismatch, so restart
1419 * 1 char after the first char we checked last time */
1420 next_to_retry++;
1421 name = next_to_retry;
1423 else return FALSE; /* bad luck */
1425 break;
1428 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
1429 mask++; /* Ignore trailing '.' or '*' in mask */
1430 return (name == name_end && mask == mask_end);
1434 /***********************************************************************
1435 * append_entry
1437 * Add a file to the directory data if it matches the mask.
1439 static BOOL append_entry( struct dir_data *data, const char *long_name,
1440 const char *short_name, const UNICODE_STRING *mask )
1442 int i, long_len, short_len;
1443 WCHAR long_nameW[MAX_DIR_ENTRY_LEN + 1];
1444 WCHAR short_nameW[13];
1445 UNICODE_STRING str;
1447 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
1448 if (long_len == -1) return TRUE;
1449 long_nameW[long_len] = 0;
1451 str.Buffer = long_nameW;
1452 str.Length = long_len * sizeof(WCHAR);
1453 str.MaximumLength = sizeof(long_nameW);
1455 if (short_name)
1457 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
1458 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) - 1 );
1459 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR) - 1;
1460 for (i = 0; i < short_len; i++) short_nameW[i] = toupperW( short_nameW[i] );
1462 else /* generate a short name if necessary */
1464 BOOLEAN spaces;
1466 short_len = 0;
1467 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1468 short_len = hash_short_file_name( &str, short_nameW );
1470 short_nameW[short_len] = 0;
1472 TRACE( "long %s short %s mask %s\n",
1473 debugstr_w( long_nameW ), debugstr_w( short_nameW ), debugstr_us( mask ));
1475 if (mask && !match_filename( &str, mask ))
1477 if (!short_len) return TRUE; /* no short name to match */
1478 str.Buffer = short_nameW;
1479 str.Length = short_len * sizeof(WCHAR);
1480 str.MaximumLength = sizeof(short_nameW);
1481 if (!match_filename( &str, mask )) return TRUE;
1484 return add_dir_data_names( data, long_nameW, short_nameW, long_name );
1488 /***********************************************************************
1489 * get_dir_data_entry
1491 * Return a directory entry from the cached data.
1493 static NTSTATUS get_dir_data_entry( struct dir_data *dir_data, void *info_ptr, IO_STATUS_BLOCK *io,
1494 ULONG max_length, FILE_INFORMATION_CLASS class,
1495 union file_directory_info **last_info )
1497 const struct dir_data_names *names = &dir_data->names[dir_data->pos];
1498 union file_directory_info *info;
1499 struct stat st;
1500 ULONG name_len, start, dir_size, attributes;
1502 if (get_file_info( names->unix_name, &st, &attributes ) == -1)
1504 TRACE( "file no longer exists %s\n", names->unix_name );
1505 return STATUS_SUCCESS;
1507 if (is_ignored_file( &st ))
1509 TRACE( "ignoring file %s\n", names->unix_name );
1510 return STATUS_SUCCESS;
1512 start = dir_info_align( io->Information );
1513 dir_size = dir_info_size( class, 0 );
1514 if (start + dir_size > max_length) return STATUS_MORE_ENTRIES;
1516 max_length -= start + dir_size;
1517 name_len = strlenW( names->long_name ) * sizeof(WCHAR);
1518 /* if this is not the first entry, fail; the first entry is always returned (but truncated) */
1519 if (*last_info && name_len > max_length) return STATUS_MORE_ENTRIES;
1521 info = (union file_directory_info *)((char *)info_ptr + start);
1522 info->dir.NextEntryOffset = 0;
1523 info->dir.FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
1525 /* all the structures except FileNamesInformation start with a FileDirectoryInformation layout */
1526 if (class != FileNamesInformation)
1528 if (st.st_dev != dir_data->id.dev) st.st_ino = 0; /* ignore inode if on a different device */
1530 if (!show_dot_files && names->long_name[0] == '.' && names->long_name[1] &&
1531 (names->long_name[1] != '.' || names->long_name[2]))
1532 attributes |= FILE_ATTRIBUTE_HIDDEN;
1534 fill_file_info( &st, attributes, info, class );
1537 switch (class)
1539 case FileDirectoryInformation:
1540 info->dir.FileNameLength = name_len;
1541 break;
1543 case FileFullDirectoryInformation:
1544 info->full.EaSize = 0; /* FIXME */
1545 info->full.FileNameLength = name_len;
1546 break;
1548 case FileIdFullDirectoryInformation:
1549 info->id_full.EaSize = 0; /* FIXME */
1550 info->id_full.FileNameLength = name_len;
1551 break;
1553 case FileBothDirectoryInformation:
1554 info->both.EaSize = 0; /* FIXME */
1555 info->both.ShortNameLength = strlenW( names->short_name ) * sizeof(WCHAR);
1556 memcpy( info->both.ShortName, names->short_name, info->both.ShortNameLength );
1557 info->both.FileNameLength = name_len;
1558 break;
1560 case FileIdBothDirectoryInformation:
1561 info->id_both.EaSize = 0; /* FIXME */
1562 info->id_both.ShortNameLength = strlenW( names->short_name ) * sizeof(WCHAR);
1563 memcpy( info->id_both.ShortName, names->short_name, info->id_both.ShortNameLength );
1564 info->id_both.FileNameLength = name_len;
1565 break;
1567 case FileIdGlobalTxDirectoryInformation:
1568 info->id_tx.TxInfoFlags = 0;
1569 info->id_tx.FileNameLength = name_len;
1570 break;
1572 case FileNamesInformation:
1573 info->names.FileNameLength = name_len;
1574 break;
1576 default:
1577 assert(0);
1578 return 0;
1581 memcpy( (char *)info + dir_size, names->long_name, min( name_len, max_length ) );
1582 io->Information = start + dir_size + min( name_len, max_length );
1583 if (*last_info) (*last_info)->next = (char *)info - (char *)*last_info;
1584 *last_info = info;
1585 return name_len > max_length ? STATUS_BUFFER_OVERFLOW : STATUS_SUCCESS;
1588 #ifdef VFAT_IOCTL_READDIR_BOTH
1590 /***********************************************************************
1591 * start_vfat_ioctl
1593 * Wrapper for the VFAT ioctl to work around various kernel bugs.
1594 * dir_section must be held by caller.
1596 static KERNEL_DIRENT *start_vfat_ioctl( int fd )
1598 static KERNEL_DIRENT *de;
1599 int res;
1601 if (!de)
1603 SIZE_T size = 2 * sizeof(*de) + page_size;
1604 void *addr = NULL;
1606 if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_RESERVE, PAGE_READWRITE ))
1607 return NULL;
1608 /* commit only the size needed for the dir entries */
1609 /* this leaves an extra unaccessible page, which should make the kernel */
1610 /* fail with -EFAULT before it stomps all over our memory */
1611 de = addr;
1612 size = 2 * sizeof(*de);
1613 NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_COMMIT, PAGE_READWRITE );
1616 /* set d_reclen to 65535 to work around an AFS kernel bug */
1617 de[0].d_reclen = 65535;
1618 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
1619 if (res == -1)
1621 if (errno != ENOENT) return NULL; /* VFAT ioctl probably not supported */
1622 de[0].d_reclen = 0; /* eof */
1624 else if (!res && de[0].d_reclen == 65535) return NULL; /* AFS bug */
1626 return de;
1630 /***********************************************************************
1631 * read_directory_vfat
1633 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
1635 static NTSTATUS read_directory_data_vfat( struct dir_data *data, int fd, const UNICODE_STRING *mask )
1637 char *short_name, *long_name;
1638 size_t len;
1639 KERNEL_DIRENT *de;
1640 NTSTATUS status = STATUS_NO_MEMORY;
1641 off_t old_pos = lseek( fd, 0, SEEK_CUR );
1643 if (!(de = start_vfat_ioctl( fd ))) return STATUS_NOT_SUPPORTED;
1645 lseek( fd, 0, SEEK_SET );
1647 if (!append_entry( data, ".", NULL, mask )) goto done;
1648 if (!append_entry( data, "..", NULL, mask )) goto done;
1650 while (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) != -1)
1652 if (!de[0].d_reclen) break; /* eof */
1654 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1655 len = min( de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1656 de[0].d_name[len] = 0;
1657 len = min( de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1658 de[1].d_name[len] = 0;
1660 if (!strcmp( de[0].d_name, "." ) || !strcmp( de[0].d_name, ".." )) continue;
1661 if (de[1].d_name[0])
1663 short_name = de[0].d_name;
1664 long_name = de[1].d_name;
1666 else
1668 long_name = de[0].d_name;
1669 short_name = NULL;
1671 if (!append_entry( data, long_name, short_name, mask )) goto done;
1673 status = STATUS_SUCCESS;
1674 done:
1675 lseek( fd, old_pos, SEEK_SET );
1676 return status;
1678 #endif /* VFAT_IOCTL_READDIR_BOTH */
1681 #ifdef HAVE_GETATTRLIST
1682 /***********************************************************************
1683 * read_directory_getattrlist
1685 * Read a single file from a directory by determining whether the file
1686 * identified by mask exists using getattrlist.
1688 static NTSTATUS read_directory_data_getattrlist( struct dir_data *data, const char *unix_name )
1690 struct attrlist attrlist;
1691 #include "pshpack4.h"
1692 struct
1694 u_int32_t length;
1695 struct attrreference name_reference;
1696 fsobj_type_t type;
1697 char name[NAME_MAX * 3 + 1];
1698 } buffer;
1699 #include "poppack.h"
1701 memset( &attrlist, 0, sizeof(attrlist) );
1702 attrlist.bitmapcount = ATTR_BIT_MAP_COUNT;
1703 attrlist.commonattr = ATTR_CMN_NAME | ATTR_CMN_OBJTYPE;
1704 if (getattrlist( unix_name, &attrlist, &buffer, sizeof(buffer), FSOPT_NOFOLLOW ) == -1)
1705 return STATUS_NO_SUCH_FILE;
1706 /* If unix_name named a symlink, the above may have succeeded even if the symlink is broken.
1707 Check that with another call without FSOPT_NOFOLLOW. We don't ask for any attributes. */
1708 if (buffer.type == VLNK)
1710 u_int32_t dummy;
1711 attrlist.commonattr = 0;
1712 if (getattrlist( unix_name, &attrlist, &dummy, sizeof(dummy), 0 ) == -1)
1713 return STATUS_NO_SUCH_FILE;
1716 TRACE( "found %s\n", buffer.name );
1718 if (!append_entry( data, buffer.name, NULL, NULL )) return STATUS_NO_MEMORY;
1720 return STATUS_SUCCESS;
1722 #endif /* HAVE_GETATTRLIST */
1725 /***********************************************************************
1726 * read_directory_stat
1728 * Read a single file from a directory by determining whether the file
1729 * identified by mask exists using stat.
1731 static NTSTATUS read_directory_data_stat( struct dir_data *data, const char *unix_name )
1733 struct stat st;
1735 /* if the file system is not case sensitive we can't find the actual name through stat() */
1736 if (!get_dir_case_sensitivity(".")) return STATUS_NO_SUCH_FILE;
1737 if (stat( unix_name, &st ) == -1) return STATUS_NO_SUCH_FILE;
1739 TRACE( "found %s\n", unix_name );
1741 if (!append_entry( data, unix_name, NULL, NULL )) return STATUS_NO_MEMORY;
1743 return STATUS_SUCCESS;
1747 /***********************************************************************
1748 * read_directory_readdir
1750 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1752 static NTSTATUS read_directory_data_readdir( struct dir_data *data, const UNICODE_STRING *mask )
1754 struct dirent *de;
1755 NTSTATUS status = STATUS_NO_MEMORY;
1756 DIR *dir = opendir( "." );
1758 if (!dir) return STATUS_NO_SUCH_FILE;
1760 if (!append_entry( data, ".", NULL, mask )) goto done;
1761 if (!append_entry( data, "..", NULL, mask )) goto done;
1762 while ((de = readdir( dir )))
1764 if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
1765 if (!append_entry( data, de->d_name, NULL, mask )) goto done;
1767 status = STATUS_SUCCESS;
1769 done:
1770 closedir( dir );
1771 return status;
1775 /***********************************************************************
1776 * read_directory_data
1778 * Read the full contents of a directory, using one of the above helper functions.
1780 static NTSTATUS read_directory_data( struct dir_data *data, int fd, const UNICODE_STRING *mask )
1782 NTSTATUS status;
1784 #ifdef VFAT_IOCTL_READDIR_BOTH
1785 if (!(status = read_directory_data_vfat( data, fd, mask ))) return status;
1786 #endif
1788 if (!has_wildcard( mask ))
1790 /* convert the mask to a Unix name and check for it */
1791 int ret, used_default;
1792 char unix_name[MAX_DIR_ENTRY_LEN * 3 + 1];
1794 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR),
1795 unix_name, sizeof(unix_name) - 1, NULL, &used_default );
1796 if (ret > 0 && !used_default)
1798 unix_name[ret] = 0;
1799 #ifdef HAVE_GETATTRLIST
1800 if (!(status = read_directory_data_getattrlist( data, unix_name ))) return status;
1801 #endif
1802 if (!(status = read_directory_data_stat( data, unix_name ))) return status;
1806 return read_directory_data_readdir( data, mask );
1810 /* compare file names for directory sorting */
1811 static int name_compare( const void *a, const void *b )
1813 const struct dir_data_names *file_a = (const struct dir_data_names *)a;
1814 const struct dir_data_names *file_b = (const struct dir_data_names *)b;
1815 int ret = RtlCompareUnicodeStrings( file_a->long_name, strlenW(file_a->long_name),
1816 file_b->long_name, strlenW(file_b->long_name), TRUE );
1817 if (!ret) ret = strcmpW( file_a->long_name, file_b->long_name );
1818 return ret;
1822 /***********************************************************************
1823 * init_cached_dir_data
1825 * Initialize the cached directory contents.
1827 static NTSTATUS init_cached_dir_data( struct dir_data **data_ret, int fd, const UNICODE_STRING *mask )
1829 struct dir_data *data;
1830 struct stat st;
1831 NTSTATUS status;
1832 unsigned int i;
1834 if (!(data = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*data) )))
1835 return STATUS_NO_MEMORY;
1837 if ((status = read_directory_data( data, fd, mask )))
1839 free_dir_data( data );
1840 return status;
1843 /* sort filenames, but not "." and ".." */
1844 i = 0;
1845 if (i < data->count && !strcmp( data->names[i].unix_name, "." )) i++;
1846 if (i < data->count && !strcmp( data->names[i].unix_name, ".." )) i++;
1847 if (i < data->count) qsort( data->names + i, data->count - i, sizeof(*data->names), name_compare );
1849 if (data->count)
1851 /* release unused space */
1852 if (data->buffer)
1853 RtlReAllocateHeap( GetProcessHeap(), HEAP_REALLOC_IN_PLACE_ONLY, data->buffer,
1854 offsetof( struct dir_data_buffer, data[data->buffer->pos] ));
1855 if (data->count < data->size)
1856 RtlReAllocateHeap( GetProcessHeap(), HEAP_REALLOC_IN_PLACE_ONLY, data->names,
1857 data->count * sizeof(*data->names) );
1858 if (!fstat( fd, &st ))
1860 data->id.dev = st.st_dev;
1861 data->id.ino = st.st_ino;
1865 TRACE( "mask %s found %u files\n", debugstr_us( mask ), data->count );
1866 for (i = 0; i < data->count; i++)
1867 TRACE( "%s %s\n", debugstr_w(data->names[i].long_name), debugstr_w(data->names[i].short_name) );
1869 *data_ret = data;
1870 return data->count ? STATUS_SUCCESS : STATUS_NO_SUCH_FILE;
1874 /***********************************************************************
1875 * get_cached_dir_data
1877 * Retrieve the cached directory data, or initialize it if necessary.
1879 static NTSTATUS get_cached_dir_data( HANDLE handle, struct dir_data **data_ret, int fd,
1880 const UNICODE_STRING *mask )
1882 unsigned int i;
1883 int entry = -1, free_entries[16];
1884 NTSTATUS status;
1886 SERVER_START_REQ( get_directory_cache_entry )
1888 req->handle = wine_server_obj_handle( handle );
1889 wine_server_set_reply( req, free_entries, sizeof(free_entries) );
1890 if (!(status = wine_server_call( req ))) entry = reply->entry;
1892 for (i = 0; i < wine_server_reply_size( reply ) / sizeof(*free_entries); i++)
1894 int free_idx = free_entries[i];
1895 if (free_idx < dir_data_cache_size)
1897 free_dir_data( dir_data_cache[free_idx] );
1898 dir_data_cache[free_idx] = NULL;
1902 SERVER_END_REQ;
1904 if (status)
1906 if (status == STATUS_SHARING_VIOLATION) FIXME( "shared directory handle not supported yet\n" );
1907 return status;
1910 if (entry >= dir_data_cache_size)
1912 unsigned int size = max( dir_data_cache_initial_size, max( dir_data_cache_size * 2, entry + 1 ) );
1913 struct dir_data **new_cache;
1915 if (dir_data_cache)
1916 new_cache = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, dir_data_cache,
1917 size * sizeof(*new_cache) );
1918 else
1919 new_cache = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, size * sizeof(*new_cache) );
1920 if (!new_cache) return STATUS_NO_MEMORY;
1921 dir_data_cache = new_cache;
1922 dir_data_cache_size = size;
1925 if (!dir_data_cache[entry]) status = init_cached_dir_data( &dir_data_cache[entry], fd, mask );
1927 *data_ret = dir_data_cache[entry];
1928 return status;
1932 /******************************************************************************
1933 * NtQueryDirectoryFile [NTDLL.@]
1934 * ZwQueryDirectoryFile [NTDLL.@]
1936 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
1937 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
1938 PIO_STATUS_BLOCK io,
1939 PVOID buffer, ULONG length,
1940 FILE_INFORMATION_CLASS info_class,
1941 BOOLEAN single_entry,
1942 PUNICODE_STRING mask,
1943 BOOLEAN restart_scan )
1945 int cwd, fd, needs_close;
1946 struct dir_data *data;
1947 NTSTATUS status;
1949 TRACE("(%p %p %p %p %p %p 0x%08x 0x%08x 0x%08x %s 0x%08x\n",
1950 handle, event, apc_routine, apc_context, io, buffer,
1951 length, info_class, single_entry, debugstr_us(mask),
1952 restart_scan);
1954 if (event || apc_routine)
1956 FIXME( "Unsupported yet option\n" );
1957 return STATUS_NOT_IMPLEMENTED;
1959 switch (info_class)
1961 case FileDirectoryInformation:
1962 case FileBothDirectoryInformation:
1963 case FileFullDirectoryInformation:
1964 case FileIdBothDirectoryInformation:
1965 case FileIdFullDirectoryInformation:
1966 case FileIdGlobalTxDirectoryInformation:
1967 case FileNamesInformation:
1968 if (length < dir_info_align( dir_info_size( info_class, 1 ))) return STATUS_INFO_LENGTH_MISMATCH;
1969 break;
1970 case FileObjectIdInformation:
1971 if (length != sizeof(FILE_OBJECTID_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
1972 return STATUS_INVALID_INFO_CLASS;
1973 case FileQuotaInformation:
1974 if (length != sizeof(FILE_QUOTA_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
1975 return STATUS_INVALID_INFO_CLASS;
1976 case FileReparsePointInformation:
1977 if (length != sizeof(FILE_REPARSE_POINT_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
1978 return STATUS_INVALID_INFO_CLASS;
1979 default:
1980 return STATUS_INVALID_INFO_CLASS;
1982 if (!buffer) return STATUS_ACCESS_VIOLATION;
1984 if ((status = server_get_unix_fd( handle, FILE_LIST_DIRECTORY, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
1985 return status;
1987 io->Information = 0;
1989 RtlRunOnceExecuteOnce( &init_once, init_options, NULL, NULL );
1991 RtlEnterCriticalSection( &dir_section );
1993 cwd = open( ".", O_RDONLY );
1994 if (fchdir( fd ) != -1)
1996 if (!(status = get_cached_dir_data( handle, &data, fd, mask )))
1998 union file_directory_info *last_info = NULL;
2000 if (restart_scan) data->pos = 0;
2002 while (!status && data->pos < data->count)
2004 status = get_dir_data_entry( data, buffer, io, length, info_class, &last_info );
2005 if (!status || status == STATUS_BUFFER_OVERFLOW) data->pos++;
2006 if (single_entry) break;
2009 if (!last_info) status = STATUS_NO_MORE_FILES;
2010 else if (status == STATUS_MORE_ENTRIES) status = STATUS_SUCCESS;
2012 io->u.Status = status;
2014 if (cwd == -1 || fchdir( cwd ) == -1) chdir( "/" );
2016 else status = FILE_GetNtStatus();
2018 RtlLeaveCriticalSection( &dir_section );
2020 if (needs_close) close( fd );
2021 if (cwd != -1) close( cwd );
2022 TRACE( "=> %x (%ld)\n", status, io->Information );
2023 return status;
2027 /***********************************************************************
2028 * find_file_in_dir
2030 * Find a file in a directory the hard way, by doing a case-insensitive search.
2031 * The file found is appended to unix_name at pos.
2032 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
2034 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
2035 BOOLEAN check_case, BOOLEAN *is_win_dir )
2037 WCHAR buffer[MAX_DIR_ENTRY_LEN];
2038 UNICODE_STRING str;
2039 BOOLEAN spaces, is_name_8_dot_3;
2040 DIR *dir;
2041 struct dirent *de;
2042 struct stat st;
2043 int ret, used_default;
2045 /* try a shortcut for this directory */
2047 unix_name[pos++] = '/';
2048 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
2049 NULL, &used_default );
2050 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
2051 /* so it cannot match the file we are looking for */
2052 if (ret >= 0 && !used_default)
2054 unix_name[pos + ret] = 0;
2055 if (!stat( unix_name, &st ))
2057 if (is_win_dir) *is_win_dir = is_same_file( &windir, &st );
2058 return STATUS_SUCCESS;
2061 if (check_case) goto not_found; /* we want an exact match */
2063 if (pos > 1) unix_name[pos - 1] = 0;
2064 else unix_name[1] = 0; /* keep the initial slash */
2066 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
2068 str.Buffer = (WCHAR *)name;
2069 str.Length = length * sizeof(WCHAR);
2070 str.MaximumLength = str.Length;
2071 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
2072 #ifndef VFAT_IOCTL_READDIR_BOTH
2073 is_name_8_dot_3 = is_name_8_dot_3 && length >= 8 && name[4] == '~';
2074 #endif
2076 if (!is_name_8_dot_3 && !get_dir_case_sensitivity( unix_name )) goto not_found;
2078 /* now look for it through the directory */
2080 #ifdef VFAT_IOCTL_READDIR_BOTH
2081 if (is_name_8_dot_3)
2083 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
2084 if (fd != -1)
2086 KERNEL_DIRENT *kde;
2088 RtlEnterCriticalSection( &dir_section );
2089 if ((kde = start_vfat_ioctl( fd )))
2091 unix_name[pos - 1] = '/';
2092 while (kde[0].d_reclen)
2094 /* make sure names are null-terminated to work around an x86-64 kernel bug */
2095 size_t len = min(kde[0].d_reclen, sizeof(kde[0].d_name) - 1 );
2096 kde[0].d_name[len] = 0;
2097 len = min(kde[1].d_reclen, sizeof(kde[1].d_name) - 1 );
2098 kde[1].d_name[len] = 0;
2100 if (kde[1].d_name[0])
2102 ret = ntdll_umbstowcs( 0, kde[1].d_name, strlen(kde[1].d_name),
2103 buffer, MAX_DIR_ENTRY_LEN );
2104 if (ret == length && !memicmpW( buffer, name, length))
2106 strcpy( unix_name + pos, kde[1].d_name );
2107 RtlLeaveCriticalSection( &dir_section );
2108 close( fd );
2109 goto success;
2112 ret = ntdll_umbstowcs( 0, kde[0].d_name, strlen(kde[0].d_name),
2113 buffer, MAX_DIR_ENTRY_LEN );
2114 if (ret == length && !memicmpW( buffer, name, length))
2116 strcpy( unix_name + pos,
2117 kde[1].d_name[0] ? kde[1].d_name : kde[0].d_name );
2118 RtlLeaveCriticalSection( &dir_section );
2119 close( fd );
2120 goto success;
2122 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)kde ) == -1)
2124 RtlLeaveCriticalSection( &dir_section );
2125 close( fd );
2126 goto not_found;
2130 RtlLeaveCriticalSection( &dir_section );
2131 close( fd );
2133 /* fall through to normal handling */
2135 #endif /* VFAT_IOCTL_READDIR_BOTH */
2137 if (!(dir = opendir( unix_name )))
2139 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
2140 else return FILE_GetNtStatus();
2142 unix_name[pos - 1] = '/';
2143 str.Buffer = buffer;
2144 str.MaximumLength = sizeof(buffer);
2145 while ((de = readdir( dir )))
2147 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
2148 if (ret == length && !memicmpW( buffer, name, length ))
2150 strcpy( unix_name + pos, de->d_name );
2151 closedir( dir );
2152 goto success;
2155 if (!is_name_8_dot_3) continue;
2157 str.Length = ret * sizeof(WCHAR);
2158 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
2160 WCHAR short_nameW[12];
2161 ret = hash_short_file_name( &str, short_nameW );
2162 if (ret == length && !memicmpW( short_nameW, name, length ))
2164 strcpy( unix_name + pos, de->d_name );
2165 closedir( dir );
2166 goto success;
2170 closedir( dir );
2172 not_found:
2173 unix_name[pos - 1] = 0;
2174 return STATUS_OBJECT_PATH_NOT_FOUND;
2176 success:
2177 if (is_win_dir && !stat( unix_name, &st )) *is_win_dir = is_same_file( &windir, &st );
2178 return STATUS_SUCCESS;
2182 #ifndef _WIN64
2184 static const WCHAR catrootW[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t',0};
2185 static const WCHAR catroot2W[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t','2',0};
2186 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};
2187 static const WCHAR driversetcW[] = {'s','y','s','t','e','m','3','2','\\','d','r','i','v','e','r','s','\\','e','t','c',0};
2188 static const WCHAR logfilesW[] = {'s','y','s','t','e','m','3','2','\\','l','o','g','f','i','l','e','s',0};
2189 static const WCHAR spoolW[] = {'s','y','s','t','e','m','3','2','\\','s','p','o','o','l',0};
2190 static const WCHAR system32W[] = {'s','y','s','t','e','m','3','2',0};
2191 static const WCHAR syswow64W[] = {'s','y','s','w','o','w','6','4',0};
2192 static const WCHAR sysnativeW[] = {'s','y','s','n','a','t','i','v','e',0};
2193 static const WCHAR regeditW[] = {'r','e','g','e','d','i','t','.','e','x','e',0};
2194 static const WCHAR wow_regeditW[] = {'s','y','s','w','o','w','6','4','\\','r','e','g','e','d','i','t','.','e','x','e',0};
2196 static struct
2198 const WCHAR *source;
2199 const WCHAR *dos_target;
2200 const char *unix_target;
2201 } redirects[] =
2203 { catrootW, NULL, NULL },
2204 { catroot2W, NULL, NULL },
2205 { driversstoreW, NULL, NULL },
2206 { driversetcW, NULL, NULL },
2207 { logfilesW, NULL, NULL },
2208 { spoolW, NULL, NULL },
2209 { system32W, syswow64W, NULL },
2210 { sysnativeW, system32W, NULL },
2211 { regeditW, wow_regeditW, NULL }
2214 static unsigned int nb_redirects;
2217 /***********************************************************************
2218 * get_redirect_target
2220 * Find the target unix name for a redirected dir.
2222 static const char *get_redirect_target( const char *windows_dir, const WCHAR *name )
2224 int used_default, len, pos, win_len = strlen( windows_dir );
2225 char *unix_name, *unix_target = NULL;
2226 NTSTATUS status;
2228 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, win_len + MAX_DIR_ENTRY_LEN + 2 )))
2229 return NULL;
2230 memcpy( unix_name, windows_dir, win_len );
2231 pos = win_len;
2233 while (*name)
2235 const WCHAR *end, *next;
2237 for (end = name; *end; end++) if (IS_SEPARATOR(*end)) break;
2238 for (next = end; *next; next++) if (!IS_SEPARATOR(*next)) break;
2240 status = find_file_in_dir( unix_name, pos, name, end - name, FALSE, NULL );
2241 if (status == STATUS_OBJECT_PATH_NOT_FOUND && !*next) /* not finding last element is ok */
2243 len = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2244 MAX_DIR_ENTRY_LEN - (pos - win_len), NULL, &used_default );
2245 if (len > 0 && !used_default)
2247 unix_name[pos] = '/';
2248 pos += len + 1;
2249 unix_name[pos] = 0;
2250 break;
2253 if (status) goto done;
2254 pos += strlen( unix_name + pos );
2255 name = next;
2258 if ((unix_target = RtlAllocateHeap( GetProcessHeap(), 0, pos - win_len )))
2259 memcpy( unix_target, unix_name + win_len + 1, pos - win_len );
2261 done:
2262 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2263 return unix_target;
2267 /***********************************************************************
2268 * init_redirects
2270 static void init_redirects(void)
2272 UNICODE_STRING nt_name;
2273 ANSI_STRING unix_name;
2274 NTSTATUS status;
2275 struct stat st;
2276 unsigned int i;
2278 if (!RtlDosPathNameToNtPathName_U( user_shared_data->NtSystemRoot, &nt_name, NULL, NULL ))
2280 ERR( "can't convert %s\n", debugstr_w(user_shared_data->NtSystemRoot) );
2281 return;
2283 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
2284 RtlFreeUnicodeString( &nt_name );
2285 if (status)
2287 ERR( "cannot open %s (%x)\n", debugstr_w(user_shared_data->NtSystemRoot), status );
2288 return;
2290 if (!stat( unix_name.Buffer, &st ))
2292 windir.dev = st.st_dev;
2293 windir.ino = st.st_ino;
2294 nb_redirects = sizeof(redirects) / sizeof(redirects[0]);
2295 for (i = 0; i < nb_redirects; i++)
2297 if (!redirects[i].dos_target) continue;
2298 redirects[i].unix_target = get_redirect_target( unix_name.Buffer, redirects[i].dos_target );
2299 TRACE( "%s -> %s\n", debugstr_w(redirects[i].source), redirects[i].unix_target );
2302 RtlFreeAnsiString( &unix_name );
2307 /***********************************************************************
2308 * match_redirect
2310 * Check if path matches a redirect name. If yes, return matched length.
2312 static int match_redirect( const WCHAR *path, int len, const WCHAR *redir, BOOLEAN check_case )
2314 int i = 0;
2316 while (i < len && *redir)
2318 if (IS_SEPARATOR(path[i]))
2320 if (*redir++ != '\\') return 0;
2321 while (i < len && IS_SEPARATOR(path[i])) i++;
2322 continue; /* move on to next path component */
2324 else if (check_case)
2326 if (path[i] != *redir) return 0;
2328 else
2330 if (tolowerW(path[i]) != tolowerW(*redir)) return 0;
2332 i++;
2333 redir++;
2335 if (*redir) return 0;
2336 if (i < len && !IS_SEPARATOR(path[i])) return 0;
2337 while (i < len && IS_SEPARATOR(path[i])) i++;
2338 return i;
2342 /***********************************************************************
2343 * get_redirect_path
2345 * Retrieve the Unix path corresponding to a redirected path if any.
2347 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, BOOLEAN check_case )
2349 unsigned int i;
2350 int len;
2352 for (i = 0; i < nb_redirects; i++)
2354 if ((len = match_redirect( name, length, redirects[i].source, check_case )))
2356 if (!redirects[i].unix_target) break;
2357 unix_name[pos++] = '/';
2358 strcpy( unix_name + pos, redirects[i].unix_target );
2359 return len;
2362 return 0;
2365 #else /* _WIN64 */
2367 /* there are no redirects on 64-bit */
2369 static const unsigned int nb_redirects = 0;
2371 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, BOOLEAN check_case )
2373 return 0;
2376 #endif
2378 /***********************************************************************
2379 * DIR_init_windows_dir
2381 void DIR_init_windows_dir( const WCHAR *win, const WCHAR *sys )
2383 /* FIXME: should probably store paths as NT file names */
2385 RtlCreateUnicodeString( &system_dir, sys );
2387 #ifndef _WIN64
2388 if (is_wow64) init_redirects();
2389 #endif
2393 /******************************************************************************
2394 * get_dos_device
2396 * Get the Unix path of a DOS device.
2398 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
2400 const char *config_dir = wine_get_config_dir();
2401 struct stat st;
2402 char *unix_name, *new_name, *dev;
2403 unsigned int i;
2404 int unix_len;
2406 /* make sure the device name is ASCII */
2407 for (i = 0; i < name_len; i++)
2408 if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
2410 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
2412 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2413 return STATUS_NO_MEMORY;
2415 strcpy( unix_name, config_dir );
2416 strcat( unix_name, "/dosdevices/" );
2417 dev = unix_name + strlen(unix_name);
2419 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
2420 dev[i] = 0;
2422 /* special case for drive devices */
2423 if (name_len == 2 && dev[1] == ':')
2425 dev[i++] = ':';
2426 dev[i] = 0;
2429 for (;;)
2431 if (!stat( unix_name, &st ))
2433 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
2434 unix_name_ret->Buffer = unix_name;
2435 unix_name_ret->Length = strlen(unix_name);
2436 unix_name_ret->MaximumLength = unix_len;
2437 return STATUS_SUCCESS;
2439 if (!dev) break;
2441 /* now try some defaults for it */
2442 if (!strcmp( dev, "aux" ))
2444 strcpy( dev, "com1" );
2445 continue;
2447 if (!strcmp( dev, "prn" ))
2449 strcpy( dev, "lpt1" );
2450 continue;
2453 new_name = NULL;
2454 if (dev[1] == ':' && dev[2] == ':') /* drive device */
2456 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
2457 new_name = get_default_drive_device( unix_name );
2460 if (!new_name) break;
2462 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2463 unix_name = new_name;
2464 unix_len = strlen(unix_name) + 1;
2465 dev = NULL; /* last try */
2467 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2468 return STATUS_BAD_DEVICE_TYPE;
2472 /* return the length of the DOS namespace prefix if any */
2473 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
2475 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
2476 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
2478 if (name->Length >= sizeof(nt_prefixW) &&
2479 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
2480 return sizeof(nt_prefixW) / sizeof(WCHAR);
2482 if (name->Length >= sizeof(dosdev_prefixW) &&
2483 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
2484 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
2486 return 0;
2490 /******************************************************************************
2491 * find_file_id
2493 * Recursively search directories from the dir queue for a given inode.
2495 static NTSTATUS find_file_id( ANSI_STRING *unix_name, ULONGLONG file_id, dev_t dev )
2497 unsigned int pos;
2498 DIR *dir;
2499 struct dirent *de;
2500 NTSTATUS status;
2501 struct stat st;
2503 while (!(status = next_dir_in_queue( unix_name->Buffer )))
2505 if (!(dir = opendir( unix_name->Buffer ))) continue;
2506 TRACE( "searching %s for %s\n", unix_name->Buffer, wine_dbgstr_longlong(file_id) );
2507 pos = strlen( unix_name->Buffer );
2508 if (pos + MAX_DIR_ENTRY_LEN >= unix_name->MaximumLength/sizeof(WCHAR))
2510 char *new = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name->Buffer,
2511 unix_name->MaximumLength * 2 );
2512 if (!new)
2514 closedir( dir );
2515 return STATUS_NO_MEMORY;
2517 unix_name->MaximumLength *= 2;
2518 unix_name->Buffer = new;
2520 unix_name->Buffer[pos++] = '/';
2521 while ((de = readdir( dir )))
2523 if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
2524 strcpy( unix_name->Buffer + pos, de->d_name );
2525 if (lstat( unix_name->Buffer, &st ) == -1) continue;
2526 if (st.st_dev != dev) continue;
2527 if (st.st_ino == file_id)
2529 closedir( dir );
2530 return STATUS_SUCCESS;
2532 if (!S_ISDIR( st.st_mode )) continue;
2533 if ((status = add_dir_to_queue( unix_name->Buffer )) != STATUS_SUCCESS)
2535 closedir( dir );
2536 return status;
2539 closedir( dir );
2541 return status;
2545 /******************************************************************************
2546 * file_id_to_unix_file_name
2548 * Lookup a file from its file id instead of its name.
2550 NTSTATUS file_id_to_unix_file_name( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name )
2552 enum server_fd_type type;
2553 int old_cwd, root_fd, needs_close;
2554 NTSTATUS status;
2555 ULONGLONG file_id;
2556 struct stat st, root_st;
2558 if (attr->ObjectName->Length != sizeof(ULONGLONG)) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2559 if (!attr->RootDirectory) return STATUS_INVALID_PARAMETER;
2560 memcpy( &file_id, attr->ObjectName->Buffer, sizeof(file_id) );
2562 unix_name->MaximumLength = 2 * MAX_DIR_ENTRY_LEN + 4;
2563 if (!(unix_name->Buffer = RtlAllocateHeap( GetProcessHeap(), 0, unix_name->MaximumLength )))
2564 return STATUS_NO_MEMORY;
2565 strcpy( unix_name->Buffer, "." );
2567 if ((status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
2568 goto done;
2570 if (type != FD_TYPE_DIR)
2572 status = STATUS_OBJECT_TYPE_MISMATCH;
2573 goto done;
2576 fstat( root_fd, &root_st );
2577 if (root_st.st_ino == file_id) /* shortcut for "." */
2579 status = STATUS_SUCCESS;
2580 goto done;
2583 RtlEnterCriticalSection( &dir_section );
2584 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2586 /* shortcut for ".." */
2587 if (!stat( "..", &st ) && st.st_dev == root_st.st_dev && st.st_ino == file_id)
2589 strcpy( unix_name->Buffer, ".." );
2590 status = STATUS_SUCCESS;
2592 else
2594 status = add_dir_to_queue( "." );
2595 if (!status)
2596 status = find_file_id( unix_name, file_id, root_st.st_dev );
2597 if (!status) /* get rid of "./" prefix */
2598 memmove( unix_name->Buffer, unix_name->Buffer + 2, strlen(unix_name->Buffer) - 1 );
2599 flush_dir_queue();
2601 if (fchdir( old_cwd ) == -1) chdir( "/" );
2603 else status = FILE_GetNtStatus();
2604 RtlLeaveCriticalSection( &dir_section );
2605 if (old_cwd != -1) close( old_cwd );
2607 done:
2608 if (status == STATUS_SUCCESS)
2610 TRACE( "%s -> %s\n", wine_dbgstr_longlong(file_id), debugstr_a(unix_name->Buffer) );
2611 unix_name->Length = strlen( unix_name->Buffer );
2613 else
2615 TRACE( "%s not found in dir %p\n", wine_dbgstr_longlong(file_id), attr->RootDirectory );
2616 RtlFreeHeap( GetProcessHeap(), 0, unix_name->Buffer );
2618 if (needs_close) close( root_fd );
2619 return status;
2623 /******************************************************************************
2624 * lookup_unix_name
2626 * Helper for nt_to_unix_file_name
2628 static NTSTATUS lookup_unix_name( const WCHAR *name, int name_len, char **buffer, int unix_len, int pos,
2629 UINT disposition, BOOLEAN check_case )
2631 NTSTATUS status;
2632 int ret, used_default, len;
2633 struct stat st;
2634 char *unix_name = *buffer;
2635 const BOOL redirect = nb_redirects && ntdll_get_thread_data()->wow64_redir;
2637 /* try a shortcut first */
2639 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
2640 NULL, &used_default );
2642 while (name_len && IS_SEPARATOR(*name))
2644 name++;
2645 name_len--;
2648 if (ret >= 0 && !used_default) /* if we used the default char the name didn't convert properly */
2650 char *p;
2651 unix_name[pos + ret] = 0;
2652 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
2653 if (!redirect || (!strstr( unix_name, "/windows/") && strncmp( unix_name, "windows/", 8 )))
2655 if (!stat( unix_name, &st ))
2657 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
2658 if (disposition == FILE_CREATE)
2659 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
2660 return STATUS_SUCCESS;
2665 if (!name_len) /* empty name -> drive root doesn't exist */
2666 return STATUS_OBJECT_PATH_NOT_FOUND;
2667 if (check_case && !redirect && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
2668 return STATUS_OBJECT_NAME_NOT_FOUND;
2670 /* now do it component by component */
2672 while (name_len)
2674 const WCHAR *end, *next;
2675 BOOLEAN is_win_dir = FALSE;
2677 end = name;
2678 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
2679 next = end;
2680 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
2681 name_len -= next - name;
2683 /* grow the buffer if needed */
2685 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
2687 char *new_name;
2688 unix_len += 2 * MAX_DIR_ENTRY_LEN;
2689 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
2690 return STATUS_NO_MEMORY;
2691 unix_name = *buffer = new_name;
2694 status = find_file_in_dir( unix_name, pos, name, end - name,
2695 check_case, redirect ? &is_win_dir : NULL );
2697 /* if this is the last element, not finding it is not necessarily fatal */
2698 if (!name_len)
2700 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
2702 status = STATUS_OBJECT_NAME_NOT_FOUND;
2703 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
2705 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2706 MAX_DIR_ENTRY_LEN, NULL, &used_default );
2707 if (ret > 0 && !used_default)
2709 unix_name[pos] = '/';
2710 unix_name[pos + 1 + ret] = 0;
2711 status = STATUS_NO_SUCH_FILE;
2712 break;
2716 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
2718 status = STATUS_OBJECT_NAME_COLLISION;
2722 if (status != STATUS_SUCCESS) break;
2724 pos += strlen( unix_name + pos );
2725 name = next;
2727 if (is_win_dir && (len = get_redirect_path( unix_name, pos, name, name_len, check_case )))
2729 name += len;
2730 name_len -= len;
2731 pos += strlen( unix_name + pos );
2732 TRACE( "redirecting -> %s + %s\n", debugstr_a(unix_name), debugstr_w(name) );
2736 return status;
2740 /******************************************************************************
2741 * nt_to_unix_file_name_attr
2743 NTSTATUS nt_to_unix_file_name_attr( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name_ret,
2744 UINT disposition )
2746 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2747 enum server_fd_type type;
2748 int old_cwd, root_fd, needs_close;
2749 const WCHAR *name, *p;
2750 char *unix_name;
2751 int name_len, unix_len;
2752 NTSTATUS status;
2753 BOOLEAN check_case = !(attr->Attributes & OBJ_CASE_INSENSITIVE);
2755 if (!attr->RootDirectory) /* without root dir fall back to normal lookup */
2756 return wine_nt_to_unix_file_name( attr->ObjectName, unix_name_ret, disposition, check_case );
2758 name = attr->ObjectName->Buffer;
2759 name_len = attr->ObjectName->Length / sizeof(WCHAR);
2761 if (name_len && IS_SEPARATOR(name[0])) return STATUS_INVALID_PARAMETER;
2763 /* check for invalid characters */
2764 for (p = name; p < name + name_len; p++)
2765 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2767 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
2768 unix_len += MAX_DIR_ENTRY_LEN + 3;
2769 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2770 return STATUS_NO_MEMORY;
2771 unix_name[0] = '.';
2773 if (!(status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
2775 if (type != FD_TYPE_DIR)
2777 if (needs_close) close( root_fd );
2778 status = STATUS_BAD_DEVICE_TYPE;
2780 else
2782 RtlEnterCriticalSection( &dir_section );
2783 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2785 status = lookup_unix_name( name, name_len, &unix_name, unix_len, 1,
2786 disposition, check_case );
2787 if (fchdir( old_cwd ) == -1) chdir( "/" );
2789 else status = FILE_GetNtStatus();
2790 RtlLeaveCriticalSection( &dir_section );
2791 if (old_cwd != -1) close( old_cwd );
2792 if (needs_close) close( root_fd );
2795 else if (status == STATUS_OBJECT_TYPE_MISMATCH) status = STATUS_BAD_DEVICE_TYPE;
2797 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
2799 TRACE( "%s -> %s\n", debugstr_us(attr->ObjectName), debugstr_a(unix_name) );
2800 unix_name_ret->Buffer = unix_name;
2801 unix_name_ret->Length = strlen(unix_name);
2802 unix_name_ret->MaximumLength = unix_len;
2804 else
2806 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
2807 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2809 return status;
2813 /******************************************************************************
2814 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
2816 * Convert a file name from NT namespace to Unix namespace.
2818 * If disposition is not FILE_OPEN or FILE_OVERWRITE, the last path
2819 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
2820 * returned, but the unix name is still filled in properly.
2822 NTSTATUS CDECL wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
2823 UINT disposition, BOOLEAN check_case )
2825 static const WCHAR unixW[] = {'u','n','i','x'};
2826 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2828 NTSTATUS status = STATUS_SUCCESS;
2829 const char *config_dir = wine_get_config_dir();
2830 const WCHAR *name, *p;
2831 struct stat st;
2832 char *unix_name;
2833 int pos, ret, name_len, unix_len, prefix_len, used_default;
2834 WCHAR prefix[MAX_DIR_ENTRY_LEN];
2835 BOOLEAN is_unix = FALSE;
2837 name = nameW->Buffer;
2838 name_len = nameW->Length / sizeof(WCHAR);
2840 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2842 if (!(pos = get_dos_prefix_len( nameW )))
2843 return STATUS_BAD_DEVICE_TYPE; /* no DOS prefix, assume NT native name */
2845 name += pos;
2846 name_len -= pos;
2848 if (!name_len) return STATUS_OBJECT_NAME_INVALID;
2850 /* check for sub-directory */
2851 for (pos = 0; pos < name_len; pos++)
2853 if (IS_SEPARATOR(name[pos])) break;
2854 if (name[pos] < 32 || strchrW( invalid_charsW, name[pos] ))
2855 return STATUS_OBJECT_NAME_INVALID;
2857 if (pos > MAX_DIR_ENTRY_LEN)
2858 return STATUS_OBJECT_NAME_INVALID;
2860 if (pos == name_len) /* no subdir, plain DOS device */
2861 return get_dos_device( name, name_len, unix_name_ret );
2863 for (prefix_len = 0; prefix_len < pos; prefix_len++)
2864 prefix[prefix_len] = tolowerW(name[prefix_len]);
2866 name += prefix_len;
2867 name_len -= prefix_len;
2869 /* check for invalid characters (all chars except 0 are valid for unix) */
2870 is_unix = (prefix_len == 4 && !memcmp( prefix, unixW, sizeof(unixW) ));
2871 if (is_unix)
2873 for (p = name; p < name + name_len; p++)
2874 if (!*p) return STATUS_OBJECT_NAME_INVALID;
2875 check_case = TRUE;
2877 else
2879 for (p = name; p < name + name_len; p++)
2880 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2883 unix_len = ntdll_wcstoumbs( 0, prefix, prefix_len, NULL, 0, NULL, NULL );
2884 unix_len += ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
2885 unix_len += MAX_DIR_ENTRY_LEN + 3;
2886 unix_len += strlen(config_dir) + sizeof("/dosdevices/");
2887 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2888 return STATUS_NO_MEMORY;
2889 strcpy( unix_name, config_dir );
2890 strcat( unix_name, "/dosdevices/" );
2891 pos = strlen(unix_name);
2893 ret = ntdll_wcstoumbs( 0, prefix, prefix_len, unix_name + pos, unix_len - pos - 1,
2894 NULL, &used_default );
2895 if (!ret || used_default)
2897 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2898 return STATUS_OBJECT_NAME_INVALID;
2900 pos += ret;
2902 /* check if prefix exists (except for DOS drives to avoid extra stat calls) */
2904 if (prefix_len != 2 || prefix[1] != ':')
2906 unix_name[pos] = 0;
2907 if (lstat( unix_name, &st ) == -1 && errno == ENOENT)
2909 if (!is_unix)
2911 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2912 return STATUS_BAD_DEVICE_TYPE;
2914 pos = 0; /* fall back to unix root */
2918 status = lookup_unix_name( name, name_len, &unix_name, unix_len, pos, disposition, check_case );
2919 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
2921 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
2922 unix_name_ret->Buffer = unix_name;
2923 unix_name_ret->Length = strlen(unix_name);
2924 unix_name_ret->MaximumLength = unix_len;
2926 else
2928 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
2929 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2931 return status;
2935 /******************************************************************
2936 * RtlWow64EnableFsRedirection (NTDLL.@)
2938 NTSTATUS WINAPI RtlWow64EnableFsRedirection( BOOLEAN enable )
2940 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
2941 ntdll_get_thread_data()->wow64_redir = enable;
2942 return STATUS_SUCCESS;
2946 /******************************************************************
2947 * RtlWow64EnableFsRedirectionEx (NTDLL.@)
2949 NTSTATUS WINAPI RtlWow64EnableFsRedirectionEx( ULONG disable, ULONG *old_value )
2951 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
2953 __TRY
2955 *old_value = !ntdll_get_thread_data()->wow64_redir;
2957 __EXCEPT_PAGE_FAULT
2959 return STATUS_ACCESS_VIOLATION;
2961 __ENDTRY
2963 ntdll_get_thread_data()->wow64_redir = !disable;
2964 return STATUS_SUCCESS;
2968 /******************************************************************
2969 * RtlDoesFileExists_U (NTDLL.@)
2971 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
2973 UNICODE_STRING nt_name;
2974 FILE_BASIC_INFORMATION basic_info;
2975 OBJECT_ATTRIBUTES attr;
2976 BOOLEAN ret;
2978 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
2980 attr.Length = sizeof(attr);
2981 attr.RootDirectory = 0;
2982 attr.ObjectName = &nt_name;
2983 attr.Attributes = OBJ_CASE_INSENSITIVE;
2984 attr.SecurityDescriptor = NULL;
2985 attr.SecurityQualityOfService = NULL;
2987 ret = NtQueryAttributesFile(&attr, &basic_info) == STATUS_SUCCESS;
2989 RtlFreeUnicodeString( &nt_name );
2990 return ret;
2994 /***********************************************************************
2995 * DIR_unmount_device
2997 * Unmount the specified device.
2999 NTSTATUS DIR_unmount_device( HANDLE handle )
3001 NTSTATUS status;
3002 int unix_fd, needs_close;
3004 if (!(status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )))
3006 struct stat st;
3007 char *mount_point = NULL;
3009 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
3010 status = STATUS_INVALID_PARAMETER;
3011 else
3013 if ((mount_point = get_device_mount_point( st.st_rdev )))
3015 #ifdef __APPLE__
3016 static const char umount[] = "diskutil unmount >/dev/null 2>&1 ";
3017 #else
3018 static const char umount[] = "umount >/dev/null 2>&1 ";
3019 #endif
3020 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
3021 if (cmd)
3023 strcpy( cmd, umount );
3024 strcat( cmd, mount_point );
3025 system( cmd );
3026 RtlFreeHeap( GetProcessHeap(), 0, cmd );
3027 #ifdef linux
3028 /* umount will fail to release the loop device since we still have
3029 a handle to it, so we release it here */
3030 if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
3031 #endif
3033 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
3036 if (needs_close) close( unix_fd );
3038 return status;
3042 /******************************************************************************
3043 * DIR_get_unix_cwd
3045 * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
3046 * Returned value must be freed by caller.
3048 NTSTATUS DIR_get_unix_cwd( char **cwd )
3050 int old_cwd, unix_fd, needs_close;
3051 CURDIR *curdir;
3052 HANDLE handle;
3053 NTSTATUS status;
3055 RtlAcquirePebLock();
3057 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
3058 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
3059 else
3060 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
3062 if (!(handle = curdir->Handle))
3064 UNICODE_STRING dirW;
3065 OBJECT_ATTRIBUTES attr;
3066 IO_STATUS_BLOCK io;
3068 if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
3070 status = STATUS_OBJECT_NAME_INVALID;
3071 goto done;
3073 attr.Length = sizeof(attr);
3074 attr.RootDirectory = 0;
3075 attr.Attributes = OBJ_CASE_INSENSITIVE;
3076 attr.ObjectName = &dirW;
3077 attr.SecurityDescriptor = NULL;
3078 attr.SecurityQualityOfService = NULL;
3080 status = NtOpenFile( &handle, SYNCHRONIZE, &attr, &io, 0,
3081 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
3082 RtlFreeUnicodeString( &dirW );
3083 if (status != STATUS_SUCCESS) goto done;
3086 if ((status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )) == STATUS_SUCCESS)
3088 RtlEnterCriticalSection( &dir_section );
3090 if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
3092 unsigned int size = 512;
3094 for (;;)
3096 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
3098 status = STATUS_NO_MEMORY;
3099 break;
3101 if (getcwd( *cwd, size )) break;
3102 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
3103 if (errno != ERANGE)
3105 status = STATUS_OBJECT_PATH_INVALID;
3106 break;
3108 size *= 2;
3110 if (fchdir( old_cwd ) == -1) chdir( "/" );
3112 else status = FILE_GetNtStatus();
3114 RtlLeaveCriticalSection( &dir_section );
3115 if (old_cwd != -1) close( old_cwd );
3116 if (needs_close) close( unix_fd );
3118 if (!curdir->Handle) NtClose( handle );
3120 done:
3121 RtlReleasePebLock();
3122 return status;