msvfw32: Simplify error handling in ICSeqCompressFrameStart.
[wine/multimedia.git] / dlls / ntdll / directory.c
blob4faafe9202a59609e167f39c795b2534f7417ac7
1 /*
2 * NTDLL directory functions
4 * Copyright 1993 Erik Bos
5 * Copyright 2003 Eric Pouech
6 * Copyright 1996, 2004 Alexandre Julliard
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include "config.h"
24 #include "wine/port.h"
26 #include <assert.h>
27 #include <sys/types.h>
28 #ifdef HAVE_DIRENT_H
29 # include <dirent.h>
30 #endif
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <stdarg.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <limits.h>
38 #ifdef HAVE_MNTENT_H
39 #include <mntent.h>
40 #endif
41 #ifdef HAVE_SYS_STAT_H
42 # include <sys/stat.h>
43 #endif
44 #ifdef HAVE_SYS_SYSCALL_H
45 # include <sys/syscall.h>
46 #endif
47 #ifdef HAVE_SYS_ATTR_H
48 #include <sys/attr.h>
49 #endif
50 #ifdef HAVE_SYS_VNODE_H
51 /* Work around a conflict with Solaris' system list defined in sys/list.h. */
52 #define list SYSLIST
53 #define list_next SYSLIST_NEXT
54 #define list_prev SYSLIST_PREV
55 #define list_head SYSLIST_HEAD
56 #define list_tail SYSLIST_TAIL
57 #define list_move_tail SYSLIST_MOVE_TAIL
58 #define list_remove SYSLIST_REMOVE
59 #include <sys/vnode.h>
60 #undef list
61 #undef list_next
62 #undef list_prev
63 #undef list_head
64 #undef list_tail
65 #undef list_move_tail
66 #undef list_remove
67 #endif
68 #ifdef HAVE_SYS_IOCTL_H
69 #include <sys/ioctl.h>
70 #endif
71 #ifdef HAVE_LINUX_IOCTL_H
72 #include <linux/ioctl.h>
73 #endif
74 #ifdef HAVE_LINUX_MAJOR_H
75 # include <linux/major.h>
76 #endif
77 #ifdef HAVE_SYS_PARAM_H
78 #include <sys/param.h>
79 #endif
80 #ifdef HAVE_SYS_MOUNT_H
81 #include <sys/mount.h>
82 #endif
83 #ifdef HAVE_SYS_STATFS_H
84 #include <sys/statfs.h>
85 #endif
86 #include <time.h>
87 #ifdef HAVE_UNISTD_H
88 # include <unistd.h>
89 #endif
91 #include "ntstatus.h"
92 #define WIN32_NO_STATUS
93 #define NONAMELESSUNION
94 #include "windef.h"
95 #include "winnt.h"
96 #include "winternl.h"
97 #include "ddk/wdm.h"
98 #include "ntdll_misc.h"
99 #include "wine/unicode.h"
100 #include "wine/server.h"
101 #include "wine/list.h"
102 #include "wine/library.h"
103 #include "wine/debug.h"
105 WINE_DEFAULT_DEBUG_CHANNEL(file);
107 /* just in case... */
108 #undef VFAT_IOCTL_READDIR_BOTH
109 #undef USE_GETDENTS
111 #ifdef linux
113 /* We want the real kernel dirent structure, not the libc one */
114 typedef struct
116 long d_ino;
117 long d_off;
118 unsigned short d_reclen;
119 char d_name[256];
120 } KERNEL_DIRENT;
122 /* Define the VFAT ioctl to get both short and long file names */
123 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
125 #ifndef O_DIRECTORY
126 # define O_DIRECTORY 0200000 /* must be directory */
127 #endif
129 #ifdef __NR_getdents64
130 typedef struct
132 ULONG64 d_ino;
133 LONG64 d_off;
134 unsigned short d_reclen;
135 unsigned char d_type;
136 char d_name[256];
137 } KERNEL_DIRENT64;
139 #undef getdents64
140 static inline int getdents64( int fd, char *de, unsigned int size )
142 return syscall( __NR_getdents64, fd, de, size );
144 #define USE_GETDENTS
145 #endif
147 #endif /* linux */
149 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
150 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
152 #define INVALID_NT_CHARS '*','?','<','>','|','"'
153 #define INVALID_DOS_CHARS INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
155 #define MAX_DIR_ENTRY_LEN 255 /* max length of a directory entry in chars */
157 #define MAX_IGNORED_FILES 4
159 struct file_identity
161 dev_t dev;
162 ino_t ino;
165 static struct file_identity ignored_files[MAX_IGNORED_FILES];
166 static unsigned int ignored_files_count;
168 union file_directory_info
170 ULONG next;
171 FILE_DIRECTORY_INFORMATION dir;
172 FILE_BOTH_DIRECTORY_INFORMATION both;
173 FILE_FULL_DIRECTORY_INFORMATION full;
174 FILE_ID_BOTH_DIRECTORY_INFORMATION id_both;
175 FILE_ID_FULL_DIRECTORY_INFORMATION id_full;
178 static BOOL show_dot_files;
179 static RTL_RUN_ONCE init_once = RTL_RUN_ONCE_INIT;
181 /* at some point we may want to allow Winelib apps to set this */
182 static const BOOL is_case_sensitive = FALSE;
184 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
186 static struct file_identity curdir;
187 static struct file_identity windir;
189 static RTL_CRITICAL_SECTION dir_section;
190 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
192 0, 0, &dir_section,
193 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
194 0, 0, { (DWORD_PTR)(__FILE__ ": dir_section") }
196 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
199 /* check if a given Unicode char is OK in a DOS short name */
200 static inline BOOL is_invalid_dos_char( WCHAR ch )
202 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
203 if (ch > 0x7f) return TRUE;
204 return strchrW( invalid_chars, ch ) != NULL;
207 /* check if the device can be a mounted volume */
208 static inline BOOL is_valid_mounted_device( const struct stat *st )
210 #if defined(linux) || defined(__sun__)
211 return S_ISBLK( st->st_mode );
212 #else
213 /* disks are char devices on *BSD */
214 return S_ISCHR( st->st_mode );
215 #endif
218 static inline void ignore_file( const char *name )
220 struct stat st;
221 assert( ignored_files_count < MAX_IGNORED_FILES );
222 if (!stat( name, &st ))
224 ignored_files[ignored_files_count].dev = st.st_dev;
225 ignored_files[ignored_files_count].ino = st.st_ino;
226 ignored_files_count++;
230 static inline BOOL is_same_file( const struct file_identity *file, const struct stat *st )
232 return st->st_dev == file->dev && st->st_ino == file->ino;
235 static inline BOOL is_ignored_file( const struct stat *st )
237 unsigned int i;
239 for (i = 0; i < ignored_files_count; i++)
240 if (is_same_file( &ignored_files[i], st )) return TRUE;
241 return FALSE;
244 static inline unsigned int dir_info_size( FILE_INFORMATION_CLASS class, unsigned int len )
246 switch (class)
248 case FileDirectoryInformation:
249 return (FIELD_OFFSET( FILE_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
250 case FileBothDirectoryInformation:
251 return (FIELD_OFFSET( FILE_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
252 case FileFullDirectoryInformation:
253 return (FIELD_OFFSET( FILE_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
254 case FileIdBothDirectoryInformation:
255 return (FIELD_OFFSET( FILE_ID_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
256 case FileIdFullDirectoryInformation:
257 return (FIELD_OFFSET( FILE_ID_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
258 default:
259 assert(0);
260 return 0;
264 static inline unsigned int max_dir_info_size( FILE_INFORMATION_CLASS class )
266 return dir_info_size( class, MAX_DIR_ENTRY_LEN );
269 static inline BOOL has_wildcard( const UNICODE_STRING *mask )
271 return (!mask ||
272 memchrW( mask->Buffer, '*', mask->Length / sizeof(WCHAR) ) ||
273 memchrW( mask->Buffer, '?', mask->Length / sizeof(WCHAR) ));
277 /* support for a directory queue for filesystem searches */
279 struct dir_name
281 struct list entry;
282 char name[1];
285 static struct list dir_queue = LIST_INIT( dir_queue );
287 static NTSTATUS add_dir_to_queue( const char *name )
289 int len = strlen( name ) + 1;
290 struct dir_name *dir = RtlAllocateHeap( GetProcessHeap(), 0,
291 FIELD_OFFSET( struct dir_name, name[len] ));
292 if (!dir) return STATUS_NO_MEMORY;
293 strcpy( dir->name, name );
294 list_add_tail( &dir_queue, &dir->entry );
295 return STATUS_SUCCESS;
298 static NTSTATUS next_dir_in_queue( char *name )
300 struct list *head = list_head( &dir_queue );
301 if (head)
303 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
304 strcpy( name, dir->name );
305 list_remove( &dir->entry );
306 RtlFreeHeap( GetProcessHeap(), 0, dir );
307 return STATUS_SUCCESS;
309 return STATUS_OBJECT_NAME_NOT_FOUND;
312 static void flush_dir_queue(void)
314 struct list *head;
316 while ((head = list_head( &dir_queue )))
318 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
319 list_remove( &dir->entry );
320 RtlFreeHeap( GetProcessHeap(), 0, dir );
325 /***********************************************************************
326 * get_default_com_device
328 * Return the default device to use for serial ports.
330 static char *get_default_com_device( int num )
332 char *ret = NULL;
334 if (!num || num > 9) return ret;
335 #ifdef linux
336 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
337 if (ret)
339 strcpy( ret, "/dev/ttyS0" );
340 ret[strlen(ret) - 1] = '0' + num - 1;
342 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
343 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuau0") );
344 if (ret)
346 strcpy( ret, "/dev/cuau0" );
347 ret[strlen(ret) - 1] = '0' + num - 1;
349 #elif defined(__DragonFly__)
350 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuaa0") );
351 if (ret)
353 strcpy( ret, "/dev/cuaa0" );
354 ret[strlen(ret) - 1] = '0' + num - 1;
356 #else
357 FIXME( "no known default for device com%d\n", num );
358 #endif
359 return ret;
363 /***********************************************************************
364 * get_default_lpt_device
366 * Return the default device to use for parallel ports.
368 static char *get_default_lpt_device( int num )
370 char *ret = NULL;
372 if (!num || num > 9) return ret;
373 #ifdef linux
374 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
375 if (ret)
377 strcpy( ret, "/dev/lp0" );
378 ret[strlen(ret) - 1] = '0' + num - 1;
380 #else
381 FIXME( "no known default for device lpt%d\n", num );
382 #endif
383 return ret;
386 #ifdef __ANDROID__
388 static char *unescape_field( char *str )
390 char *in, *out;
392 for (in = out = str; *in; in++, out++)
394 *out = *in;
395 if (in[0] == '\\')
397 if (in[1] == '\\')
399 out[0] = '\\';
400 in++;
402 else if (in[1] == '0' && in[2] == '4' && in[3] == '0')
404 out[0] = ' ';
405 in += 3;
407 else if (in[1] == '0' && in[2] == '1' && in[3] == '1')
409 out[0] = '\t';
410 in += 3;
412 else if (in[1] == '0' && in[2] == '1' && in[3] == '2')
414 out[0] = '\n';
415 in += 3;
417 else if (in[1] == '1' && in[2] == '3' && in[3] == '4')
419 out[0] = '\\';
420 in += 3;
424 *out = '\0';
426 return str;
429 static inline char *get_field( char **str )
431 char *ret;
433 ret = strsep( str, " \t" );
434 if (*str) *str += strspn( *str, " \t" );
436 return ret;
438 /************************************************************************
439 * getmntent_replacement
441 * getmntent replacement for Android.
443 * NB returned static buffer is not thread safe; protect with dir_section.
445 static struct mntent *getmntent_replacement( FILE *f )
447 static struct mntent entry;
448 static char buf[4096];
449 char *p, *start;
453 if (!fgets( buf, sizeof(buf), f )) return NULL;
454 p = strchr( buf, '\n' );
455 if (p) *p = '\0';
456 else /* Partially unread line, move file ptr to end */
458 char tmp[1024];
459 while (fgets( tmp, sizeof(tmp), f ))
460 if (strchr( tmp, '\n' )) break;
462 start = buf + strspn( buf, " \t" );
463 } while (start[0] == '\0' || start[0] == '#');
465 p = get_field( &start );
466 entry.mnt_fsname = p ? unescape_field( p ) : (char *)"";
468 p = get_field( &start );
469 entry.mnt_dir = p ? unescape_field( p ) : (char *)"";
471 p = get_field( &start );
472 entry.mnt_type = p ? unescape_field( p ) : (char *)"";
474 p = get_field( &start );
475 entry.mnt_opts = p ? unescape_field( p ) : (char *)"";
477 p = get_field( &start );
478 entry.mnt_freq = p ? atoi(p) : 0;
480 p = get_field( &start );
481 entry.mnt_passno = p ? atoi(p) : 0;
483 return &entry;
485 #define getmntent getmntent_replacement
486 #endif
488 /***********************************************************************
489 * DIR_get_drives_info
491 * Retrieve device/inode number for all the drives. Helper for find_drive_root.
493 unsigned int DIR_get_drives_info( struct drive_info info[MAX_DOS_DRIVES] )
495 static struct drive_info cache[MAX_DOS_DRIVES];
496 static time_t last_update;
497 static unsigned int nb_drives;
498 unsigned int ret;
499 time_t now = time(NULL);
501 RtlEnterCriticalSection( &dir_section );
502 if (now != last_update)
504 const char *config_dir = wine_get_config_dir();
505 char *buffer, *p;
506 struct stat st;
507 unsigned int i;
509 if ((buffer = RtlAllocateHeap( GetProcessHeap(), 0,
510 strlen(config_dir) + sizeof("/dosdevices/a:") )))
512 strcpy( buffer, config_dir );
513 strcat( buffer, "/dosdevices/a:" );
514 p = buffer + strlen(buffer) - 2;
516 for (i = nb_drives = 0; i < MAX_DOS_DRIVES; i++)
518 *p = 'a' + i;
519 if (!stat( buffer, &st ))
521 cache[i].dev = st.st_dev;
522 cache[i].ino = st.st_ino;
523 nb_drives++;
525 else
527 cache[i].dev = 0;
528 cache[i].ino = 0;
531 RtlFreeHeap( GetProcessHeap(), 0, buffer );
533 last_update = now;
535 memcpy( info, cache, sizeof(cache) );
536 ret = nb_drives;
537 RtlLeaveCriticalSection( &dir_section );
538 return ret;
542 /***********************************************************************
543 * parse_mount_entries
545 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
548 #ifdef sun
549 #include <sys/vfstab.h>
550 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
552 struct vfstab entry;
553 struct stat st;
554 char *device;
556 while (! getvfsent( f, &entry ))
558 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
559 if (!strcmp( entry.vfs_fstype, "nfs" ) ||
560 !strcmp( entry.vfs_fstype, "smbfs" ) ||
561 !strcmp( entry.vfs_fstype, "ncpfs" )) continue;
563 if (stat( entry.vfs_mountp, &st ) == -1) continue;
564 if (st.st_dev != dev || st.st_ino != ino) continue;
565 if (!strcmp( entry.vfs_fstype, "fd" ))
567 if ((device = strstr( entry.vfs_mntopts, "dev=" )))
569 char *p = strchr( device + 4, ',' );
570 if (p) *p = 0;
571 return device + 4;
574 else
575 return entry.vfs_special;
577 return NULL;
579 #endif
581 #ifdef linux
582 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
584 struct mntent *entry;
585 struct stat st;
586 char *device;
588 while ((entry = getmntent( f )))
590 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
591 if (!strcmp( entry->mnt_type, "nfs" ) ||
592 !strcmp( entry->mnt_type, "smbfs" ) ||
593 !strcmp( entry->mnt_type, "ncpfs" )) continue;
595 if (stat( entry->mnt_dir, &st ) == -1) continue;
596 if (st.st_dev != dev || st.st_ino != ino) continue;
597 if (!strcmp( entry->mnt_type, "supermount" ))
599 if ((device = strstr( entry->mnt_opts, "dev=" )))
601 char *p = strchr( device + 4, ',' );
602 if (p) *p = 0;
603 return device + 4;
606 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
608 /* if device is a regular file check for a loop mount */
609 if ((device = strstr( entry->mnt_opts, "loop=" )))
611 char *p = strchr( device + 5, ',' );
612 if (p) *p = 0;
613 return device + 5;
616 else
617 return entry->mnt_fsname;
619 return NULL;
621 #endif
623 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
624 #include <fstab.h>
625 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
627 struct fstab *entry;
628 struct stat st;
630 while ((entry = getfsent()))
632 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
633 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
634 !strcmp( entry->fs_vfstype, "smbfs" ) ||
635 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
637 if (stat( entry->fs_file, &st ) == -1) continue;
638 if (st.st_dev != dev || st.st_ino != ino) continue;
639 return entry->fs_spec;
641 return NULL;
643 #endif
645 #ifdef sun
646 #include <sys/mnttab.h>
647 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
649 struct mnttab entry;
650 struct stat st;
651 char *device;
654 while (( ! getmntent( f, &entry) ))
656 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
657 if (!strcmp( entry.mnt_fstype, "nfs" ) ||
658 !strcmp( entry.mnt_fstype, "smbfs" ) ||
659 !strcmp( entry.mnt_fstype, "ncpfs" )) continue;
661 if (stat( entry.mnt_mountp, &st ) == -1) continue;
662 if (st.st_dev != dev || st.st_ino != ino) continue;
663 if (!strcmp( entry.mnt_fstype, "fd" ))
665 if ((device = strstr( entry.mnt_mntopts, "dev=" )))
667 char *p = strchr( device + 4, ',' );
668 if (p) *p = 0;
669 return device + 4;
672 else
673 return entry.mnt_special;
675 return NULL;
677 #endif
679 /***********************************************************************
680 * get_default_drive_device
682 * Return the default device to use for a given drive mount point.
684 static char *get_default_drive_device( const char *root )
686 char *ret = NULL;
688 #ifdef linux
689 FILE *f;
690 char *device = NULL;
691 int fd, res = -1;
692 struct stat st;
694 /* try to open it first to force it to get mounted */
695 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
697 res = fstat( fd, &st );
698 close( fd );
700 /* now try normal stat just in case */
701 if (res == -1) res = stat( root, &st );
702 if (res == -1) return NULL;
704 RtlEnterCriticalSection( &dir_section );
706 #ifdef __ANDROID__
707 if ((f = fopen( "/proc/mounts", "r" )))
709 device = parse_mount_entries( f, st.st_dev, st.st_ino );
710 fclose( f );
712 #else
713 if ((f = fopen( "/etc/mtab", "r" )))
715 device = parse_mount_entries( f, st.st_dev, st.st_ino );
716 fclose( f );
718 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
719 if (!device && (f = fopen( "/etc/fstab", "r" )))
721 device = parse_mount_entries( f, st.st_dev, st.st_ino );
722 fclose( f );
724 #endif
725 if (device)
727 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
728 if (ret) strcpy( ret, device );
730 RtlLeaveCriticalSection( &dir_section );
732 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ ) || defined(__DragonFly__)
733 char *device = NULL;
734 int fd, res = -1;
735 struct stat st;
737 /* try to open it first to force it to get mounted */
738 if ((fd = open( root, O_RDONLY )) != -1)
740 res = fstat( fd, &st );
741 close( fd );
743 /* now try normal stat just in case */
744 if (res == -1) res = stat( root, &st );
745 if (res == -1) return NULL;
747 RtlEnterCriticalSection( &dir_section );
749 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
750 * pass NULL. Leave the argument in for symmetry.
752 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
753 if (device)
755 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
756 if (ret) strcpy( ret, device );
758 RtlLeaveCriticalSection( &dir_section );
760 #elif defined( sun )
761 FILE *f;
762 char *device = NULL;
763 int fd, res = -1;
764 struct stat st;
766 /* try to open it first to force it to get mounted */
767 if ((fd = open( root, O_RDONLY )) != -1)
769 res = fstat( fd, &st );
770 close( fd );
772 /* now try normal stat just in case */
773 if (res == -1) res = stat( root, &st );
774 if (res == -1) return NULL;
776 RtlEnterCriticalSection( &dir_section );
778 if ((f = fopen( "/etc/mnttab", "r" )))
780 device = parse_mount_entries( f, st.st_dev, st.st_ino);
781 fclose( f );
783 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
784 if (!device && (f = fopen( "/etc/vfstab", "r" )))
786 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
787 fclose( f );
789 if (device)
791 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
792 if (ret) strcpy( ret, device );
794 RtlLeaveCriticalSection( &dir_section );
796 #elif defined(__APPLE__)
797 struct statfs *mntStat;
798 struct stat st;
799 int i;
800 int mntSize;
801 dev_t dev;
802 ino_t ino;
803 static const char path_bsd_device[] = "/dev/disk";
804 int res;
806 res = stat( root, &st );
807 if (res == -1) return NULL;
809 dev = st.st_dev;
810 ino = st.st_ino;
812 RtlEnterCriticalSection( &dir_section );
814 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
816 for (i = 0; i < mntSize && !ret; i++)
818 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
819 if (st.st_dev != dev || st.st_ino != ino) continue;
821 /* FIXME add support for mounted network drive */
822 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
824 /* set return value to the corresponding raw BSD node */
825 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
826 if (ret)
828 strcpy(ret, "/dev/r");
829 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
833 RtlLeaveCriticalSection( &dir_section );
834 #else
835 static int warned;
836 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
837 #endif
838 return ret;
842 /***********************************************************************
843 * get_device_mount_point
845 * Return the current mount point for a device.
847 static char *get_device_mount_point( dev_t dev )
849 char *ret = NULL;
851 #ifdef linux
852 FILE *f;
854 RtlEnterCriticalSection( &dir_section );
856 #ifdef __ANDROID__
857 if ((f = fopen( "/proc/mounts", "r" )))
858 #else
859 if ((f = fopen( "/etc/mtab", "r" )))
860 #endif
862 struct mntent *entry;
863 struct stat st;
864 char *p, *device;
866 while ((entry = getmntent( f )))
868 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
869 if (!strcmp( entry->mnt_type, "nfs" ) ||
870 !strcmp( entry->mnt_type, "smbfs" ) ||
871 !strcmp( entry->mnt_type, "ncpfs" )) continue;
873 if (!strcmp( entry->mnt_type, "supermount" ))
875 if ((device = strstr( entry->mnt_opts, "dev=" )))
877 device += 4;
878 if ((p = strchr( device, ',' ))) *p = 0;
881 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
883 /* if device is a regular file check for a loop mount */
884 if ((device = strstr( entry->mnt_opts, "loop=" )))
886 device += 5;
887 if ((p = strchr( device, ',' ))) *p = 0;
890 else device = entry->mnt_fsname;
892 if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
894 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
895 if (ret) strcpy( ret, entry->mnt_dir );
896 break;
899 fclose( f );
901 RtlLeaveCriticalSection( &dir_section );
902 #elif defined(__APPLE__)
903 struct statfs *entry;
904 struct stat st;
905 int i, size;
907 RtlEnterCriticalSection( &dir_section );
909 size = getmntinfo( &entry, MNT_NOWAIT );
910 for (i = 0; i < size; i++)
912 if (stat( entry[i].f_mntfromname, &st ) == -1) continue;
913 if (S_ISBLK(st.st_mode) && st.st_rdev == dev)
915 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry[i].f_mntonname) + 1 );
916 if (ret) strcpy( ret, entry[i].f_mntonname );
917 break;
920 RtlLeaveCriticalSection( &dir_section );
921 #else
922 static int warned;
923 if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
924 #endif
925 return ret;
929 #if defined(HAVE_GETATTRLIST) && defined(ATTR_VOL_CAPABILITIES) && \
930 defined(VOL_CAPABILITIES_FORMAT) && defined(VOL_CAP_FMT_CASE_SENSITIVE)
932 struct get_fsid
934 ULONG size;
935 dev_t dev;
936 fsid_t fsid;
939 struct fs_cache
941 dev_t dev;
942 fsid_t fsid;
943 BOOLEAN case_sensitive;
944 } fs_cache[64];
946 struct vol_caps
948 ULONG size;
949 vol_capabilities_attr_t caps;
952 /***********************************************************************
953 * look_up_fs_cache
955 * Checks if the specified file system is in the cache.
957 static struct fs_cache *look_up_fs_cache( dev_t dev )
959 int i;
960 for (i = 0; i < sizeof(fs_cache)/sizeof(fs_cache[0]); i++)
961 if (fs_cache[i].dev == dev)
962 return fs_cache+i;
963 return NULL;
966 /***********************************************************************
967 * add_fs_cache
969 * Adds the specified file system to the cache.
971 static void add_fs_cache( dev_t dev, fsid_t fsid, BOOLEAN case_sensitive )
973 int i;
974 struct fs_cache *entry = look_up_fs_cache( dev );
975 static int once = 0;
976 if (entry)
978 /* Update the cache */
979 entry->fsid = fsid;
980 entry->case_sensitive = case_sensitive;
981 return;
984 /* Add a new entry */
985 for (i = 0; i < sizeof(fs_cache)/sizeof(fs_cache[0]); i++)
986 if (fs_cache[i].dev == 0)
988 /* This entry is empty, use it */
989 fs_cache[i].dev = dev;
990 fs_cache[i].fsid = fsid;
991 fs_cache[i].case_sensitive = case_sensitive;
992 return;
995 /* Cache is out of space, warn */
996 if (!once++)
997 WARN( "FS cache is out of space, expect performance problems\n" );
1000 /***********************************************************************
1001 * get_dir_case_sensitivity_attr
1003 * Checks if the volume containing the specified directory is case
1004 * sensitive or not. Uses getattrlist(2).
1006 static int get_dir_case_sensitivity_attr( const char *dir )
1008 char *mntpoint = NULL;
1009 struct attrlist attr;
1010 struct vol_caps caps;
1011 struct get_fsid get_fsid;
1012 struct fs_cache *entry;
1014 /* First get the FS ID of the volume */
1015 attr.bitmapcount = ATTR_BIT_MAP_COUNT;
1016 attr.reserved = 0;
1017 attr.commonattr = ATTR_CMN_DEVID|ATTR_CMN_FSID;
1018 attr.volattr = attr.dirattr = attr.fileattr = attr.forkattr = 0;
1019 get_fsid.size = 0;
1020 if (getattrlist( dir, &attr, &get_fsid, sizeof(get_fsid), 0 ) != 0 ||
1021 get_fsid.size != sizeof(get_fsid))
1022 return -1;
1023 /* Try to look it up in the cache */
1024 entry = look_up_fs_cache( get_fsid.dev );
1025 if (entry && !memcmp( &entry->fsid, &get_fsid.fsid, sizeof(fsid_t) ))
1026 /* Cache lookup succeeded */
1027 return entry->case_sensitive;
1028 /* Cache is stale at this point, we have to update it */
1030 mntpoint = get_device_mount_point( get_fsid.dev );
1031 /* Now look up the case-sensitivity */
1032 attr.commonattr = 0;
1033 attr.volattr = ATTR_VOL_INFO|ATTR_VOL_CAPABILITIES;
1034 if (getattrlist( mntpoint, &attr, &caps, sizeof(caps), 0 ) < 0)
1036 RtlFreeHeap( GetProcessHeap(), 0, mntpoint );
1037 add_fs_cache( get_fsid.dev, get_fsid.fsid, TRUE );
1038 return TRUE;
1040 RtlFreeHeap( GetProcessHeap(), 0, mntpoint );
1041 if (caps.size == sizeof(caps) &&
1042 (caps.caps.valid[VOL_CAPABILITIES_FORMAT] &
1043 (VOL_CAP_FMT_CASE_SENSITIVE | VOL_CAP_FMT_CASE_PRESERVING)) ==
1044 (VOL_CAP_FMT_CASE_SENSITIVE | VOL_CAP_FMT_CASE_PRESERVING))
1046 BOOLEAN ret;
1048 if ((caps.caps.capabilities[VOL_CAPABILITIES_FORMAT] &
1049 VOL_CAP_FMT_CASE_SENSITIVE) != VOL_CAP_FMT_CASE_SENSITIVE)
1050 ret = FALSE;
1051 else
1052 ret = TRUE;
1053 /* Update the cache */
1054 add_fs_cache( get_fsid.dev, get_fsid.fsid, ret );
1055 return ret;
1057 return FALSE;
1059 #endif
1061 /***********************************************************************
1062 * get_dir_case_sensitivity_stat
1064 * Checks if the volume containing the specified directory is case
1065 * sensitive or not. Uses statfs(2) or statvfs(2).
1067 static BOOLEAN get_dir_case_sensitivity_stat( const char *dir )
1069 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1070 struct statfs stfs;
1072 if (statfs( dir, &stfs ) == -1) return FALSE;
1073 /* Assume these file systems are always case insensitive on Mac OS.
1074 * For FreeBSD, only assume CIOPFS is case insensitive (AFAIK, Mac OS
1075 * is the only UNIX that supports case-insensitive lookup).
1077 if (!strcmp( stfs.f_fstypename, "fusefs" ) &&
1078 !strncmp( stfs.f_mntfromname, "ciopfs", 5 ))
1079 return FALSE;
1080 #ifdef __APPLE__
1081 if (!strcmp( stfs.f_fstypename, "msdos" ) ||
1082 !strcmp( stfs.f_fstypename, "cd9660" ) ||
1083 !strcmp( stfs.f_fstypename, "udf" ) ||
1084 !strcmp( stfs.f_fstypename, "ntfs" ) ||
1085 !strcmp( stfs.f_fstypename, "smbfs" ))
1086 return FALSE;
1087 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1088 if (!strcmp( stfs.f_fstypename, "hfs" ) && (stfs.f_fssubtype == 0 ||
1089 stfs.f_fssubtype == 1 ||
1090 stfs.f_fssubtype == 128))
1091 return FALSE;
1092 #else
1093 /* The field says "reserved", but a quick look at the kernel source
1094 * tells us that this "reserved" field is really the same as the
1095 * "fssubtype" field from the inode64 structure (see munge_statfs()
1096 * in <xnu-source>/bsd/vfs/vfs_syscalls.c).
1098 if (!strcmp( stfs.f_fstypename, "hfs" ) && (stfs.f_reserved1 == 0 ||
1099 stfs.f_reserved1 == 1 ||
1100 stfs.f_reserved1 == 128))
1101 return FALSE;
1102 #endif
1103 #endif
1104 return TRUE;
1106 #elif defined(__NetBSD__)
1107 struct statvfs stfs;
1109 if (statvfs( dir, &stfs ) == -1) return FALSE;
1110 /* Only assume CIOPFS is case insensitive. */
1111 if (strcmp( stfs.f_fstypename, "fusefs" ) ||
1112 strncmp( stfs.f_mntfromname, "ciopfs", 5 ))
1113 return TRUE;
1114 return FALSE;
1116 #elif defined(__linux__)
1117 struct statfs stfs;
1118 struct stat st;
1119 char *cifile;
1121 /* Only assume CIOPFS is case insensitive. */
1122 if (statfs( dir, &stfs ) == -1) return FALSE;
1123 if (stfs.f_type != 0x65735546 /* FUSE_SUPER_MAGIC */)
1124 return TRUE;
1125 /* Normally, we'd have to parse the mtab to find out exactly what
1126 * kind of FUSE FS this is. But, someone on wine-devel suggested
1127 * a shortcut. We'll stat a special file in the directory. If it's
1128 * there, we'll assume it's a CIOPFS, else not.
1129 * This will break if somebody puts a file named ".ciopfs" in a non-
1130 * CIOPFS directory.
1132 cifile = RtlAllocateHeap( GetProcessHeap(), 0, strlen( dir )+sizeof("/.ciopfs") );
1133 if (!cifile) return TRUE;
1134 strcpy( cifile, dir );
1135 strcat( cifile, "/.ciopfs" );
1136 if (stat( cifile, &st ) == 0)
1138 RtlFreeHeap( GetProcessHeap(), 0, cifile );
1139 return FALSE;
1141 RtlFreeHeap( GetProcessHeap(), 0, cifile );
1142 return TRUE;
1143 #else
1144 return TRUE;
1145 #endif
1149 /***********************************************************************
1150 * get_dir_case_sensitivity
1152 * Checks if the volume containing the specified directory is case
1153 * sensitive or not. Uses statfs(2) or statvfs(2).
1155 static BOOLEAN get_dir_case_sensitivity( const char *dir )
1157 #if defined(HAVE_GETATTRLIST) && defined(ATTR_VOL_CAPABILITIES) && \
1158 defined(VOL_CAPABILITIES_FORMAT) && defined(VOL_CAP_FMT_CASE_SENSITIVE)
1159 int case_sensitive = get_dir_case_sensitivity_attr( dir );
1160 if (case_sensitive != -1) return case_sensitive;
1161 #endif
1162 return get_dir_case_sensitivity_stat( dir );
1166 /***********************************************************************
1167 * init_options
1169 * Initialize the show_dot_files options.
1171 static DWORD WINAPI init_options( RTL_RUN_ONCE *once, void *param, void **context )
1173 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
1174 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
1175 char tmp[80];
1176 HANDLE root, hkey;
1177 DWORD dummy;
1178 OBJECT_ATTRIBUTES attr;
1179 UNICODE_STRING nameW;
1181 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
1182 attr.Length = sizeof(attr);
1183 attr.RootDirectory = root;
1184 attr.ObjectName = &nameW;
1185 attr.Attributes = 0;
1186 attr.SecurityDescriptor = NULL;
1187 attr.SecurityQualityOfService = NULL;
1188 RtlInitUnicodeString( &nameW, WineW );
1190 /* @@ Wine registry key: HKCU\Software\Wine */
1191 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
1193 RtlInitUnicodeString( &nameW, ShowDotFilesW );
1194 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
1196 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
1197 show_dot_files = IS_OPTION_TRUE( str[0] );
1199 NtClose( hkey );
1201 NtClose( root );
1203 /* a couple of directories that we don't want to return in directory searches */
1204 ignore_file( wine_get_config_dir() );
1205 ignore_file( "/dev" );
1206 ignore_file( "/proc" );
1207 #ifdef linux
1208 ignore_file( "/sys" );
1209 #endif
1210 return TRUE;
1214 /***********************************************************************
1215 * DIR_is_hidden_file
1217 * Check if the specified file should be hidden based on its name and the show dot files option.
1219 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
1221 WCHAR *p, *end;
1223 RtlRunOnceExecuteOnce( &init_once, init_options, NULL, NULL );
1225 if (show_dot_files) return FALSE;
1227 end = p = name->Buffer + name->Length/sizeof(WCHAR);
1228 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
1229 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
1230 if (p == end || *p != '.') return FALSE;
1231 /* make sure it isn't '.' or '..' */
1232 if (p + 1 == end) return FALSE;
1233 if (p[1] == '.' && p + 2 == end) return FALSE;
1234 return TRUE;
1238 /***********************************************************************
1239 * hash_short_file_name
1241 * Transform a Unix file name into a hashed DOS name. If the name is a valid
1242 * DOS name, it is converted to upper-case; otherwise it is replaced by a
1243 * hashed version that fits in 8.3 format.
1244 * 'buffer' must be at least 12 characters long.
1245 * Returns length of short name in bytes; short name is NOT null-terminated.
1247 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
1249 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
1251 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
1252 LPWSTR dst;
1253 unsigned short hash;
1254 int i;
1256 /* Compute the hash code of the file name */
1257 /* If you know something about hash functions, feel free to */
1258 /* insert a better algorithm here... */
1259 if (!is_case_sensitive)
1261 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
1262 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
1263 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
1265 else
1267 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
1268 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
1269 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
1272 /* Find last dot for start of the extension */
1273 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
1275 /* Copy first 4 chars, replacing invalid chars with '_' */
1276 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
1278 if (p == end || p == ext) break;
1279 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
1281 /* Pad to 5 chars with '~' */
1282 while (i-- >= 0) *dst++ = '~';
1284 /* Insert hash code converted to 3 ASCII chars */
1285 *dst++ = hash_chars[(hash >> 10) & 0x1f];
1286 *dst++ = hash_chars[(hash >> 5) & 0x1f];
1287 *dst++ = hash_chars[hash & 0x1f];
1289 /* Copy the first 3 chars of the extension (if any) */
1290 if (ext)
1292 *dst++ = '.';
1293 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
1294 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
1296 return dst - buffer;
1300 /***********************************************************************
1301 * match_filename
1303 * Check a long file name against a mask.
1305 * Tests (done in W95 DOS shell - case insensitive):
1306 * *.txt test1.test.txt *
1307 * *st1* test1.txt *
1308 * *.t??????.t* test1.ta.tornado.txt *
1309 * *tornado* test1.ta.tornado.txt *
1310 * t*t test1.ta.tornado.txt *
1311 * ?est* test1.txt *
1312 * ?est??? test1.txt -
1313 * *test1.txt* test1.txt *
1314 * h?l?o*t.dat hellothisisatest.dat *
1316 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
1318 BOOL mismatch;
1319 const WCHAR *name = name_str->Buffer;
1320 const WCHAR *mask = mask_str->Buffer;
1321 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
1322 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
1323 const WCHAR *lastjoker = NULL;
1324 const WCHAR *next_to_retry = NULL;
1326 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
1328 while (name < name_end && mask < mask_end)
1330 switch(*mask)
1332 case '*':
1333 mask++;
1334 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
1335 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
1336 lastjoker = mask;
1338 /* skip to the next match after the joker(s) */
1339 if (is_case_sensitive)
1340 while (name < name_end && (*name != *mask)) name++;
1341 else
1342 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
1343 next_to_retry = name;
1344 break;
1345 case '?':
1346 mask++;
1347 name++;
1348 break;
1349 default:
1350 if (is_case_sensitive) mismatch = (*mask != *name);
1351 else mismatch = (toupperW(*mask) != toupperW(*name));
1353 if (!mismatch)
1355 mask++;
1356 name++;
1357 if (mask == mask_end)
1359 if (name == name_end) return TRUE;
1360 if (lastjoker) mask = lastjoker;
1363 else /* mismatch ! */
1365 if (lastjoker) /* we had an '*', so we can try unlimitedly */
1367 mask = lastjoker;
1369 /* this scan sequence was a mismatch, so restart
1370 * 1 char after the first char we checked last time */
1371 next_to_retry++;
1372 name = next_to_retry;
1374 else return FALSE; /* bad luck */
1376 break;
1379 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
1380 mask++; /* Ignore trailing '.' or '*' in mask */
1381 return (name == name_end && mask == mask_end);
1385 /***********************************************************************
1386 * append_entry
1388 * helper for NtQueryDirectoryFile
1390 static union file_directory_info *append_entry( void *info_ptr, IO_STATUS_BLOCK *io, ULONG max_length,
1391 const char *long_name, const char *short_name,
1392 const UNICODE_STRING *mask, FILE_INFORMATION_CLASS class )
1394 union file_directory_info *info;
1395 int i, long_len, short_len, total_len;
1396 struct stat st;
1397 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
1398 WCHAR short_nameW[12];
1399 WCHAR *filename;
1400 UNICODE_STRING str;
1401 ULONG attributes;
1403 io->u.Status = STATUS_SUCCESS;
1404 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
1405 if (long_len == -1) return NULL;
1407 str.Buffer = long_nameW;
1408 str.Length = long_len * sizeof(WCHAR);
1409 str.MaximumLength = sizeof(long_nameW);
1411 if (short_name)
1413 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
1414 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
1415 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
1417 else /* generate a short name if necessary */
1419 BOOLEAN spaces;
1421 short_len = 0;
1422 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1423 short_len = hash_short_file_name( &str, short_nameW );
1426 TRACE( "long %s short %s mask %s\n",
1427 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
1429 if (mask && !match_filename( &str, mask ))
1431 if (!short_len) return NULL; /* no short name to match */
1432 str.Buffer = short_nameW;
1433 str.Length = short_len * sizeof(WCHAR);
1434 str.MaximumLength = sizeof(short_nameW);
1435 if (!match_filename( &str, mask )) return NULL;
1438 if (get_file_info( long_name, &st, &attributes ) == -1) return NULL;
1439 if (is_ignored_file( &st ))
1441 TRACE( "ignoring file %s\n", long_name );
1442 return NULL;
1444 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
1445 attributes |= FILE_ATTRIBUTE_HIDDEN;
1447 total_len = dir_info_size( class, long_len );
1448 if (io->Information + total_len > max_length)
1450 total_len = max_length - io->Information;
1451 io->u.Status = STATUS_BUFFER_OVERFLOW;
1453 info = (union file_directory_info *)((char *)info_ptr + io->Information);
1454 if (st.st_dev != curdir.dev) st.st_ino = 0; /* ignore inode if on a different device */
1455 /* all the structures start with a FileDirectoryInformation layout */
1456 fill_file_info( &st, attributes, info, class );
1457 info->dir.NextEntryOffset = total_len;
1458 info->dir.FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
1460 switch (class)
1462 case FileDirectoryInformation:
1463 info->dir.FileNameLength = long_len * sizeof(WCHAR);
1464 filename = info->dir.FileName;
1465 break;
1467 case FileFullDirectoryInformation:
1468 info->full.EaSize = 0; /* FIXME */
1469 info->full.FileNameLength = long_len * sizeof(WCHAR);
1470 filename = info->full.FileName;
1471 break;
1473 case FileIdFullDirectoryInformation:
1474 info->id_full.EaSize = 0; /* FIXME */
1475 info->id_full.FileNameLength = long_len * sizeof(WCHAR);
1476 filename = info->id_full.FileName;
1477 break;
1479 case FileBothDirectoryInformation:
1480 info->both.EaSize = 0; /* FIXME */
1481 info->both.ShortNameLength = short_len * sizeof(WCHAR);
1482 for (i = 0; i < short_len; i++) info->both.ShortName[i] = toupperW(short_nameW[i]);
1483 info->both.FileNameLength = long_len * sizeof(WCHAR);
1484 filename = info->both.FileName;
1485 break;
1487 case FileIdBothDirectoryInformation:
1488 info->id_both.EaSize = 0; /* FIXME */
1489 info->id_both.ShortNameLength = short_len * sizeof(WCHAR);
1490 for (i = 0; i < short_len; i++) info->id_both.ShortName[i] = toupperW(short_nameW[i]);
1491 info->id_both.FileNameLength = long_len * sizeof(WCHAR);
1492 filename = info->id_both.FileName;
1493 break;
1495 default:
1496 assert(0);
1497 return NULL;
1499 memcpy( filename, long_nameW, long_len * sizeof(WCHAR) );
1500 io->Information += total_len;
1501 return info;
1505 #ifdef VFAT_IOCTL_READDIR_BOTH
1507 /***********************************************************************
1508 * start_vfat_ioctl
1510 * Wrapper for the VFAT ioctl to work around various kernel bugs.
1511 * dir_section must be held by caller.
1513 static KERNEL_DIRENT *start_vfat_ioctl( int fd )
1515 static KERNEL_DIRENT *de;
1516 int res;
1518 if (!de)
1520 SIZE_T size = 2 * sizeof(*de) + page_size;
1521 void *addr = NULL;
1523 if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_RESERVE, PAGE_READWRITE ))
1524 return NULL;
1525 /* commit only the size needed for the dir entries */
1526 /* this leaves an extra unaccessible page, which should make the kernel */
1527 /* fail with -EFAULT before it stomps all over our memory */
1528 de = addr;
1529 size = 2 * sizeof(*de);
1530 NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_COMMIT, PAGE_READWRITE );
1533 /* set d_reclen to 65535 to work around an AFS kernel bug */
1534 de[0].d_reclen = 65535;
1535 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
1536 if (res == -1)
1538 if (errno != ENOENT) return NULL; /* VFAT ioctl probably not supported */
1539 de[0].d_reclen = 0; /* eof */
1541 else if (!res && de[0].d_reclen == 65535) return NULL; /* AFS bug */
1543 return de;
1547 /***********************************************************************
1548 * read_directory_vfat
1550 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
1552 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1553 BOOLEAN single_entry, const UNICODE_STRING *mask,
1554 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1557 size_t len;
1558 KERNEL_DIRENT *de;
1559 union file_directory_info *info, *last_info = NULL;
1561 io->u.Status = STATUS_SUCCESS;
1563 if (restart_scan) lseek( fd, 0, SEEK_SET );
1565 if (length < max_dir_info_size(class)) /* we may have to return a partial entry here */
1567 off_t old_pos = lseek( fd, 0, SEEK_CUR );
1569 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1571 while (de[0].d_reclen)
1573 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1574 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1575 de[0].d_name[len] = 0;
1576 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1577 de[1].d_name[len] = 0;
1579 if (de[1].d_name[0])
1580 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1581 else
1582 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1583 if (info)
1585 last_info = info;
1586 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1587 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1588 break;
1590 old_pos = lseek( fd, 0, SEEK_CUR );
1591 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1594 else /* we'll only return full entries, no need to worry about overflow */
1596 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1598 while (de[0].d_reclen)
1600 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1601 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1602 de[0].d_name[len] = 0;
1603 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1604 de[1].d_name[len] = 0;
1606 if (de[1].d_name[0])
1607 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1608 else
1609 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1610 if (info)
1612 last_info = info;
1613 if (single_entry) break;
1614 /* check if we still have enough space for the largest possible entry */
1615 if (io->Information + max_dir_info_size(class) > length) break;
1617 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1621 if (last_info) last_info->next = 0;
1622 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1623 return 0;
1625 #endif /* VFAT_IOCTL_READDIR_BOTH */
1628 #ifdef USE_GETDENTS
1629 /***********************************************************************
1630 * read_first_dent_name
1632 * reads name of first or second dentry (if they have inodes).
1634 static char *read_first_dent_name( int which, int fd, off_t second_offs, KERNEL_DIRENT64 *de_first_two,
1635 char *buffer, size_t size, BOOL *buffer_changed )
1637 KERNEL_DIRENT64 *de;
1638 int res;
1640 de = de_first_two;
1641 if (de != NULL)
1643 if (which == 1)
1644 de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1646 return de->d_ino ? de->d_name : NULL;
1649 *buffer_changed = TRUE;
1650 lseek( fd, which == 1 ? second_offs : 0, SEEK_SET );
1651 res = getdents64( fd, buffer, size );
1652 if (res <= 0)
1653 return NULL;
1655 de = (KERNEL_DIRENT64 *)buffer;
1656 return de->d_ino ? de->d_name : NULL;
1659 /***********************************************************************
1660 * read_directory_getdents
1662 * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
1664 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1665 BOOLEAN single_entry, const UNICODE_STRING *mask,
1666 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1668 static off_t second_entry_pos;
1669 static struct file_identity last_dir_id;
1670 off_t old_pos = 0, next_pos;
1671 size_t size = length;
1672 char *data, local_buffer[8192];
1673 KERNEL_DIRENT64 *de, *de_first_two = NULL;
1674 union file_directory_info *info, *last_info = NULL;
1675 const char *filename;
1676 BOOL data_buffer_changed;
1677 int res, swap_to;
1679 if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1681 size = sizeof(local_buffer);
1682 data = local_buffer;
1685 if (restart_scan) lseek( fd, 0, SEEK_SET );
1686 else
1688 old_pos = lseek( fd, 0, SEEK_CUR );
1689 if (old_pos == -1)
1691 io->u.Status = (errno == ENOENT) ? STATUS_NO_MORE_FILES : FILE_GetNtStatus();
1692 res = 0;
1693 goto done;
1697 io->u.Status = STATUS_SUCCESS;
1698 de = (KERNEL_DIRENT64 *)data;
1700 /* if old_pos is not 0 we don't know how many entries have been returned already,
1701 * so maintain second_entry_pos to know when to return '..' */
1702 if (old_pos != 0 && (last_dir_id.dev != curdir.dev || last_dir_id.ino != curdir.ino))
1704 lseek( fd, 0, SEEK_SET );
1705 res = getdents64( fd, data, size );
1706 if (res > 0)
1708 second_entry_pos = de->d_off;
1709 last_dir_id = curdir;
1711 lseek( fd, old_pos, SEEK_SET );
1714 res = getdents64( fd, data, size );
1715 if (res == -1)
1717 if (errno != ENOSYS)
1719 io->u.Status = FILE_GetNtStatus();
1720 res = 0;
1722 goto done;
1725 if (old_pos == 0 && res > 0)
1727 second_entry_pos = de->d_off;
1728 last_dir_id = curdir;
1729 if (res > de->d_reclen)
1730 de_first_two = de;
1733 while (res > 0)
1735 res -= de->d_reclen;
1736 next_pos = de->d_off;
1737 filename = NULL;
1739 /* we must return first 2 entries as "." and "..", but getdents64()
1740 * can return them anywhere, so swap first entries with "." and ".." */
1741 if (old_pos == 0)
1742 filename = ".";
1743 else if (old_pos == second_entry_pos)
1744 filename = "..";
1745 else if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))
1747 swap_to = !strcmp( de->d_name, "." ) ? 0 : 1;
1748 data_buffer_changed = FALSE;
1750 filename = read_first_dent_name( swap_to, fd, second_entry_pos, de_first_two,
1751 data, size, &data_buffer_changed );
1752 if (filename != NULL && (!strcmp( filename, "." ) || !strcmp( filename, ".." )))
1753 filename = read_first_dent_name( swap_to ^ 1, fd, second_entry_pos, NULL,
1754 data, size, &data_buffer_changed );
1755 if (data_buffer_changed)
1757 lseek( fd, next_pos, SEEK_SET );
1758 res = 0;
1761 else if (de->d_ino)
1762 filename = de->d_name;
1764 if (filename && (info = append_entry( buffer, io, length, filename, NULL, mask, class )))
1766 last_info = info;
1767 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1769 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1770 break;
1772 /* check if we still have enough space for the largest possible entry */
1773 if (single_entry || io->Information + max_dir_info_size(class) > length)
1775 if (res > 0) lseek( fd, next_pos, SEEK_SET ); /* set pos to next entry */
1776 break;
1779 old_pos = next_pos;
1780 /* move on to the next entry */
1781 if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1782 else
1784 res = getdents64( fd, data, size );
1785 de = (KERNEL_DIRENT64 *)data;
1786 de_first_two = NULL;
1790 if (last_info) last_info->next = 0;
1791 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1792 res = 0;
1793 done:
1794 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1795 return res;
1798 #elif defined HAVE_GETDIRENTRIES
1800 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1802 /* Darwin doesn't provide a version of getdirentries with support for 64-bit
1803 * inodes. When 64-bit inodes are enabled, the getdirentries symbol is mapped
1804 * to _getdirentries_is_not_available_when_64_bit_inodes_are_in_effect so that
1805 * we get link errors if we try to use it. We still need getdirentries, but we
1806 * don't need it to support 64-bit inodes. So, we use the legacy getdirentries
1807 * with 32-bit inodes. We have to be careful to use a corresponding dirent
1808 * structure, too.
1810 int darwin_legacy_getdirentries(int, char *, int, long *) __asm("_getdirentries");
1811 #define getdirentries darwin_legacy_getdirentries
1813 struct darwin_legacy_dirent {
1814 __uint32_t d_ino;
1815 __uint16_t d_reclen;
1816 __uint8_t d_type;
1817 __uint8_t d_namlen;
1818 char d_name[__DARWIN_MAXNAMLEN + 1];
1820 #define dirent darwin_legacy_dirent
1822 #endif
1824 /***********************************************************************
1825 * wine_getdirentries
1827 * Wrapper for the BSD getdirentries system call to fix a bug in the
1828 * Mac OS X version. For some file systems (at least Apple Filing
1829 * Protocol a.k.a. AFP), getdirentries resets the file position to 0
1830 * when it's about to return 0 (no more entries). So, a subsequent
1831 * getdirentries call starts over at the beginning again, causing an
1832 * infinite loop.
1834 static inline int wine_getdirentries(int fd, char *buf, int nbytes, long *basep)
1836 int res = getdirentries(fd, buf, nbytes, basep);
1837 #ifdef __APPLE__
1838 if (res == 0)
1839 lseek(fd, *basep, SEEK_SET);
1840 #endif
1841 return res;
1844 static inline int dir_reclen(struct dirent *de)
1846 #ifdef HAVE_STRUCT_DIRENT_D_RECLEN
1847 return de->d_reclen;
1848 #else
1849 return _DIRENT_RECLEN(de->d_namlen);
1850 #endif
1853 /***********************************************************************
1854 * read_directory_getdirentries
1856 * Read a directory using the BSD getdirentries system call; helper for NtQueryDirectoryFile.
1858 static int read_directory_getdirentries( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1859 BOOLEAN single_entry, const UNICODE_STRING *mask,
1860 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1862 long restart_pos;
1863 ULONG_PTR restart_info_pos = 0;
1864 size_t size, initial_size = length;
1865 int res, fake_dot_dot = 1;
1866 char *data, local_buffer[8192];
1867 struct dirent *de;
1868 union file_directory_info *info, *last_info = NULL, *restart_last_info = NULL;
1870 size = initial_size;
1871 data = local_buffer;
1872 if (size > sizeof(local_buffer) && !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1874 io->u.Status = STATUS_NO_MEMORY;
1875 return io->u.Status;
1878 if (restart_scan) lseek( fd, 0, SEEK_SET );
1880 io->u.Status = STATUS_SUCCESS;
1882 /* FIXME: should make sure size is larger than filesystem block size */
1883 res = wine_getdirentries( fd, data, size, &restart_pos );
1884 if (res == -1)
1886 io->u.Status = FILE_GetNtStatus();
1887 res = 0;
1888 goto done;
1891 de = (struct dirent *)data;
1893 if (restart_scan)
1895 /* check if we got . and .. from getdirentries */
1896 if (res > 0)
1898 if (!strcmp( de->d_name, "." ) && res > dir_reclen(de))
1900 struct dirent *next_de = (struct dirent *)(data + dir_reclen(de));
1901 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1904 /* make sure we have enough room for both entries */
1905 if (fake_dot_dot)
1907 const ULONG min_info_size = dir_info_size( class, 1 ) + dir_info_size( class, 2 );
1908 if (length < min_info_size || single_entry)
1910 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1911 fake_dot_dot = 0;
1915 if (fake_dot_dot)
1917 if ((info = append_entry( buffer, io, length, ".", NULL, mask, class )))
1918 last_info = info;
1919 if ((info = append_entry( buffer, io, length, "..", NULL, mask, class )))
1920 last_info = info;
1922 restart_last_info = last_info;
1923 restart_info_pos = io->Information;
1925 /* check if we still have enough space for the largest possible entry */
1926 if (last_info && io->Information + max_dir_info_size(class) > length)
1928 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1929 res = 0;
1934 while (res > 0)
1936 res -= dir_reclen(de);
1937 if (de->d_fileno &&
1938 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1939 ((info = append_entry( buffer, io, length, de->d_name, NULL, mask, class ))))
1941 last_info = info;
1942 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1944 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1945 if (restart_info_pos) /* if we have a complete read already, return it */
1947 io->u.Status = STATUS_SUCCESS;
1948 io->Information = restart_info_pos;
1949 last_info = restart_last_info;
1950 break;
1952 /* otherwise restart from the start with a smaller size */
1953 size = (char *)de - data;
1954 if (!size) break;
1955 io->Information = 0;
1956 last_info = NULL;
1957 goto restart;
1959 if (!has_wildcard( mask )) break;
1960 /* if we have to return but the buffer contains more data, restart with a smaller size */
1961 if (res > 0 && (single_entry || io->Information + max_dir_info_size(class) > length))
1963 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1964 size = (char *)de + dir_reclen(de) - data;
1965 io->Information = restart_info_pos;
1966 last_info = restart_last_info;
1967 goto restart;
1970 /* move on to the next entry */
1971 if (res > 0)
1973 de = (struct dirent *)((char *)de + dir_reclen(de));
1974 continue;
1976 if (size < initial_size) break; /* already restarted once, give up now */
1977 restart_last_info = last_info;
1978 restart_info_pos = io->Information;
1979 restart:
1980 res = wine_getdirentries( fd, data, size, &restart_pos );
1981 de = (struct dirent *)data;
1984 if (last_info) last_info->next = 0;
1985 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1986 res = 0;
1987 done:
1988 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1989 return res;
1992 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1993 #undef getdirentries
1994 #undef dirent
1995 #endif
1997 #endif /* HAVE_GETDIRENTRIES */
2000 /***********************************************************************
2001 * read_directory_readdir
2003 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
2005 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
2006 BOOLEAN single_entry, const UNICODE_STRING *mask,
2007 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
2009 DIR *dir;
2010 off_t i, old_pos = 0;
2011 struct dirent *de;
2012 union file_directory_info *info, *last_info = NULL;
2014 if (!(dir = opendir( "." )))
2016 io->u.Status = FILE_GetNtStatus();
2017 return;
2020 if (!restart_scan)
2022 old_pos = lseek( fd, 0, SEEK_CUR );
2023 /* skip the right number of entries */
2024 for (i = 0; i < old_pos - 2; i++)
2026 if (!readdir( dir ))
2028 closedir( dir );
2029 io->u.Status = STATUS_NO_MORE_FILES;
2030 return;
2034 io->u.Status = STATUS_SUCCESS;
2036 for (;;)
2038 if (old_pos == 0)
2039 info = append_entry( buffer, io, length, ".", NULL, mask, class );
2040 else if (old_pos == 1)
2041 info = append_entry( buffer, io, length, "..", NULL, mask, class );
2042 else if ((de = readdir( dir )))
2044 if (strcmp( de->d_name, "." ) && strcmp( de->d_name, ".." ))
2045 info = append_entry( buffer, io, length, de->d_name, NULL, mask, class );
2046 else
2047 info = NULL;
2049 else
2050 break;
2051 old_pos++;
2052 if (info)
2054 last_info = info;
2055 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
2057 old_pos--; /* restore pos to previous entry */
2058 break;
2060 if (single_entry) break;
2061 /* check if we still have enough space for the largest possible entry */
2062 if (io->Information + max_dir_info_size(class) > length) break;
2066 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
2067 closedir( dir );
2069 if (last_info) last_info->next = 0;
2070 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
2073 /***********************************************************************
2074 * read_directory_stat
2076 * Read a single file from a directory by determining whether the file
2077 * identified by mask exists using stat.
2079 static int read_directory_stat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
2080 BOOLEAN single_entry, const UNICODE_STRING *mask,
2081 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
2083 int unix_len, ret, used_default;
2084 char *unix_name;
2085 struct stat st;
2086 BOOL case_sensitive = get_dir_case_sensitivity(".");
2088 TRACE("looking up file %s\n", debugstr_us( mask ));
2090 unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
2091 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
2093 io->u.Status = STATUS_NO_MEMORY;
2094 return 0;
2096 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
2097 NULL, &used_default );
2098 if (ret > 0 && !used_default)
2100 unix_name[ret] = 0;
2101 if (restart_scan)
2103 lseek( fd, 0, SEEK_SET );
2105 else if (lseek( fd, 0, SEEK_CUR ) != 0)
2107 io->u.Status = STATUS_NO_MORE_FILES;
2108 ret = 0;
2109 goto done;
2112 ret = stat( unix_name, &st );
2113 if (case_sensitive && !ret)
2115 union file_directory_info *info = append_entry( buffer, io, length, unix_name, NULL, NULL, class );
2116 if (info)
2118 info->next = 0;
2119 if (io->u.Status != STATUS_BUFFER_OVERFLOW) lseek( fd, 1, SEEK_CUR );
2121 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
2123 else if (!case_sensitive && ret && (errno == ENOENT || errno == ENOTDIR))
2125 /* If the file does not exist, return that info.
2126 * If the file DOES exist, return failure and fallback to the next
2127 * read_directory_* function (we need to return the case-preserved
2128 * filename stored on the filesystem). */
2129 ret = 0;
2130 io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
2132 else
2134 ret = -1;
2137 else ret = -1;
2139 done:
2140 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2142 TRACE("returning %d\n", ret);
2144 return ret;
2147 #ifdef HAVE_GETATTRLIST
2148 /***********************************************************************
2149 * read_directory_getattrlist
2151 * Read a single file from a directory by determining whether the file
2152 * identified by mask exists using getattrlist.
2154 static int read_directory_getattrlist( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
2155 BOOLEAN single_entry, const UNICODE_STRING *mask,
2156 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
2158 int unix_len, ret, used_default;
2159 char *unix_name;
2160 struct attrlist attrlist;
2161 #include "pshpack4.h"
2162 struct
2164 u_int32_t length;
2165 struct attrreference name_reference;
2166 fsobj_type_t type;
2167 char name[NAME_MAX * 3 + 1];
2168 } attrlist_buffer;
2169 #include "poppack.h"
2171 TRACE("looking up file %s\n", debugstr_us( mask ));
2173 unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
2174 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
2176 io->u.Status = STATUS_NO_MEMORY;
2177 return 0;
2179 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
2180 NULL, &used_default );
2181 if (ret > 0 && !used_default)
2183 unix_name[ret] = 0;
2184 if (restart_scan)
2186 lseek( fd, 0, SEEK_SET );
2188 else if (lseek( fd, 0, SEEK_CUR ) != 0)
2190 io->u.Status = STATUS_NO_MORE_FILES;
2191 ret = 0;
2192 goto done;
2195 memset( &attrlist, 0, sizeof(attrlist) );
2196 attrlist.bitmapcount = ATTR_BIT_MAP_COUNT;
2197 attrlist.commonattr = ATTR_CMN_NAME | ATTR_CMN_OBJTYPE;
2198 ret = getattrlist( unix_name, &attrlist, &attrlist_buffer, sizeof(attrlist_buffer), FSOPT_NOFOLLOW );
2199 /* If unix_name named a symlink, the above may have succeeded even if the symlink is broken.
2200 Check that with another call without FSOPT_NOFOLLOW. We don't ask for any attributes. */
2201 if (!ret && attrlist_buffer.type == VLNK)
2203 u_int32_t dummy;
2204 attrlist.commonattr = 0;
2205 ret = getattrlist( unix_name, &attrlist, &dummy, sizeof(dummy), 0 );
2207 if (!ret)
2209 union file_directory_info *info = append_entry( buffer, io, length, attrlist_buffer.name, NULL, NULL, class );
2210 if (info)
2212 info->next = 0;
2213 if (io->u.Status != STATUS_BUFFER_OVERFLOW) lseek( fd, 1, SEEK_CUR );
2215 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
2217 else if ((errno == ENOENT || errno == ENOTDIR) && !get_dir_case_sensitivity("."))
2219 io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
2220 ret = 0;
2223 else ret = -1;
2225 done:
2226 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2228 TRACE("returning %d\n", ret);
2230 return ret;
2232 #endif
2235 /******************************************************************************
2236 * NtQueryDirectoryFile [NTDLL.@]
2237 * ZwQueryDirectoryFile [NTDLL.@]
2239 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
2240 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
2241 PIO_STATUS_BLOCK io,
2242 PVOID buffer, ULONG length,
2243 FILE_INFORMATION_CLASS info_class,
2244 BOOLEAN single_entry,
2245 PUNICODE_STRING mask,
2246 BOOLEAN restart_scan )
2248 int cwd, fd, needs_close;
2250 TRACE("(%p %p %p %p %p %p 0x%08x 0x%08x 0x%08x %s 0x%08x\n",
2251 handle, event, apc_routine, apc_context, io, buffer,
2252 length, info_class, single_entry, debugstr_us(mask),
2253 restart_scan);
2255 if (event || apc_routine)
2257 FIXME( "Unsupported yet option\n" );
2258 return io->u.Status = STATUS_NOT_IMPLEMENTED;
2260 switch (info_class)
2262 case FileDirectoryInformation:
2263 case FileBothDirectoryInformation:
2264 case FileFullDirectoryInformation:
2265 case FileIdBothDirectoryInformation:
2266 case FileIdFullDirectoryInformation:
2267 if (length < dir_info_size( info_class, 1 )) return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
2268 if (!buffer) return io->u.Status = STATUS_ACCESS_VIOLATION;
2269 break;
2270 default:
2271 FIXME( "Unsupported file info class %d\n", info_class );
2272 return io->u.Status = STATUS_NOT_IMPLEMENTED;
2275 if ((io->u.Status = server_get_unix_fd( handle, FILE_LIST_DIRECTORY, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
2276 return io->u.Status;
2278 io->Information = 0;
2280 RtlRunOnceExecuteOnce( &init_once, init_options, NULL, NULL );
2282 RtlEnterCriticalSection( &dir_section );
2284 cwd = open( ".", O_RDONLY );
2285 if (fchdir( fd ) != -1)
2287 struct stat st;
2288 fstat( fd, &st );
2289 curdir.dev = st.st_dev;
2290 curdir.ino = st.st_ino;
2291 #ifdef VFAT_IOCTL_READDIR_BOTH
2292 if ((read_directory_vfat( fd, io, buffer, length, single_entry,
2293 mask, restart_scan, info_class )) != -1) goto done;
2294 #endif
2295 if (!has_wildcard( mask ))
2297 #ifdef HAVE_GETATTRLIST
2298 if (read_directory_getattrlist( fd, io, buffer, length, single_entry,
2299 mask, restart_scan, info_class ) != -1) goto done;
2300 #endif
2301 if (read_directory_stat( fd, io, buffer, length, single_entry,
2302 mask, restart_scan, info_class ) != -1) goto done;
2304 #ifdef USE_GETDENTS
2305 if ((read_directory_getdents( fd, io, buffer, length, single_entry,
2306 mask, restart_scan, info_class )) != -1) goto done;
2307 #elif defined HAVE_GETDIRENTRIES
2308 if ((read_directory_getdirentries( fd, io, buffer, length, single_entry,
2309 mask, restart_scan, info_class )) != -1) goto done;
2310 #endif
2311 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan, info_class );
2313 done:
2314 if (cwd == -1 || fchdir( cwd ) == -1) chdir( "/" );
2316 else io->u.Status = FILE_GetNtStatus();
2318 RtlLeaveCriticalSection( &dir_section );
2320 if (needs_close) close( fd );
2321 if (cwd != -1) close( cwd );
2322 TRACE( "=> %x (%ld)\n", io->u.Status, io->Information );
2323 return io->u.Status;
2327 /***********************************************************************
2328 * find_file_in_dir
2330 * Find a file in a directory the hard way, by doing a case-insensitive search.
2331 * The file found is appended to unix_name at pos.
2332 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
2334 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
2335 BOOLEAN check_case, BOOLEAN *is_win_dir )
2337 WCHAR buffer[MAX_DIR_ENTRY_LEN];
2338 UNICODE_STRING str;
2339 BOOLEAN spaces, is_name_8_dot_3;
2340 DIR *dir;
2341 struct dirent *de;
2342 struct stat st;
2343 int ret, used_default;
2345 /* try a shortcut for this directory */
2347 unix_name[pos++] = '/';
2348 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
2349 NULL, &used_default );
2350 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
2351 /* so it cannot match the file we are looking for */
2352 if (ret >= 0 && !used_default)
2354 unix_name[pos + ret] = 0;
2355 if (!stat( unix_name, &st ))
2357 if (is_win_dir) *is_win_dir = is_same_file( &windir, &st );
2358 return STATUS_SUCCESS;
2361 if (check_case) goto not_found; /* we want an exact match */
2363 if (pos > 1) unix_name[pos - 1] = 0;
2364 else unix_name[1] = 0; /* keep the initial slash */
2366 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
2368 str.Buffer = (WCHAR *)name;
2369 str.Length = length * sizeof(WCHAR);
2370 str.MaximumLength = str.Length;
2371 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
2372 #ifndef VFAT_IOCTL_READDIR_BOTH
2373 is_name_8_dot_3 = is_name_8_dot_3 && length >= 8 && name[4] == '~';
2374 #endif
2376 if (!is_name_8_dot_3 && !get_dir_case_sensitivity( unix_name )) goto not_found;
2378 /* now look for it through the directory */
2380 #ifdef VFAT_IOCTL_READDIR_BOTH
2381 if (is_name_8_dot_3)
2383 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
2384 if (fd != -1)
2386 KERNEL_DIRENT *kde;
2388 RtlEnterCriticalSection( &dir_section );
2389 if ((kde = start_vfat_ioctl( fd )))
2391 unix_name[pos - 1] = '/';
2392 while (kde[0].d_reclen)
2394 /* make sure names are null-terminated to work around an x86-64 kernel bug */
2395 size_t len = min(kde[0].d_reclen, sizeof(kde[0].d_name) - 1 );
2396 kde[0].d_name[len] = 0;
2397 len = min(kde[1].d_reclen, sizeof(kde[1].d_name) - 1 );
2398 kde[1].d_name[len] = 0;
2400 if (kde[1].d_name[0])
2402 ret = ntdll_umbstowcs( 0, kde[1].d_name, strlen(kde[1].d_name),
2403 buffer, MAX_DIR_ENTRY_LEN );
2404 if (ret == length && !memicmpW( buffer, name, length))
2406 strcpy( unix_name + pos, kde[1].d_name );
2407 RtlLeaveCriticalSection( &dir_section );
2408 close( fd );
2409 goto success;
2412 ret = ntdll_umbstowcs( 0, kde[0].d_name, strlen(kde[0].d_name),
2413 buffer, MAX_DIR_ENTRY_LEN );
2414 if (ret == length && !memicmpW( buffer, name, length))
2416 strcpy( unix_name + pos,
2417 kde[1].d_name[0] ? kde[1].d_name : kde[0].d_name );
2418 RtlLeaveCriticalSection( &dir_section );
2419 close( fd );
2420 goto success;
2422 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)kde ) == -1)
2424 RtlLeaveCriticalSection( &dir_section );
2425 close( fd );
2426 goto not_found;
2430 RtlLeaveCriticalSection( &dir_section );
2431 close( fd );
2433 /* fall through to normal handling */
2435 #endif /* VFAT_IOCTL_READDIR_BOTH */
2437 if (!(dir = opendir( unix_name )))
2439 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
2440 else return FILE_GetNtStatus();
2442 unix_name[pos - 1] = '/';
2443 str.Buffer = buffer;
2444 str.MaximumLength = sizeof(buffer);
2445 while ((de = readdir( dir )))
2447 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
2448 if (ret == length && !memicmpW( buffer, name, length ))
2450 strcpy( unix_name + pos, de->d_name );
2451 closedir( dir );
2452 goto success;
2455 if (!is_name_8_dot_3) continue;
2457 str.Length = ret * sizeof(WCHAR);
2458 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
2460 WCHAR short_nameW[12];
2461 ret = hash_short_file_name( &str, short_nameW );
2462 if (ret == length && !memicmpW( short_nameW, name, length ))
2464 strcpy( unix_name + pos, de->d_name );
2465 closedir( dir );
2466 goto success;
2470 closedir( dir );
2472 not_found:
2473 unix_name[pos - 1] = 0;
2474 return STATUS_OBJECT_PATH_NOT_FOUND;
2476 success:
2477 if (is_win_dir && !stat( unix_name, &st )) *is_win_dir = is_same_file( &windir, &st );
2478 return STATUS_SUCCESS;
2482 #ifndef _WIN64
2484 static const WCHAR catrootW[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t',0};
2485 static const WCHAR catroot2W[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t','2',0};
2486 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};
2487 static const WCHAR driversetcW[] = {'s','y','s','t','e','m','3','2','\\','d','r','i','v','e','r','s','\\','e','t','c',0};
2488 static const WCHAR logfilesW[] = {'s','y','s','t','e','m','3','2','\\','l','o','g','f','i','l','e','s',0};
2489 static const WCHAR spoolW[] = {'s','y','s','t','e','m','3','2','\\','s','p','o','o','l',0};
2490 static const WCHAR system32W[] = {'s','y','s','t','e','m','3','2',0};
2491 static const WCHAR syswow64W[] = {'s','y','s','w','o','w','6','4',0};
2492 static const WCHAR sysnativeW[] = {'s','y','s','n','a','t','i','v','e',0};
2493 static const WCHAR regeditW[] = {'r','e','g','e','d','i','t','.','e','x','e',0};
2494 static const WCHAR wow_regeditW[] = {'s','y','s','w','o','w','6','4','\\','r','e','g','e','d','i','t','.','e','x','e',0};
2496 static struct
2498 const WCHAR *source;
2499 const WCHAR *dos_target;
2500 const char *unix_target;
2501 } redirects[] =
2503 { catrootW, NULL, NULL },
2504 { catroot2W, NULL, NULL },
2505 { driversstoreW, NULL, NULL },
2506 { driversetcW, NULL, NULL },
2507 { logfilesW, NULL, NULL },
2508 { spoolW, NULL, NULL },
2509 { system32W, syswow64W, NULL },
2510 { sysnativeW, system32W, NULL },
2511 { regeditW, wow_regeditW, NULL }
2514 static unsigned int nb_redirects;
2517 /***********************************************************************
2518 * get_redirect_target
2520 * Find the target unix name for a redirected dir.
2522 static const char *get_redirect_target( const char *windows_dir, const WCHAR *name )
2524 int used_default, len, pos, win_len = strlen( windows_dir );
2525 char *unix_name, *unix_target = NULL;
2526 NTSTATUS status;
2528 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, win_len + MAX_DIR_ENTRY_LEN + 2 )))
2529 return NULL;
2530 memcpy( unix_name, windows_dir, win_len );
2531 pos = win_len;
2533 while (*name)
2535 const WCHAR *end, *next;
2537 for (end = name; *end; end++) if (IS_SEPARATOR(*end)) break;
2538 for (next = end; *next; next++) if (!IS_SEPARATOR(*next)) break;
2540 status = find_file_in_dir( unix_name, pos, name, end - name, FALSE, NULL );
2541 if (status == STATUS_OBJECT_PATH_NOT_FOUND && !*next) /* not finding last element is ok */
2543 len = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2544 MAX_DIR_ENTRY_LEN - (pos - win_len), NULL, &used_default );
2545 if (len > 0 && !used_default)
2547 unix_name[pos] = '/';
2548 pos += len + 1;
2549 unix_name[pos] = 0;
2550 break;
2553 if (status) goto done;
2554 pos += strlen( unix_name + pos );
2555 name = next;
2558 if ((unix_target = RtlAllocateHeap( GetProcessHeap(), 0, pos - win_len )))
2559 memcpy( unix_target, unix_name + win_len + 1, pos - win_len );
2561 done:
2562 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2563 return unix_target;
2567 /***********************************************************************
2568 * init_redirects
2570 static void init_redirects(void)
2572 UNICODE_STRING nt_name;
2573 ANSI_STRING unix_name;
2574 NTSTATUS status;
2575 struct stat st;
2576 unsigned int i;
2578 if (!RtlDosPathNameToNtPathName_U( user_shared_data->NtSystemRoot, &nt_name, NULL, NULL ))
2580 ERR( "can't convert %s\n", debugstr_w(user_shared_data->NtSystemRoot) );
2581 return;
2583 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
2584 RtlFreeUnicodeString( &nt_name );
2585 if (status)
2587 ERR( "cannot open %s (%x)\n", debugstr_w(user_shared_data->NtSystemRoot), status );
2588 return;
2590 if (!stat( unix_name.Buffer, &st ))
2592 windir.dev = st.st_dev;
2593 windir.ino = st.st_ino;
2594 nb_redirects = sizeof(redirects) / sizeof(redirects[0]);
2595 for (i = 0; i < nb_redirects; i++)
2597 if (!redirects[i].dos_target) continue;
2598 redirects[i].unix_target = get_redirect_target( unix_name.Buffer, redirects[i].dos_target );
2599 TRACE( "%s -> %s\n", debugstr_w(redirects[i].source), redirects[i].unix_target );
2602 RtlFreeAnsiString( &unix_name );
2607 /***********************************************************************
2608 * match_redirect
2610 * Check if path matches a redirect name. If yes, return matched length.
2612 static int match_redirect( const WCHAR *path, int len, const WCHAR *redir, BOOLEAN check_case )
2614 int i = 0;
2616 while (i < len && *redir)
2618 if (IS_SEPARATOR(path[i]))
2620 if (*redir++ != '\\') return 0;
2621 while (i < len && IS_SEPARATOR(path[i])) i++;
2622 continue; /* move on to next path component */
2624 else if (check_case)
2626 if (path[i] != *redir) return 0;
2628 else
2630 if (tolowerW(path[i]) != tolowerW(*redir)) return 0;
2632 i++;
2633 redir++;
2635 if (*redir) return 0;
2636 if (i < len && !IS_SEPARATOR(path[i])) return 0;
2637 while (i < len && IS_SEPARATOR(path[i])) i++;
2638 return i;
2642 /***********************************************************************
2643 * get_redirect_path
2645 * Retrieve the Unix path corresponding to a redirected path if any.
2647 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, BOOLEAN check_case )
2649 unsigned int i;
2650 int len;
2652 for (i = 0; i < nb_redirects; i++)
2654 if ((len = match_redirect( name, length, redirects[i].source, check_case )))
2656 if (!redirects[i].unix_target) break;
2657 unix_name[pos++] = '/';
2658 strcpy( unix_name + pos, redirects[i].unix_target );
2659 return len;
2662 return 0;
2665 #else /* _WIN64 */
2667 /* there are no redirects on 64-bit */
2669 static const unsigned int nb_redirects = 0;
2671 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, BOOLEAN check_case )
2673 return 0;
2676 #endif
2678 /***********************************************************************
2679 * DIR_init_windows_dir
2681 void DIR_init_windows_dir( const WCHAR *win, const WCHAR *sys )
2683 /* FIXME: should probably store paths as NT file names */
2685 RtlCreateUnicodeString( &system_dir, sys );
2687 #ifndef _WIN64
2688 if (is_wow64) init_redirects();
2689 #endif
2693 /******************************************************************************
2694 * get_dos_device
2696 * Get the Unix path of a DOS device.
2698 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
2700 const char *config_dir = wine_get_config_dir();
2701 struct stat st;
2702 char *unix_name, *new_name, *dev;
2703 unsigned int i;
2704 int unix_len;
2706 /* make sure the device name is ASCII */
2707 for (i = 0; i < name_len; i++)
2708 if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
2710 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
2712 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2713 return STATUS_NO_MEMORY;
2715 strcpy( unix_name, config_dir );
2716 strcat( unix_name, "/dosdevices/" );
2717 dev = unix_name + strlen(unix_name);
2719 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
2720 dev[i] = 0;
2722 /* special case for drive devices */
2723 if (name_len == 2 && dev[1] == ':')
2725 dev[i++] = ':';
2726 dev[i] = 0;
2729 for (;;)
2731 if (!stat( unix_name, &st ))
2733 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
2734 unix_name_ret->Buffer = unix_name;
2735 unix_name_ret->Length = strlen(unix_name);
2736 unix_name_ret->MaximumLength = unix_len;
2737 return STATUS_SUCCESS;
2739 if (!dev) break;
2741 /* now try some defaults for it */
2742 if (!strcmp( dev, "aux" ))
2744 strcpy( dev, "com1" );
2745 continue;
2747 if (!strcmp( dev, "prn" ))
2749 strcpy( dev, "lpt1" );
2750 continue;
2753 new_name = NULL;
2754 if (dev[1] == ':' && dev[2] == ':') /* drive device */
2756 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
2757 new_name = get_default_drive_device( unix_name );
2759 else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( atoi(dev + 3 ));
2760 else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( atoi(dev + 3 ));
2762 if (!new_name) break;
2764 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2765 unix_name = new_name;
2766 unix_len = strlen(unix_name) + 1;
2767 dev = NULL; /* last try */
2769 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2770 return STATUS_BAD_DEVICE_TYPE;
2774 /* return the length of the DOS namespace prefix if any */
2775 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
2777 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
2778 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
2780 if (name->Length >= sizeof(nt_prefixW) &&
2781 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
2782 return sizeof(nt_prefixW) / sizeof(WCHAR);
2784 if (name->Length >= sizeof(dosdev_prefixW) &&
2785 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
2786 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
2788 return 0;
2792 /******************************************************************************
2793 * find_file_id
2795 * Recursively search directories from the dir queue for a given inode.
2797 static NTSTATUS find_file_id( ANSI_STRING *unix_name, ULONGLONG file_id, dev_t dev )
2799 unsigned int pos;
2800 DIR *dir;
2801 struct dirent *de;
2802 NTSTATUS status;
2803 struct stat st;
2805 while (!(status = next_dir_in_queue( unix_name->Buffer )))
2807 if (!(dir = opendir( unix_name->Buffer ))) continue;
2808 TRACE( "searching %s for %s\n", unix_name->Buffer, wine_dbgstr_longlong(file_id) );
2809 pos = strlen( unix_name->Buffer );
2810 if (pos + MAX_DIR_ENTRY_LEN >= unix_name->MaximumLength/sizeof(WCHAR))
2812 char *new = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name->Buffer,
2813 unix_name->MaximumLength * 2 );
2814 if (!new)
2816 closedir( dir );
2817 return STATUS_NO_MEMORY;
2819 unix_name->MaximumLength *= 2;
2820 unix_name->Buffer = new;
2822 unix_name->Buffer[pos++] = '/';
2823 while ((de = readdir( dir )))
2825 if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
2826 strcpy( unix_name->Buffer + pos, de->d_name );
2827 if (lstat( unix_name->Buffer, &st ) == -1) continue;
2828 if (st.st_dev != dev) continue;
2829 if (st.st_ino == file_id)
2831 closedir( dir );
2832 return STATUS_SUCCESS;
2834 if (!S_ISDIR( st.st_mode )) continue;
2835 if ((status = add_dir_to_queue( unix_name->Buffer )) != STATUS_SUCCESS)
2837 closedir( dir );
2838 return status;
2841 closedir( dir );
2843 return status;
2847 /******************************************************************************
2848 * file_id_to_unix_file_name
2850 * Lookup a file from its file id instead of its name.
2852 NTSTATUS file_id_to_unix_file_name( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name )
2854 enum server_fd_type type;
2855 int old_cwd, root_fd, needs_close;
2856 NTSTATUS status;
2857 ULONGLONG file_id;
2858 struct stat st, root_st;
2860 if (attr->ObjectName->Length != sizeof(ULONGLONG)) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2861 if (!attr->RootDirectory) return STATUS_INVALID_PARAMETER;
2862 memcpy( &file_id, attr->ObjectName->Buffer, sizeof(file_id) );
2864 unix_name->MaximumLength = 2 * MAX_DIR_ENTRY_LEN + 4;
2865 if (!(unix_name->Buffer = RtlAllocateHeap( GetProcessHeap(), 0, unix_name->MaximumLength )))
2866 return STATUS_NO_MEMORY;
2867 strcpy( unix_name->Buffer, "." );
2869 if ((status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
2870 goto done;
2872 if (type != FD_TYPE_DIR)
2874 status = STATUS_OBJECT_TYPE_MISMATCH;
2875 goto done;
2878 fstat( root_fd, &root_st );
2879 if (root_st.st_ino == file_id) /* shortcut for "." */
2881 status = STATUS_SUCCESS;
2882 goto done;
2885 RtlEnterCriticalSection( &dir_section );
2886 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2888 /* shortcut for ".." */
2889 if (!stat( "..", &st ) && st.st_dev == root_st.st_dev && st.st_ino == file_id)
2891 strcpy( unix_name->Buffer, ".." );
2892 status = STATUS_SUCCESS;
2894 else
2896 status = add_dir_to_queue( "." );
2897 if (!status)
2898 status = find_file_id( unix_name, file_id, root_st.st_dev );
2899 if (!status) /* get rid of "./" prefix */
2900 memmove( unix_name->Buffer, unix_name->Buffer + 2, strlen(unix_name->Buffer) - 1 );
2901 flush_dir_queue();
2903 if (fchdir( old_cwd ) == -1) chdir( "/" );
2905 else status = FILE_GetNtStatus();
2906 RtlLeaveCriticalSection( &dir_section );
2907 if (old_cwd != -1) close( old_cwd );
2909 done:
2910 if (status == STATUS_SUCCESS)
2912 TRACE( "%s -> %s\n", wine_dbgstr_longlong(file_id), debugstr_a(unix_name->Buffer) );
2913 unix_name->Length = strlen( unix_name->Buffer );
2915 else
2917 TRACE( "%s not found in dir %p\n", wine_dbgstr_longlong(file_id), attr->RootDirectory );
2918 RtlFreeHeap( GetProcessHeap(), 0, unix_name->Buffer );
2920 if (needs_close) close( root_fd );
2921 return status;
2925 /******************************************************************************
2926 * lookup_unix_name
2928 * Helper for nt_to_unix_file_name
2930 static NTSTATUS lookup_unix_name( const WCHAR *name, int name_len, char **buffer, int unix_len, int pos,
2931 UINT disposition, BOOLEAN check_case )
2933 NTSTATUS status;
2934 int ret, used_default, len;
2935 struct stat st;
2936 char *unix_name = *buffer;
2937 const BOOL redirect = nb_redirects && ntdll_get_thread_data()->wow64_redir;
2939 /* try a shortcut first */
2941 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
2942 NULL, &used_default );
2944 while (name_len && IS_SEPARATOR(*name))
2946 name++;
2947 name_len--;
2950 if (ret >= 0 && !used_default) /* if we used the default char the name didn't convert properly */
2952 char *p;
2953 unix_name[pos + ret] = 0;
2954 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
2955 if (!redirect || (!strstr( unix_name, "/windows/") && strncmp( unix_name, "windows/", 8 )))
2957 if (!stat( unix_name, &st ))
2959 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
2960 if (disposition == FILE_CREATE)
2961 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
2962 return STATUS_SUCCESS;
2967 if (!name_len) /* empty name -> drive root doesn't exist */
2968 return STATUS_OBJECT_PATH_NOT_FOUND;
2969 if (check_case && !redirect && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
2970 return STATUS_OBJECT_NAME_NOT_FOUND;
2972 /* now do it component by component */
2974 while (name_len)
2976 const WCHAR *end, *next;
2977 BOOLEAN is_win_dir = FALSE;
2979 end = name;
2980 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
2981 next = end;
2982 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
2983 name_len -= next - name;
2985 /* grow the buffer if needed */
2987 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
2989 char *new_name;
2990 unix_len += 2 * MAX_DIR_ENTRY_LEN;
2991 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
2992 return STATUS_NO_MEMORY;
2993 unix_name = *buffer = new_name;
2996 status = find_file_in_dir( unix_name, pos, name, end - name,
2997 check_case, redirect ? &is_win_dir : NULL );
2999 /* if this is the last element, not finding it is not necessarily fatal */
3000 if (!name_len)
3002 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
3004 status = STATUS_OBJECT_NAME_NOT_FOUND;
3005 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
3007 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
3008 MAX_DIR_ENTRY_LEN, NULL, &used_default );
3009 if (ret > 0 && !used_default)
3011 unix_name[pos] = '/';
3012 unix_name[pos + 1 + ret] = 0;
3013 status = STATUS_NO_SUCH_FILE;
3014 break;
3018 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
3020 status = STATUS_OBJECT_NAME_COLLISION;
3024 if (status != STATUS_SUCCESS) break;
3026 pos += strlen( unix_name + pos );
3027 name = next;
3029 if (is_win_dir && (len = get_redirect_path( unix_name, pos, name, name_len, check_case )))
3031 name += len;
3032 name_len -= len;
3033 pos += strlen( unix_name + pos );
3034 TRACE( "redirecting -> %s + %s\n", debugstr_a(unix_name), debugstr_w(name) );
3038 return status;
3042 /******************************************************************************
3043 * nt_to_unix_file_name_attr
3045 NTSTATUS nt_to_unix_file_name_attr( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name_ret,
3046 UINT disposition )
3048 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
3049 enum server_fd_type type;
3050 int old_cwd, root_fd, needs_close;
3051 const WCHAR *name, *p;
3052 char *unix_name;
3053 int name_len, unix_len;
3054 NTSTATUS status;
3055 BOOLEAN check_case = !(attr->Attributes & OBJ_CASE_INSENSITIVE);
3057 if (!attr->RootDirectory) /* without root dir fall back to normal lookup */
3058 return wine_nt_to_unix_file_name( attr->ObjectName, unix_name_ret, disposition, check_case );
3060 name = attr->ObjectName->Buffer;
3061 name_len = attr->ObjectName->Length / sizeof(WCHAR);
3063 if (name_len && IS_SEPARATOR(name[0])) return STATUS_INVALID_PARAMETER;
3065 /* check for invalid characters */
3066 for (p = name; p < name + name_len; p++)
3067 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
3069 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
3070 unix_len += MAX_DIR_ENTRY_LEN + 3;
3071 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
3072 return STATUS_NO_MEMORY;
3073 unix_name[0] = '.';
3075 if (!(status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
3077 if (type != FD_TYPE_DIR)
3079 if (needs_close) close( root_fd );
3080 status = STATUS_BAD_DEVICE_TYPE;
3082 else
3084 RtlEnterCriticalSection( &dir_section );
3085 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
3087 status = lookup_unix_name( name, name_len, &unix_name, unix_len, 1,
3088 disposition, check_case );
3089 if (fchdir( old_cwd ) == -1) chdir( "/" );
3091 else status = FILE_GetNtStatus();
3092 RtlLeaveCriticalSection( &dir_section );
3093 if (old_cwd != -1) close( old_cwd );
3094 if (needs_close) close( root_fd );
3097 else if (status == STATUS_OBJECT_TYPE_MISMATCH) status = STATUS_BAD_DEVICE_TYPE;
3099 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
3101 TRACE( "%s -> %s\n", debugstr_us(attr->ObjectName), debugstr_a(unix_name) );
3102 unix_name_ret->Buffer = unix_name;
3103 unix_name_ret->Length = strlen(unix_name);
3104 unix_name_ret->MaximumLength = unix_len;
3106 else
3108 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
3109 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3111 return status;
3115 /******************************************************************************
3116 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
3118 * Convert a file name from NT namespace to Unix namespace.
3120 * If disposition is not FILE_OPEN or FILE_OVERWRITE, the last path
3121 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
3122 * returned, but the unix name is still filled in properly.
3124 NTSTATUS CDECL wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
3125 UINT disposition, BOOLEAN check_case )
3127 static const WCHAR unixW[] = {'u','n','i','x'};
3128 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
3130 NTSTATUS status = STATUS_SUCCESS;
3131 const char *config_dir = wine_get_config_dir();
3132 const WCHAR *name, *p;
3133 struct stat st;
3134 char *unix_name;
3135 int pos, ret, name_len, unix_len, prefix_len, used_default;
3136 WCHAR prefix[MAX_DIR_ENTRY_LEN];
3137 BOOLEAN is_unix = FALSE;
3139 name = nameW->Buffer;
3140 name_len = nameW->Length / sizeof(WCHAR);
3142 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
3144 if (!(pos = get_dos_prefix_len( nameW )))
3145 return STATUS_BAD_DEVICE_TYPE; /* no DOS prefix, assume NT native name */
3147 name += pos;
3148 name_len -= pos;
3150 if (!name_len) return STATUS_OBJECT_NAME_INVALID;
3152 /* check for sub-directory */
3153 for (pos = 0; pos < name_len; pos++)
3155 if (IS_SEPARATOR(name[pos])) break;
3156 if (name[pos] < 32 || strchrW( invalid_charsW, name[pos] ))
3157 return STATUS_OBJECT_NAME_INVALID;
3159 if (pos > MAX_DIR_ENTRY_LEN)
3160 return STATUS_OBJECT_NAME_INVALID;
3162 if (pos == name_len) /* no subdir, plain DOS device */
3163 return get_dos_device( name, name_len, unix_name_ret );
3165 for (prefix_len = 0; prefix_len < pos; prefix_len++)
3166 prefix[prefix_len] = tolowerW(name[prefix_len]);
3168 name += prefix_len;
3169 name_len -= prefix_len;
3171 /* check for invalid characters (all chars except 0 are valid for unix) */
3172 is_unix = (prefix_len == 4 && !memcmp( prefix, unixW, sizeof(unixW) ));
3173 if (is_unix)
3175 for (p = name; p < name + name_len; p++)
3176 if (!*p) return STATUS_OBJECT_NAME_INVALID;
3177 check_case = TRUE;
3179 else
3181 for (p = name; p < name + name_len; p++)
3182 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
3185 unix_len = ntdll_wcstoumbs( 0, prefix, prefix_len, NULL, 0, NULL, NULL );
3186 unix_len += ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
3187 unix_len += MAX_DIR_ENTRY_LEN + 3;
3188 unix_len += strlen(config_dir) + sizeof("/dosdevices/");
3189 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
3190 return STATUS_NO_MEMORY;
3191 strcpy( unix_name, config_dir );
3192 strcat( unix_name, "/dosdevices/" );
3193 pos = strlen(unix_name);
3195 ret = ntdll_wcstoumbs( 0, prefix, prefix_len, unix_name + pos, unix_len - pos - 1,
3196 NULL, &used_default );
3197 if (!ret || used_default)
3199 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3200 return STATUS_OBJECT_NAME_INVALID;
3202 pos += ret;
3204 /* check if prefix exists (except for DOS drives to avoid extra stat calls) */
3206 if (prefix_len != 2 || prefix[1] != ':')
3208 unix_name[pos] = 0;
3209 if (lstat( unix_name, &st ) == -1 && errno == ENOENT)
3211 if (!is_unix)
3213 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3214 return STATUS_BAD_DEVICE_TYPE;
3216 pos = 0; /* fall back to unix root */
3220 status = lookup_unix_name( name, name_len, &unix_name, unix_len, pos, disposition, check_case );
3221 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
3223 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
3224 unix_name_ret->Buffer = unix_name;
3225 unix_name_ret->Length = strlen(unix_name);
3226 unix_name_ret->MaximumLength = unix_len;
3228 else
3230 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
3231 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3233 return status;
3237 /******************************************************************
3238 * RtlWow64EnableFsRedirection (NTDLL.@)
3240 NTSTATUS WINAPI RtlWow64EnableFsRedirection( BOOLEAN enable )
3242 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
3243 ntdll_get_thread_data()->wow64_redir = enable;
3244 return STATUS_SUCCESS;
3248 /******************************************************************
3249 * RtlWow64EnableFsRedirectionEx (NTDLL.@)
3251 NTSTATUS WINAPI RtlWow64EnableFsRedirectionEx( ULONG disable, ULONG *old_value )
3253 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
3254 if (((ULONG_PTR)old_value >> 16) == 0) return STATUS_ACCESS_VIOLATION;
3256 *old_value = !ntdll_get_thread_data()->wow64_redir;
3257 ntdll_get_thread_data()->wow64_redir = !disable;
3258 return STATUS_SUCCESS;
3262 /******************************************************************
3263 * RtlDoesFileExists_U (NTDLL.@)
3265 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
3267 UNICODE_STRING nt_name;
3268 FILE_BASIC_INFORMATION basic_info;
3269 OBJECT_ATTRIBUTES attr;
3270 BOOLEAN ret;
3272 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
3274 attr.Length = sizeof(attr);
3275 attr.RootDirectory = 0;
3276 attr.ObjectName = &nt_name;
3277 attr.Attributes = OBJ_CASE_INSENSITIVE;
3278 attr.SecurityDescriptor = NULL;
3279 attr.SecurityQualityOfService = NULL;
3281 ret = NtQueryAttributesFile(&attr, &basic_info) == STATUS_SUCCESS;
3283 RtlFreeUnicodeString( &nt_name );
3284 return ret;
3288 /***********************************************************************
3289 * DIR_unmount_device
3291 * Unmount the specified device.
3293 NTSTATUS DIR_unmount_device( HANDLE handle )
3295 NTSTATUS status;
3296 int unix_fd, needs_close;
3298 if (!(status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )))
3300 struct stat st;
3301 char *mount_point = NULL;
3303 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
3304 status = STATUS_INVALID_PARAMETER;
3305 else
3307 if ((mount_point = get_device_mount_point( st.st_rdev )))
3309 #ifdef __APPLE__
3310 static const char umount[] = "diskutil unmount >/dev/null 2>&1 ";
3311 #else
3312 static const char umount[] = "umount >/dev/null 2>&1 ";
3313 #endif
3314 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
3315 if (cmd)
3317 strcpy( cmd, umount );
3318 strcat( cmd, mount_point );
3319 system( cmd );
3320 RtlFreeHeap( GetProcessHeap(), 0, cmd );
3321 #ifdef linux
3322 /* umount will fail to release the loop device since we still have
3323 a handle to it, so we release it here */
3324 if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
3325 #endif
3327 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
3330 if (needs_close) close( unix_fd );
3332 return status;
3336 /******************************************************************************
3337 * DIR_get_unix_cwd
3339 * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
3340 * Returned value must be freed by caller.
3342 NTSTATUS DIR_get_unix_cwd( char **cwd )
3344 int old_cwd, unix_fd, needs_close;
3345 CURDIR *curdir;
3346 HANDLE handle;
3347 NTSTATUS status;
3349 RtlAcquirePebLock();
3351 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
3352 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
3353 else
3354 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
3356 if (!(handle = curdir->Handle))
3358 UNICODE_STRING dirW;
3359 OBJECT_ATTRIBUTES attr;
3360 IO_STATUS_BLOCK io;
3362 if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
3364 status = STATUS_OBJECT_NAME_INVALID;
3365 goto done;
3367 attr.Length = sizeof(attr);
3368 attr.RootDirectory = 0;
3369 attr.Attributes = OBJ_CASE_INSENSITIVE;
3370 attr.ObjectName = &dirW;
3371 attr.SecurityDescriptor = NULL;
3372 attr.SecurityQualityOfService = NULL;
3374 status = NtOpenFile( &handle, 0, &attr, &io, 0,
3375 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
3376 RtlFreeUnicodeString( &dirW );
3377 if (status != STATUS_SUCCESS) goto done;
3380 if ((status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )) == STATUS_SUCCESS)
3382 RtlEnterCriticalSection( &dir_section );
3384 if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
3386 unsigned int size = 512;
3388 for (;;)
3390 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
3392 status = STATUS_NO_MEMORY;
3393 break;
3395 if (getcwd( *cwd, size )) break;
3396 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
3397 if (errno != ERANGE)
3399 status = STATUS_OBJECT_PATH_INVALID;
3400 break;
3402 size *= 2;
3404 if (fchdir( old_cwd ) == -1) chdir( "/" );
3406 else status = FILE_GetNtStatus();
3408 RtlLeaveCriticalSection( &dir_section );
3409 if (old_cwd != -1) close( old_cwd );
3410 if (needs_close) close( unix_fd );
3412 if (!curdir->Handle) NtClose( handle );
3414 done:
3415 RtlReleasePebLock();
3416 return status;