msvcirt: Add implementation of streambuf::snextc.
[wine.git] / dlls / ntdll / directory.c
blob0e02f2e29585b4cb9f7d20755c454307f6ee1fe1
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 #include <sys/vnode.h>
52 #endif
53 #ifdef HAVE_SYS_IOCTL_H
54 #include <sys/ioctl.h>
55 #endif
56 #ifdef HAVE_LINUX_IOCTL_H
57 #include <linux/ioctl.h>
58 #endif
59 #ifdef HAVE_LINUX_MAJOR_H
60 # include <linux/major.h>
61 #endif
62 #ifdef HAVE_SYS_PARAM_H
63 #include <sys/param.h>
64 #endif
65 #ifdef HAVE_SYS_MOUNT_H
66 #include <sys/mount.h>
67 #endif
68 #ifdef HAVE_SYS_STATFS_H
69 #include <sys/statfs.h>
70 #endif
71 #include <time.h>
72 #ifdef HAVE_UNISTD_H
73 # include <unistd.h>
74 #endif
76 #include "ntstatus.h"
77 #define WIN32_NO_STATUS
78 #define NONAMELESSUNION
79 #include "windef.h"
80 #include "winnt.h"
81 #include "winternl.h"
82 #include "ddk/wdm.h"
83 #include "ntdll_misc.h"
84 #include "wine/unicode.h"
85 #include "wine/server.h"
86 #include "wine/list.h"
87 #include "wine/library.h"
88 #include "wine/debug.h"
90 WINE_DEFAULT_DEBUG_CHANNEL(file);
92 /* just in case... */
93 #undef VFAT_IOCTL_READDIR_BOTH
94 #undef USE_GETDENTS
96 #ifdef linux
98 /* We want the real kernel dirent structure, not the libc one */
99 typedef struct
101 long d_ino;
102 long d_off;
103 unsigned short d_reclen;
104 char d_name[256];
105 } KERNEL_DIRENT;
107 /* Define the VFAT ioctl to get both short and long file names */
108 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
110 #ifndef O_DIRECTORY
111 # define O_DIRECTORY 0200000 /* must be directory */
112 #endif
114 #ifdef __NR_getdents64
115 typedef struct
117 ULONG64 d_ino;
118 LONG64 d_off;
119 unsigned short d_reclen;
120 unsigned char d_type;
121 char d_name[256];
122 } KERNEL_DIRENT64;
124 #undef getdents64
125 static inline int getdents64( int fd, char *de, unsigned int size )
127 return syscall( __NR_getdents64, fd, de, size );
129 #define USE_GETDENTS
130 #endif
132 #endif /* linux */
134 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
135 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
137 #define INVALID_NT_CHARS '*','?','<','>','|','"'
138 #define INVALID_DOS_CHARS INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
140 #define MAX_DIR_ENTRY_LEN 255 /* max length of a directory entry in chars */
142 #define MAX_IGNORED_FILES 4
144 struct file_identity
146 dev_t dev;
147 ino_t ino;
150 static struct file_identity ignored_files[MAX_IGNORED_FILES];
151 static unsigned int ignored_files_count;
153 union file_directory_info
155 ULONG next;
156 FILE_DIRECTORY_INFORMATION dir;
157 FILE_BOTH_DIRECTORY_INFORMATION both;
158 FILE_FULL_DIRECTORY_INFORMATION full;
159 FILE_ID_BOTH_DIRECTORY_INFORMATION id_both;
160 FILE_ID_FULL_DIRECTORY_INFORMATION id_full;
163 static BOOL show_dot_files;
164 static RTL_RUN_ONCE init_once = RTL_RUN_ONCE_INIT;
166 /* at some point we may want to allow Winelib apps to set this */
167 static const BOOL is_case_sensitive = FALSE;
169 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
171 static struct file_identity curdir;
172 static struct file_identity windir;
174 static RTL_CRITICAL_SECTION dir_section;
175 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
177 0, 0, &dir_section,
178 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
179 0, 0, { (DWORD_PTR)(__FILE__ ": dir_section") }
181 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
184 /* check if a given Unicode char is OK in a DOS short name */
185 static inline BOOL is_invalid_dos_char( WCHAR ch )
187 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
188 if (ch > 0x7f) return TRUE;
189 return strchrW( invalid_chars, ch ) != NULL;
192 /* check if the device can be a mounted volume */
193 static inline BOOL is_valid_mounted_device( const struct stat *st )
195 #if defined(linux) || defined(__sun__)
196 return S_ISBLK( st->st_mode );
197 #else
198 /* disks are char devices on *BSD */
199 return S_ISCHR( st->st_mode );
200 #endif
203 static inline void ignore_file( const char *name )
205 struct stat st;
206 assert( ignored_files_count < MAX_IGNORED_FILES );
207 if (!stat( name, &st ))
209 ignored_files[ignored_files_count].dev = st.st_dev;
210 ignored_files[ignored_files_count].ino = st.st_ino;
211 ignored_files_count++;
215 static inline BOOL is_same_file( const struct file_identity *file, const struct stat *st )
217 return st->st_dev == file->dev && st->st_ino == file->ino;
220 static inline BOOL is_ignored_file( const struct stat *st )
222 unsigned int i;
224 for (i = 0; i < ignored_files_count; i++)
225 if (is_same_file( &ignored_files[i], st )) return TRUE;
226 return FALSE;
229 static inline unsigned int dir_info_size( FILE_INFORMATION_CLASS class, unsigned int len )
231 switch (class)
233 case FileDirectoryInformation:
234 return (FIELD_OFFSET( FILE_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
235 case FileBothDirectoryInformation:
236 return (FIELD_OFFSET( FILE_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
237 case FileFullDirectoryInformation:
238 return (FIELD_OFFSET( FILE_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
239 case FileIdBothDirectoryInformation:
240 return (FIELD_OFFSET( FILE_ID_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
241 case FileIdFullDirectoryInformation:
242 return (FIELD_OFFSET( FILE_ID_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
243 default:
244 assert(0);
245 return 0;
249 static inline unsigned int max_dir_info_size( FILE_INFORMATION_CLASS class )
251 return dir_info_size( class, MAX_DIR_ENTRY_LEN );
254 static inline BOOL has_wildcard( const UNICODE_STRING *mask )
256 return (!mask ||
257 memchrW( mask->Buffer, '*', mask->Length / sizeof(WCHAR) ) ||
258 memchrW( mask->Buffer, '?', mask->Length / sizeof(WCHAR) ));
262 /* support for a directory queue for filesystem searches */
264 struct dir_name
266 struct list entry;
267 char name[1];
270 static struct list dir_queue = LIST_INIT( dir_queue );
272 static NTSTATUS add_dir_to_queue( const char *name )
274 int len = strlen( name ) + 1;
275 struct dir_name *dir = RtlAllocateHeap( GetProcessHeap(), 0,
276 FIELD_OFFSET( struct dir_name, name[len] ));
277 if (!dir) return STATUS_NO_MEMORY;
278 strcpy( dir->name, name );
279 list_add_tail( &dir_queue, &dir->entry );
280 return STATUS_SUCCESS;
283 static NTSTATUS next_dir_in_queue( char *name )
285 struct list *head = list_head( &dir_queue );
286 if (head)
288 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
289 strcpy( name, dir->name );
290 list_remove( &dir->entry );
291 RtlFreeHeap( GetProcessHeap(), 0, dir );
292 return STATUS_SUCCESS;
294 return STATUS_OBJECT_NAME_NOT_FOUND;
297 static void flush_dir_queue(void)
299 struct list *head;
301 while ((head = list_head( &dir_queue )))
303 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
304 list_remove( &dir->entry );
305 RtlFreeHeap( GetProcessHeap(), 0, dir );
310 /***********************************************************************
311 * get_default_com_device
313 * Return the default device to use for serial ports.
315 static char *get_default_com_device( int num )
317 char *ret = NULL;
319 if (!num || num > 9) return ret;
320 #ifdef linux
321 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
322 if (ret)
324 strcpy( ret, "/dev/ttyS0" );
325 ret[strlen(ret) - 1] = '0' + num - 1;
327 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
328 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuau0") );
329 if (ret)
331 strcpy( ret, "/dev/cuau0" );
332 ret[strlen(ret) - 1] = '0' + num - 1;
334 #elif defined(__DragonFly__)
335 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuaa0") );
336 if (ret)
338 strcpy( ret, "/dev/cuaa0" );
339 ret[strlen(ret) - 1] = '0' + num - 1;
341 #else
342 FIXME( "no known default for device com%d\n", num );
343 #endif
344 return ret;
348 /***********************************************************************
349 * get_default_lpt_device
351 * Return the default device to use for parallel ports.
353 static char *get_default_lpt_device( int num )
355 char *ret = NULL;
357 if (!num || num > 9) return ret;
358 #ifdef linux
359 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
360 if (ret)
362 strcpy( ret, "/dev/lp0" );
363 ret[strlen(ret) - 1] = '0' + num - 1;
365 #else
366 FIXME( "no known default for device lpt%d\n", num );
367 #endif
368 return ret;
371 #ifdef __ANDROID__
373 static char *unescape_field( char *str )
375 char *in, *out;
377 for (in = out = str; *in; in++, out++)
379 *out = *in;
380 if (in[0] == '\\')
382 if (in[1] == '\\')
384 out[0] = '\\';
385 in++;
387 else if (in[1] == '0' && in[2] == '4' && in[3] == '0')
389 out[0] = ' ';
390 in += 3;
392 else if (in[1] == '0' && in[2] == '1' && in[3] == '1')
394 out[0] = '\t';
395 in += 3;
397 else if (in[1] == '0' && in[2] == '1' && in[3] == '2')
399 out[0] = '\n';
400 in += 3;
402 else if (in[1] == '1' && in[2] == '3' && in[3] == '4')
404 out[0] = '\\';
405 in += 3;
409 *out = '\0';
411 return str;
414 static inline char *get_field( char **str )
416 char *ret;
418 ret = strsep( str, " \t" );
419 if (*str) *str += strspn( *str, " \t" );
421 return ret;
423 /************************************************************************
424 * getmntent_replacement
426 * getmntent replacement for Android.
428 * NB returned static buffer is not thread safe; protect with dir_section.
430 static struct mntent *getmntent_replacement( FILE *f )
432 static struct mntent entry;
433 static char buf[4096];
434 char *p, *start;
438 if (!fgets( buf, sizeof(buf), f )) return NULL;
439 p = strchr( buf, '\n' );
440 if (p) *p = '\0';
441 else /* Partially unread line, move file ptr to end */
443 char tmp[1024];
444 while (fgets( tmp, sizeof(tmp), f ))
445 if (strchr( tmp, '\n' )) break;
447 start = buf + strspn( buf, " \t" );
448 } while (start[0] == '\0' || start[0] == '#');
450 p = get_field( &start );
451 entry.mnt_fsname = p ? unescape_field( p ) : (char *)"";
453 p = get_field( &start );
454 entry.mnt_dir = p ? unescape_field( p ) : (char *)"";
456 p = get_field( &start );
457 entry.mnt_type = p ? unescape_field( p ) : (char *)"";
459 p = get_field( &start );
460 entry.mnt_opts = p ? unescape_field( p ) : (char *)"";
462 p = get_field( &start );
463 entry.mnt_freq = p ? atoi(p) : 0;
465 p = get_field( &start );
466 entry.mnt_passno = p ? atoi(p) : 0;
468 return &entry;
470 #define getmntent getmntent_replacement
471 #endif
473 /***********************************************************************
474 * DIR_get_drives_info
476 * Retrieve device/inode number for all the drives. Helper for find_drive_root.
478 unsigned int DIR_get_drives_info( struct drive_info info[MAX_DOS_DRIVES] )
480 static struct drive_info cache[MAX_DOS_DRIVES];
481 static time_t last_update;
482 static unsigned int nb_drives;
483 unsigned int ret;
484 time_t now = time(NULL);
486 RtlEnterCriticalSection( &dir_section );
487 if (now != last_update)
489 const char *config_dir = wine_get_config_dir();
490 char *buffer, *p;
491 struct stat st;
492 unsigned int i;
494 if ((buffer = RtlAllocateHeap( GetProcessHeap(), 0,
495 strlen(config_dir) + sizeof("/dosdevices/a:") )))
497 strcpy( buffer, config_dir );
498 strcat( buffer, "/dosdevices/a:" );
499 p = buffer + strlen(buffer) - 2;
501 for (i = nb_drives = 0; i < MAX_DOS_DRIVES; i++)
503 *p = 'a' + i;
504 if (!stat( buffer, &st ))
506 cache[i].dev = st.st_dev;
507 cache[i].ino = st.st_ino;
508 nb_drives++;
510 else
512 cache[i].dev = 0;
513 cache[i].ino = 0;
516 RtlFreeHeap( GetProcessHeap(), 0, buffer );
518 last_update = now;
520 memcpy( info, cache, sizeof(cache) );
521 ret = nb_drives;
522 RtlLeaveCriticalSection( &dir_section );
523 return ret;
527 /***********************************************************************
528 * parse_mount_entries
530 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
533 #ifdef sun
534 #include <sys/vfstab.h>
535 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
537 struct vfstab entry;
538 struct stat st;
539 char *device;
541 while (! getvfsent( f, &entry ))
543 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
544 if (!strcmp( entry.vfs_fstype, "nfs" ) ||
545 !strcmp( entry.vfs_fstype, "smbfs" ) ||
546 !strcmp( entry.vfs_fstype, "ncpfs" )) continue;
548 if (stat( entry.vfs_mountp, &st ) == -1) continue;
549 if (st.st_dev != dev || st.st_ino != ino) continue;
550 if (!strcmp( entry.vfs_fstype, "fd" ))
552 if ((device = strstr( entry.vfs_mntopts, "dev=" )))
554 char *p = strchr( device + 4, ',' );
555 if (p) *p = 0;
556 return device + 4;
559 else
560 return entry.vfs_special;
562 return NULL;
564 #endif
566 #ifdef linux
567 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
569 struct mntent *entry;
570 struct stat st;
571 char *device;
573 while ((entry = getmntent( f )))
575 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
576 if (!strcmp( entry->mnt_type, "nfs" ) ||
577 !strcmp( entry->mnt_type, "smbfs" ) ||
578 !strcmp( entry->mnt_type, "ncpfs" )) continue;
580 if (stat( entry->mnt_dir, &st ) == -1) continue;
581 if (st.st_dev != dev || st.st_ino != ino) continue;
582 if (!strcmp( entry->mnt_type, "supermount" ))
584 if ((device = strstr( entry->mnt_opts, "dev=" )))
586 char *p = strchr( device + 4, ',' );
587 if (p) *p = 0;
588 return device + 4;
591 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
593 /* if device is a regular file check for a loop mount */
594 if ((device = strstr( entry->mnt_opts, "loop=" )))
596 char *p = strchr( device + 5, ',' );
597 if (p) *p = 0;
598 return device + 5;
601 else
602 return entry->mnt_fsname;
604 return NULL;
606 #endif
608 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
609 #include <fstab.h>
610 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
612 struct fstab *entry;
613 struct stat st;
615 while ((entry = getfsent()))
617 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
618 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
619 !strcmp( entry->fs_vfstype, "smbfs" ) ||
620 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
622 if (stat( entry->fs_file, &st ) == -1) continue;
623 if (st.st_dev != dev || st.st_ino != ino) continue;
624 return entry->fs_spec;
626 return NULL;
628 #endif
630 #ifdef sun
631 #include <sys/mnttab.h>
632 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
634 struct mnttab entry;
635 struct stat st;
636 char *device;
639 while (( ! getmntent( f, &entry) ))
641 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
642 if (!strcmp( entry.mnt_fstype, "nfs" ) ||
643 !strcmp( entry.mnt_fstype, "smbfs" ) ||
644 !strcmp( entry.mnt_fstype, "ncpfs" )) continue;
646 if (stat( entry.mnt_mountp, &st ) == -1) continue;
647 if (st.st_dev != dev || st.st_ino != ino) continue;
648 if (!strcmp( entry.mnt_fstype, "fd" ))
650 if ((device = strstr( entry.mnt_mntopts, "dev=" )))
652 char *p = strchr( device + 4, ',' );
653 if (p) *p = 0;
654 return device + 4;
657 else
658 return entry.mnt_special;
660 return NULL;
662 #endif
664 /***********************************************************************
665 * get_default_drive_device
667 * Return the default device to use for a given drive mount point.
669 static char *get_default_drive_device( const char *root )
671 char *ret = NULL;
673 #ifdef linux
674 FILE *f;
675 char *device = NULL;
676 int fd, res = -1;
677 struct stat st;
679 /* try to open it first to force it to get mounted */
680 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
682 res = fstat( fd, &st );
683 close( fd );
685 /* now try normal stat just in case */
686 if (res == -1) res = stat( root, &st );
687 if (res == -1) return NULL;
689 RtlEnterCriticalSection( &dir_section );
691 #ifdef __ANDROID__
692 if ((f = fopen( "/proc/mounts", "r" )))
694 device = parse_mount_entries( f, st.st_dev, st.st_ino );
695 fclose( f );
697 #else
698 if ((f = fopen( "/etc/mtab", "r" )))
700 device = parse_mount_entries( f, st.st_dev, st.st_ino );
701 fclose( f );
703 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
704 if (!device && (f = fopen( "/etc/fstab", "r" )))
706 device = parse_mount_entries( f, st.st_dev, st.st_ino );
707 fclose( f );
709 #endif
710 if (device)
712 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
713 if (ret) strcpy( ret, device );
715 RtlLeaveCriticalSection( &dir_section );
717 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ ) || defined(__DragonFly__)
718 char *device = NULL;
719 int fd, res = -1;
720 struct stat st;
722 /* try to open it first to force it to get mounted */
723 if ((fd = open( root, O_RDONLY )) != -1)
725 res = fstat( fd, &st );
726 close( fd );
728 /* now try normal stat just in case */
729 if (res == -1) res = stat( root, &st );
730 if (res == -1) return NULL;
732 RtlEnterCriticalSection( &dir_section );
734 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
735 * pass NULL. Leave the argument in for symmetry.
737 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
738 if (device)
740 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
741 if (ret) strcpy( ret, device );
743 RtlLeaveCriticalSection( &dir_section );
745 #elif defined( sun )
746 FILE *f;
747 char *device = NULL;
748 int fd, res = -1;
749 struct stat st;
751 /* try to open it first to force it to get mounted */
752 if ((fd = open( root, O_RDONLY )) != -1)
754 res = fstat( fd, &st );
755 close( fd );
757 /* now try normal stat just in case */
758 if (res == -1) res = stat( root, &st );
759 if (res == -1) return NULL;
761 RtlEnterCriticalSection( &dir_section );
763 if ((f = fopen( "/etc/mnttab", "r" )))
765 device = parse_mount_entries( f, st.st_dev, st.st_ino);
766 fclose( f );
768 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
769 if (!device && (f = fopen( "/etc/vfstab", "r" )))
771 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
772 fclose( f );
774 if (device)
776 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
777 if (ret) strcpy( ret, device );
779 RtlLeaveCriticalSection( &dir_section );
781 #elif defined(__APPLE__)
782 struct statfs *mntStat;
783 struct stat st;
784 int i;
785 int mntSize;
786 dev_t dev;
787 ino_t ino;
788 static const char path_bsd_device[] = "/dev/disk";
789 int res;
791 res = stat( root, &st );
792 if (res == -1) return NULL;
794 dev = st.st_dev;
795 ino = st.st_ino;
797 RtlEnterCriticalSection( &dir_section );
799 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
801 for (i = 0; i < mntSize && !ret; i++)
803 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
804 if (st.st_dev != dev || st.st_ino != ino) continue;
806 /* FIXME add support for mounted network drive */
807 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
809 /* set return value to the corresponding raw BSD node */
810 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
811 if (ret)
813 strcpy(ret, "/dev/r");
814 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
818 RtlLeaveCriticalSection( &dir_section );
819 #else
820 static int warned;
821 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
822 #endif
823 return ret;
827 /***********************************************************************
828 * get_device_mount_point
830 * Return the current mount point for a device.
832 static char *get_device_mount_point( dev_t dev )
834 char *ret = NULL;
836 #ifdef linux
837 FILE *f;
839 RtlEnterCriticalSection( &dir_section );
841 #ifdef __ANDROID__
842 if ((f = fopen( "/proc/mounts", "r" )))
843 #else
844 if ((f = fopen( "/etc/mtab", "r" )))
845 #endif
847 struct mntent *entry;
848 struct stat st;
849 char *p, *device;
851 while ((entry = getmntent( f )))
853 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
854 if (!strcmp( entry->mnt_type, "nfs" ) ||
855 !strcmp( entry->mnt_type, "smbfs" ) ||
856 !strcmp( entry->mnt_type, "ncpfs" )) continue;
858 if (!strcmp( entry->mnt_type, "supermount" ))
860 if ((device = strstr( entry->mnt_opts, "dev=" )))
862 device += 4;
863 if ((p = strchr( device, ',' ))) *p = 0;
866 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
868 /* if device is a regular file check for a loop mount */
869 if ((device = strstr( entry->mnt_opts, "loop=" )))
871 device += 5;
872 if ((p = strchr( device, ',' ))) *p = 0;
875 else device = entry->mnt_fsname;
877 if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
879 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
880 if (ret) strcpy( ret, entry->mnt_dir );
881 break;
884 fclose( f );
886 RtlLeaveCriticalSection( &dir_section );
887 #elif defined(__APPLE__)
888 struct statfs *entry;
889 struct stat st;
890 int i, size;
892 RtlEnterCriticalSection( &dir_section );
894 size = getmntinfo( &entry, MNT_NOWAIT );
895 for (i = 0; i < size; i++)
897 if (stat( entry[i].f_mntfromname, &st ) == -1) continue;
898 if (S_ISBLK(st.st_mode) && st.st_rdev == dev)
900 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry[i].f_mntonname) + 1 );
901 if (ret) strcpy( ret, entry[i].f_mntonname );
902 break;
905 RtlLeaveCriticalSection( &dir_section );
906 #else
907 static int warned;
908 if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
909 #endif
910 return ret;
914 #if defined(HAVE_GETATTRLIST) && defined(ATTR_VOL_CAPABILITIES) && \
915 defined(VOL_CAPABILITIES_FORMAT) && defined(VOL_CAP_FMT_CASE_SENSITIVE)
917 struct get_fsid
919 ULONG size;
920 dev_t dev;
921 fsid_t fsid;
924 struct fs_cache
926 dev_t dev;
927 fsid_t fsid;
928 BOOLEAN case_sensitive;
929 } fs_cache[64];
931 struct vol_caps
933 ULONG size;
934 vol_capabilities_attr_t caps;
937 /***********************************************************************
938 * look_up_fs_cache
940 * Checks if the specified file system is in the cache.
942 static struct fs_cache *look_up_fs_cache( dev_t dev )
944 int i;
945 for (i = 0; i < sizeof(fs_cache)/sizeof(fs_cache[0]); i++)
946 if (fs_cache[i].dev == dev)
947 return fs_cache+i;
948 return NULL;
951 /***********************************************************************
952 * add_fs_cache
954 * Adds the specified file system to the cache.
956 static void add_fs_cache( dev_t dev, fsid_t fsid, BOOLEAN case_sensitive )
958 int i;
959 struct fs_cache *entry = look_up_fs_cache( dev );
960 static int once = 0;
961 if (entry)
963 /* Update the cache */
964 entry->fsid = fsid;
965 entry->case_sensitive = case_sensitive;
966 return;
969 /* Add a new entry */
970 for (i = 0; i < sizeof(fs_cache)/sizeof(fs_cache[0]); i++)
971 if (fs_cache[i].dev == 0)
973 /* This entry is empty, use it */
974 fs_cache[i].dev = dev;
975 fs_cache[i].fsid = fsid;
976 fs_cache[i].case_sensitive = case_sensitive;
977 return;
980 /* Cache is out of space, warn */
981 if (!once++)
982 WARN( "FS cache is out of space, expect performance problems\n" );
985 /***********************************************************************
986 * get_dir_case_sensitivity_attr
988 * Checks if the volume containing the specified directory is case
989 * sensitive or not. Uses getattrlist(2).
991 static int get_dir_case_sensitivity_attr( const char *dir )
993 char *mntpoint = NULL;
994 struct attrlist attr;
995 struct vol_caps caps;
996 struct get_fsid get_fsid;
997 struct fs_cache *entry;
999 /* First get the FS ID of the volume */
1000 attr.bitmapcount = ATTR_BIT_MAP_COUNT;
1001 attr.reserved = 0;
1002 attr.commonattr = ATTR_CMN_DEVID|ATTR_CMN_FSID;
1003 attr.volattr = attr.dirattr = attr.fileattr = attr.forkattr = 0;
1004 get_fsid.size = 0;
1005 if (getattrlist( dir, &attr, &get_fsid, sizeof(get_fsid), 0 ) != 0 ||
1006 get_fsid.size != sizeof(get_fsid))
1007 return -1;
1008 /* Try to look it up in the cache */
1009 entry = look_up_fs_cache( get_fsid.dev );
1010 if (entry && !memcmp( &entry->fsid, &get_fsid.fsid, sizeof(fsid_t) ))
1011 /* Cache lookup succeeded */
1012 return entry->case_sensitive;
1013 /* Cache is stale at this point, we have to update it */
1015 mntpoint = get_device_mount_point( get_fsid.dev );
1016 /* Now look up the case-sensitivity */
1017 attr.commonattr = 0;
1018 attr.volattr = ATTR_VOL_INFO|ATTR_VOL_CAPABILITIES;
1019 if (getattrlist( mntpoint, &attr, &caps, sizeof(caps), 0 ) < 0)
1021 RtlFreeHeap( GetProcessHeap(), 0, mntpoint );
1022 add_fs_cache( get_fsid.dev, get_fsid.fsid, TRUE );
1023 return TRUE;
1025 RtlFreeHeap( GetProcessHeap(), 0, mntpoint );
1026 if (caps.size == sizeof(caps) &&
1027 (caps.caps.valid[VOL_CAPABILITIES_FORMAT] &
1028 (VOL_CAP_FMT_CASE_SENSITIVE | VOL_CAP_FMT_CASE_PRESERVING)) ==
1029 (VOL_CAP_FMT_CASE_SENSITIVE | VOL_CAP_FMT_CASE_PRESERVING))
1031 BOOLEAN ret;
1033 if ((caps.caps.capabilities[VOL_CAPABILITIES_FORMAT] &
1034 VOL_CAP_FMT_CASE_SENSITIVE) != VOL_CAP_FMT_CASE_SENSITIVE)
1035 ret = FALSE;
1036 else
1037 ret = TRUE;
1038 /* Update the cache */
1039 add_fs_cache( get_fsid.dev, get_fsid.fsid, ret );
1040 return ret;
1042 return FALSE;
1044 #endif
1046 /***********************************************************************
1047 * get_dir_case_sensitivity_stat
1049 * Checks if the volume containing the specified directory is case
1050 * sensitive or not. Uses statfs(2) or statvfs(2).
1052 static BOOLEAN get_dir_case_sensitivity_stat( const char *dir )
1054 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1055 struct statfs stfs;
1057 if (statfs( dir, &stfs ) == -1) return FALSE;
1058 /* Assume these file systems are always case insensitive on Mac OS.
1059 * For FreeBSD, only assume CIOPFS is case insensitive (AFAIK, Mac OS
1060 * is the only UNIX that supports case-insensitive lookup).
1062 if (!strcmp( stfs.f_fstypename, "fusefs" ) &&
1063 !strncmp( stfs.f_mntfromname, "ciopfs", 5 ))
1064 return FALSE;
1065 #ifdef __APPLE__
1066 if (!strcmp( stfs.f_fstypename, "msdos" ) ||
1067 !strcmp( stfs.f_fstypename, "cd9660" ) ||
1068 !strcmp( stfs.f_fstypename, "udf" ) ||
1069 !strcmp( stfs.f_fstypename, "ntfs" ) ||
1070 !strcmp( stfs.f_fstypename, "smbfs" ))
1071 return FALSE;
1072 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1073 if (!strcmp( stfs.f_fstypename, "hfs" ) && (stfs.f_fssubtype == 0 ||
1074 stfs.f_fssubtype == 1 ||
1075 stfs.f_fssubtype == 128))
1076 return FALSE;
1077 #else
1078 /* The field says "reserved", but a quick look at the kernel source
1079 * tells us that this "reserved" field is really the same as the
1080 * "fssubtype" field from the inode64 structure (see munge_statfs()
1081 * in <xnu-source>/bsd/vfs/vfs_syscalls.c).
1083 if (!strcmp( stfs.f_fstypename, "hfs" ) && (stfs.f_reserved1 == 0 ||
1084 stfs.f_reserved1 == 1 ||
1085 stfs.f_reserved1 == 128))
1086 return FALSE;
1087 #endif
1088 #endif
1089 return TRUE;
1091 #elif defined(__NetBSD__)
1092 struct statvfs stfs;
1094 if (statvfs( dir, &stfs ) == -1) return FALSE;
1095 /* Only assume CIOPFS is case insensitive. */
1096 if (strcmp( stfs.f_fstypename, "fusefs" ) ||
1097 strncmp( stfs.f_mntfromname, "ciopfs", 5 ))
1098 return TRUE;
1099 return FALSE;
1101 #elif defined(__linux__)
1102 struct statfs stfs;
1103 struct stat st;
1104 char *cifile;
1106 /* Only assume CIOPFS is case insensitive. */
1107 if (statfs( dir, &stfs ) == -1) return FALSE;
1108 if (stfs.f_type != 0x65735546 /* FUSE_SUPER_MAGIC */)
1109 return TRUE;
1110 /* Normally, we'd have to parse the mtab to find out exactly what
1111 * kind of FUSE FS this is. But, someone on wine-devel suggested
1112 * a shortcut. We'll stat a special file in the directory. If it's
1113 * there, we'll assume it's a CIOPFS, else not.
1114 * This will break if somebody puts a file named ".ciopfs" in a non-
1115 * CIOPFS directory.
1117 cifile = RtlAllocateHeap( GetProcessHeap(), 0, strlen( dir )+sizeof("/.ciopfs") );
1118 if (!cifile) return TRUE;
1119 strcpy( cifile, dir );
1120 strcat( cifile, "/.ciopfs" );
1121 if (stat( cifile, &st ) == 0)
1123 RtlFreeHeap( GetProcessHeap(), 0, cifile );
1124 return FALSE;
1126 RtlFreeHeap( GetProcessHeap(), 0, cifile );
1127 return TRUE;
1128 #else
1129 return TRUE;
1130 #endif
1134 /***********************************************************************
1135 * get_dir_case_sensitivity
1137 * Checks if the volume containing the specified directory is case
1138 * sensitive or not. Uses statfs(2) or statvfs(2).
1140 static BOOLEAN get_dir_case_sensitivity( const char *dir )
1142 #if defined(HAVE_GETATTRLIST) && defined(ATTR_VOL_CAPABILITIES) && \
1143 defined(VOL_CAPABILITIES_FORMAT) && defined(VOL_CAP_FMT_CASE_SENSITIVE)
1144 int case_sensitive = get_dir_case_sensitivity_attr( dir );
1145 if (case_sensitive != -1) return case_sensitive;
1146 #endif
1147 return get_dir_case_sensitivity_stat( dir );
1151 /***********************************************************************
1152 * init_options
1154 * Initialize the show_dot_files options.
1156 static DWORD WINAPI init_options( RTL_RUN_ONCE *once, void *param, void **context )
1158 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
1159 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
1160 char tmp[80];
1161 HANDLE root, hkey;
1162 DWORD dummy;
1163 OBJECT_ATTRIBUTES attr;
1164 UNICODE_STRING nameW;
1166 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
1167 attr.Length = sizeof(attr);
1168 attr.RootDirectory = root;
1169 attr.ObjectName = &nameW;
1170 attr.Attributes = 0;
1171 attr.SecurityDescriptor = NULL;
1172 attr.SecurityQualityOfService = NULL;
1173 RtlInitUnicodeString( &nameW, WineW );
1175 /* @@ Wine registry key: HKCU\Software\Wine */
1176 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
1178 RtlInitUnicodeString( &nameW, ShowDotFilesW );
1179 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
1181 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
1182 show_dot_files = IS_OPTION_TRUE( str[0] );
1184 NtClose( hkey );
1186 NtClose( root );
1188 /* a couple of directories that we don't want to return in directory searches */
1189 ignore_file( wine_get_config_dir() );
1190 ignore_file( "/dev" );
1191 ignore_file( "/proc" );
1192 #ifdef linux
1193 ignore_file( "/sys" );
1194 #endif
1195 return TRUE;
1199 /***********************************************************************
1200 * DIR_is_hidden_file
1202 * Check if the specified file should be hidden based on its name and the show dot files option.
1204 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
1206 WCHAR *p, *end;
1208 RtlRunOnceExecuteOnce( &init_once, init_options, NULL, NULL );
1210 if (show_dot_files) return FALSE;
1212 end = p = name->Buffer + name->Length/sizeof(WCHAR);
1213 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
1214 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
1215 if (p == end || *p != '.') return FALSE;
1216 /* make sure it isn't '.' or '..' */
1217 if (p + 1 == end) return FALSE;
1218 if (p[1] == '.' && p + 2 == end) return FALSE;
1219 return TRUE;
1223 /***********************************************************************
1224 * hash_short_file_name
1226 * Transform a Unix file name into a hashed DOS name. If the name is a valid
1227 * DOS name, it is converted to upper-case; otherwise it is replaced by a
1228 * hashed version that fits in 8.3 format.
1229 * 'buffer' must be at least 12 characters long.
1230 * Returns length of short name in bytes; short name is NOT null-terminated.
1232 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
1234 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
1236 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
1237 LPWSTR dst;
1238 unsigned short hash;
1239 int i;
1241 /* Compute the hash code of the file name */
1242 /* If you know something about hash functions, feel free to */
1243 /* insert a better algorithm here... */
1244 if (!is_case_sensitive)
1246 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
1247 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
1248 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
1250 else
1252 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
1253 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
1254 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
1257 /* Find last dot for start of the extension */
1258 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
1260 /* Copy first 4 chars, replacing invalid chars with '_' */
1261 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
1263 if (p == end || p == ext) break;
1264 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
1266 /* Pad to 5 chars with '~' */
1267 while (i-- >= 0) *dst++ = '~';
1269 /* Insert hash code converted to 3 ASCII chars */
1270 *dst++ = hash_chars[(hash >> 10) & 0x1f];
1271 *dst++ = hash_chars[(hash >> 5) & 0x1f];
1272 *dst++ = hash_chars[hash & 0x1f];
1274 /* Copy the first 3 chars of the extension (if any) */
1275 if (ext)
1277 *dst++ = '.';
1278 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
1279 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
1281 return dst - buffer;
1285 /***********************************************************************
1286 * match_filename
1288 * Check a long file name against a mask.
1290 * Tests (done in W95 DOS shell - case insensitive):
1291 * *.txt test1.test.txt *
1292 * *st1* test1.txt *
1293 * *.t??????.t* test1.ta.tornado.txt *
1294 * *tornado* test1.ta.tornado.txt *
1295 * t*t test1.ta.tornado.txt *
1296 * ?est* test1.txt *
1297 * ?est??? test1.txt -
1298 * *test1.txt* test1.txt *
1299 * h?l?o*t.dat hellothisisatest.dat *
1301 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
1303 BOOL mismatch;
1304 const WCHAR *name = name_str->Buffer;
1305 const WCHAR *mask = mask_str->Buffer;
1306 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
1307 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
1308 const WCHAR *lastjoker = NULL;
1309 const WCHAR *next_to_retry = NULL;
1311 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
1313 while (name < name_end && mask < mask_end)
1315 switch(*mask)
1317 case '*':
1318 mask++;
1319 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
1320 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
1321 lastjoker = mask;
1323 /* skip to the next match after the joker(s) */
1324 if (is_case_sensitive)
1325 while (name < name_end && (*name != *mask)) name++;
1326 else
1327 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
1328 next_to_retry = name;
1329 break;
1330 case '?':
1331 mask++;
1332 name++;
1333 break;
1334 default:
1335 if (is_case_sensitive) mismatch = (*mask != *name);
1336 else mismatch = (toupperW(*mask) != toupperW(*name));
1338 if (!mismatch)
1340 mask++;
1341 name++;
1342 if (mask == mask_end)
1344 if (name == name_end) return TRUE;
1345 if (lastjoker) mask = lastjoker;
1348 else /* mismatch ! */
1350 if (lastjoker) /* we had an '*', so we can try unlimitedly */
1352 mask = lastjoker;
1354 /* this scan sequence was a mismatch, so restart
1355 * 1 char after the first char we checked last time */
1356 next_to_retry++;
1357 name = next_to_retry;
1359 else return FALSE; /* bad luck */
1361 break;
1364 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
1365 mask++; /* Ignore trailing '.' or '*' in mask */
1366 return (name == name_end && mask == mask_end);
1370 /***********************************************************************
1371 * append_entry
1373 * helper for NtQueryDirectoryFile
1375 static union file_directory_info *append_entry( void *info_ptr, IO_STATUS_BLOCK *io, ULONG max_length,
1376 const char *long_name, const char *short_name,
1377 const UNICODE_STRING *mask, FILE_INFORMATION_CLASS class )
1379 union file_directory_info *info;
1380 int i, long_len, short_len, total_len;
1381 struct stat st;
1382 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
1383 WCHAR short_nameW[12];
1384 WCHAR *filename;
1385 UNICODE_STRING str;
1386 ULONG attributes;
1388 io->u.Status = STATUS_SUCCESS;
1389 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
1390 if (long_len == -1) return NULL;
1392 str.Buffer = long_nameW;
1393 str.Length = long_len * sizeof(WCHAR);
1394 str.MaximumLength = sizeof(long_nameW);
1396 if (short_name)
1398 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
1399 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
1400 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
1402 else /* generate a short name if necessary */
1404 BOOLEAN spaces;
1406 short_len = 0;
1407 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1408 short_len = hash_short_file_name( &str, short_nameW );
1411 TRACE( "long %s short %s mask %s\n",
1412 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
1414 if (mask && !match_filename( &str, mask ))
1416 if (!short_len) return NULL; /* no short name to match */
1417 str.Buffer = short_nameW;
1418 str.Length = short_len * sizeof(WCHAR);
1419 str.MaximumLength = sizeof(short_nameW);
1420 if (!match_filename( &str, mask )) return NULL;
1423 if (get_file_info( long_name, &st, &attributes ) == -1) return NULL;
1424 if (is_ignored_file( &st ))
1426 TRACE( "ignoring file %s\n", long_name );
1427 return NULL;
1429 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
1430 attributes |= FILE_ATTRIBUTE_HIDDEN;
1432 total_len = dir_info_size( class, long_len );
1433 if (io->Information + total_len > max_length)
1435 total_len = max_length - io->Information;
1436 io->u.Status = STATUS_BUFFER_OVERFLOW;
1438 info = (union file_directory_info *)((char *)info_ptr + io->Information);
1439 if (st.st_dev != curdir.dev) st.st_ino = 0; /* ignore inode if on a different device */
1440 /* all the structures start with a FileDirectoryInformation layout */
1441 fill_file_info( &st, attributes, info, class );
1442 info->dir.NextEntryOffset = total_len;
1443 info->dir.FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
1445 switch (class)
1447 case FileDirectoryInformation:
1448 info->dir.FileNameLength = long_len * sizeof(WCHAR);
1449 filename = info->dir.FileName;
1450 break;
1452 case FileFullDirectoryInformation:
1453 info->full.EaSize = 0; /* FIXME */
1454 info->full.FileNameLength = long_len * sizeof(WCHAR);
1455 filename = info->full.FileName;
1456 break;
1458 case FileIdFullDirectoryInformation:
1459 info->id_full.EaSize = 0; /* FIXME */
1460 info->id_full.FileNameLength = long_len * sizeof(WCHAR);
1461 filename = info->id_full.FileName;
1462 break;
1464 case FileBothDirectoryInformation:
1465 info->both.EaSize = 0; /* FIXME */
1466 info->both.ShortNameLength = short_len * sizeof(WCHAR);
1467 for (i = 0; i < short_len; i++) info->both.ShortName[i] = toupperW(short_nameW[i]);
1468 info->both.FileNameLength = long_len * sizeof(WCHAR);
1469 filename = info->both.FileName;
1470 break;
1472 case FileIdBothDirectoryInformation:
1473 info->id_both.EaSize = 0; /* FIXME */
1474 info->id_both.ShortNameLength = short_len * sizeof(WCHAR);
1475 for (i = 0; i < short_len; i++) info->id_both.ShortName[i] = toupperW(short_nameW[i]);
1476 info->id_both.FileNameLength = long_len * sizeof(WCHAR);
1477 filename = info->id_both.FileName;
1478 break;
1480 default:
1481 assert(0);
1482 return NULL;
1484 memcpy( filename, long_nameW, long_len * sizeof(WCHAR) );
1485 io->Information += total_len;
1486 return info;
1490 #ifdef VFAT_IOCTL_READDIR_BOTH
1492 /***********************************************************************
1493 * start_vfat_ioctl
1495 * Wrapper for the VFAT ioctl to work around various kernel bugs.
1496 * dir_section must be held by caller.
1498 static KERNEL_DIRENT *start_vfat_ioctl( int fd )
1500 static KERNEL_DIRENT *de;
1501 int res;
1503 if (!de)
1505 SIZE_T size = 2 * sizeof(*de) + page_size;
1506 void *addr = NULL;
1508 if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_RESERVE, PAGE_READWRITE ))
1509 return NULL;
1510 /* commit only the size needed for the dir entries */
1511 /* this leaves an extra unaccessible page, which should make the kernel */
1512 /* fail with -EFAULT before it stomps all over our memory */
1513 de = addr;
1514 size = 2 * sizeof(*de);
1515 NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_COMMIT, PAGE_READWRITE );
1518 /* set d_reclen to 65535 to work around an AFS kernel bug */
1519 de[0].d_reclen = 65535;
1520 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
1521 if (res == -1)
1523 if (errno != ENOENT) return NULL; /* VFAT ioctl probably not supported */
1524 de[0].d_reclen = 0; /* eof */
1526 else if (!res && de[0].d_reclen == 65535) return NULL; /* AFS bug */
1528 return de;
1532 /***********************************************************************
1533 * read_directory_vfat
1535 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
1537 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1538 BOOLEAN single_entry, const UNICODE_STRING *mask,
1539 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1542 size_t len;
1543 KERNEL_DIRENT *de;
1544 union file_directory_info *info, *last_info = NULL;
1546 io->u.Status = STATUS_SUCCESS;
1548 if (restart_scan) lseek( fd, 0, SEEK_SET );
1550 if (length < max_dir_info_size(class)) /* we may have to return a partial entry here */
1552 off_t old_pos = lseek( fd, 0, SEEK_CUR );
1554 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1556 while (de[0].d_reclen)
1558 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1559 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1560 de[0].d_name[len] = 0;
1561 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1562 de[1].d_name[len] = 0;
1564 if (de[1].d_name[0])
1565 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1566 else
1567 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1568 if (info)
1570 last_info = info;
1571 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1572 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1573 break;
1575 old_pos = lseek( fd, 0, SEEK_CUR );
1576 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1579 else /* we'll only return full entries, no need to worry about overflow */
1581 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1583 while (de[0].d_reclen)
1585 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1586 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1587 de[0].d_name[len] = 0;
1588 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1589 de[1].d_name[len] = 0;
1591 if (de[1].d_name[0])
1592 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1593 else
1594 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1595 if (info)
1597 last_info = info;
1598 if (single_entry) break;
1599 /* check if we still have enough space for the largest possible entry */
1600 if (io->Information + max_dir_info_size(class) > length) break;
1602 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1606 if (last_info) last_info->next = 0;
1607 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1608 return 0;
1610 #endif /* VFAT_IOCTL_READDIR_BOTH */
1613 #ifdef USE_GETDENTS
1614 /***********************************************************************
1615 * read_first_dent_name
1617 * reads name of first or second dentry (if they have inodes).
1619 static char *read_first_dent_name( int which, int fd, off_t second_offs, KERNEL_DIRENT64 *de_first_two,
1620 char *buffer, size_t size, BOOL *buffer_changed )
1622 KERNEL_DIRENT64 *de;
1623 int res;
1625 de = de_first_two;
1626 if (de != NULL)
1628 if (which == 1)
1629 de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1631 return de->d_ino ? de->d_name : NULL;
1634 *buffer_changed = TRUE;
1635 lseek( fd, which == 1 ? second_offs : 0, SEEK_SET );
1636 res = getdents64( fd, buffer, size );
1637 if (res <= 0)
1638 return NULL;
1640 de = (KERNEL_DIRENT64 *)buffer;
1641 return de->d_ino ? de->d_name : NULL;
1644 /***********************************************************************
1645 * read_directory_getdents
1647 * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
1649 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1650 BOOLEAN single_entry, const UNICODE_STRING *mask,
1651 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1653 static off_t second_entry_pos;
1654 static struct file_identity last_dir_id;
1655 off_t old_pos = 0, next_pos;
1656 size_t size = length;
1657 char *data, local_buffer[8192];
1658 KERNEL_DIRENT64 *de, *de_first_two = NULL;
1659 union file_directory_info *info, *last_info = NULL;
1660 const char *filename;
1661 BOOL data_buffer_changed;
1662 int res, swap_to;
1664 if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1666 size = sizeof(local_buffer);
1667 data = local_buffer;
1670 if (restart_scan) lseek( fd, 0, SEEK_SET );
1671 else
1673 old_pos = lseek( fd, 0, SEEK_CUR );
1674 if (old_pos == -1)
1676 io->u.Status = (errno == ENOENT) ? STATUS_NO_MORE_FILES : FILE_GetNtStatus();
1677 res = 0;
1678 goto done;
1682 io->u.Status = STATUS_SUCCESS;
1683 de = (KERNEL_DIRENT64 *)data;
1685 /* if old_pos is not 0 we don't know how many entries have been returned already,
1686 * so maintain second_entry_pos to know when to return '..' */
1687 if (old_pos != 0 && (last_dir_id.dev != curdir.dev || last_dir_id.ino != curdir.ino))
1689 lseek( fd, 0, SEEK_SET );
1690 res = getdents64( fd, data, size );
1691 if (res > 0)
1693 second_entry_pos = de->d_off;
1694 last_dir_id = curdir;
1696 lseek( fd, old_pos, SEEK_SET );
1699 res = getdents64( fd, data, size );
1700 if (res == -1)
1702 if (errno != ENOSYS)
1704 io->u.Status = FILE_GetNtStatus();
1705 res = 0;
1707 goto done;
1710 if (old_pos == 0 && res > 0)
1712 second_entry_pos = de->d_off;
1713 last_dir_id = curdir;
1714 if (res > de->d_reclen)
1715 de_first_two = de;
1718 while (res > 0)
1720 res -= de->d_reclen;
1721 next_pos = de->d_off;
1722 filename = NULL;
1724 /* we must return first 2 entries as "." and "..", but getdents64()
1725 * can return them anywhere, so swap first entries with "." and ".." */
1726 if (old_pos == 0)
1727 filename = ".";
1728 else if (old_pos == second_entry_pos)
1729 filename = "..";
1730 else if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))
1732 swap_to = !strcmp( de->d_name, "." ) ? 0 : 1;
1733 data_buffer_changed = FALSE;
1735 filename = read_first_dent_name( swap_to, fd, second_entry_pos, de_first_two,
1736 data, size, &data_buffer_changed );
1737 if (filename != NULL && (!strcmp( filename, "." ) || !strcmp( filename, ".." )))
1738 filename = read_first_dent_name( swap_to ^ 1, fd, second_entry_pos, NULL,
1739 data, size, &data_buffer_changed );
1740 if (data_buffer_changed)
1742 lseek( fd, next_pos, SEEK_SET );
1743 res = 0;
1746 else if (de->d_ino)
1747 filename = de->d_name;
1749 if (filename && (info = append_entry( buffer, io, length, filename, NULL, mask, class )))
1751 last_info = info;
1752 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1754 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1755 break;
1757 /* check if we still have enough space for the largest possible entry */
1758 if (single_entry || io->Information + max_dir_info_size(class) > length)
1760 if (res > 0) lseek( fd, next_pos, SEEK_SET ); /* set pos to next entry */
1761 break;
1764 old_pos = next_pos;
1765 /* move on to the next entry */
1766 if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1767 else
1769 res = getdents64( fd, data, size );
1770 de = (KERNEL_DIRENT64 *)data;
1771 de_first_two = NULL;
1775 if (last_info) last_info->next = 0;
1776 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1777 res = 0;
1778 done:
1779 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1780 return res;
1783 #elif defined HAVE_GETDIRENTRIES
1785 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1787 /* Darwin doesn't provide a version of getdirentries with support for 64-bit
1788 * inodes. When 64-bit inodes are enabled, the getdirentries symbol is mapped
1789 * to _getdirentries_is_not_available_when_64_bit_inodes_are_in_effect so that
1790 * we get link errors if we try to use it. We still need getdirentries, but we
1791 * don't need it to support 64-bit inodes. So, we use the legacy getdirentries
1792 * with 32-bit inodes. We have to be careful to use a corresponding dirent
1793 * structure, too.
1795 int darwin_legacy_getdirentries(int, char *, int, long *) __asm("_getdirentries");
1796 #define getdirentries darwin_legacy_getdirentries
1798 struct darwin_legacy_dirent {
1799 __uint32_t d_ino;
1800 __uint16_t d_reclen;
1801 __uint8_t d_type;
1802 __uint8_t d_namlen;
1803 char d_name[__DARWIN_MAXNAMLEN + 1];
1805 #define dirent darwin_legacy_dirent
1807 #endif
1809 /***********************************************************************
1810 * wine_getdirentries
1812 * Wrapper for the BSD getdirentries system call to fix a bug in the
1813 * Mac OS X version. For some file systems (at least Apple Filing
1814 * Protocol a.k.a. AFP), getdirentries resets the file position to 0
1815 * when it's about to return 0 (no more entries). So, a subsequent
1816 * getdirentries call starts over at the beginning again, causing an
1817 * infinite loop.
1819 static inline int wine_getdirentries(int fd, char *buf, int nbytes, long *basep)
1821 int res = getdirentries(fd, buf, nbytes, basep);
1822 #ifdef __APPLE__
1823 if (res == 0)
1824 lseek(fd, *basep, SEEK_SET);
1825 #endif
1826 return res;
1829 static inline int dir_reclen(struct dirent *de)
1831 #ifdef HAVE_STRUCT_DIRENT_D_RECLEN
1832 return de->d_reclen;
1833 #else
1834 return _DIRENT_RECLEN(de->d_namlen);
1835 #endif
1838 /***********************************************************************
1839 * read_directory_getdirentries
1841 * Read a directory using the BSD getdirentries system call; helper for NtQueryDirectoryFile.
1843 static int read_directory_getdirentries( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1844 BOOLEAN single_entry, const UNICODE_STRING *mask,
1845 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1847 long restart_pos;
1848 ULONG_PTR restart_info_pos = 0;
1849 size_t size, initial_size = length;
1850 int res, fake_dot_dot = 1;
1851 char *data, local_buffer[8192];
1852 struct dirent *de;
1853 union file_directory_info *info, *last_info = NULL, *restart_last_info = NULL;
1855 size = initial_size;
1856 data = local_buffer;
1857 if (size > sizeof(local_buffer) && !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1859 io->u.Status = STATUS_NO_MEMORY;
1860 return io->u.Status;
1863 if (restart_scan) lseek( fd, 0, SEEK_SET );
1865 io->u.Status = STATUS_SUCCESS;
1867 /* FIXME: should make sure size is larger than filesystem block size */
1868 res = wine_getdirentries( fd, data, size, &restart_pos );
1869 if (res == -1)
1871 io->u.Status = FILE_GetNtStatus();
1872 res = 0;
1873 goto done;
1876 de = (struct dirent *)data;
1878 if (restart_scan)
1880 /* check if we got . and .. from getdirentries */
1881 if (res > 0)
1883 if (!strcmp( de->d_name, "." ) && res > dir_reclen(de))
1885 struct dirent *next_de = (struct dirent *)(data + dir_reclen(de));
1886 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1889 /* make sure we have enough room for both entries */
1890 if (fake_dot_dot)
1892 const ULONG min_info_size = dir_info_size( class, 1 ) + dir_info_size( class, 2 );
1893 if (length < min_info_size || single_entry)
1895 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1896 fake_dot_dot = 0;
1900 if (fake_dot_dot)
1902 if ((info = append_entry( buffer, io, length, ".", NULL, mask, class )))
1903 last_info = info;
1904 if ((info = append_entry( buffer, io, length, "..", NULL, mask, class )))
1905 last_info = info;
1907 restart_last_info = last_info;
1908 restart_info_pos = io->Information;
1910 /* check if we still have enough space for the largest possible entry */
1911 if (last_info && io->Information + max_dir_info_size(class) > length)
1913 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1914 res = 0;
1919 while (res > 0)
1921 res -= dir_reclen(de);
1922 if (de->d_fileno &&
1923 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1924 ((info = append_entry( buffer, io, length, de->d_name, NULL, mask, class ))))
1926 last_info = info;
1927 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1929 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1930 if (restart_info_pos) /* if we have a complete read already, return it */
1932 io->u.Status = STATUS_SUCCESS;
1933 io->Information = restart_info_pos;
1934 last_info = restart_last_info;
1935 break;
1937 /* otherwise restart from the start with a smaller size */
1938 size = (char *)de - data;
1939 if (!size) break;
1940 io->Information = 0;
1941 last_info = NULL;
1942 goto restart;
1944 if (!has_wildcard( mask )) break;
1945 /* if we have to return but the buffer contains more data, restart with a smaller size */
1946 if (res > 0 && (single_entry || io->Information + max_dir_info_size(class) > length))
1948 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1949 size = (char *)de + dir_reclen(de) - data;
1950 io->Information = restart_info_pos;
1951 last_info = restart_last_info;
1952 goto restart;
1955 /* move on to the next entry */
1956 if (res > 0)
1958 de = (struct dirent *)((char *)de + dir_reclen(de));
1959 continue;
1961 if (size < initial_size) break; /* already restarted once, give up now */
1962 restart_last_info = last_info;
1963 restart_info_pos = io->Information;
1964 restart:
1965 res = wine_getdirentries( fd, data, size, &restart_pos );
1966 de = (struct dirent *)data;
1969 if (last_info) last_info->next = 0;
1970 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1971 res = 0;
1972 done:
1973 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1974 return res;
1977 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1978 #undef getdirentries
1979 #undef dirent
1980 #endif
1982 #endif /* HAVE_GETDIRENTRIES */
1985 /***********************************************************************
1986 * read_directory_readdir
1988 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1990 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1991 BOOLEAN single_entry, const UNICODE_STRING *mask,
1992 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1994 DIR *dir;
1995 off_t i, old_pos = 0;
1996 struct dirent *de;
1997 union file_directory_info *info, *last_info = NULL;
1999 if (!(dir = opendir( "." )))
2001 io->u.Status = FILE_GetNtStatus();
2002 return;
2005 if (!restart_scan)
2007 old_pos = lseek( fd, 0, SEEK_CUR );
2008 /* skip the right number of entries */
2009 for (i = 0; i < old_pos - 2; i++)
2011 if (!readdir( dir ))
2013 closedir( dir );
2014 io->u.Status = STATUS_NO_MORE_FILES;
2015 return;
2019 io->u.Status = STATUS_SUCCESS;
2021 for (;;)
2023 if (old_pos == 0)
2024 info = append_entry( buffer, io, length, ".", NULL, mask, class );
2025 else if (old_pos == 1)
2026 info = append_entry( buffer, io, length, "..", NULL, mask, class );
2027 else if ((de = readdir( dir )))
2029 if (strcmp( de->d_name, "." ) && strcmp( de->d_name, ".." ))
2030 info = append_entry( buffer, io, length, de->d_name, NULL, mask, class );
2031 else
2032 info = NULL;
2034 else
2035 break;
2036 old_pos++;
2037 if (info)
2039 last_info = info;
2040 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
2042 old_pos--; /* restore pos to previous entry */
2043 break;
2045 if (single_entry) break;
2046 /* check if we still have enough space for the largest possible entry */
2047 if (io->Information + max_dir_info_size(class) > length) break;
2051 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
2052 closedir( dir );
2054 if (last_info) last_info->next = 0;
2055 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
2058 /***********************************************************************
2059 * read_directory_stat
2061 * Read a single file from a directory by determining whether the file
2062 * identified by mask exists using stat.
2064 static int read_directory_stat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
2065 BOOLEAN single_entry, const UNICODE_STRING *mask,
2066 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
2068 int unix_len, ret, used_default;
2069 char *unix_name;
2070 struct stat st;
2071 BOOL case_sensitive = get_dir_case_sensitivity(".");
2073 TRACE("looking up file %s\n", debugstr_us( mask ));
2075 unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
2076 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
2078 io->u.Status = STATUS_NO_MEMORY;
2079 return 0;
2081 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
2082 NULL, &used_default );
2083 if (ret > 0 && !used_default)
2085 unix_name[ret] = 0;
2086 if (restart_scan)
2088 lseek( fd, 0, SEEK_SET );
2090 else if (lseek( fd, 0, SEEK_CUR ) != 0)
2092 io->u.Status = STATUS_NO_MORE_FILES;
2093 ret = 0;
2094 goto done;
2097 ret = stat( unix_name, &st );
2098 if (case_sensitive && !ret)
2100 union file_directory_info *info = append_entry( buffer, io, length, unix_name, NULL, NULL, class );
2101 if (info)
2103 info->next = 0;
2104 if (io->u.Status != STATUS_BUFFER_OVERFLOW) lseek( fd, 1, SEEK_CUR );
2106 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
2108 else if (!case_sensitive && ret && (errno == ENOENT || errno == ENOTDIR))
2110 /* If the file does not exist, return that info.
2111 * If the file DOES exist, return failure and fallback to the next
2112 * read_directory_* function (we need to return the case-preserved
2113 * filename stored on the filesystem). */
2114 ret = 0;
2115 io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
2117 else
2119 ret = -1;
2122 else ret = -1;
2124 done:
2125 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2127 TRACE("returning %d\n", ret);
2129 return ret;
2132 #ifdef HAVE_GETATTRLIST
2133 /***********************************************************************
2134 * read_directory_getattrlist
2136 * Read a single file from a directory by determining whether the file
2137 * identified by mask exists using getattrlist.
2139 static int read_directory_getattrlist( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
2140 BOOLEAN single_entry, const UNICODE_STRING *mask,
2141 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
2143 int unix_len, ret, used_default;
2144 char *unix_name;
2145 struct attrlist attrlist;
2146 #include "pshpack4.h"
2147 struct
2149 u_int32_t length;
2150 struct attrreference name_reference;
2151 fsobj_type_t type;
2152 char name[NAME_MAX * 3 + 1];
2153 } attrlist_buffer;
2154 #include "poppack.h"
2156 TRACE("looking up file %s\n", debugstr_us( mask ));
2158 unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
2159 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
2161 io->u.Status = STATUS_NO_MEMORY;
2162 return 0;
2164 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
2165 NULL, &used_default );
2166 if (ret > 0 && !used_default)
2168 unix_name[ret] = 0;
2169 if (restart_scan)
2171 lseek( fd, 0, SEEK_SET );
2173 else if (lseek( fd, 0, SEEK_CUR ) != 0)
2175 io->u.Status = STATUS_NO_MORE_FILES;
2176 ret = 0;
2177 goto done;
2180 memset( &attrlist, 0, sizeof(attrlist) );
2181 attrlist.bitmapcount = ATTR_BIT_MAP_COUNT;
2182 attrlist.commonattr = ATTR_CMN_NAME | ATTR_CMN_OBJTYPE;
2183 ret = getattrlist( unix_name, &attrlist, &attrlist_buffer, sizeof(attrlist_buffer), FSOPT_NOFOLLOW );
2184 /* If unix_name named a symlink, the above may have succeeded even if the symlink is broken.
2185 Check that with another call without FSOPT_NOFOLLOW. We don't ask for any attributes. */
2186 if (!ret && attrlist_buffer.type == VLNK)
2188 u_int32_t dummy;
2189 attrlist.commonattr = 0;
2190 ret = getattrlist( unix_name, &attrlist, &dummy, sizeof(dummy), 0 );
2192 if (!ret)
2194 union file_directory_info *info = append_entry( buffer, io, length, attrlist_buffer.name, NULL, NULL, class );
2195 if (info)
2197 info->next = 0;
2198 if (io->u.Status != STATUS_BUFFER_OVERFLOW) lseek( fd, 1, SEEK_CUR );
2200 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
2202 else if ((errno == ENOENT || errno == ENOTDIR) && !get_dir_case_sensitivity("."))
2204 io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
2205 ret = 0;
2208 else ret = -1;
2210 done:
2211 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2213 TRACE("returning %d\n", ret);
2215 return ret;
2217 #endif
2220 /******************************************************************************
2221 * NtQueryDirectoryFile [NTDLL.@]
2222 * ZwQueryDirectoryFile [NTDLL.@]
2224 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
2225 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
2226 PIO_STATUS_BLOCK io,
2227 PVOID buffer, ULONG length,
2228 FILE_INFORMATION_CLASS info_class,
2229 BOOLEAN single_entry,
2230 PUNICODE_STRING mask,
2231 BOOLEAN restart_scan )
2233 int cwd, fd, needs_close;
2235 TRACE("(%p %p %p %p %p %p 0x%08x 0x%08x 0x%08x %s 0x%08x\n",
2236 handle, event, apc_routine, apc_context, io, buffer,
2237 length, info_class, single_entry, debugstr_us(mask),
2238 restart_scan);
2240 if (event || apc_routine)
2242 FIXME( "Unsupported yet option\n" );
2243 return io->u.Status = STATUS_NOT_IMPLEMENTED;
2245 switch (info_class)
2247 case FileDirectoryInformation:
2248 case FileBothDirectoryInformation:
2249 case FileFullDirectoryInformation:
2250 case FileIdBothDirectoryInformation:
2251 case FileIdFullDirectoryInformation:
2252 if (length < dir_info_size( info_class, 1 )) return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
2253 if (!buffer) return io->u.Status = STATUS_ACCESS_VIOLATION;
2254 break;
2255 default:
2256 FIXME( "Unsupported file info class %d\n", info_class );
2257 return io->u.Status = STATUS_NOT_IMPLEMENTED;
2260 if ((io->u.Status = server_get_unix_fd( handle, FILE_LIST_DIRECTORY, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
2261 return io->u.Status;
2263 io->Information = 0;
2265 RtlRunOnceExecuteOnce( &init_once, init_options, NULL, NULL );
2267 RtlEnterCriticalSection( &dir_section );
2269 cwd = open( ".", O_RDONLY );
2270 if (fchdir( fd ) != -1)
2272 struct stat st;
2273 fstat( fd, &st );
2274 curdir.dev = st.st_dev;
2275 curdir.ino = st.st_ino;
2276 #ifdef VFAT_IOCTL_READDIR_BOTH
2277 if ((read_directory_vfat( fd, io, buffer, length, single_entry,
2278 mask, restart_scan, info_class )) != -1) goto done;
2279 #endif
2280 if (!has_wildcard( mask ))
2282 #ifdef HAVE_GETATTRLIST
2283 if (read_directory_getattrlist( fd, io, buffer, length, single_entry,
2284 mask, restart_scan, info_class ) != -1) goto done;
2285 #endif
2286 if (read_directory_stat( fd, io, buffer, length, single_entry,
2287 mask, restart_scan, info_class ) != -1) goto done;
2289 #ifdef USE_GETDENTS
2290 if ((read_directory_getdents( fd, io, buffer, length, single_entry,
2291 mask, restart_scan, info_class )) != -1) goto done;
2292 #elif defined HAVE_GETDIRENTRIES
2293 if ((read_directory_getdirentries( fd, io, buffer, length, single_entry,
2294 mask, restart_scan, info_class )) != -1) goto done;
2295 #endif
2296 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan, info_class );
2298 done:
2299 if (cwd == -1 || fchdir( cwd ) == -1) chdir( "/" );
2301 else io->u.Status = FILE_GetNtStatus();
2303 RtlLeaveCriticalSection( &dir_section );
2305 if (needs_close) close( fd );
2306 if (cwd != -1) close( cwd );
2307 TRACE( "=> %x (%ld)\n", io->u.Status, io->Information );
2308 return io->u.Status;
2312 /***********************************************************************
2313 * find_file_in_dir
2315 * Find a file in a directory the hard way, by doing a case-insensitive search.
2316 * The file found is appended to unix_name at pos.
2317 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
2319 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
2320 BOOLEAN check_case, BOOLEAN *is_win_dir )
2322 WCHAR buffer[MAX_DIR_ENTRY_LEN];
2323 UNICODE_STRING str;
2324 BOOLEAN spaces, is_name_8_dot_3;
2325 DIR *dir;
2326 struct dirent *de;
2327 struct stat st;
2328 int ret, used_default;
2330 /* try a shortcut for this directory */
2332 unix_name[pos++] = '/';
2333 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
2334 NULL, &used_default );
2335 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
2336 /* so it cannot match the file we are looking for */
2337 if (ret >= 0 && !used_default)
2339 unix_name[pos + ret] = 0;
2340 if (!stat( unix_name, &st ))
2342 if (is_win_dir) *is_win_dir = is_same_file( &windir, &st );
2343 return STATUS_SUCCESS;
2346 if (check_case) goto not_found; /* we want an exact match */
2348 if (pos > 1) unix_name[pos - 1] = 0;
2349 else unix_name[1] = 0; /* keep the initial slash */
2351 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
2353 str.Buffer = (WCHAR *)name;
2354 str.Length = length * sizeof(WCHAR);
2355 str.MaximumLength = str.Length;
2356 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
2357 #ifndef VFAT_IOCTL_READDIR_BOTH
2358 is_name_8_dot_3 = is_name_8_dot_3 && length >= 8 && name[4] == '~';
2359 #endif
2361 if (!is_name_8_dot_3 && !get_dir_case_sensitivity( unix_name )) goto not_found;
2363 /* now look for it through the directory */
2365 #ifdef VFAT_IOCTL_READDIR_BOTH
2366 if (is_name_8_dot_3)
2368 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
2369 if (fd != -1)
2371 KERNEL_DIRENT *kde;
2373 RtlEnterCriticalSection( &dir_section );
2374 if ((kde = start_vfat_ioctl( fd )))
2376 unix_name[pos - 1] = '/';
2377 while (kde[0].d_reclen)
2379 /* make sure names are null-terminated to work around an x86-64 kernel bug */
2380 size_t len = min(kde[0].d_reclen, sizeof(kde[0].d_name) - 1 );
2381 kde[0].d_name[len] = 0;
2382 len = min(kde[1].d_reclen, sizeof(kde[1].d_name) - 1 );
2383 kde[1].d_name[len] = 0;
2385 if (kde[1].d_name[0])
2387 ret = ntdll_umbstowcs( 0, kde[1].d_name, strlen(kde[1].d_name),
2388 buffer, MAX_DIR_ENTRY_LEN );
2389 if (ret == length && !memicmpW( buffer, name, length))
2391 strcpy( unix_name + pos, kde[1].d_name );
2392 RtlLeaveCriticalSection( &dir_section );
2393 close( fd );
2394 goto success;
2397 ret = ntdll_umbstowcs( 0, kde[0].d_name, strlen(kde[0].d_name),
2398 buffer, MAX_DIR_ENTRY_LEN );
2399 if (ret == length && !memicmpW( buffer, name, length))
2401 strcpy( unix_name + pos,
2402 kde[1].d_name[0] ? kde[1].d_name : kde[0].d_name );
2403 RtlLeaveCriticalSection( &dir_section );
2404 close( fd );
2405 goto success;
2407 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)kde ) == -1)
2409 RtlLeaveCriticalSection( &dir_section );
2410 close( fd );
2411 goto not_found;
2415 RtlLeaveCriticalSection( &dir_section );
2416 close( fd );
2418 /* fall through to normal handling */
2420 #endif /* VFAT_IOCTL_READDIR_BOTH */
2422 if (!(dir = opendir( unix_name )))
2424 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
2425 else return FILE_GetNtStatus();
2427 unix_name[pos - 1] = '/';
2428 str.Buffer = buffer;
2429 str.MaximumLength = sizeof(buffer);
2430 while ((de = readdir( dir )))
2432 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
2433 if (ret == length && !memicmpW( buffer, name, length ))
2435 strcpy( unix_name + pos, de->d_name );
2436 closedir( dir );
2437 goto success;
2440 if (!is_name_8_dot_3) continue;
2442 str.Length = ret * sizeof(WCHAR);
2443 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
2445 WCHAR short_nameW[12];
2446 ret = hash_short_file_name( &str, short_nameW );
2447 if (ret == length && !memicmpW( short_nameW, name, length ))
2449 strcpy( unix_name + pos, de->d_name );
2450 closedir( dir );
2451 goto success;
2455 closedir( dir );
2457 not_found:
2458 unix_name[pos - 1] = 0;
2459 return STATUS_OBJECT_PATH_NOT_FOUND;
2461 success:
2462 if (is_win_dir && !stat( unix_name, &st )) *is_win_dir = is_same_file( &windir, &st );
2463 return STATUS_SUCCESS;
2467 #ifndef _WIN64
2469 static const WCHAR catrootW[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t',0};
2470 static const WCHAR catroot2W[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t','2',0};
2471 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};
2472 static const WCHAR driversetcW[] = {'s','y','s','t','e','m','3','2','\\','d','r','i','v','e','r','s','\\','e','t','c',0};
2473 static const WCHAR logfilesW[] = {'s','y','s','t','e','m','3','2','\\','l','o','g','f','i','l','e','s',0};
2474 static const WCHAR spoolW[] = {'s','y','s','t','e','m','3','2','\\','s','p','o','o','l',0};
2475 static const WCHAR system32W[] = {'s','y','s','t','e','m','3','2',0};
2476 static const WCHAR syswow64W[] = {'s','y','s','w','o','w','6','4',0};
2477 static const WCHAR sysnativeW[] = {'s','y','s','n','a','t','i','v','e',0};
2478 static const WCHAR regeditW[] = {'r','e','g','e','d','i','t','.','e','x','e',0};
2479 static const WCHAR wow_regeditW[] = {'s','y','s','w','o','w','6','4','\\','r','e','g','e','d','i','t','.','e','x','e',0};
2481 static struct
2483 const WCHAR *source;
2484 const WCHAR *dos_target;
2485 const char *unix_target;
2486 } redirects[] =
2488 { catrootW, NULL, NULL },
2489 { catroot2W, NULL, NULL },
2490 { driversstoreW, NULL, NULL },
2491 { driversetcW, NULL, NULL },
2492 { logfilesW, NULL, NULL },
2493 { spoolW, NULL, NULL },
2494 { system32W, syswow64W, NULL },
2495 { sysnativeW, system32W, NULL },
2496 { regeditW, wow_regeditW, NULL }
2499 static unsigned int nb_redirects;
2502 /***********************************************************************
2503 * get_redirect_target
2505 * Find the target unix name for a redirected dir.
2507 static const char *get_redirect_target( const char *windows_dir, const WCHAR *name )
2509 int used_default, len, pos, win_len = strlen( windows_dir );
2510 char *unix_name, *unix_target = NULL;
2511 NTSTATUS status;
2513 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, win_len + MAX_DIR_ENTRY_LEN + 2 )))
2514 return NULL;
2515 memcpy( unix_name, windows_dir, win_len );
2516 pos = win_len;
2518 while (*name)
2520 const WCHAR *end, *next;
2522 for (end = name; *end; end++) if (IS_SEPARATOR(*end)) break;
2523 for (next = end; *next; next++) if (!IS_SEPARATOR(*next)) break;
2525 status = find_file_in_dir( unix_name, pos, name, end - name, FALSE, NULL );
2526 if (status == STATUS_OBJECT_PATH_NOT_FOUND && !*next) /* not finding last element is ok */
2528 len = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2529 MAX_DIR_ENTRY_LEN - (pos - win_len), NULL, &used_default );
2530 if (len > 0 && !used_default)
2532 unix_name[pos] = '/';
2533 pos += len + 1;
2534 unix_name[pos] = 0;
2535 break;
2538 if (status) goto done;
2539 pos += strlen( unix_name + pos );
2540 name = next;
2543 if ((unix_target = RtlAllocateHeap( GetProcessHeap(), 0, pos - win_len )))
2544 memcpy( unix_target, unix_name + win_len + 1, pos - win_len );
2546 done:
2547 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2548 return unix_target;
2552 /***********************************************************************
2553 * init_redirects
2555 static void init_redirects(void)
2557 UNICODE_STRING nt_name;
2558 ANSI_STRING unix_name;
2559 NTSTATUS status;
2560 struct stat st;
2561 unsigned int i;
2563 if (!RtlDosPathNameToNtPathName_U( user_shared_data->NtSystemRoot, &nt_name, NULL, NULL ))
2565 ERR( "can't convert %s\n", debugstr_w(user_shared_data->NtSystemRoot) );
2566 return;
2568 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
2569 RtlFreeUnicodeString( &nt_name );
2570 if (status)
2572 ERR( "cannot open %s (%x)\n", debugstr_w(user_shared_data->NtSystemRoot), status );
2573 return;
2575 if (!stat( unix_name.Buffer, &st ))
2577 windir.dev = st.st_dev;
2578 windir.ino = st.st_ino;
2579 nb_redirects = sizeof(redirects) / sizeof(redirects[0]);
2580 for (i = 0; i < nb_redirects; i++)
2582 if (!redirects[i].dos_target) continue;
2583 redirects[i].unix_target = get_redirect_target( unix_name.Buffer, redirects[i].dos_target );
2584 TRACE( "%s -> %s\n", debugstr_w(redirects[i].source), redirects[i].unix_target );
2587 RtlFreeAnsiString( &unix_name );
2592 /***********************************************************************
2593 * match_redirect
2595 * Check if path matches a redirect name. If yes, return matched length.
2597 static int match_redirect( const WCHAR *path, int len, const WCHAR *redir, BOOLEAN check_case )
2599 int i = 0;
2601 while (i < len && *redir)
2603 if (IS_SEPARATOR(path[i]))
2605 if (*redir++ != '\\') return 0;
2606 while (i < len && IS_SEPARATOR(path[i])) i++;
2607 continue; /* move on to next path component */
2609 else if (check_case)
2611 if (path[i] != *redir) return 0;
2613 else
2615 if (tolowerW(path[i]) != tolowerW(*redir)) return 0;
2617 i++;
2618 redir++;
2620 if (*redir) return 0;
2621 if (i < len && !IS_SEPARATOR(path[i])) return 0;
2622 while (i < len && IS_SEPARATOR(path[i])) i++;
2623 return i;
2627 /***********************************************************************
2628 * get_redirect_path
2630 * Retrieve the Unix path corresponding to a redirected path if any.
2632 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, BOOLEAN check_case )
2634 unsigned int i;
2635 int len;
2637 for (i = 0; i < nb_redirects; i++)
2639 if ((len = match_redirect( name, length, redirects[i].source, check_case )))
2641 if (!redirects[i].unix_target) break;
2642 unix_name[pos++] = '/';
2643 strcpy( unix_name + pos, redirects[i].unix_target );
2644 return len;
2647 return 0;
2650 #else /* _WIN64 */
2652 /* there are no redirects on 64-bit */
2654 static const unsigned int nb_redirects = 0;
2656 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, BOOLEAN check_case )
2658 return 0;
2661 #endif
2663 /***********************************************************************
2664 * DIR_init_windows_dir
2666 void DIR_init_windows_dir( const WCHAR *win, const WCHAR *sys )
2668 /* FIXME: should probably store paths as NT file names */
2670 RtlCreateUnicodeString( &system_dir, sys );
2672 #ifndef _WIN64
2673 if (is_wow64) init_redirects();
2674 #endif
2678 /******************************************************************************
2679 * get_dos_device
2681 * Get the Unix path of a DOS device.
2683 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
2685 const char *config_dir = wine_get_config_dir();
2686 struct stat st;
2687 char *unix_name, *new_name, *dev;
2688 unsigned int i;
2689 int unix_len;
2691 /* make sure the device name is ASCII */
2692 for (i = 0; i < name_len; i++)
2693 if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
2695 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
2697 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2698 return STATUS_NO_MEMORY;
2700 strcpy( unix_name, config_dir );
2701 strcat( unix_name, "/dosdevices/" );
2702 dev = unix_name + strlen(unix_name);
2704 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
2705 dev[i] = 0;
2707 /* special case for drive devices */
2708 if (name_len == 2 && dev[1] == ':')
2710 dev[i++] = ':';
2711 dev[i] = 0;
2714 for (;;)
2716 if (!stat( unix_name, &st ))
2718 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
2719 unix_name_ret->Buffer = unix_name;
2720 unix_name_ret->Length = strlen(unix_name);
2721 unix_name_ret->MaximumLength = unix_len;
2722 return STATUS_SUCCESS;
2724 if (!dev) break;
2726 /* now try some defaults for it */
2727 if (!strcmp( dev, "aux" ))
2729 strcpy( dev, "com1" );
2730 continue;
2732 if (!strcmp( dev, "prn" ))
2734 strcpy( dev, "lpt1" );
2735 continue;
2738 new_name = NULL;
2739 if (dev[1] == ':' && dev[2] == ':') /* drive device */
2741 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
2742 new_name = get_default_drive_device( unix_name );
2744 else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( atoi(dev + 3 ));
2745 else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( atoi(dev + 3 ));
2747 if (!new_name) break;
2749 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2750 unix_name = new_name;
2751 unix_len = strlen(unix_name) + 1;
2752 dev = NULL; /* last try */
2754 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2755 return STATUS_BAD_DEVICE_TYPE;
2759 /* return the length of the DOS namespace prefix if any */
2760 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
2762 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
2763 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
2765 if (name->Length > sizeof(nt_prefixW) &&
2766 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
2767 return sizeof(nt_prefixW) / sizeof(WCHAR);
2769 if (name->Length > sizeof(dosdev_prefixW) &&
2770 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
2771 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
2773 return 0;
2777 /******************************************************************************
2778 * find_file_id
2780 * Recursively search directories from the dir queue for a given inode.
2782 static NTSTATUS find_file_id( ANSI_STRING *unix_name, ULONGLONG file_id, dev_t dev )
2784 unsigned int pos;
2785 DIR *dir;
2786 struct dirent *de;
2787 NTSTATUS status;
2788 struct stat st;
2790 while (!(status = next_dir_in_queue( unix_name->Buffer )))
2792 if (!(dir = opendir( unix_name->Buffer ))) continue;
2793 TRACE( "searching %s for %s\n", unix_name->Buffer, wine_dbgstr_longlong(file_id) );
2794 pos = strlen( unix_name->Buffer );
2795 if (pos + MAX_DIR_ENTRY_LEN >= unix_name->MaximumLength/sizeof(WCHAR))
2797 char *new = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name->Buffer,
2798 unix_name->MaximumLength * 2 );
2799 if (!new)
2801 closedir( dir );
2802 return STATUS_NO_MEMORY;
2804 unix_name->MaximumLength *= 2;
2805 unix_name->Buffer = new;
2807 unix_name->Buffer[pos++] = '/';
2808 while ((de = readdir( dir )))
2810 if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
2811 strcpy( unix_name->Buffer + pos, de->d_name );
2812 if (lstat( unix_name->Buffer, &st ) == -1) continue;
2813 if (st.st_dev != dev) continue;
2814 if (st.st_ino == file_id)
2816 closedir( dir );
2817 return STATUS_SUCCESS;
2819 if (!S_ISDIR( st.st_mode )) continue;
2820 if ((status = add_dir_to_queue( unix_name->Buffer )) != STATUS_SUCCESS)
2822 closedir( dir );
2823 return status;
2826 closedir( dir );
2828 return status;
2832 /******************************************************************************
2833 * file_id_to_unix_file_name
2835 * Lookup a file from its file id instead of its name.
2837 NTSTATUS file_id_to_unix_file_name( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name )
2839 enum server_fd_type type;
2840 int old_cwd, root_fd, needs_close;
2841 NTSTATUS status;
2842 ULONGLONG file_id;
2843 struct stat st, root_st;
2845 if (attr->ObjectName->Length != sizeof(ULONGLONG)) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2846 if (!attr->RootDirectory) return STATUS_INVALID_PARAMETER;
2847 memcpy( &file_id, attr->ObjectName->Buffer, sizeof(file_id) );
2849 unix_name->MaximumLength = 2 * MAX_DIR_ENTRY_LEN + 4;
2850 if (!(unix_name->Buffer = RtlAllocateHeap( GetProcessHeap(), 0, unix_name->MaximumLength )))
2851 return STATUS_NO_MEMORY;
2852 strcpy( unix_name->Buffer, "." );
2854 if ((status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
2855 goto done;
2857 if (type != FD_TYPE_DIR)
2859 status = STATUS_OBJECT_TYPE_MISMATCH;
2860 goto done;
2863 fstat( root_fd, &root_st );
2864 if (root_st.st_ino == file_id) /* shortcut for "." */
2866 status = STATUS_SUCCESS;
2867 goto done;
2870 RtlEnterCriticalSection( &dir_section );
2871 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2873 /* shortcut for ".." */
2874 if (!stat( "..", &st ) && st.st_dev == root_st.st_dev && st.st_ino == file_id)
2876 strcpy( unix_name->Buffer, ".." );
2877 status = STATUS_SUCCESS;
2879 else
2881 status = add_dir_to_queue( "." );
2882 if (!status)
2883 status = find_file_id( unix_name, file_id, root_st.st_dev );
2884 if (!status) /* get rid of "./" prefix */
2885 memmove( unix_name->Buffer, unix_name->Buffer + 2, strlen(unix_name->Buffer) - 1 );
2886 flush_dir_queue();
2888 if (fchdir( old_cwd ) == -1) chdir( "/" );
2890 else status = FILE_GetNtStatus();
2891 RtlLeaveCriticalSection( &dir_section );
2892 if (old_cwd != -1) close( old_cwd );
2894 done:
2895 if (status == STATUS_SUCCESS)
2897 TRACE( "%s -> %s\n", wine_dbgstr_longlong(file_id), debugstr_a(unix_name->Buffer) );
2898 unix_name->Length = strlen( unix_name->Buffer );
2900 else
2902 TRACE( "%s not found in dir %p\n", wine_dbgstr_longlong(file_id), attr->RootDirectory );
2903 RtlFreeHeap( GetProcessHeap(), 0, unix_name->Buffer );
2905 if (needs_close) close( root_fd );
2906 return status;
2910 /******************************************************************************
2911 * lookup_unix_name
2913 * Helper for nt_to_unix_file_name
2915 static NTSTATUS lookup_unix_name( const WCHAR *name, int name_len, char **buffer, int unix_len, int pos,
2916 UINT disposition, BOOLEAN check_case )
2918 NTSTATUS status;
2919 int ret, used_default, len;
2920 struct stat st;
2921 char *unix_name = *buffer;
2922 const BOOL redirect = nb_redirects && ntdll_get_thread_data()->wow64_redir;
2924 /* try a shortcut first */
2926 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
2927 NULL, &used_default );
2929 while (name_len && IS_SEPARATOR(*name))
2931 name++;
2932 name_len--;
2935 if (ret >= 0 && !used_default) /* if we used the default char the name didn't convert properly */
2937 char *p;
2938 unix_name[pos + ret] = 0;
2939 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
2940 if (!redirect || (!strstr( unix_name, "/windows/") && strncmp( unix_name, "windows/", 8 )))
2942 if (!stat( unix_name, &st ))
2944 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
2945 if (disposition == FILE_CREATE)
2946 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
2947 return STATUS_SUCCESS;
2952 if (!name_len) /* empty name -> drive root doesn't exist */
2953 return STATUS_OBJECT_PATH_NOT_FOUND;
2954 if (check_case && !redirect && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
2955 return STATUS_OBJECT_NAME_NOT_FOUND;
2957 /* now do it component by component */
2959 while (name_len)
2961 const WCHAR *end, *next;
2962 BOOLEAN is_win_dir = FALSE;
2964 end = name;
2965 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
2966 next = end;
2967 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
2968 name_len -= next - name;
2970 /* grow the buffer if needed */
2972 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
2974 char *new_name;
2975 unix_len += 2 * MAX_DIR_ENTRY_LEN;
2976 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
2977 return STATUS_NO_MEMORY;
2978 unix_name = *buffer = new_name;
2981 status = find_file_in_dir( unix_name, pos, name, end - name,
2982 check_case, redirect ? &is_win_dir : NULL );
2984 /* if this is the last element, not finding it is not necessarily fatal */
2985 if (!name_len)
2987 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
2989 status = STATUS_OBJECT_NAME_NOT_FOUND;
2990 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
2992 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2993 MAX_DIR_ENTRY_LEN, NULL, &used_default );
2994 if (ret > 0 && !used_default)
2996 unix_name[pos] = '/';
2997 unix_name[pos + 1 + ret] = 0;
2998 status = STATUS_NO_SUCH_FILE;
2999 break;
3003 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
3005 status = STATUS_OBJECT_NAME_COLLISION;
3009 if (status != STATUS_SUCCESS) break;
3011 pos += strlen( unix_name + pos );
3012 name = next;
3014 if (is_win_dir && (len = get_redirect_path( unix_name, pos, name, name_len, check_case )))
3016 name += len;
3017 name_len -= len;
3018 pos += strlen( unix_name + pos );
3019 TRACE( "redirecting -> %s + %s\n", debugstr_a(unix_name), debugstr_w(name) );
3023 return status;
3027 /******************************************************************************
3028 * nt_to_unix_file_name_attr
3030 NTSTATUS nt_to_unix_file_name_attr( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name_ret,
3031 UINT disposition )
3033 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
3034 enum server_fd_type type;
3035 int old_cwd, root_fd, needs_close;
3036 const WCHAR *name, *p;
3037 char *unix_name;
3038 int name_len, unix_len;
3039 NTSTATUS status;
3040 BOOLEAN check_case = !(attr->Attributes & OBJ_CASE_INSENSITIVE);
3042 if (!attr->RootDirectory) /* without root dir fall back to normal lookup */
3043 return wine_nt_to_unix_file_name( attr->ObjectName, unix_name_ret, disposition, check_case );
3045 name = attr->ObjectName->Buffer;
3046 name_len = attr->ObjectName->Length / sizeof(WCHAR);
3048 if (name_len && IS_SEPARATOR(name[0])) return STATUS_INVALID_PARAMETER;
3050 /* check for invalid characters */
3051 for (p = name; p < name + name_len; p++)
3052 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
3054 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
3055 unix_len += MAX_DIR_ENTRY_LEN + 3;
3056 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
3057 return STATUS_NO_MEMORY;
3058 unix_name[0] = '.';
3060 if (!(status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
3062 if (type != FD_TYPE_DIR)
3064 if (needs_close) close( root_fd );
3065 status = STATUS_BAD_DEVICE_TYPE;
3067 else
3069 RtlEnterCriticalSection( &dir_section );
3070 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
3072 status = lookup_unix_name( name, name_len, &unix_name, unix_len, 1,
3073 disposition, check_case );
3074 if (fchdir( old_cwd ) == -1) chdir( "/" );
3076 else status = FILE_GetNtStatus();
3077 RtlLeaveCriticalSection( &dir_section );
3078 if (old_cwd != -1) close( old_cwd );
3079 if (needs_close) close( root_fd );
3082 else if (status == STATUS_OBJECT_TYPE_MISMATCH) status = STATUS_BAD_DEVICE_TYPE;
3084 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
3086 TRACE( "%s -> %s\n", debugstr_us(attr->ObjectName), debugstr_a(unix_name) );
3087 unix_name_ret->Buffer = unix_name;
3088 unix_name_ret->Length = strlen(unix_name);
3089 unix_name_ret->MaximumLength = unix_len;
3091 else
3093 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
3094 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3096 return status;
3100 /******************************************************************************
3101 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
3103 * Convert a file name from NT namespace to Unix namespace.
3105 * If disposition is not FILE_OPEN or FILE_OVERWRITE, the last path
3106 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
3107 * returned, but the unix name is still filled in properly.
3109 NTSTATUS CDECL wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
3110 UINT disposition, BOOLEAN check_case )
3112 static const WCHAR unixW[] = {'u','n','i','x'};
3113 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
3115 NTSTATUS status = STATUS_SUCCESS;
3116 const char *config_dir = wine_get_config_dir();
3117 const WCHAR *name, *p;
3118 struct stat st;
3119 char *unix_name;
3120 int pos, ret, name_len, unix_len, prefix_len, used_default;
3121 WCHAR prefix[MAX_DIR_ENTRY_LEN];
3122 BOOLEAN is_unix = FALSE;
3124 name = nameW->Buffer;
3125 name_len = nameW->Length / sizeof(WCHAR);
3127 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
3129 if (!(pos = get_dos_prefix_len( nameW )))
3130 return STATUS_BAD_DEVICE_TYPE; /* no DOS prefix, assume NT native name */
3132 name += pos;
3133 name_len -= pos;
3135 /* check for sub-directory */
3136 for (pos = 0; pos < name_len; pos++)
3138 if (IS_SEPARATOR(name[pos])) break;
3139 if (name[pos] < 32 || strchrW( invalid_charsW, name[pos] ))
3140 return STATUS_OBJECT_NAME_INVALID;
3142 if (pos > MAX_DIR_ENTRY_LEN)
3143 return STATUS_OBJECT_NAME_INVALID;
3145 if (pos == name_len) /* no subdir, plain DOS device */
3146 return get_dos_device( name, name_len, unix_name_ret );
3148 for (prefix_len = 0; prefix_len < pos; prefix_len++)
3149 prefix[prefix_len] = tolowerW(name[prefix_len]);
3151 name += prefix_len;
3152 name_len -= prefix_len;
3154 /* check for invalid characters (all chars except 0 are valid for unix) */
3155 is_unix = (prefix_len == 4 && !memcmp( prefix, unixW, sizeof(unixW) ));
3156 if (is_unix)
3158 for (p = name; p < name + name_len; p++)
3159 if (!*p) return STATUS_OBJECT_NAME_INVALID;
3160 check_case = TRUE;
3162 else
3164 for (p = name; p < name + name_len; p++)
3165 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
3168 unix_len = ntdll_wcstoumbs( 0, prefix, prefix_len, NULL, 0, NULL, NULL );
3169 unix_len += ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
3170 unix_len += MAX_DIR_ENTRY_LEN + 3;
3171 unix_len += strlen(config_dir) + sizeof("/dosdevices/");
3172 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
3173 return STATUS_NO_MEMORY;
3174 strcpy( unix_name, config_dir );
3175 strcat( unix_name, "/dosdevices/" );
3176 pos = strlen(unix_name);
3178 ret = ntdll_wcstoumbs( 0, prefix, prefix_len, unix_name + pos, unix_len - pos - 1,
3179 NULL, &used_default );
3180 if (!ret || used_default)
3182 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3183 return STATUS_OBJECT_NAME_INVALID;
3185 pos += ret;
3187 /* check if prefix exists (except for DOS drives to avoid extra stat calls) */
3189 if (prefix_len != 2 || prefix[1] != ':')
3191 unix_name[pos] = 0;
3192 if (lstat( unix_name, &st ) == -1 && errno == ENOENT)
3194 if (!is_unix)
3196 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3197 return STATUS_BAD_DEVICE_TYPE;
3199 pos = 0; /* fall back to unix root */
3203 status = lookup_unix_name( name, name_len, &unix_name, unix_len, pos, disposition, check_case );
3204 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
3206 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
3207 unix_name_ret->Buffer = unix_name;
3208 unix_name_ret->Length = strlen(unix_name);
3209 unix_name_ret->MaximumLength = unix_len;
3211 else
3213 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
3214 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3216 return status;
3220 /******************************************************************
3221 * RtlWow64EnableFsRedirection (NTDLL.@)
3223 NTSTATUS WINAPI RtlWow64EnableFsRedirection( BOOLEAN enable )
3225 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
3226 ntdll_get_thread_data()->wow64_redir = enable;
3227 return STATUS_SUCCESS;
3231 /******************************************************************
3232 * RtlWow64EnableFsRedirectionEx (NTDLL.@)
3234 NTSTATUS WINAPI RtlWow64EnableFsRedirectionEx( ULONG disable, ULONG *old_value )
3236 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
3237 if (((ULONG_PTR)old_value >> 16) == 0) return STATUS_ACCESS_VIOLATION;
3239 *old_value = !ntdll_get_thread_data()->wow64_redir;
3240 ntdll_get_thread_data()->wow64_redir = !disable;
3241 return STATUS_SUCCESS;
3245 /******************************************************************
3246 * RtlDoesFileExists_U (NTDLL.@)
3248 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
3250 UNICODE_STRING nt_name;
3251 FILE_BASIC_INFORMATION basic_info;
3252 OBJECT_ATTRIBUTES attr;
3253 BOOLEAN ret;
3255 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
3257 attr.Length = sizeof(attr);
3258 attr.RootDirectory = 0;
3259 attr.ObjectName = &nt_name;
3260 attr.Attributes = OBJ_CASE_INSENSITIVE;
3261 attr.SecurityDescriptor = NULL;
3262 attr.SecurityQualityOfService = NULL;
3264 ret = NtQueryAttributesFile(&attr, &basic_info) == STATUS_SUCCESS;
3266 RtlFreeUnicodeString( &nt_name );
3267 return ret;
3271 /***********************************************************************
3272 * DIR_unmount_device
3274 * Unmount the specified device.
3276 NTSTATUS DIR_unmount_device( HANDLE handle )
3278 NTSTATUS status;
3279 int unix_fd, needs_close;
3281 if (!(status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )))
3283 struct stat st;
3284 char *mount_point = NULL;
3286 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
3287 status = STATUS_INVALID_PARAMETER;
3288 else
3290 if ((mount_point = get_device_mount_point( st.st_rdev )))
3292 #ifdef __APPLE__
3293 static const char umount[] = "diskutil unmount >/dev/null 2>&1 ";
3294 #else
3295 static const char umount[] = "umount >/dev/null 2>&1 ";
3296 #endif
3297 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
3298 if (cmd)
3300 strcpy( cmd, umount );
3301 strcat( cmd, mount_point );
3302 system( cmd );
3303 RtlFreeHeap( GetProcessHeap(), 0, cmd );
3304 #ifdef linux
3305 /* umount will fail to release the loop device since we still have
3306 a handle to it, so we release it here */
3307 if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
3308 #endif
3310 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
3313 if (needs_close) close( unix_fd );
3315 return status;
3319 /******************************************************************************
3320 * DIR_get_unix_cwd
3322 * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
3323 * Returned value must be freed by caller.
3325 NTSTATUS DIR_get_unix_cwd( char **cwd )
3327 int old_cwd, unix_fd, needs_close;
3328 CURDIR *curdir;
3329 HANDLE handle;
3330 NTSTATUS status;
3332 RtlAcquirePebLock();
3334 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
3335 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
3336 else
3337 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
3339 if (!(handle = curdir->Handle))
3341 UNICODE_STRING dirW;
3342 OBJECT_ATTRIBUTES attr;
3343 IO_STATUS_BLOCK io;
3345 if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
3347 status = STATUS_OBJECT_NAME_INVALID;
3348 goto done;
3350 attr.Length = sizeof(attr);
3351 attr.RootDirectory = 0;
3352 attr.Attributes = OBJ_CASE_INSENSITIVE;
3353 attr.ObjectName = &dirW;
3354 attr.SecurityDescriptor = NULL;
3355 attr.SecurityQualityOfService = NULL;
3357 status = NtOpenFile( &handle, 0, &attr, &io, 0,
3358 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
3359 RtlFreeUnicodeString( &dirW );
3360 if (status != STATUS_SUCCESS) goto done;
3363 if ((status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )) == STATUS_SUCCESS)
3365 RtlEnterCriticalSection( &dir_section );
3367 if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
3369 unsigned int size = 512;
3371 for (;;)
3373 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
3375 status = STATUS_NO_MEMORY;
3376 break;
3378 if (getcwd( *cwd, size )) break;
3379 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
3380 if (errno != ERANGE)
3382 status = STATUS_OBJECT_PATH_INVALID;
3383 break;
3385 size *= 2;
3387 if (fchdir( old_cwd ) == -1) chdir( "/" );
3389 else status = FILE_GetNtStatus();
3391 RtlLeaveCriticalSection( &dir_section );
3392 if (old_cwd != -1) close( old_cwd );
3393 if (needs_close) close( unix_fd );
3395 if (!curdir->Handle) NtClose( handle );
3397 done:
3398 RtlReleasePebLock();
3399 return status;