comctl32/tests: Make test_combo_WS_VSCROLL() static.
[wine.git] / dlls / ntdll / directory.c
blob3b76f9bfd3ff0e04bb8eae2b1c0aa8f4025d5340
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, "cifs" ) ||
644 !strcmp( entry->mnt_type, "smbfs" ) ||
645 !strcmp( entry->mnt_type, "ncpfs" )) continue;
647 if (stat( entry->mnt_dir, &st ) == -1) continue;
648 if (st.st_dev != dev || st.st_ino != ino) continue;
649 if (!strcmp( entry->mnt_type, "supermount" ))
651 if ((device = strstr( entry->mnt_opts, "dev=" )))
653 char *p = strchr( device + 4, ',' );
654 if (p) *p = 0;
655 return device + 4;
658 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
660 /* if device is a regular file check for a loop mount */
661 if ((device = strstr( entry->mnt_opts, "loop=" )))
663 char *p = strchr( device + 5, ',' );
664 if (p) *p = 0;
665 return device + 5;
668 else
669 return entry->mnt_fsname;
671 return NULL;
673 #endif
675 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
676 #include <fstab.h>
677 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
679 struct fstab *entry;
680 struct stat st;
682 while ((entry = getfsent()))
684 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
685 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
686 !strcmp( entry->fs_vfstype, "smbfs" ) ||
687 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
689 if (stat( entry->fs_file, &st ) == -1) continue;
690 if (st.st_dev != dev || st.st_ino != ino) continue;
691 return entry->fs_spec;
693 return NULL;
695 #endif
697 #ifdef sun
698 #include <sys/mnttab.h>
699 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
701 struct mnttab entry;
702 struct stat st;
703 char *device;
706 while (( ! getmntent( f, &entry) ))
708 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
709 if (!strcmp( entry.mnt_fstype, "nfs" ) ||
710 !strcmp( entry.mnt_fstype, "smbfs" ) ||
711 !strcmp( entry.mnt_fstype, "ncpfs" )) continue;
713 if (stat( entry.mnt_mountp, &st ) == -1) continue;
714 if (st.st_dev != dev || st.st_ino != ino) continue;
715 if (!strcmp( entry.mnt_fstype, "fd" ))
717 if ((device = strstr( entry.mnt_mntopts, "dev=" )))
719 char *p = strchr( device + 4, ',' );
720 if (p) *p = 0;
721 return device + 4;
724 else
725 return entry.mnt_special;
727 return NULL;
729 #endif
731 /***********************************************************************
732 * get_default_drive_device
734 * Return the default device to use for a given drive mount point.
736 static char *get_default_drive_device( const char *root )
738 char *ret = NULL;
740 #ifdef linux
741 FILE *f;
742 char *device = NULL;
743 int fd, res = -1;
744 struct stat st;
746 /* try to open it first to force it to get mounted */
747 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
749 res = fstat( fd, &st );
750 close( fd );
752 /* now try normal stat just in case */
753 if (res == -1) res = stat( root, &st );
754 if (res == -1) return NULL;
756 RtlEnterCriticalSection( &dir_section );
758 #ifdef __ANDROID__
759 if ((f = fopen( "/proc/mounts", "r" )))
761 device = parse_mount_entries( f, st.st_dev, st.st_ino );
762 fclose( f );
764 #else
765 if ((f = fopen( "/etc/mtab", "r" )))
767 device = parse_mount_entries( f, st.st_dev, st.st_ino );
768 fclose( f );
770 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
771 if (!device && (f = fopen( "/etc/fstab", "r" )))
773 device = parse_mount_entries( f, st.st_dev, st.st_ino );
774 fclose( f );
776 #endif
777 if (device)
779 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
780 if (ret) strcpy( ret, device );
782 RtlLeaveCriticalSection( &dir_section );
784 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ ) || defined(__DragonFly__)
785 char *device = NULL;
786 int fd, res = -1;
787 struct stat st;
789 /* try to open it first to force it to get mounted */
790 if ((fd = open( root, O_RDONLY )) != -1)
792 res = fstat( fd, &st );
793 close( fd );
795 /* now try normal stat just in case */
796 if (res == -1) res = stat( root, &st );
797 if (res == -1) return NULL;
799 RtlEnterCriticalSection( &dir_section );
801 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
802 * pass NULL. Leave the argument in for symmetry.
804 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
805 if (device)
807 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
808 if (ret) strcpy( ret, device );
810 RtlLeaveCriticalSection( &dir_section );
812 #elif defined( sun )
813 FILE *f;
814 char *device = NULL;
815 int fd, res = -1;
816 struct stat st;
818 /* try to open it first to force it to get mounted */
819 if ((fd = open( root, O_RDONLY )) != -1)
821 res = fstat( fd, &st );
822 close( fd );
824 /* now try normal stat just in case */
825 if (res == -1) res = stat( root, &st );
826 if (res == -1) return NULL;
828 RtlEnterCriticalSection( &dir_section );
830 if ((f = fopen( "/etc/mnttab", "r" )))
832 device = parse_mount_entries( f, st.st_dev, st.st_ino);
833 fclose( f );
835 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
836 if (!device && (f = fopen( "/etc/vfstab", "r" )))
838 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
839 fclose( f );
841 if (device)
843 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
844 if (ret) strcpy( ret, device );
846 RtlLeaveCriticalSection( &dir_section );
848 #elif defined(__APPLE__)
849 struct statfs *mntStat;
850 struct stat st;
851 int i;
852 int mntSize;
853 dev_t dev;
854 ino_t ino;
855 static const char path_bsd_device[] = "/dev/disk";
856 int res;
858 res = stat( root, &st );
859 if (res == -1) return NULL;
861 dev = st.st_dev;
862 ino = st.st_ino;
864 RtlEnterCriticalSection( &dir_section );
866 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
868 for (i = 0; i < mntSize && !ret; i++)
870 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
871 if (st.st_dev != dev || st.st_ino != ino) continue;
873 /* FIXME add support for mounted network drive */
874 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
876 /* set return value to the corresponding raw BSD node */
877 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
878 if (ret)
880 strcpy(ret, "/dev/r");
881 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
885 RtlLeaveCriticalSection( &dir_section );
886 #else
887 static int warned;
888 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
889 #endif
890 return ret;
894 /***********************************************************************
895 * get_device_mount_point
897 * Return the current mount point for a device.
899 static char *get_device_mount_point( dev_t dev )
901 char *ret = NULL;
903 #ifdef linux
904 FILE *f;
906 RtlEnterCriticalSection( &dir_section );
908 #ifdef __ANDROID__
909 if ((f = fopen( "/proc/mounts", "r" )))
910 #else
911 if ((f = fopen( "/etc/mtab", "r" )))
912 #endif
914 struct mntent *entry;
915 struct stat st;
916 char *p, *device;
918 while ((entry = getmntent( f )))
920 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
921 if (!strcmp( entry->mnt_type, "nfs" ) ||
922 !strcmp( entry->mnt_type, "cifs" ) ||
923 !strcmp( entry->mnt_type, "smbfs" ) ||
924 !strcmp( entry->mnt_type, "ncpfs" )) continue;
926 if (!strcmp( entry->mnt_type, "supermount" ))
928 if ((device = strstr( entry->mnt_opts, "dev=" )))
930 device += 4;
931 if ((p = strchr( device, ',' ))) *p = 0;
934 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
936 /* if device is a regular file check for a loop mount */
937 if ((device = strstr( entry->mnt_opts, "loop=" )))
939 device += 5;
940 if ((p = strchr( device, ',' ))) *p = 0;
943 else device = entry->mnt_fsname;
945 if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
947 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
948 if (ret) strcpy( ret, entry->mnt_dir );
949 break;
952 fclose( f );
954 RtlLeaveCriticalSection( &dir_section );
955 #elif defined(__APPLE__)
956 struct statfs *entry;
957 struct stat st;
958 int i, size;
960 RtlEnterCriticalSection( &dir_section );
962 size = getmntinfo( &entry, MNT_NOWAIT );
963 for (i = 0; i < size; i++)
965 if (stat( entry[i].f_mntfromname, &st ) == -1) continue;
966 if (S_ISBLK(st.st_mode) && st.st_rdev == dev)
968 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry[i].f_mntonname) + 1 );
969 if (ret) strcpy( ret, entry[i].f_mntonname );
970 break;
973 RtlLeaveCriticalSection( &dir_section );
974 #else
975 static int warned;
976 if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
977 #endif
978 return ret;
982 #if defined(HAVE_GETATTRLIST) && defined(ATTR_VOL_CAPABILITIES) && \
983 defined(VOL_CAPABILITIES_FORMAT) && defined(VOL_CAP_FMT_CASE_SENSITIVE)
985 struct get_fsid
987 ULONG size;
988 dev_t dev;
989 fsid_t fsid;
992 struct fs_cache
994 dev_t dev;
995 fsid_t fsid;
996 BOOLEAN case_sensitive;
997 } fs_cache[64];
999 struct vol_caps
1001 ULONG size;
1002 vol_capabilities_attr_t caps;
1005 /***********************************************************************
1006 * look_up_fs_cache
1008 * Checks if the specified file system is in the cache.
1010 static struct fs_cache *look_up_fs_cache( dev_t dev )
1012 int i;
1013 for (i = 0; i < sizeof(fs_cache)/sizeof(fs_cache[0]); i++)
1014 if (fs_cache[i].dev == dev)
1015 return fs_cache+i;
1016 return NULL;
1019 /***********************************************************************
1020 * add_fs_cache
1022 * Adds the specified file system to the cache.
1024 static void add_fs_cache( dev_t dev, fsid_t fsid, BOOLEAN case_sensitive )
1026 int i;
1027 struct fs_cache *entry = look_up_fs_cache( dev );
1028 static int once = 0;
1029 if (entry)
1031 /* Update the cache */
1032 entry->fsid = fsid;
1033 entry->case_sensitive = case_sensitive;
1034 return;
1037 /* Add a new entry */
1038 for (i = 0; i < sizeof(fs_cache)/sizeof(fs_cache[0]); i++)
1039 if (fs_cache[i].dev == 0)
1041 /* This entry is empty, use it */
1042 fs_cache[i].dev = dev;
1043 fs_cache[i].fsid = fsid;
1044 fs_cache[i].case_sensitive = case_sensitive;
1045 return;
1048 /* Cache is out of space, warn */
1049 if (!once++)
1050 WARN( "FS cache is out of space, expect performance problems\n" );
1053 /***********************************************************************
1054 * get_dir_case_sensitivity_attr
1056 * Checks if the volume containing the specified directory is case
1057 * sensitive or not. Uses getattrlist(2).
1059 static int get_dir_case_sensitivity_attr( const char *dir )
1061 char *mntpoint;
1062 struct attrlist attr;
1063 struct vol_caps caps;
1064 struct get_fsid get_fsid;
1065 struct fs_cache *entry;
1067 /* First get the FS ID of the volume */
1068 attr.bitmapcount = ATTR_BIT_MAP_COUNT;
1069 attr.reserved = 0;
1070 attr.commonattr = ATTR_CMN_DEVID|ATTR_CMN_FSID;
1071 attr.volattr = attr.dirattr = attr.fileattr = attr.forkattr = 0;
1072 get_fsid.size = 0;
1073 if (getattrlist( dir, &attr, &get_fsid, sizeof(get_fsid), 0 ) != 0 ||
1074 get_fsid.size != sizeof(get_fsid))
1075 return -1;
1076 /* Try to look it up in the cache */
1077 entry = look_up_fs_cache( get_fsid.dev );
1078 if (entry && !memcmp( &entry->fsid, &get_fsid.fsid, sizeof(fsid_t) ))
1079 /* Cache lookup succeeded */
1080 return entry->case_sensitive;
1081 /* Cache is stale at this point, we have to update it */
1083 mntpoint = get_device_mount_point( get_fsid.dev );
1084 /* Now look up the case-sensitivity */
1085 attr.commonattr = 0;
1086 attr.volattr = ATTR_VOL_INFO|ATTR_VOL_CAPABILITIES;
1087 if (getattrlist( mntpoint, &attr, &caps, sizeof(caps), 0 ) < 0)
1089 RtlFreeHeap( GetProcessHeap(), 0, mntpoint );
1090 add_fs_cache( get_fsid.dev, get_fsid.fsid, TRUE );
1091 return TRUE;
1093 RtlFreeHeap( GetProcessHeap(), 0, mntpoint );
1094 if (caps.size == sizeof(caps) &&
1095 (caps.caps.valid[VOL_CAPABILITIES_FORMAT] &
1096 (VOL_CAP_FMT_CASE_SENSITIVE | VOL_CAP_FMT_CASE_PRESERVING)) ==
1097 (VOL_CAP_FMT_CASE_SENSITIVE | VOL_CAP_FMT_CASE_PRESERVING))
1099 BOOLEAN ret;
1101 if ((caps.caps.capabilities[VOL_CAPABILITIES_FORMAT] &
1102 VOL_CAP_FMT_CASE_SENSITIVE) != VOL_CAP_FMT_CASE_SENSITIVE)
1103 ret = FALSE;
1104 else
1105 ret = TRUE;
1106 /* Update the cache */
1107 add_fs_cache( get_fsid.dev, get_fsid.fsid, ret );
1108 return ret;
1110 return FALSE;
1112 #endif
1114 /***********************************************************************
1115 * get_dir_case_sensitivity_stat
1117 * Checks if the volume containing the specified directory is case
1118 * sensitive or not. Uses statfs(2) or statvfs(2).
1120 static BOOLEAN get_dir_case_sensitivity_stat( const char *dir )
1122 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1123 struct statfs stfs;
1125 if (statfs( dir, &stfs ) == -1) return FALSE;
1126 /* Assume these file systems are always case insensitive on Mac OS.
1127 * For FreeBSD, only assume CIOPFS is case insensitive (AFAIK, Mac OS
1128 * is the only UNIX that supports case-insensitive lookup).
1130 if (!strcmp( stfs.f_fstypename, "fusefs" ) &&
1131 !strncmp( stfs.f_mntfromname, "ciopfs", 5 ))
1132 return FALSE;
1133 #ifdef __APPLE__
1134 if (!strcmp( stfs.f_fstypename, "msdos" ) ||
1135 !strcmp( stfs.f_fstypename, "cd9660" ) ||
1136 !strcmp( stfs.f_fstypename, "udf" ) ||
1137 !strcmp( stfs.f_fstypename, "ntfs" ) ||
1138 !strcmp( stfs.f_fstypename, "smbfs" ))
1139 return FALSE;
1140 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1141 if (!strcmp( stfs.f_fstypename, "hfs" ) && (stfs.f_fssubtype == 0 ||
1142 stfs.f_fssubtype == 1 ||
1143 stfs.f_fssubtype == 128))
1144 return FALSE;
1145 #else
1146 /* The field says "reserved", but a quick look at the kernel source
1147 * tells us that this "reserved" field is really the same as the
1148 * "fssubtype" field from the inode64 structure (see munge_statfs()
1149 * in <xnu-source>/bsd/vfs/vfs_syscalls.c).
1151 if (!strcmp( stfs.f_fstypename, "hfs" ) && (stfs.f_reserved1 == 0 ||
1152 stfs.f_reserved1 == 1 ||
1153 stfs.f_reserved1 == 128))
1154 return FALSE;
1155 #endif
1156 #endif
1157 return TRUE;
1159 #elif defined(__NetBSD__)
1160 struct statvfs stfs;
1162 if (statvfs( dir, &stfs ) == -1) return FALSE;
1163 /* Only assume CIOPFS is case insensitive. */
1164 if (strcmp( stfs.f_fstypename, "fusefs" ) ||
1165 strncmp( stfs.f_mntfromname, "ciopfs", 5 ))
1166 return TRUE;
1167 return FALSE;
1169 #elif defined(__linux__)
1170 struct statfs stfs;
1171 struct stat st;
1172 char *cifile;
1174 /* Only assume CIOPFS is case insensitive. */
1175 if (statfs( dir, &stfs ) == -1) return FALSE;
1176 if (stfs.f_type != 0x65735546 /* FUSE_SUPER_MAGIC */)
1177 return TRUE;
1178 /* Normally, we'd have to parse the mtab to find out exactly what
1179 * kind of FUSE FS this is. But, someone on wine-devel suggested
1180 * a shortcut. We'll stat a special file in the directory. If it's
1181 * there, we'll assume it's a CIOPFS, else not.
1182 * This will break if somebody puts a file named ".ciopfs" in a non-
1183 * CIOPFS directory.
1185 cifile = RtlAllocateHeap( GetProcessHeap(), 0, strlen( dir )+sizeof("/.ciopfs") );
1186 if (!cifile) return TRUE;
1187 strcpy( cifile, dir );
1188 strcat( cifile, "/.ciopfs" );
1189 if (stat( cifile, &st ) == 0)
1191 RtlFreeHeap( GetProcessHeap(), 0, cifile );
1192 return FALSE;
1194 RtlFreeHeap( GetProcessHeap(), 0, cifile );
1195 return TRUE;
1196 #else
1197 return TRUE;
1198 #endif
1202 /***********************************************************************
1203 * get_dir_case_sensitivity
1205 * Checks if the volume containing the specified directory is case
1206 * sensitive or not. Uses statfs(2) or statvfs(2).
1208 static BOOLEAN get_dir_case_sensitivity( const char *dir )
1210 #if defined(HAVE_GETATTRLIST) && defined(ATTR_VOL_CAPABILITIES) && \
1211 defined(VOL_CAPABILITIES_FORMAT) && defined(VOL_CAP_FMT_CASE_SENSITIVE)
1212 int case_sensitive = get_dir_case_sensitivity_attr( dir );
1213 if (case_sensitive != -1) return case_sensitive;
1214 #endif
1215 return get_dir_case_sensitivity_stat( dir );
1219 /***********************************************************************
1220 * init_options
1222 * Initialize the show_dot_files options.
1224 static DWORD WINAPI init_options( RTL_RUN_ONCE *once, void *param, void **context )
1226 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
1227 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
1228 char tmp[80];
1229 HANDLE root, hkey;
1230 DWORD dummy;
1231 OBJECT_ATTRIBUTES attr;
1232 UNICODE_STRING nameW;
1234 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
1235 attr.Length = sizeof(attr);
1236 attr.RootDirectory = root;
1237 attr.ObjectName = &nameW;
1238 attr.Attributes = 0;
1239 attr.SecurityDescriptor = NULL;
1240 attr.SecurityQualityOfService = NULL;
1241 RtlInitUnicodeString( &nameW, WineW );
1243 /* @@ Wine registry key: HKCU\Software\Wine */
1244 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
1246 RtlInitUnicodeString( &nameW, ShowDotFilesW );
1247 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
1249 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
1250 show_dot_files = IS_OPTION_TRUE( str[0] );
1252 NtClose( hkey );
1254 NtClose( root );
1256 /* a couple of directories that we don't want to return in directory searches */
1257 ignore_file( wine_get_config_dir() );
1258 ignore_file( "/dev" );
1259 ignore_file( "/proc" );
1260 #ifdef linux
1261 ignore_file( "/sys" );
1262 #endif
1263 return TRUE;
1267 /***********************************************************************
1268 * DIR_is_hidden_file
1270 * Check if the specified file should be hidden based on its name and the show dot files option.
1272 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
1274 WCHAR *p, *end;
1276 RtlRunOnceExecuteOnce( &init_once, init_options, NULL, NULL );
1278 if (show_dot_files) return FALSE;
1280 end = p = name->Buffer + name->Length/sizeof(WCHAR);
1281 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
1282 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
1283 if (p == end || *p != '.') return FALSE;
1284 /* make sure it isn't '.' or '..' */
1285 if (p + 1 == end) return FALSE;
1286 if (p[1] == '.' && p + 2 == end) return FALSE;
1287 return TRUE;
1291 /***********************************************************************
1292 * hash_short_file_name
1294 * Transform a Unix file name into a hashed DOS name. If the name is a valid
1295 * DOS name, it is converted to upper-case; otherwise it is replaced by a
1296 * hashed version that fits in 8.3 format.
1297 * 'buffer' must be at least 12 characters long.
1298 * Returns length of short name in bytes; short name is NOT null-terminated.
1300 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
1302 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
1304 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
1305 LPWSTR dst;
1306 unsigned short hash;
1307 int i;
1309 /* Compute the hash code of the file name */
1310 /* If you know something about hash functions, feel free to */
1311 /* insert a better algorithm here... */
1312 if (!is_case_sensitive)
1314 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
1315 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
1316 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
1318 else
1320 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
1321 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
1322 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
1325 /* Find last dot for start of the extension */
1326 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
1328 /* Copy first 4 chars, replacing invalid chars with '_' */
1329 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
1331 if (p == end || p == ext) break;
1332 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
1334 /* Pad to 5 chars with '~' */
1335 while (i-- >= 0) *dst++ = '~';
1337 /* Insert hash code converted to 3 ASCII chars */
1338 *dst++ = hash_chars[(hash >> 10) & 0x1f];
1339 *dst++ = hash_chars[(hash >> 5) & 0x1f];
1340 *dst++ = hash_chars[hash & 0x1f];
1342 /* Copy the first 3 chars of the extension (if any) */
1343 if (ext)
1345 *dst++ = '.';
1346 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
1347 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
1349 return dst - buffer;
1353 /***********************************************************************
1354 * match_filename
1356 * Check a long file name against a mask.
1358 * Tests (done in W95 DOS shell - case insensitive):
1359 * *.txt test1.test.txt *
1360 * *st1* test1.txt *
1361 * *.t??????.t* test1.ta.tornado.txt *
1362 * *tornado* test1.ta.tornado.txt *
1363 * t*t test1.ta.tornado.txt *
1364 * ?est* test1.txt *
1365 * ?est??? test1.txt -
1366 * *test1.txt* test1.txt *
1367 * h?l?o*t.dat hellothisisatest.dat *
1369 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
1371 BOOL mismatch;
1372 const WCHAR *name = name_str->Buffer;
1373 const WCHAR *mask = mask_str->Buffer;
1374 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
1375 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
1376 const WCHAR *lastjoker = NULL;
1377 const WCHAR *next_to_retry = NULL;
1379 while (name < name_end && mask < mask_end)
1381 switch(*mask)
1383 case '*':
1384 mask++;
1385 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
1386 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
1387 lastjoker = mask;
1389 /* skip to the next match after the joker(s) */
1390 if (is_case_sensitive)
1391 while (name < name_end && (*name != *mask)) name++;
1392 else
1393 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
1394 next_to_retry = name;
1395 break;
1396 case '?':
1397 mask++;
1398 name++;
1399 break;
1400 default:
1401 if (is_case_sensitive) mismatch = (*mask != *name);
1402 else mismatch = (toupperW(*mask) != toupperW(*name));
1404 if (!mismatch)
1406 mask++;
1407 name++;
1408 if (mask == mask_end)
1410 if (name == name_end) return TRUE;
1411 if (lastjoker) mask = lastjoker;
1414 else /* mismatch ! */
1416 if (lastjoker) /* we had an '*', so we can try unlimitedly */
1418 mask = lastjoker;
1420 /* this scan sequence was a mismatch, so restart
1421 * 1 char after the first char we checked last time */
1422 next_to_retry++;
1423 name = next_to_retry;
1425 else return FALSE; /* bad luck */
1427 break;
1430 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
1431 mask++; /* Ignore trailing '.' or '*' in mask */
1432 return (name == name_end && mask == mask_end);
1436 /***********************************************************************
1437 * append_entry
1439 * Add a file to the directory data if it matches the mask.
1441 static BOOL append_entry( struct dir_data *data, const char *long_name,
1442 const char *short_name, const UNICODE_STRING *mask )
1444 int i, long_len, short_len;
1445 WCHAR long_nameW[MAX_DIR_ENTRY_LEN + 1];
1446 WCHAR short_nameW[13];
1447 UNICODE_STRING str;
1449 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
1450 if (long_len == -1) return TRUE;
1451 long_nameW[long_len] = 0;
1453 str.Buffer = long_nameW;
1454 str.Length = long_len * sizeof(WCHAR);
1455 str.MaximumLength = sizeof(long_nameW);
1457 if (short_name)
1459 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
1460 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) - 1 );
1461 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR) - 1;
1462 for (i = 0; i < short_len; i++) short_nameW[i] = toupperW( short_nameW[i] );
1464 else /* generate a short name if necessary */
1466 BOOLEAN spaces;
1468 short_len = 0;
1469 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1470 short_len = hash_short_file_name( &str, short_nameW );
1472 short_nameW[short_len] = 0;
1474 TRACE( "long %s short %s mask %s\n",
1475 debugstr_w( long_nameW ), debugstr_w( short_nameW ), debugstr_us( mask ));
1477 if (mask && !match_filename( &str, mask ))
1479 if (!short_len) return TRUE; /* no short name to match */
1480 str.Buffer = short_nameW;
1481 str.Length = short_len * sizeof(WCHAR);
1482 str.MaximumLength = sizeof(short_nameW);
1483 if (!match_filename( &str, mask )) return TRUE;
1486 return add_dir_data_names( data, long_nameW, short_nameW, long_name );
1490 /***********************************************************************
1491 * get_dir_data_entry
1493 * Return a directory entry from the cached data.
1495 static NTSTATUS get_dir_data_entry( struct dir_data *dir_data, void *info_ptr, IO_STATUS_BLOCK *io,
1496 ULONG max_length, FILE_INFORMATION_CLASS class,
1497 union file_directory_info **last_info )
1499 const struct dir_data_names *names = &dir_data->names[dir_data->pos];
1500 union file_directory_info *info;
1501 struct stat st;
1502 ULONG name_len, start, dir_size, attributes;
1504 if (get_file_info( names->unix_name, &st, &attributes ) == -1)
1506 TRACE( "file no longer exists %s\n", names->unix_name );
1507 return STATUS_SUCCESS;
1509 if (is_ignored_file( &st ))
1511 TRACE( "ignoring file %s\n", names->unix_name );
1512 return STATUS_SUCCESS;
1514 start = dir_info_align( io->Information );
1515 dir_size = dir_info_size( class, 0 );
1516 if (start + dir_size > max_length) return STATUS_MORE_ENTRIES;
1518 max_length -= start + dir_size;
1519 name_len = strlenW( names->long_name ) * sizeof(WCHAR);
1520 /* if this is not the first entry, fail; the first entry is always returned (but truncated) */
1521 if (*last_info && name_len > max_length) return STATUS_MORE_ENTRIES;
1523 info = (union file_directory_info *)((char *)info_ptr + start);
1524 info->dir.NextEntryOffset = 0;
1525 info->dir.FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
1527 /* all the structures except FileNamesInformation start with a FileDirectoryInformation layout */
1528 if (class != FileNamesInformation)
1530 if (st.st_dev != dir_data->id.dev) st.st_ino = 0; /* ignore inode if on a different device */
1532 if (!show_dot_files && names->long_name[0] == '.' && names->long_name[1] &&
1533 (names->long_name[1] != '.' || names->long_name[2]))
1534 attributes |= FILE_ATTRIBUTE_HIDDEN;
1536 fill_file_info( &st, attributes, info, class );
1539 switch (class)
1541 case FileDirectoryInformation:
1542 info->dir.FileNameLength = name_len;
1543 break;
1545 case FileFullDirectoryInformation:
1546 info->full.EaSize = 0; /* FIXME */
1547 info->full.FileNameLength = name_len;
1548 break;
1550 case FileIdFullDirectoryInformation:
1551 info->id_full.EaSize = 0; /* FIXME */
1552 info->id_full.FileNameLength = name_len;
1553 break;
1555 case FileBothDirectoryInformation:
1556 info->both.EaSize = 0; /* FIXME */
1557 info->both.ShortNameLength = strlenW( names->short_name ) * sizeof(WCHAR);
1558 memcpy( info->both.ShortName, names->short_name, info->both.ShortNameLength );
1559 info->both.FileNameLength = name_len;
1560 break;
1562 case FileIdBothDirectoryInformation:
1563 info->id_both.EaSize = 0; /* FIXME */
1564 info->id_both.ShortNameLength = strlenW( names->short_name ) * sizeof(WCHAR);
1565 memcpy( info->id_both.ShortName, names->short_name, info->id_both.ShortNameLength );
1566 info->id_both.FileNameLength = name_len;
1567 break;
1569 case FileIdGlobalTxDirectoryInformation:
1570 info->id_tx.TxInfoFlags = 0;
1571 info->id_tx.FileNameLength = name_len;
1572 break;
1574 case FileNamesInformation:
1575 info->names.FileNameLength = name_len;
1576 break;
1578 default:
1579 assert(0);
1580 return 0;
1583 memcpy( (char *)info + dir_size, names->long_name, min( name_len, max_length ) );
1584 io->Information = start + dir_size + min( name_len, max_length );
1585 if (*last_info) (*last_info)->next = (char *)info - (char *)*last_info;
1586 *last_info = info;
1587 return name_len > max_length ? STATUS_BUFFER_OVERFLOW : STATUS_SUCCESS;
1590 #ifdef VFAT_IOCTL_READDIR_BOTH
1592 /***********************************************************************
1593 * start_vfat_ioctl
1595 * Wrapper for the VFAT ioctl to work around various kernel bugs.
1596 * dir_section must be held by caller.
1598 static KERNEL_DIRENT *start_vfat_ioctl( int fd )
1600 static KERNEL_DIRENT *de;
1601 int res;
1603 if (!de)
1605 SIZE_T size = 2 * sizeof(*de) + page_size;
1606 void *addr = NULL;
1608 if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_RESERVE, PAGE_READWRITE ))
1609 return NULL;
1610 /* commit only the size needed for the dir entries */
1611 /* this leaves an extra unaccessible page, which should make the kernel */
1612 /* fail with -EFAULT before it stomps all over our memory */
1613 de = addr;
1614 size = 2 * sizeof(*de);
1615 NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_COMMIT, PAGE_READWRITE );
1618 /* set d_reclen to 65535 to work around an AFS kernel bug */
1619 de[0].d_reclen = 65535;
1620 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
1621 if (res == -1)
1623 if (errno != ENOENT) return NULL; /* VFAT ioctl probably not supported */
1624 de[0].d_reclen = 0; /* eof */
1626 else if (!res && de[0].d_reclen == 65535) return NULL; /* AFS bug */
1628 return de;
1632 /***********************************************************************
1633 * read_directory_vfat
1635 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
1637 static NTSTATUS read_directory_data_vfat( struct dir_data *data, int fd, const UNICODE_STRING *mask )
1639 char *short_name, *long_name;
1640 size_t len;
1641 KERNEL_DIRENT *de;
1642 NTSTATUS status = STATUS_NO_MEMORY;
1643 off_t old_pos = lseek( fd, 0, SEEK_CUR );
1645 if (!(de = start_vfat_ioctl( fd ))) return STATUS_NOT_SUPPORTED;
1647 lseek( fd, 0, SEEK_SET );
1649 if (!append_entry( data, ".", NULL, mask )) goto done;
1650 if (!append_entry( data, "..", NULL, mask )) goto done;
1652 while (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) != -1)
1654 if (!de[0].d_reclen) break; /* eof */
1656 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1657 len = min( de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1658 de[0].d_name[len] = 0;
1659 len = min( de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1660 de[1].d_name[len] = 0;
1662 if (!strcmp( de[0].d_name, "." ) || !strcmp( de[0].d_name, ".." )) continue;
1663 if (de[1].d_name[0])
1665 short_name = de[0].d_name;
1666 long_name = de[1].d_name;
1668 else
1670 long_name = de[0].d_name;
1671 short_name = NULL;
1673 if (!append_entry( data, long_name, short_name, mask )) goto done;
1675 status = STATUS_SUCCESS;
1676 done:
1677 lseek( fd, old_pos, SEEK_SET );
1678 return status;
1680 #endif /* VFAT_IOCTL_READDIR_BOTH */
1683 #ifdef HAVE_GETATTRLIST
1684 /***********************************************************************
1685 * read_directory_getattrlist
1687 * Read a single file from a directory by determining whether the file
1688 * identified by mask exists using getattrlist.
1690 static NTSTATUS read_directory_data_getattrlist( struct dir_data *data, const char *unix_name )
1692 struct attrlist attrlist;
1693 #include "pshpack4.h"
1694 struct
1696 u_int32_t length;
1697 struct attrreference name_reference;
1698 fsobj_type_t type;
1699 char name[NAME_MAX * 3 + 1];
1700 } buffer;
1701 #include "poppack.h"
1703 memset( &attrlist, 0, sizeof(attrlist) );
1704 attrlist.bitmapcount = ATTR_BIT_MAP_COUNT;
1705 attrlist.commonattr = ATTR_CMN_NAME | ATTR_CMN_OBJTYPE;
1706 if (getattrlist( unix_name, &attrlist, &buffer, sizeof(buffer), FSOPT_NOFOLLOW ) == -1)
1707 return STATUS_NO_SUCH_FILE;
1708 /* If unix_name named a symlink, the above may have succeeded even if the symlink is broken.
1709 Check that with another call without FSOPT_NOFOLLOW. We don't ask for any attributes. */
1710 if (buffer.type == VLNK)
1712 u_int32_t dummy;
1713 attrlist.commonattr = 0;
1714 if (getattrlist( unix_name, &attrlist, &dummy, sizeof(dummy), 0 ) == -1)
1715 return STATUS_NO_SUCH_FILE;
1718 TRACE( "found %s\n", buffer.name );
1720 if (!append_entry( data, buffer.name, NULL, NULL )) return STATUS_NO_MEMORY;
1722 return STATUS_SUCCESS;
1724 #endif /* HAVE_GETATTRLIST */
1727 /***********************************************************************
1728 * read_directory_stat
1730 * Read a single file from a directory by determining whether the file
1731 * identified by mask exists using stat.
1733 static NTSTATUS read_directory_data_stat( struct dir_data *data, const char *unix_name )
1735 struct stat st;
1737 /* if the file system is not case sensitive we can't find the actual name through stat() */
1738 if (!get_dir_case_sensitivity(".")) return STATUS_NO_SUCH_FILE;
1739 if (stat( unix_name, &st ) == -1) return STATUS_NO_SUCH_FILE;
1741 TRACE( "found %s\n", unix_name );
1743 if (!append_entry( data, unix_name, NULL, NULL )) return STATUS_NO_MEMORY;
1745 return STATUS_SUCCESS;
1749 /***********************************************************************
1750 * read_directory_readdir
1752 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1754 static NTSTATUS read_directory_data_readdir( struct dir_data *data, const UNICODE_STRING *mask )
1756 struct dirent *de;
1757 NTSTATUS status = STATUS_NO_MEMORY;
1758 DIR *dir = opendir( "." );
1760 if (!dir) return STATUS_NO_SUCH_FILE;
1762 if (!append_entry( data, ".", NULL, mask )) goto done;
1763 if (!append_entry( data, "..", NULL, mask )) goto done;
1764 while ((de = readdir( dir )))
1766 if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
1767 if (!append_entry( data, de->d_name, NULL, mask )) goto done;
1769 status = STATUS_SUCCESS;
1771 done:
1772 closedir( dir );
1773 return status;
1777 /***********************************************************************
1778 * read_directory_data
1780 * Read the full contents of a directory, using one of the above helper functions.
1782 static NTSTATUS read_directory_data( struct dir_data *data, int fd, const UNICODE_STRING *mask )
1784 NTSTATUS status;
1786 #ifdef VFAT_IOCTL_READDIR_BOTH
1787 if (!(status = read_directory_data_vfat( data, fd, mask ))) return status;
1788 #endif
1790 if (!has_wildcard( mask ))
1792 /* convert the mask to a Unix name and check for it */
1793 int ret, used_default;
1794 char unix_name[MAX_DIR_ENTRY_LEN * 3 + 1];
1796 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR),
1797 unix_name, sizeof(unix_name) - 1, NULL, &used_default );
1798 if (ret > 0 && !used_default)
1800 unix_name[ret] = 0;
1801 #ifdef HAVE_GETATTRLIST
1802 if (!(status = read_directory_data_getattrlist( data, unix_name ))) return status;
1803 #endif
1804 if (!(status = read_directory_data_stat( data, unix_name ))) return status;
1808 return read_directory_data_readdir( data, mask );
1812 /* compare file names for directory sorting */
1813 static int name_compare( const void *a, const void *b )
1815 const struct dir_data_names *file_a = (const struct dir_data_names *)a;
1816 const struct dir_data_names *file_b = (const struct dir_data_names *)b;
1817 int ret = RtlCompareUnicodeStrings( file_a->long_name, strlenW(file_a->long_name),
1818 file_b->long_name, strlenW(file_b->long_name), TRUE );
1819 if (!ret) ret = strcmpW( file_a->long_name, file_b->long_name );
1820 return ret;
1824 /***********************************************************************
1825 * init_cached_dir_data
1827 * Initialize the cached directory contents.
1829 static NTSTATUS init_cached_dir_data( struct dir_data **data_ret, int fd, const UNICODE_STRING *mask )
1831 struct dir_data *data;
1832 struct stat st;
1833 NTSTATUS status;
1834 unsigned int i;
1836 if (!(data = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*data) )))
1837 return STATUS_NO_MEMORY;
1839 if ((status = read_directory_data( data, fd, mask )))
1841 free_dir_data( data );
1842 return status;
1845 /* sort filenames, but not "." and ".." */
1846 i = 0;
1847 if (i < data->count && !strcmp( data->names[i].unix_name, "." )) i++;
1848 if (i < data->count && !strcmp( data->names[i].unix_name, ".." )) i++;
1849 if (i < data->count) qsort( data->names + i, data->count - i, sizeof(*data->names), name_compare );
1851 if (data->count)
1853 /* release unused space */
1854 if (data->buffer)
1855 RtlReAllocateHeap( GetProcessHeap(), HEAP_REALLOC_IN_PLACE_ONLY, data->buffer,
1856 offsetof( struct dir_data_buffer, data[data->buffer->pos] ));
1857 if (data->count < data->size)
1858 RtlReAllocateHeap( GetProcessHeap(), HEAP_REALLOC_IN_PLACE_ONLY, data->names,
1859 data->count * sizeof(*data->names) );
1860 if (!fstat( fd, &st ))
1862 data->id.dev = st.st_dev;
1863 data->id.ino = st.st_ino;
1867 TRACE( "mask %s found %u files\n", debugstr_us( mask ), data->count );
1868 for (i = 0; i < data->count; i++)
1869 TRACE( "%s %s\n", debugstr_w(data->names[i].long_name), debugstr_w(data->names[i].short_name) );
1871 *data_ret = data;
1872 return data->count ? STATUS_SUCCESS : STATUS_NO_SUCH_FILE;
1876 /***********************************************************************
1877 * get_cached_dir_data
1879 * Retrieve the cached directory data, or initialize it if necessary.
1881 static NTSTATUS get_cached_dir_data( HANDLE handle, struct dir_data **data_ret, int fd,
1882 const UNICODE_STRING *mask )
1884 unsigned int i;
1885 int entry = -1, free_entries[16];
1886 NTSTATUS status;
1888 SERVER_START_REQ( get_directory_cache_entry )
1890 req->handle = wine_server_obj_handle( handle );
1891 wine_server_set_reply( req, free_entries, sizeof(free_entries) );
1892 if (!(status = wine_server_call( req ))) entry = reply->entry;
1894 for (i = 0; i < wine_server_reply_size( reply ) / sizeof(*free_entries); i++)
1896 int free_idx = free_entries[i];
1897 if (free_idx < dir_data_cache_size)
1899 free_dir_data( dir_data_cache[free_idx] );
1900 dir_data_cache[free_idx] = NULL;
1904 SERVER_END_REQ;
1906 if (status)
1908 if (status == STATUS_SHARING_VIOLATION) FIXME( "shared directory handle not supported yet\n" );
1909 return status;
1912 if (entry >= dir_data_cache_size)
1914 unsigned int size = max( dir_data_cache_initial_size, max( dir_data_cache_size * 2, entry + 1 ) );
1915 struct dir_data **new_cache;
1917 if (dir_data_cache)
1918 new_cache = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, dir_data_cache,
1919 size * sizeof(*new_cache) );
1920 else
1921 new_cache = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, size * sizeof(*new_cache) );
1922 if (!new_cache) return STATUS_NO_MEMORY;
1923 dir_data_cache = new_cache;
1924 dir_data_cache_size = size;
1927 if (!dir_data_cache[entry]) status = init_cached_dir_data( &dir_data_cache[entry], fd, mask );
1929 *data_ret = dir_data_cache[entry];
1930 return status;
1934 /******************************************************************************
1935 * NtQueryDirectoryFile [NTDLL.@]
1936 * ZwQueryDirectoryFile [NTDLL.@]
1938 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
1939 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
1940 PIO_STATUS_BLOCK io,
1941 PVOID buffer, ULONG length,
1942 FILE_INFORMATION_CLASS info_class,
1943 BOOLEAN single_entry,
1944 PUNICODE_STRING mask,
1945 BOOLEAN restart_scan )
1947 int cwd, fd, needs_close;
1948 struct dir_data *data;
1949 NTSTATUS status;
1951 TRACE("(%p %p %p %p %p %p 0x%08x 0x%08x 0x%08x %s 0x%08x\n",
1952 handle, event, apc_routine, apc_context, io, buffer,
1953 length, info_class, single_entry, debugstr_us(mask),
1954 restart_scan);
1956 if (event || apc_routine)
1958 FIXME( "Unsupported yet option\n" );
1959 return STATUS_NOT_IMPLEMENTED;
1961 switch (info_class)
1963 case FileDirectoryInformation:
1964 case FileBothDirectoryInformation:
1965 case FileFullDirectoryInformation:
1966 case FileIdBothDirectoryInformation:
1967 case FileIdFullDirectoryInformation:
1968 case FileIdGlobalTxDirectoryInformation:
1969 case FileNamesInformation:
1970 if (length < dir_info_align( dir_info_size( info_class, 1 ))) return STATUS_INFO_LENGTH_MISMATCH;
1971 break;
1972 case FileObjectIdInformation:
1973 if (length != sizeof(FILE_OBJECTID_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
1974 return STATUS_INVALID_INFO_CLASS;
1975 case FileQuotaInformation:
1976 if (length != sizeof(FILE_QUOTA_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
1977 return STATUS_INVALID_INFO_CLASS;
1978 case FileReparsePointInformation:
1979 if (length != sizeof(FILE_REPARSE_POINT_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
1980 return STATUS_INVALID_INFO_CLASS;
1981 default:
1982 return STATUS_INVALID_INFO_CLASS;
1984 if (!buffer) return STATUS_ACCESS_VIOLATION;
1986 if ((status = server_get_unix_fd( handle, FILE_LIST_DIRECTORY, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
1987 return status;
1989 io->Information = 0;
1991 RtlRunOnceExecuteOnce( &init_once, init_options, NULL, NULL );
1993 RtlEnterCriticalSection( &dir_section );
1995 cwd = open( ".", O_RDONLY );
1996 if (fchdir( fd ) != -1)
1998 if (!(status = get_cached_dir_data( handle, &data, fd, mask )))
2000 union file_directory_info *last_info = NULL;
2002 if (restart_scan) data->pos = 0;
2004 while (!status && data->pos < data->count)
2006 status = get_dir_data_entry( data, buffer, io, length, info_class, &last_info );
2007 if (!status || status == STATUS_BUFFER_OVERFLOW) data->pos++;
2008 if (single_entry) break;
2011 if (!last_info) status = STATUS_NO_MORE_FILES;
2012 else if (status == STATUS_MORE_ENTRIES) status = STATUS_SUCCESS;
2014 io->u.Status = status;
2016 if (cwd == -1 || fchdir( cwd ) == -1) chdir( "/" );
2018 else status = FILE_GetNtStatus();
2020 RtlLeaveCriticalSection( &dir_section );
2022 if (needs_close) close( fd );
2023 if (cwd != -1) close( cwd );
2024 TRACE( "=> %x (%ld)\n", status, io->Information );
2025 return status;
2029 /***********************************************************************
2030 * find_file_in_dir
2032 * Find a file in a directory the hard way, by doing a case-insensitive search.
2033 * The file found is appended to unix_name at pos.
2034 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
2036 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
2037 BOOLEAN check_case, BOOLEAN *is_win_dir )
2039 WCHAR buffer[MAX_DIR_ENTRY_LEN];
2040 UNICODE_STRING str;
2041 BOOLEAN spaces, is_name_8_dot_3;
2042 DIR *dir;
2043 struct dirent *de;
2044 struct stat st;
2045 int ret, used_default;
2047 /* try a shortcut for this directory */
2049 unix_name[pos++] = '/';
2050 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
2051 NULL, &used_default );
2052 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
2053 /* so it cannot match the file we are looking for */
2054 if (ret >= 0 && !used_default)
2056 unix_name[pos + ret] = 0;
2057 if (!stat( unix_name, &st ))
2059 if (is_win_dir) *is_win_dir = is_same_file( &windir, &st );
2060 return STATUS_SUCCESS;
2063 if (check_case) goto not_found; /* we want an exact match */
2065 if (pos > 1) unix_name[pos - 1] = 0;
2066 else unix_name[1] = 0; /* keep the initial slash */
2068 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
2070 str.Buffer = (WCHAR *)name;
2071 str.Length = length * sizeof(WCHAR);
2072 str.MaximumLength = str.Length;
2073 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
2074 #ifndef VFAT_IOCTL_READDIR_BOTH
2075 is_name_8_dot_3 = is_name_8_dot_3 && length >= 8 && name[4] == '~';
2076 #endif
2078 if (!is_name_8_dot_3 && !get_dir_case_sensitivity( unix_name )) goto not_found;
2080 /* now look for it through the directory */
2082 #ifdef VFAT_IOCTL_READDIR_BOTH
2083 if (is_name_8_dot_3)
2085 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
2086 if (fd != -1)
2088 KERNEL_DIRENT *kde;
2090 RtlEnterCriticalSection( &dir_section );
2091 if ((kde = start_vfat_ioctl( fd )))
2093 unix_name[pos - 1] = '/';
2094 while (kde[0].d_reclen)
2096 /* make sure names are null-terminated to work around an x86-64 kernel bug */
2097 size_t len = min(kde[0].d_reclen, sizeof(kde[0].d_name) - 1 );
2098 kde[0].d_name[len] = 0;
2099 len = min(kde[1].d_reclen, sizeof(kde[1].d_name) - 1 );
2100 kde[1].d_name[len] = 0;
2102 if (kde[1].d_name[0])
2104 ret = ntdll_umbstowcs( 0, kde[1].d_name, strlen(kde[1].d_name),
2105 buffer, MAX_DIR_ENTRY_LEN );
2106 if (ret == length && !memicmpW( buffer, name, length))
2108 strcpy( unix_name + pos, kde[1].d_name );
2109 RtlLeaveCriticalSection( &dir_section );
2110 close( fd );
2111 goto success;
2114 ret = ntdll_umbstowcs( 0, kde[0].d_name, strlen(kde[0].d_name),
2115 buffer, MAX_DIR_ENTRY_LEN );
2116 if (ret == length && !memicmpW( buffer, name, length))
2118 strcpy( unix_name + pos,
2119 kde[1].d_name[0] ? kde[1].d_name : kde[0].d_name );
2120 RtlLeaveCriticalSection( &dir_section );
2121 close( fd );
2122 goto success;
2124 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)kde ) == -1)
2126 RtlLeaveCriticalSection( &dir_section );
2127 close( fd );
2128 goto not_found;
2132 RtlLeaveCriticalSection( &dir_section );
2133 close( fd );
2135 /* fall through to normal handling */
2137 #endif /* VFAT_IOCTL_READDIR_BOTH */
2139 if (!(dir = opendir( unix_name )))
2141 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
2142 else return FILE_GetNtStatus();
2144 unix_name[pos - 1] = '/';
2145 str.Buffer = buffer;
2146 str.MaximumLength = sizeof(buffer);
2147 while ((de = readdir( dir )))
2149 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
2150 if (ret == length && !memicmpW( buffer, name, length ))
2152 strcpy( unix_name + pos, de->d_name );
2153 closedir( dir );
2154 goto success;
2157 if (!is_name_8_dot_3) continue;
2159 str.Length = ret * sizeof(WCHAR);
2160 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
2162 WCHAR short_nameW[12];
2163 ret = hash_short_file_name( &str, short_nameW );
2164 if (ret == length && !memicmpW( short_nameW, name, length ))
2166 strcpy( unix_name + pos, de->d_name );
2167 closedir( dir );
2168 goto success;
2172 closedir( dir );
2174 not_found:
2175 unix_name[pos - 1] = 0;
2176 return STATUS_OBJECT_PATH_NOT_FOUND;
2178 success:
2179 if (is_win_dir && !stat( unix_name, &st )) *is_win_dir = is_same_file( &windir, &st );
2180 return STATUS_SUCCESS;
2184 #ifndef _WIN64
2186 static const WCHAR catrootW[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t',0};
2187 static const WCHAR catroot2W[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t','2',0};
2188 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};
2189 static const WCHAR driversetcW[] = {'s','y','s','t','e','m','3','2','\\','d','r','i','v','e','r','s','\\','e','t','c',0};
2190 static const WCHAR logfilesW[] = {'s','y','s','t','e','m','3','2','\\','l','o','g','f','i','l','e','s',0};
2191 static const WCHAR spoolW[] = {'s','y','s','t','e','m','3','2','\\','s','p','o','o','l',0};
2192 static const WCHAR system32W[] = {'s','y','s','t','e','m','3','2',0};
2193 static const WCHAR syswow64W[] = {'s','y','s','w','o','w','6','4',0};
2194 static const WCHAR sysnativeW[] = {'s','y','s','n','a','t','i','v','e',0};
2195 static const WCHAR regeditW[] = {'r','e','g','e','d','i','t','.','e','x','e',0};
2196 static const WCHAR wow_regeditW[] = {'s','y','s','w','o','w','6','4','\\','r','e','g','e','d','i','t','.','e','x','e',0};
2198 static struct
2200 const WCHAR *source;
2201 const WCHAR *dos_target;
2202 const char *unix_target;
2203 } redirects[] =
2205 { catrootW, NULL, NULL },
2206 { catroot2W, NULL, NULL },
2207 { driversstoreW, NULL, NULL },
2208 { driversetcW, NULL, NULL },
2209 { logfilesW, NULL, NULL },
2210 { spoolW, NULL, NULL },
2211 { system32W, syswow64W, NULL },
2212 { sysnativeW, system32W, NULL },
2213 { regeditW, wow_regeditW, NULL }
2216 static unsigned int nb_redirects;
2219 /***********************************************************************
2220 * get_redirect_target
2222 * Find the target unix name for a redirected dir.
2224 static const char *get_redirect_target( const char *windows_dir, const WCHAR *name )
2226 int used_default, len, pos, win_len = strlen( windows_dir );
2227 char *unix_name, *unix_target = NULL;
2228 NTSTATUS status;
2230 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, win_len + MAX_DIR_ENTRY_LEN + 2 )))
2231 return NULL;
2232 memcpy( unix_name, windows_dir, win_len );
2233 pos = win_len;
2235 while (*name)
2237 const WCHAR *end, *next;
2239 for (end = name; *end; end++) if (IS_SEPARATOR(*end)) break;
2240 for (next = end; *next; next++) if (!IS_SEPARATOR(*next)) break;
2242 status = find_file_in_dir( unix_name, pos, name, end - name, FALSE, NULL );
2243 if (status == STATUS_OBJECT_PATH_NOT_FOUND && !*next) /* not finding last element is ok */
2245 len = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2246 MAX_DIR_ENTRY_LEN - (pos - win_len), NULL, &used_default );
2247 if (len > 0 && !used_default)
2249 unix_name[pos] = '/';
2250 pos += len + 1;
2251 unix_name[pos] = 0;
2252 break;
2255 if (status) goto done;
2256 pos += strlen( unix_name + pos );
2257 name = next;
2260 if ((unix_target = RtlAllocateHeap( GetProcessHeap(), 0, pos - win_len )))
2261 memcpy( unix_target, unix_name + win_len + 1, pos - win_len );
2263 done:
2264 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2265 return unix_target;
2269 /***********************************************************************
2270 * init_redirects
2272 static void init_redirects(void)
2274 UNICODE_STRING nt_name;
2275 ANSI_STRING unix_name;
2276 NTSTATUS status;
2277 struct stat st;
2278 unsigned int i;
2280 if (!RtlDosPathNameToNtPathName_U( user_shared_data->NtSystemRoot, &nt_name, NULL, NULL ))
2282 ERR( "can't convert %s\n", debugstr_w(user_shared_data->NtSystemRoot) );
2283 return;
2285 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
2286 RtlFreeUnicodeString( &nt_name );
2287 if (status)
2289 ERR( "cannot open %s (%x)\n", debugstr_w(user_shared_data->NtSystemRoot), status );
2290 return;
2292 if (!stat( unix_name.Buffer, &st ))
2294 windir.dev = st.st_dev;
2295 windir.ino = st.st_ino;
2296 nb_redirects = sizeof(redirects) / sizeof(redirects[0]);
2297 for (i = 0; i < nb_redirects; i++)
2299 if (!redirects[i].dos_target) continue;
2300 redirects[i].unix_target = get_redirect_target( unix_name.Buffer, redirects[i].dos_target );
2301 TRACE( "%s -> %s\n", debugstr_w(redirects[i].source), redirects[i].unix_target );
2304 RtlFreeAnsiString( &unix_name );
2309 /***********************************************************************
2310 * match_redirect
2312 * Check if path matches a redirect name. If yes, return matched length.
2314 static int match_redirect( const WCHAR *path, int len, const WCHAR *redir, BOOLEAN check_case )
2316 int i = 0;
2318 while (i < len && *redir)
2320 if (IS_SEPARATOR(path[i]))
2322 if (*redir++ != '\\') return 0;
2323 while (i < len && IS_SEPARATOR(path[i])) i++;
2324 continue; /* move on to next path component */
2326 else if (check_case)
2328 if (path[i] != *redir) return 0;
2330 else
2332 if (tolowerW(path[i]) != tolowerW(*redir)) return 0;
2334 i++;
2335 redir++;
2337 if (*redir) return 0;
2338 if (i < len && !IS_SEPARATOR(path[i])) return 0;
2339 while (i < len && IS_SEPARATOR(path[i])) i++;
2340 return i;
2344 /***********************************************************************
2345 * get_redirect_path
2347 * Retrieve the Unix path corresponding to a redirected path if any.
2349 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, BOOLEAN check_case )
2351 unsigned int i;
2352 int len;
2354 for (i = 0; i < nb_redirects; i++)
2356 if ((len = match_redirect( name, length, redirects[i].source, check_case )))
2358 if (!redirects[i].unix_target) break;
2359 unix_name[pos++] = '/';
2360 strcpy( unix_name + pos, redirects[i].unix_target );
2361 return len;
2364 return 0;
2367 #else /* _WIN64 */
2369 /* there are no redirects on 64-bit */
2371 static const unsigned int nb_redirects = 0;
2373 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, BOOLEAN check_case )
2375 return 0;
2378 #endif
2380 /***********************************************************************
2381 * DIR_init_windows_dir
2383 void DIR_init_windows_dir( const WCHAR *win, const WCHAR *sys )
2385 /* FIXME: should probably store paths as NT file names */
2387 RtlCreateUnicodeString( &system_dir, sys );
2389 #ifndef _WIN64
2390 if (is_wow64) init_redirects();
2391 #endif
2395 /******************************************************************************
2396 * get_dos_device
2398 * Get the Unix path of a DOS device.
2400 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
2402 const char *config_dir = wine_get_config_dir();
2403 struct stat st;
2404 char *unix_name, *new_name, *dev;
2405 unsigned int i;
2406 int unix_len;
2408 /* make sure the device name is ASCII */
2409 for (i = 0; i < name_len; i++)
2410 if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
2412 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
2414 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2415 return STATUS_NO_MEMORY;
2417 strcpy( unix_name, config_dir );
2418 strcat( unix_name, "/dosdevices/" );
2419 dev = unix_name + strlen(unix_name);
2421 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
2422 dev[i] = 0;
2424 /* special case for drive devices */
2425 if (name_len == 2 && dev[1] == ':')
2427 dev[i++] = ':';
2428 dev[i] = 0;
2431 for (;;)
2433 if (!stat( unix_name, &st ))
2435 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
2436 unix_name_ret->Buffer = unix_name;
2437 unix_name_ret->Length = strlen(unix_name);
2438 unix_name_ret->MaximumLength = unix_len;
2439 return STATUS_SUCCESS;
2441 if (!dev) break;
2443 /* now try some defaults for it */
2444 if (!strcmp( dev, "aux" ))
2446 strcpy( dev, "com1" );
2447 continue;
2449 if (!strcmp( dev, "prn" ))
2451 strcpy( dev, "lpt1" );
2452 continue;
2455 new_name = NULL;
2456 if (dev[1] == ':' && dev[2] == ':') /* drive device */
2458 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
2459 new_name = get_default_drive_device( unix_name );
2462 if (!new_name) break;
2464 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2465 unix_name = new_name;
2466 unix_len = strlen(unix_name) + 1;
2467 dev = NULL; /* last try */
2469 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2470 return STATUS_BAD_DEVICE_TYPE;
2474 /* return the length of the DOS namespace prefix if any */
2475 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
2477 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
2478 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
2480 if (name->Length >= sizeof(nt_prefixW) &&
2481 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
2482 return sizeof(nt_prefixW) / sizeof(WCHAR);
2484 if (name->Length >= sizeof(dosdev_prefixW) &&
2485 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
2486 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
2488 return 0;
2492 /******************************************************************************
2493 * find_file_id
2495 * Recursively search directories from the dir queue for a given inode.
2497 static NTSTATUS find_file_id( ANSI_STRING *unix_name, ULONGLONG file_id, dev_t dev )
2499 unsigned int pos;
2500 DIR *dir;
2501 struct dirent *de;
2502 NTSTATUS status;
2503 struct stat st;
2505 while (!(status = next_dir_in_queue( unix_name->Buffer )))
2507 if (!(dir = opendir( unix_name->Buffer ))) continue;
2508 TRACE( "searching %s for %s\n", unix_name->Buffer, wine_dbgstr_longlong(file_id) );
2509 pos = strlen( unix_name->Buffer );
2510 if (pos + MAX_DIR_ENTRY_LEN >= unix_name->MaximumLength/sizeof(WCHAR))
2512 char *new = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name->Buffer,
2513 unix_name->MaximumLength * 2 );
2514 if (!new)
2516 closedir( dir );
2517 return STATUS_NO_MEMORY;
2519 unix_name->MaximumLength *= 2;
2520 unix_name->Buffer = new;
2522 unix_name->Buffer[pos++] = '/';
2523 while ((de = readdir( dir )))
2525 if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
2526 strcpy( unix_name->Buffer + pos, de->d_name );
2527 if (lstat( unix_name->Buffer, &st ) == -1) continue;
2528 if (st.st_dev != dev) continue;
2529 if (st.st_ino == file_id)
2531 closedir( dir );
2532 return STATUS_SUCCESS;
2534 if (!S_ISDIR( st.st_mode )) continue;
2535 if ((status = add_dir_to_queue( unix_name->Buffer )) != STATUS_SUCCESS)
2537 closedir( dir );
2538 return status;
2541 closedir( dir );
2543 return status;
2547 /******************************************************************************
2548 * file_id_to_unix_file_name
2550 * Lookup a file from its file id instead of its name.
2552 NTSTATUS file_id_to_unix_file_name( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name )
2554 enum server_fd_type type;
2555 int old_cwd, root_fd, needs_close;
2556 NTSTATUS status;
2557 ULONGLONG file_id;
2558 struct stat st, root_st;
2560 if (attr->ObjectName->Length != sizeof(ULONGLONG)) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2561 if (!attr->RootDirectory) return STATUS_INVALID_PARAMETER;
2562 memcpy( &file_id, attr->ObjectName->Buffer, sizeof(file_id) );
2564 unix_name->MaximumLength = 2 * MAX_DIR_ENTRY_LEN + 4;
2565 if (!(unix_name->Buffer = RtlAllocateHeap( GetProcessHeap(), 0, unix_name->MaximumLength )))
2566 return STATUS_NO_MEMORY;
2567 strcpy( unix_name->Buffer, "." );
2569 if ((status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
2570 goto done;
2572 if (type != FD_TYPE_DIR)
2574 status = STATUS_OBJECT_TYPE_MISMATCH;
2575 goto done;
2578 fstat( root_fd, &root_st );
2579 if (root_st.st_ino == file_id) /* shortcut for "." */
2581 status = STATUS_SUCCESS;
2582 goto done;
2585 RtlEnterCriticalSection( &dir_section );
2586 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2588 /* shortcut for ".." */
2589 if (!stat( "..", &st ) && st.st_dev == root_st.st_dev && st.st_ino == file_id)
2591 strcpy( unix_name->Buffer, ".." );
2592 status = STATUS_SUCCESS;
2594 else
2596 status = add_dir_to_queue( "." );
2597 if (!status)
2598 status = find_file_id( unix_name, file_id, root_st.st_dev );
2599 if (!status) /* get rid of "./" prefix */
2600 memmove( unix_name->Buffer, unix_name->Buffer + 2, strlen(unix_name->Buffer) - 1 );
2601 flush_dir_queue();
2603 if (fchdir( old_cwd ) == -1) chdir( "/" );
2605 else status = FILE_GetNtStatus();
2606 RtlLeaveCriticalSection( &dir_section );
2607 if (old_cwd != -1) close( old_cwd );
2609 done:
2610 if (status == STATUS_SUCCESS)
2612 TRACE( "%s -> %s\n", wine_dbgstr_longlong(file_id), debugstr_a(unix_name->Buffer) );
2613 unix_name->Length = strlen( unix_name->Buffer );
2615 else
2617 TRACE( "%s not found in dir %p\n", wine_dbgstr_longlong(file_id), attr->RootDirectory );
2618 RtlFreeHeap( GetProcessHeap(), 0, unix_name->Buffer );
2620 if (needs_close) close( root_fd );
2621 return status;
2625 /******************************************************************************
2626 * lookup_unix_name
2628 * Helper for nt_to_unix_file_name
2630 static NTSTATUS lookup_unix_name( const WCHAR *name, int name_len, char **buffer, int unix_len, int pos,
2631 UINT disposition, BOOLEAN check_case )
2633 NTSTATUS status;
2634 int ret, used_default, len;
2635 struct stat st;
2636 char *unix_name = *buffer;
2637 const BOOL redirect = nb_redirects && ntdll_get_thread_data()->wow64_redir;
2639 /* try a shortcut first */
2641 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
2642 NULL, &used_default );
2644 while (name_len && IS_SEPARATOR(*name))
2646 name++;
2647 name_len--;
2650 if (ret >= 0 && !used_default) /* if we used the default char the name didn't convert properly */
2652 char *p;
2653 unix_name[pos + ret] = 0;
2654 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
2655 if (!redirect || (!strstr( unix_name, "/windows/") && strncmp( unix_name, "windows/", 8 )))
2657 if (!stat( unix_name, &st ))
2659 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
2660 if (disposition == FILE_CREATE)
2661 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
2662 return STATUS_SUCCESS;
2667 if (!name_len) /* empty name -> drive root doesn't exist */
2668 return STATUS_OBJECT_PATH_NOT_FOUND;
2669 if (check_case && !redirect && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
2670 return STATUS_OBJECT_NAME_NOT_FOUND;
2672 /* now do it component by component */
2674 while (name_len)
2676 const WCHAR *end, *next;
2677 BOOLEAN is_win_dir = FALSE;
2679 end = name;
2680 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
2681 next = end;
2682 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
2683 name_len -= next - name;
2685 /* grow the buffer if needed */
2687 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
2689 char *new_name;
2690 unix_len += 2 * MAX_DIR_ENTRY_LEN;
2691 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
2692 return STATUS_NO_MEMORY;
2693 unix_name = *buffer = new_name;
2696 status = find_file_in_dir( unix_name, pos, name, end - name,
2697 check_case, redirect ? &is_win_dir : NULL );
2699 /* if this is the last element, not finding it is not necessarily fatal */
2700 if (!name_len)
2702 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
2704 status = STATUS_OBJECT_NAME_NOT_FOUND;
2705 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
2707 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2708 MAX_DIR_ENTRY_LEN, NULL, &used_default );
2709 if (ret > 0 && !used_default)
2711 unix_name[pos] = '/';
2712 unix_name[pos + 1 + ret] = 0;
2713 status = STATUS_NO_SUCH_FILE;
2714 break;
2718 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
2720 status = STATUS_OBJECT_NAME_COLLISION;
2724 if (status != STATUS_SUCCESS) break;
2726 pos += strlen( unix_name + pos );
2727 name = next;
2729 if (is_win_dir && (len = get_redirect_path( unix_name, pos, name, name_len, check_case )))
2731 name += len;
2732 name_len -= len;
2733 pos += strlen( unix_name + pos );
2734 TRACE( "redirecting -> %s + %s\n", debugstr_a(unix_name), debugstr_w(name) );
2738 return status;
2742 /******************************************************************************
2743 * nt_to_unix_file_name_attr
2745 NTSTATUS nt_to_unix_file_name_attr( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name_ret,
2746 UINT disposition )
2748 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2749 enum server_fd_type type;
2750 int old_cwd, root_fd, needs_close;
2751 const WCHAR *name, *p;
2752 char *unix_name;
2753 int name_len, unix_len;
2754 NTSTATUS status;
2755 BOOLEAN check_case = !(attr->Attributes & OBJ_CASE_INSENSITIVE);
2757 if (!attr->RootDirectory) /* without root dir fall back to normal lookup */
2758 return wine_nt_to_unix_file_name( attr->ObjectName, unix_name_ret, disposition, check_case );
2760 name = attr->ObjectName->Buffer;
2761 name_len = attr->ObjectName->Length / sizeof(WCHAR);
2763 if (name_len && IS_SEPARATOR(name[0])) return STATUS_INVALID_PARAMETER;
2765 /* check for invalid characters */
2766 for (p = name; p < name + name_len; p++)
2767 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2769 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
2770 unix_len += MAX_DIR_ENTRY_LEN + 3;
2771 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2772 return STATUS_NO_MEMORY;
2773 unix_name[0] = '.';
2775 if (!(status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
2777 if (type != FD_TYPE_DIR)
2779 if (needs_close) close( root_fd );
2780 status = STATUS_BAD_DEVICE_TYPE;
2782 else
2784 RtlEnterCriticalSection( &dir_section );
2785 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2787 status = lookup_unix_name( name, name_len, &unix_name, unix_len, 1,
2788 disposition, check_case );
2789 if (fchdir( old_cwd ) == -1) chdir( "/" );
2791 else status = FILE_GetNtStatus();
2792 RtlLeaveCriticalSection( &dir_section );
2793 if (old_cwd != -1) close( old_cwd );
2794 if (needs_close) close( root_fd );
2797 else if (status == STATUS_OBJECT_TYPE_MISMATCH) status = STATUS_BAD_DEVICE_TYPE;
2799 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
2801 TRACE( "%s -> %s\n", debugstr_us(attr->ObjectName), debugstr_a(unix_name) );
2802 unix_name_ret->Buffer = unix_name;
2803 unix_name_ret->Length = strlen(unix_name);
2804 unix_name_ret->MaximumLength = unix_len;
2806 else
2808 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
2809 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2811 return status;
2815 /******************************************************************************
2816 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
2818 * Convert a file name from NT namespace to Unix namespace.
2820 * If disposition is not FILE_OPEN or FILE_OVERWRITE, the last path
2821 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
2822 * returned, but the unix name is still filled in properly.
2824 NTSTATUS CDECL wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
2825 UINT disposition, BOOLEAN check_case )
2827 static const WCHAR unixW[] = {'u','n','i','x'};
2828 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2830 NTSTATUS status = STATUS_SUCCESS;
2831 const char *config_dir = wine_get_config_dir();
2832 const WCHAR *name, *p;
2833 struct stat st;
2834 char *unix_name;
2835 int pos, ret, name_len, unix_len, prefix_len, used_default;
2836 WCHAR prefix[MAX_DIR_ENTRY_LEN];
2837 BOOLEAN is_unix = FALSE;
2839 name = nameW->Buffer;
2840 name_len = nameW->Length / sizeof(WCHAR);
2842 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2844 if (!(pos = get_dos_prefix_len( nameW )))
2845 return STATUS_BAD_DEVICE_TYPE; /* no DOS prefix, assume NT native name */
2847 name += pos;
2848 name_len -= pos;
2850 if (!name_len) return STATUS_OBJECT_NAME_INVALID;
2852 /* check for sub-directory */
2853 for (pos = 0; pos < name_len; pos++)
2855 if (IS_SEPARATOR(name[pos])) break;
2856 if (name[pos] < 32 || strchrW( invalid_charsW, name[pos] ))
2857 return STATUS_OBJECT_NAME_INVALID;
2859 if (pos > MAX_DIR_ENTRY_LEN)
2860 return STATUS_OBJECT_NAME_INVALID;
2862 if (pos == name_len) /* no subdir, plain DOS device */
2863 return get_dos_device( name, name_len, unix_name_ret );
2865 for (prefix_len = 0; prefix_len < pos; prefix_len++)
2866 prefix[prefix_len] = tolowerW(name[prefix_len]);
2868 name += prefix_len;
2869 name_len -= prefix_len;
2871 /* check for invalid characters (all chars except 0 are valid for unix) */
2872 is_unix = (prefix_len == 4 && !memcmp( prefix, unixW, sizeof(unixW) ));
2873 if (is_unix)
2875 for (p = name; p < name + name_len; p++)
2876 if (!*p) return STATUS_OBJECT_NAME_INVALID;
2877 check_case = TRUE;
2879 else
2881 for (p = name; p < name + name_len; p++)
2882 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2885 unix_len = ntdll_wcstoumbs( 0, prefix, prefix_len, NULL, 0, NULL, NULL );
2886 unix_len += ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
2887 unix_len += MAX_DIR_ENTRY_LEN + 3;
2888 unix_len += strlen(config_dir) + sizeof("/dosdevices/");
2889 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2890 return STATUS_NO_MEMORY;
2891 strcpy( unix_name, config_dir );
2892 strcat( unix_name, "/dosdevices/" );
2893 pos = strlen(unix_name);
2895 ret = ntdll_wcstoumbs( 0, prefix, prefix_len, unix_name + pos, unix_len - pos - 1,
2896 NULL, &used_default );
2897 if (!ret || used_default)
2899 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2900 return STATUS_OBJECT_NAME_INVALID;
2902 pos += ret;
2904 /* check if prefix exists (except for DOS drives to avoid extra stat calls) */
2906 if (prefix_len != 2 || prefix[1] != ':')
2908 unix_name[pos] = 0;
2909 if (lstat( unix_name, &st ) == -1 && errno == ENOENT)
2911 if (!is_unix)
2913 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2914 return STATUS_BAD_DEVICE_TYPE;
2916 pos = 0; /* fall back to unix root */
2920 status = lookup_unix_name( name, name_len, &unix_name, unix_len, pos, disposition, check_case );
2921 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
2923 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
2924 unix_name_ret->Buffer = unix_name;
2925 unix_name_ret->Length = strlen(unix_name);
2926 unix_name_ret->MaximumLength = unix_len;
2928 else
2930 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
2931 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2933 return status;
2937 /******************************************************************
2938 * RtlWow64EnableFsRedirection (NTDLL.@)
2940 NTSTATUS WINAPI RtlWow64EnableFsRedirection( BOOLEAN enable )
2942 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
2943 ntdll_get_thread_data()->wow64_redir = enable;
2944 return STATUS_SUCCESS;
2948 /******************************************************************
2949 * RtlWow64EnableFsRedirectionEx (NTDLL.@)
2951 NTSTATUS WINAPI RtlWow64EnableFsRedirectionEx( ULONG disable, ULONG *old_value )
2953 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
2955 __TRY
2957 *old_value = !ntdll_get_thread_data()->wow64_redir;
2959 __EXCEPT_PAGE_FAULT
2961 return STATUS_ACCESS_VIOLATION;
2963 __ENDTRY
2965 ntdll_get_thread_data()->wow64_redir = !disable;
2966 return STATUS_SUCCESS;
2970 /******************************************************************
2971 * RtlDoesFileExists_U (NTDLL.@)
2973 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
2975 UNICODE_STRING nt_name;
2976 FILE_BASIC_INFORMATION basic_info;
2977 OBJECT_ATTRIBUTES attr;
2978 BOOLEAN ret;
2980 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
2982 attr.Length = sizeof(attr);
2983 attr.RootDirectory = 0;
2984 attr.ObjectName = &nt_name;
2985 attr.Attributes = OBJ_CASE_INSENSITIVE;
2986 attr.SecurityDescriptor = NULL;
2987 attr.SecurityQualityOfService = NULL;
2989 ret = NtQueryAttributesFile(&attr, &basic_info) == STATUS_SUCCESS;
2991 RtlFreeUnicodeString( &nt_name );
2992 return ret;
2996 /***********************************************************************
2997 * DIR_unmount_device
2999 * Unmount the specified device.
3001 NTSTATUS DIR_unmount_device( HANDLE handle )
3003 NTSTATUS status;
3004 int unix_fd, needs_close;
3006 if (!(status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )))
3008 struct stat st;
3009 char *mount_point = NULL;
3011 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
3012 status = STATUS_INVALID_PARAMETER;
3013 else
3015 if ((mount_point = get_device_mount_point( st.st_rdev )))
3017 #ifdef __APPLE__
3018 static const char umount[] = "diskutil unmount >/dev/null 2>&1 ";
3019 #else
3020 static const char umount[] = "umount >/dev/null 2>&1 ";
3021 #endif
3022 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
3023 if (cmd)
3025 strcpy( cmd, umount );
3026 strcat( cmd, mount_point );
3027 system( cmd );
3028 RtlFreeHeap( GetProcessHeap(), 0, cmd );
3029 #ifdef linux
3030 /* umount will fail to release the loop device since we still have
3031 a handle to it, so we release it here */
3032 if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
3033 #endif
3035 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
3038 if (needs_close) close( unix_fd );
3040 return status;
3044 /******************************************************************************
3045 * DIR_get_unix_cwd
3047 * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
3048 * Returned value must be freed by caller.
3050 NTSTATUS DIR_get_unix_cwd( char **cwd )
3052 int old_cwd, unix_fd, needs_close;
3053 CURDIR *curdir;
3054 HANDLE handle;
3055 NTSTATUS status;
3057 RtlAcquirePebLock();
3059 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
3060 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
3061 else
3062 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
3064 if (!(handle = curdir->Handle))
3066 UNICODE_STRING dirW;
3067 OBJECT_ATTRIBUTES attr;
3068 IO_STATUS_BLOCK io;
3070 if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
3072 status = STATUS_OBJECT_NAME_INVALID;
3073 goto done;
3075 attr.Length = sizeof(attr);
3076 attr.RootDirectory = 0;
3077 attr.Attributes = OBJ_CASE_INSENSITIVE;
3078 attr.ObjectName = &dirW;
3079 attr.SecurityDescriptor = NULL;
3080 attr.SecurityQualityOfService = NULL;
3082 status = NtOpenFile( &handle, SYNCHRONIZE, &attr, &io, 0,
3083 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
3084 RtlFreeUnicodeString( &dirW );
3085 if (status != STATUS_SUCCESS) goto done;
3088 if ((status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )) == STATUS_SUCCESS)
3090 RtlEnterCriticalSection( &dir_section );
3092 if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
3094 unsigned int size = 512;
3096 for (;;)
3098 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
3100 status = STATUS_NO_MEMORY;
3101 break;
3103 if (getcwd( *cwd, size )) break;
3104 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
3105 if (errno != ERANGE)
3107 status = STATUS_OBJECT_PATH_INVALID;
3108 break;
3110 size *= 2;
3112 if (fchdir( old_cwd ) == -1) chdir( "/" );
3114 else status = FILE_GetNtStatus();
3116 RtlLeaveCriticalSection( &dir_section );
3117 if (old_cwd != -1) close( old_cwd );
3118 if (needs_close) close( unix_fd );
3120 if (!curdir->Handle) NtClose( handle );
3122 done:
3123 RtlReleasePebLock();
3124 return status;