Release 1.1.37.
[wine/gsoc-2012-control.git] / dlls / ntdll / directory.c
blobecd94189470f54554a20dde7c9e38a22b3aa7ffc
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_IOCTL_H
45 #include <sys/ioctl.h>
46 #endif
47 #ifdef HAVE_LINUX_IOCTL_H
48 #include <linux/ioctl.h>
49 #endif
50 #ifdef HAVE_LINUX_MAJOR_H
51 # include <linux/major.h>
52 #endif
53 #ifdef HAVE_SYS_PARAM_H
54 #include <sys/param.h>
55 #endif
56 #ifdef HAVE_SYS_MOUNT_H
57 #include <sys/mount.h>
58 #endif
59 #include <time.h>
60 #ifdef HAVE_UNISTD_H
61 # include <unistd.h>
62 #endif
64 #define NONAMELESSUNION
65 #define NONAMELESSSTRUCT
66 #include "ntstatus.h"
67 #define WIN32_NO_STATUS
68 #include "windef.h"
69 #include "winnt.h"
70 #include "winternl.h"
71 #include "ntdll_misc.h"
72 #include "wine/unicode.h"
73 #include "wine/server.h"
74 #include "wine/list.h"
75 #include "wine/library.h"
76 #include "wine/debug.h"
78 WINE_DEFAULT_DEBUG_CHANNEL(file);
80 /* just in case... */
81 #undef VFAT_IOCTL_READDIR_BOTH
82 #undef USE_GETDENTS
84 #ifdef linux
86 /* We want the real kernel dirent structure, not the libc one */
87 typedef struct
89 long d_ino;
90 long d_off;
91 unsigned short d_reclen;
92 char d_name[256];
93 } KERNEL_DIRENT;
95 /* Define the VFAT ioctl to get both short and long file names */
96 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
98 #ifndef O_DIRECTORY
99 # define O_DIRECTORY 0200000 /* must be directory */
100 #endif
102 #ifdef __i386__
104 typedef struct
106 ULONG64 d_ino;
107 LONG64 d_off;
108 unsigned short d_reclen;
109 unsigned char d_type;
110 char d_name[256];
111 } KERNEL_DIRENT64;
113 static inline int getdents64( int fd, char *de, unsigned int size )
115 int ret;
116 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
117 : "=a" (ret)
118 : "0" (220 /*NR_getdents64*/), "r" (fd), "c" (de), "d" (size)
119 : "memory" );
120 if (ret < 0)
122 errno = -ret;
123 ret = -1;
125 return ret;
127 #define USE_GETDENTS
129 #endif /* i386 */
131 #endif /* linux */
133 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
134 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
136 #define INVALID_NT_CHARS '*','?','<','>','|','"'
137 #define INVALID_DOS_CHARS INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
139 #define MAX_DIR_ENTRY_LEN 255 /* max length of a directory entry in chars */
141 #define MAX_IGNORED_FILES 4
143 struct file_identity
145 dev_t dev;
146 ino_t ino;
149 static struct file_identity ignored_files[MAX_IGNORED_FILES];
150 static int ignored_files_count;
152 union file_directory_info
154 ULONG next;
155 FILE_DIRECTORY_INFORMATION dir;
156 FILE_BOTH_DIRECTORY_INFORMATION both;
157 FILE_FULL_DIRECTORY_INFORMATION full;
158 FILE_ID_BOTH_DIRECTORY_INFORMATION id_both;
159 FILE_ID_FULL_DIRECTORY_INFORMATION id_full;
162 static int show_dot_files = -1;
164 /* at some point we may want to allow Winelib apps to set this */
165 static const int is_case_sensitive = FALSE;
167 UNICODE_STRING windows_dir = { 0, 0, NULL }; /* windows directory */
168 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
170 static struct file_identity curdir;
171 static struct file_identity windir;
173 static RTL_CRITICAL_SECTION dir_section;
174 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
176 0, 0, &dir_section,
177 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
178 0, 0, { (DWORD_PTR)(__FILE__ ": dir_section") }
180 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
183 /* check if a given Unicode char is OK in a DOS short name */
184 static inline BOOL is_invalid_dos_char( WCHAR ch )
186 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
187 if (ch > 0x7f) return TRUE;
188 return strchrW( invalid_chars, ch ) != NULL;
191 /* check if the device can be a mounted volume */
192 static inline int is_valid_mounted_device( const struct stat *st )
194 #if defined(linux) || defined(__sun__)
195 return S_ISBLK( st->st_mode );
196 #else
197 /* disks are char devices on *BSD */
198 return S_ISCHR( st->st_mode );
199 #endif
202 static inline void ignore_file( const char *name )
204 struct stat st;
205 assert( ignored_files_count < MAX_IGNORED_FILES );
206 if (!stat( name, &st ))
208 ignored_files[ignored_files_count].dev = st.st_dev;
209 ignored_files[ignored_files_count].ino = st.st_ino;
210 ignored_files_count++;
214 static inline BOOL is_same_file( const struct file_identity *file, const struct stat *st )
216 return st->st_dev == file->dev && st->st_ino == file->ino;
219 static inline BOOL is_ignored_file( const struct stat *st )
221 unsigned int i;
223 for (i = 0; i < ignored_files_count; i++)
224 if (is_same_file( &ignored_files[i], st )) return TRUE;
225 return FALSE;
228 static inline unsigned int dir_info_size( FILE_INFORMATION_CLASS class, unsigned int len )
230 switch (class)
232 case FileDirectoryInformation:
233 return (FIELD_OFFSET( FILE_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
234 case FileBothDirectoryInformation:
235 return (FIELD_OFFSET( FILE_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
236 case FileFullDirectoryInformation:
237 return (FIELD_OFFSET( FILE_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
238 case FileIdBothDirectoryInformation:
239 return (FIELD_OFFSET( FILE_ID_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
240 case FileIdFullDirectoryInformation:
241 return (FIELD_OFFSET( FILE_ID_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
242 default:
243 assert(0);
244 return 0;
248 static inline unsigned int max_dir_info_size( FILE_INFORMATION_CLASS class )
250 return dir_info_size( class, MAX_DIR_ENTRY_LEN );
254 /* support for a directory queue for filesystem searches */
256 struct dir_name
258 struct list entry;
259 char name[1];
262 static struct list dir_queue = LIST_INIT( dir_queue );
264 static NTSTATUS add_dir_to_queue( const char *name )
266 int len = strlen( name ) + 1;
267 struct dir_name *dir = RtlAllocateHeap( GetProcessHeap(), 0,
268 FIELD_OFFSET( struct dir_name, name[len] ));
269 if (!dir) return STATUS_NO_MEMORY;
270 strcpy( dir->name, name );
271 list_add_tail( &dir_queue, &dir->entry );
272 return STATUS_SUCCESS;
275 static NTSTATUS next_dir_in_queue( char *name )
277 struct list *head = list_head( &dir_queue );
278 if (head)
280 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
281 strcpy( name, dir->name );
282 list_remove( &dir->entry );
283 RtlFreeHeap( GetProcessHeap(), 0, dir );
284 return STATUS_SUCCESS;
286 return STATUS_OBJECT_NAME_NOT_FOUND;
289 static void flush_dir_queue(void)
291 struct list *head;
293 while ((head = list_head( &dir_queue )))
295 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
296 list_remove( &dir->entry );
297 RtlFreeHeap( GetProcessHeap(), 0, dir );
302 /***********************************************************************
303 * get_default_com_device
305 * Return the default device to use for serial ports.
307 static char *get_default_com_device( int num )
309 char *ret = NULL;
311 if (!num || num > 9) return ret;
312 #ifdef linux
313 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
314 if (ret)
316 strcpy( ret, "/dev/ttyS0" );
317 ret[strlen(ret) - 1] = '0' + num - 1;
319 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
320 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuad0") );
321 if (ret)
323 strcpy( ret, "/dev/cuad0" );
324 ret[strlen(ret) - 1] = '0' + num - 1;
326 #else
327 FIXME( "no known default for device com%d\n", num );
328 #endif
329 return ret;
333 /***********************************************************************
334 * get_default_lpt_device
336 * Return the default device to use for parallel ports.
338 static char *get_default_lpt_device( int num )
340 char *ret = NULL;
342 if (!num || num > 9) return ret;
343 #ifdef linux
344 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
345 if (ret)
347 strcpy( ret, "/dev/lp0" );
348 ret[strlen(ret) - 1] = '0' + num - 1;
350 #else
351 FIXME( "no known default for device lpt%d\n", num );
352 #endif
353 return ret;
357 /***********************************************************************
358 * DIR_get_drives_info
360 * Retrieve device/inode number for all the drives. Helper for find_drive_root.
362 unsigned int DIR_get_drives_info( struct drive_info info[MAX_DOS_DRIVES] )
364 static struct drive_info cache[MAX_DOS_DRIVES];
365 static time_t last_update;
366 static unsigned int nb_drives;
367 unsigned int ret;
368 time_t now = time(NULL);
370 RtlEnterCriticalSection( &dir_section );
371 if (now != last_update)
373 const char *config_dir = wine_get_config_dir();
374 char *buffer, *p;
375 struct stat st;
376 unsigned int i;
378 if ((buffer = RtlAllocateHeap( GetProcessHeap(), 0,
379 strlen(config_dir) + sizeof("/dosdevices/a:") )))
381 strcpy( buffer, config_dir );
382 strcat( buffer, "/dosdevices/a:" );
383 p = buffer + strlen(buffer) - 2;
385 for (i = nb_drives = 0; i < MAX_DOS_DRIVES; i++)
387 *p = 'a' + i;
388 if (!stat( buffer, &st ))
390 cache[i].dev = st.st_dev;
391 cache[i].ino = st.st_ino;
392 nb_drives++;
394 else
396 cache[i].dev = 0;
397 cache[i].ino = 0;
400 RtlFreeHeap( GetProcessHeap(), 0, buffer );
402 last_update = now;
404 memcpy( info, cache, sizeof(cache) );
405 ret = nb_drives;
406 RtlLeaveCriticalSection( &dir_section );
407 return ret;
411 /***********************************************************************
412 * parse_mount_entries
414 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
417 #ifdef sun
418 #include <sys/vfstab.h>
419 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
421 struct vfstab entry;
422 struct stat st;
423 char *device;
425 while (! getvfsent( f, &entry ))
427 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
428 if (!strcmp( entry.vfs_fstype, "nfs" ) ||
429 !strcmp( entry.vfs_fstype, "smbfs" ) ||
430 !strcmp( entry.vfs_fstype, "ncpfs" )) continue;
432 if (stat( entry.vfs_mountp, &st ) == -1) continue;
433 if (st.st_dev != dev || st.st_ino != ino) continue;
434 if (!strcmp( entry.vfs_fstype, "fd" ))
436 if ((device = strstr( entry.vfs_mntopts, "dev=" )))
438 char *p = strchr( device + 4, ',' );
439 if (p) *p = 0;
440 return device + 4;
443 else
444 return entry.vfs_special;
446 return NULL;
448 #endif
450 #ifdef linux
451 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
453 struct mntent *entry;
454 struct stat st;
455 char *device;
457 while ((entry = getmntent( f )))
459 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
460 if (!strcmp( entry->mnt_type, "nfs" ) ||
461 !strcmp( entry->mnt_type, "smbfs" ) ||
462 !strcmp( entry->mnt_type, "ncpfs" )) continue;
464 if (stat( entry->mnt_dir, &st ) == -1) continue;
465 if (st.st_dev != dev || st.st_ino != ino) continue;
466 if (!strcmp( entry->mnt_type, "supermount" ))
468 if ((device = strstr( entry->mnt_opts, "dev=" )))
470 char *p = strchr( device + 4, ',' );
471 if (p) *p = 0;
472 return device + 4;
475 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
477 /* if device is a regular file check for a loop mount */
478 if ((device = strstr( entry->mnt_opts, "loop=" )))
480 char *p = strchr( device + 5, ',' );
481 if (p) *p = 0;
482 return device + 5;
485 else
486 return entry->mnt_fsname;
488 return NULL;
490 #endif
492 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
493 #include <fstab.h>
494 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
496 struct fstab *entry;
497 struct stat st;
499 while ((entry = getfsent()))
501 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
502 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
503 !strcmp( entry->fs_vfstype, "smbfs" ) ||
504 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
506 if (stat( entry->fs_file, &st ) == -1) continue;
507 if (st.st_dev != dev || st.st_ino != ino) continue;
508 return entry->fs_spec;
510 return NULL;
512 #endif
514 #ifdef sun
515 #include <sys/mnttab.h>
516 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
518 struct mnttab entry;
519 struct stat st;
520 char *device;
523 while (( ! getmntent( f, &entry) ))
525 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
526 if (!strcmp( entry.mnt_fstype, "nfs" ) ||
527 !strcmp( entry.mnt_fstype, "smbfs" ) ||
528 !strcmp( entry.mnt_fstype, "ncpfs" )) continue;
530 if (stat( entry.mnt_mountp, &st ) == -1) continue;
531 if (st.st_dev != dev || st.st_ino != ino) continue;
532 if (!strcmp( entry.mnt_fstype, "fd" ))
534 if ((device = strstr( entry.mnt_mntopts, "dev=" )))
536 char *p = strchr( device + 4, ',' );
537 if (p) *p = 0;
538 return device + 4;
541 else
542 return entry.mnt_special;
544 return NULL;
546 #endif
548 /***********************************************************************
549 * get_default_drive_device
551 * Return the default device to use for a given drive mount point.
553 static char *get_default_drive_device( const char *root )
555 char *ret = NULL;
557 #ifdef linux
558 FILE *f;
559 char *device = NULL;
560 int fd, res = -1;
561 struct stat st;
563 /* try to open it first to force it to get mounted */
564 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
566 res = fstat( fd, &st );
567 close( fd );
569 /* now try normal stat just in case */
570 if (res == -1) res = stat( root, &st );
571 if (res == -1) return NULL;
573 RtlEnterCriticalSection( &dir_section );
575 if ((f = fopen( "/etc/mtab", "r" )))
577 device = parse_mount_entries( f, st.st_dev, st.st_ino );
578 endmntent( f );
580 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
581 if (!device && (f = fopen( "/etc/fstab", "r" )))
583 device = parse_mount_entries( f, st.st_dev, st.st_ino );
584 endmntent( f );
586 if (device)
588 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
589 if (ret) strcpy( ret, device );
591 RtlLeaveCriticalSection( &dir_section );
593 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ )
594 char *device = NULL;
595 int fd, res = -1;
596 struct stat st;
598 /* try to open it first to force it to get mounted */
599 if ((fd = open( root, O_RDONLY )) != -1)
601 res = fstat( fd, &st );
602 close( fd );
604 /* now try normal stat just in case */
605 if (res == -1) res = stat( root, &st );
606 if (res == -1) return NULL;
608 RtlEnterCriticalSection( &dir_section );
610 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
611 * pass NULL. Leave the argument in for symmetry.
613 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
614 if (device)
616 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
617 if (ret) strcpy( ret, device );
619 RtlLeaveCriticalSection( &dir_section );
621 #elif defined( sun )
622 FILE *f;
623 char *device = NULL;
624 int fd, res = -1;
625 struct stat st;
627 /* try to open it first to force it to get mounted */
628 if ((fd = open( root, O_RDONLY )) != -1)
630 res = fstat( fd, &st );
631 close( fd );
633 /* now try normal stat just in case */
634 if (res == -1) res = stat( root, &st );
635 if (res == -1) return NULL;
637 RtlEnterCriticalSection( &dir_section );
639 if ((f = fopen( "/etc/mnttab", "r" )))
641 device = parse_mount_entries( f, st.st_dev, st.st_ino);
642 fclose( f );
644 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
645 if (!device && (f = fopen( "/etc/vfstab", "r" )))
647 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
648 fclose( f );
650 if (device)
652 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
653 if (ret) strcpy( ret, device );
655 RtlLeaveCriticalSection( &dir_section );
657 #elif defined(__APPLE__)
658 struct statfs *mntStat;
659 struct stat st;
660 int i;
661 int mntSize;
662 dev_t dev;
663 ino_t ino;
664 static const char path_bsd_device[] = "/dev/disk";
665 int res;
667 res = stat( root, &st );
668 if (res == -1) return NULL;
670 dev = st.st_dev;
671 ino = st.st_ino;
673 RtlEnterCriticalSection( &dir_section );
675 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
677 for (i = 0; i < mntSize && !ret; i++)
679 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
680 if (st.st_dev != dev || st.st_ino != ino) continue;
682 /* FIXME add support for mounted network drive */
683 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
685 /* set return value to the corresponding raw BSD node */
686 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
687 if (ret)
689 strcpy(ret, "/dev/r");
690 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
694 RtlLeaveCriticalSection( &dir_section );
695 #else
696 static int warned;
697 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
698 #endif
699 return ret;
703 /***********************************************************************
704 * get_device_mount_point
706 * Return the current mount point for a device.
708 static char *get_device_mount_point( dev_t dev )
710 char *ret = NULL;
712 #ifdef linux
713 FILE *f;
715 RtlEnterCriticalSection( &dir_section );
717 if ((f = fopen( "/etc/mtab", "r" )))
719 struct mntent *entry;
720 struct stat st;
721 char *p, *device;
723 while ((entry = getmntent( f )))
725 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
726 if (!strcmp( entry->mnt_type, "nfs" ) ||
727 !strcmp( entry->mnt_type, "smbfs" ) ||
728 !strcmp( entry->mnt_type, "ncpfs" )) continue;
730 if (!strcmp( entry->mnt_type, "supermount" ))
732 if ((device = strstr( entry->mnt_opts, "dev=" )))
734 device += 4;
735 if ((p = strchr( device, ',' ))) *p = 0;
738 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
740 /* if device is a regular file check for a loop mount */
741 if ((device = strstr( entry->mnt_opts, "loop=" )))
743 device += 5;
744 if ((p = strchr( device, ',' ))) *p = 0;
747 else device = entry->mnt_fsname;
749 if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
751 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
752 if (ret) strcpy( ret, entry->mnt_dir );
753 break;
756 endmntent( f );
758 RtlLeaveCriticalSection( &dir_section );
759 #elif defined(__APPLE__)
760 struct statfs *entry;
761 struct stat st;
762 int i, size;
764 RtlEnterCriticalSection( &dir_section );
766 size = getmntinfo( &entry, MNT_NOWAIT );
767 for (i = 0; i < size; i++)
769 if (stat( entry[i].f_mntfromname, &st ) == -1) continue;
770 if (S_ISBLK(st.st_mode) && st.st_rdev == dev)
772 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry[i].f_mntfromname) + 1 );
773 if (ret) strcpy( ret, entry[i].f_mntfromname );
774 break;
777 RtlLeaveCriticalSection( &dir_section );
778 #else
779 static int warned;
780 if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
781 #endif
782 return ret;
786 /***********************************************************************
787 * init_options
789 * Initialize the show_dot_files options.
791 static void init_options(void)
793 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
794 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
795 char tmp[80];
796 HANDLE root, hkey;
797 DWORD dummy;
798 OBJECT_ATTRIBUTES attr;
799 UNICODE_STRING nameW;
801 show_dot_files = 0;
803 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
804 attr.Length = sizeof(attr);
805 attr.RootDirectory = root;
806 attr.ObjectName = &nameW;
807 attr.Attributes = 0;
808 attr.SecurityDescriptor = NULL;
809 attr.SecurityQualityOfService = NULL;
810 RtlInitUnicodeString( &nameW, WineW );
812 /* @@ Wine registry key: HKCU\Software\Wine */
813 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
815 RtlInitUnicodeString( &nameW, ShowDotFilesW );
816 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
818 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
819 show_dot_files = IS_OPTION_TRUE( str[0] );
821 NtClose( hkey );
823 NtClose( root );
825 /* a couple of directories that we don't want to return in directory searches */
826 ignore_file( wine_get_config_dir() );
827 ignore_file( "/dev" );
828 ignore_file( "/proc" );
829 #ifdef linux
830 ignore_file( "/sys" );
831 #endif
835 /***********************************************************************
836 * DIR_is_hidden_file
838 * Check if the specified file should be hidden based on its name and the show dot files option.
840 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
842 WCHAR *p, *end;
844 if (show_dot_files == -1) init_options();
845 if (show_dot_files) return FALSE;
847 end = p = name->Buffer + name->Length/sizeof(WCHAR);
848 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
849 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
850 if (p == end || *p != '.') return FALSE;
851 /* make sure it isn't '.' or '..' */
852 if (p + 1 == end) return FALSE;
853 if (p[1] == '.' && p + 2 == end) return FALSE;
854 return TRUE;
858 /***********************************************************************
859 * hash_short_file_name
861 * Transform a Unix file name into a hashed DOS name. If the name is a valid
862 * DOS name, it is converted to upper-case; otherwise it is replaced by a
863 * hashed version that fits in 8.3 format.
864 * 'buffer' must be at least 12 characters long.
865 * Returns length of short name in bytes; short name is NOT null-terminated.
867 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
869 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
871 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
872 LPWSTR dst;
873 unsigned short hash;
874 int i;
876 /* Compute the hash code of the file name */
877 /* If you know something about hash functions, feel free to */
878 /* insert a better algorithm here... */
879 if (!is_case_sensitive)
881 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
882 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
883 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
885 else
887 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
888 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
889 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
892 /* Find last dot for start of the extension */
893 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
895 /* Copy first 4 chars, replacing invalid chars with '_' */
896 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
898 if (p == end || p == ext) break;
899 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
901 /* Pad to 5 chars with '~' */
902 while (i-- >= 0) *dst++ = '~';
904 /* Insert hash code converted to 3 ASCII chars */
905 *dst++ = hash_chars[(hash >> 10) & 0x1f];
906 *dst++ = hash_chars[(hash >> 5) & 0x1f];
907 *dst++ = hash_chars[hash & 0x1f];
909 /* Copy the first 3 chars of the extension (if any) */
910 if (ext)
912 *dst++ = '.';
913 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
914 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
916 return dst - buffer;
920 /***********************************************************************
921 * match_filename
923 * Check a long file name against a mask.
925 * Tests (done in W95 DOS shell - case insensitive):
926 * *.txt test1.test.txt *
927 * *st1* test1.txt *
928 * *.t??????.t* test1.ta.tornado.txt *
929 * *tornado* test1.ta.tornado.txt *
930 * t*t test1.ta.tornado.txt *
931 * ?est* test1.txt *
932 * ?est??? test1.txt -
933 * *test1.txt* test1.txt *
934 * h?l?o*t.dat hellothisisatest.dat *
936 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
938 int mismatch;
939 const WCHAR *name = name_str->Buffer;
940 const WCHAR *mask = mask_str->Buffer;
941 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
942 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
943 const WCHAR *lastjoker = NULL;
944 const WCHAR *next_to_retry = NULL;
946 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
948 while (name < name_end && mask < mask_end)
950 switch(*mask)
952 case '*':
953 mask++;
954 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
955 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
956 lastjoker = mask;
958 /* skip to the next match after the joker(s) */
959 if (is_case_sensitive)
960 while (name < name_end && (*name != *mask)) name++;
961 else
962 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
963 next_to_retry = name;
964 break;
965 case '?':
966 mask++;
967 name++;
968 break;
969 default:
970 if (is_case_sensitive) mismatch = (*mask != *name);
971 else mismatch = (toupperW(*mask) != toupperW(*name));
973 if (!mismatch)
975 mask++;
976 name++;
977 if (mask == mask_end)
979 if (name == name_end) return TRUE;
980 if (lastjoker) mask = lastjoker;
983 else /* mismatch ! */
985 if (lastjoker) /* we had an '*', so we can try unlimitedly */
987 mask = lastjoker;
989 /* this scan sequence was a mismatch, so restart
990 * 1 char after the first char we checked last time */
991 next_to_retry++;
992 name = next_to_retry;
994 else return FALSE; /* bad luck */
996 break;
999 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
1000 mask++; /* Ignore trailing '.' or '*' in mask */
1001 return (name == name_end && mask == mask_end);
1005 /***********************************************************************
1006 * append_entry
1008 * helper for NtQueryDirectoryFile
1010 static union file_directory_info *append_entry( void *info_ptr, IO_STATUS_BLOCK *io, ULONG max_length,
1011 const char *long_name, const char *short_name,
1012 const UNICODE_STRING *mask, FILE_INFORMATION_CLASS class )
1014 union file_directory_info *info;
1015 int i, long_len, short_len, total_len;
1016 struct stat st;
1017 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
1018 WCHAR short_nameW[12];
1019 WCHAR *filename;
1020 UNICODE_STRING str;
1021 ULONG attributes = 0;
1023 io->u.Status = STATUS_SUCCESS;
1024 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
1025 if (long_len == -1) return NULL;
1027 str.Buffer = long_nameW;
1028 str.Length = long_len * sizeof(WCHAR);
1029 str.MaximumLength = sizeof(long_nameW);
1031 if (short_name)
1033 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
1034 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
1035 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
1037 else /* generate a short name if necessary */
1039 BOOLEAN spaces;
1041 short_len = 0;
1042 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1043 short_len = hash_short_file_name( &str, short_nameW );
1046 TRACE( "long %s short %s mask %s\n",
1047 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
1049 if (mask && !match_filename( &str, mask ))
1051 if (!short_len) return NULL; /* no short name to match */
1052 str.Buffer = short_nameW;
1053 str.Length = short_len * sizeof(WCHAR);
1054 str.MaximumLength = sizeof(short_nameW);
1055 if (!match_filename( &str, mask )) return NULL;
1058 if (lstat( long_name, &st ) == -1) return NULL;
1059 if (S_ISLNK( st.st_mode ))
1061 if (stat( long_name, &st ) == -1) return NULL;
1062 if (S_ISDIR( st.st_mode )) attributes |= FILE_ATTRIBUTE_REPARSE_POINT;
1064 if (is_ignored_file( &st ))
1066 TRACE( "ignoring file %s\n", long_name );
1067 return NULL;
1069 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
1070 attributes |= FILE_ATTRIBUTE_HIDDEN;
1072 total_len = dir_info_size( class, long_len );
1073 if (io->Information + total_len > max_length)
1075 total_len = max_length - io->Information;
1076 io->u.Status = STATUS_BUFFER_OVERFLOW;
1078 info = (union file_directory_info *)((char *)info_ptr + io->Information);
1079 if (st.st_dev != curdir.dev) st.st_ino = 0; /* ignore inode if on a different device */
1080 /* all the structures start with a FileDirectoryInformation layout */
1081 fill_stat_info( &st, info, class );
1082 info->dir.NextEntryOffset = total_len;
1083 info->dir.FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
1084 info->dir.FileAttributes |= attributes;
1086 switch (class)
1088 case FileDirectoryInformation:
1089 info->dir.FileNameLength = long_len * sizeof(WCHAR);
1090 filename = info->dir.FileName;
1091 break;
1093 case FileFullDirectoryInformation:
1094 info->full.EaSize = 0; /* FIXME */
1095 info->full.FileNameLength = long_len * sizeof(WCHAR);
1096 filename = info->full.FileName;
1097 break;
1099 case FileIdFullDirectoryInformation:
1100 info->id_full.EaSize = 0; /* FIXME */
1101 info->id_full.FileNameLength = long_len * sizeof(WCHAR);
1102 filename = info->id_full.FileName;
1103 break;
1105 case FileBothDirectoryInformation:
1106 info->both.EaSize = 0; /* FIXME */
1107 info->both.ShortNameLength = short_len * sizeof(WCHAR);
1108 for (i = 0; i < short_len; i++) info->both.ShortName[i] = toupperW(short_nameW[i]);
1109 info->both.FileNameLength = long_len * sizeof(WCHAR);
1110 filename = info->both.FileName;
1111 break;
1113 case FileIdBothDirectoryInformation:
1114 info->id_both.EaSize = 0; /* FIXME */
1115 info->id_both.ShortNameLength = short_len * sizeof(WCHAR);
1116 for (i = 0; i < short_len; i++) info->id_both.ShortName[i] = toupperW(short_nameW[i]);
1117 info->id_both.FileNameLength = long_len * sizeof(WCHAR);
1118 filename = info->id_both.FileName;
1119 break;
1121 default:
1122 assert(0);
1124 memcpy( filename, long_nameW, total_len - ((char *)filename - (char *)info) );
1125 io->Information += total_len;
1126 return info;
1130 #ifdef VFAT_IOCTL_READDIR_BOTH
1132 /***********************************************************************
1133 * start_vfat_ioctl
1135 * Wrapper for the VFAT ioctl to work around various kernel bugs.
1136 * dir_section must be held by caller.
1138 static KERNEL_DIRENT *start_vfat_ioctl( int fd )
1140 static KERNEL_DIRENT *de;
1141 int res;
1143 if (!de)
1145 const size_t page_size = getpagesize();
1146 SIZE_T size = 2 * sizeof(*de) + page_size;
1147 void *addr = NULL;
1149 if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_RESERVE, PAGE_READWRITE ))
1150 return NULL;
1151 /* commit only the size needed for the dir entries */
1152 /* this leaves an extra unaccessible page, which should make the kernel */
1153 /* fail with -EFAULT before it stomps all over our memory */
1154 de = addr;
1155 size = 2 * sizeof(*de);
1156 NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_COMMIT, PAGE_READWRITE );
1159 /* set d_reclen to 65535 to work around an AFS kernel bug */
1160 de[0].d_reclen = 65535;
1161 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
1162 if (res == -1)
1164 if (errno != ENOENT) return NULL; /* VFAT ioctl probably not supported */
1165 de[0].d_reclen = 0; /* eof */
1167 else if (!res && de[0].d_reclen == 65535) return NULL; /* AFS bug */
1169 return de;
1173 /***********************************************************************
1174 * read_directory_vfat
1176 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
1178 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1179 BOOLEAN single_entry, const UNICODE_STRING *mask,
1180 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1183 size_t len;
1184 KERNEL_DIRENT *de;
1185 union file_directory_info *info, *last_info = NULL;
1187 io->u.Status = STATUS_SUCCESS;
1189 if (restart_scan) lseek( fd, 0, SEEK_SET );
1191 if (length < max_dir_info_size(class)) /* we may have to return a partial entry here */
1193 off_t old_pos = lseek( fd, 0, SEEK_CUR );
1195 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1197 while (de[0].d_reclen)
1199 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1200 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1201 de[0].d_name[len] = 0;
1202 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1203 de[1].d_name[len] = 0;
1205 if (de[1].d_name[0])
1206 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1207 else
1208 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1209 if (info)
1211 last_info = info;
1212 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1213 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1214 break;
1216 old_pos = lseek( fd, 0, SEEK_CUR );
1217 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1220 else /* we'll only return full entries, no need to worry about overflow */
1222 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1224 while (de[0].d_reclen)
1226 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1227 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1228 de[0].d_name[len] = 0;
1229 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1230 de[1].d_name[len] = 0;
1232 if (de[1].d_name[0])
1233 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1234 else
1235 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1236 if (info)
1238 last_info = info;
1239 if (single_entry) break;
1240 /* check if we still have enough space for the largest possible entry */
1241 if (io->Information + max_dir_info_size(class) > length) break;
1243 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1247 if (last_info) last_info->next = 0;
1248 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1249 return 0;
1251 #endif /* VFAT_IOCTL_READDIR_BOTH */
1254 /***********************************************************************
1255 * read_directory_getdents
1257 * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
1259 #ifdef USE_GETDENTS
1260 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1261 BOOLEAN single_entry, const UNICODE_STRING *mask,
1262 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1264 off_t old_pos = 0;
1265 size_t size = length;
1266 int res, fake_dot_dot = 1;
1267 char *data, local_buffer[8192];
1268 KERNEL_DIRENT64 *de;
1269 union file_directory_info *info, *last_info = NULL;
1271 if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1273 size = sizeof(local_buffer);
1274 data = local_buffer;
1277 if (restart_scan) lseek( fd, 0, SEEK_SET );
1278 else if (length < max_dir_info_size(class)) /* we may have to return a partial entry here */
1280 old_pos = lseek( fd, 0, SEEK_CUR );
1281 if (old_pos == -1 && errno == ENOENT)
1283 io->u.Status = STATUS_NO_MORE_FILES;
1284 res = 0;
1285 goto done;
1289 io->u.Status = STATUS_SUCCESS;
1291 res = getdents64( fd, data, size );
1292 if (res == -1)
1294 if (errno != ENOSYS)
1296 io->u.Status = FILE_GetNtStatus();
1297 res = 0;
1299 goto done;
1302 de = (KERNEL_DIRENT64 *)data;
1304 if (restart_scan)
1306 /* check if we got . and .. from getdents */
1307 if (res > 0)
1309 if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1311 KERNEL_DIRENT64 *next_de = (KERNEL_DIRENT64 *)(data + de->d_reclen);
1312 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1315 /* make sure we have enough room for both entries */
1316 if (fake_dot_dot)
1318 const ULONG min_info_size = dir_info_size( class, 1 ) + dir_info_size( class, 2 );
1319 if (length < min_info_size || single_entry)
1321 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1322 fake_dot_dot = 0;
1326 if (fake_dot_dot)
1328 if ((info = append_entry( buffer, io, length, ".", NULL, mask, class )))
1329 last_info = info;
1330 if ((info = append_entry( buffer, io, length, "..", NULL, mask, class )))
1331 last_info = info;
1333 /* check if we still have enough space for the largest possible entry */
1334 if (last_info && io->Information + max_dir_info_size(class) > length)
1336 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1337 res = 0;
1342 while (res > 0)
1344 res -= de->d_reclen;
1345 if (de->d_ino &&
1346 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1347 (info = append_entry( buffer, io, length, de->d_name, NULL, mask, class )))
1349 last_info = info;
1350 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1352 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1353 break;
1355 /* check if we still have enough space for the largest possible entry */
1356 if (single_entry || io->Information + max_dir_info_size(class) > length)
1358 if (res > 0) lseek( fd, de->d_off, SEEK_SET ); /* set pos to next entry */
1359 break;
1362 old_pos = de->d_off;
1363 /* move on to the next entry */
1364 if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1365 else
1367 res = getdents64( fd, data, size );
1368 de = (KERNEL_DIRENT64 *)data;
1372 if (last_info) last_info->next = 0;
1373 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1374 res = 0;
1375 done:
1376 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1377 return res;
1380 #elif defined HAVE_GETDIRENTRIES
1382 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1384 /* Darwin doesn't provide a version of getdirentries with support for 64-bit
1385 * inodes. When 64-bit inodes are enabled, the getdirentries symbol is mapped
1386 * to _getdirentries_is_not_available_when_64_bit_inodes_are_in_effect so that
1387 * we get link errors if we try to use it. We still need getdirentries, but we
1388 * don't need it to support 64-bit inodes. So, we use the legacy getdirentries
1389 * with 32-bit inodes. We have to be careful to use a corresponding dirent
1390 * structure, too.
1392 int darwin_legacy_getdirentries(int, char *, int, long *) __asm("_getdirentries");
1393 #define getdirentries darwin_legacy_getdirentries
1395 struct darwin_legacy_dirent {
1396 __uint32_t d_ino;
1397 __uint16_t d_reclen;
1398 __uint8_t d_type;
1399 __uint8_t d_namlen;
1400 char d_name[__DARWIN_MAXNAMLEN + 1];
1402 #define dirent darwin_legacy_dirent
1404 #endif
1406 /***********************************************************************
1407 * wine_getdirentries
1409 * Wrapper for the BSD getdirentries system call to fix a bug in the
1410 * Mac OS X version. For some file systems (at least Apple Filing
1411 * Protocol a.k.a. AFP), getdirentries resets the file position to 0
1412 * when it's about to return 0 (no more entries). So, a subsequent
1413 * getdirentries call starts over at the beginning again, causing an
1414 * infinite loop.
1416 static inline int wine_getdirentries(int fd, char *buf, int nbytes, long *basep)
1418 int res = getdirentries(fd, buf, nbytes, basep);
1419 #ifdef __APPLE__
1420 if (res == 0)
1421 lseek(fd, *basep, SEEK_SET);
1422 #endif
1423 return res;
1426 /***********************************************************************
1427 * read_directory_getdirentries
1429 * Read a directory using the BSD getdirentries system call; helper for NtQueryDirectoryFile.
1431 static int read_directory_getdirentries( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1432 BOOLEAN single_entry, const UNICODE_STRING *mask,
1433 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1435 long restart_pos;
1436 ULONG_PTR restart_info_pos = 0;
1437 size_t size, initial_size = length;
1438 int res, fake_dot_dot = 1;
1439 char *data, local_buffer[8192];
1440 struct dirent *de;
1441 union file_directory_info *info, *last_info = NULL, *restart_last_info = NULL;
1443 size = initial_size;
1444 data = local_buffer;
1445 if (size > sizeof(local_buffer) && !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1447 io->u.Status = STATUS_NO_MEMORY;
1448 return io->u.Status;
1451 if (restart_scan) lseek( fd, 0, SEEK_SET );
1453 io->u.Status = STATUS_SUCCESS;
1455 /* FIXME: should make sure size is larger than filesystem block size */
1456 res = wine_getdirentries( fd, data, size, &restart_pos );
1457 if (res == -1)
1459 io->u.Status = FILE_GetNtStatus();
1460 res = 0;
1461 goto done;
1464 de = (struct dirent *)data;
1466 if (restart_scan)
1468 /* check if we got . and .. from getdirentries */
1469 if (res > 0)
1471 if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1473 struct dirent *next_de = (struct dirent *)(data + de->d_reclen);
1474 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1477 /* make sure we have enough room for both entries */
1478 if (fake_dot_dot)
1480 const ULONG min_info_size = dir_info_size( class, 1 ) + dir_info_size( class, 2 );
1481 if (length < min_info_size || single_entry)
1483 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1484 fake_dot_dot = 0;
1488 if (fake_dot_dot)
1490 if ((info = append_entry( buffer, io, length, ".", NULL, mask, class )))
1491 last_info = info;
1492 if ((info = append_entry( buffer, io, length, "..", NULL, mask, class )))
1493 last_info = info;
1495 restart_last_info = last_info;
1496 restart_info_pos = io->Information;
1498 /* check if we still have enough space for the largest possible entry */
1499 if (last_info && io->Information + max_dir_info_size(class) > length)
1501 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1502 res = 0;
1507 while (res > 0)
1509 res -= de->d_reclen;
1510 if (de->d_fileno &&
1511 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1512 ((info = append_entry( buffer, io, length, de->d_name, NULL, mask, class ))))
1514 last_info = info;
1515 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1517 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1518 if (restart_info_pos) /* if we have a complete read already, return it */
1520 io->u.Status = STATUS_SUCCESS;
1521 io->Information = restart_info_pos;
1522 last_info = restart_last_info;
1523 break;
1525 /* otherwise restart from the start with a smaller size */
1526 size = (char *)de - data;
1527 if (!size) break;
1528 io->Information = 0;
1529 last_info = NULL;
1530 goto restart;
1532 /* if we have to return but the buffer contains more data, restart with a smaller size */
1533 if (res > 0 && (single_entry || io->Information + max_dir_info_size(class) > length))
1535 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1536 size = (char *)de - data;
1537 io->Information = restart_info_pos;
1538 last_info = restart_last_info;
1539 goto restart;
1542 /* move on to the next entry */
1543 if (res > 0)
1545 de = (struct dirent *)((char *)de + de->d_reclen);
1546 continue;
1548 if (size < initial_size) break; /* already restarted once, give up now */
1549 size = min( size, length - io->Information );
1550 /* if size is too small don't bother to continue */
1551 if (size < max_dir_info_size(class) && last_info) break;
1552 restart_last_info = last_info;
1553 restart_info_pos = io->Information;
1554 restart:
1555 res = wine_getdirentries( fd, data, size, &restart_pos );
1556 de = (struct dirent *)data;
1559 if (last_info) last_info->next = 0;
1560 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1561 res = 0;
1562 done:
1563 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1564 return res;
1567 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1568 #undef getdirentries
1569 #undef dirent
1570 #endif
1572 #endif /* HAVE_GETDIRENTRIES */
1575 /***********************************************************************
1576 * read_directory_readdir
1578 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1580 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1581 BOOLEAN single_entry, const UNICODE_STRING *mask,
1582 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1584 DIR *dir;
1585 off_t i, old_pos = 0;
1586 struct dirent *de;
1587 union file_directory_info *info, *last_info = NULL;
1589 if (!(dir = opendir( "." )))
1591 io->u.Status = FILE_GetNtStatus();
1592 return;
1595 if (!restart_scan)
1597 old_pos = lseek( fd, 0, SEEK_CUR );
1598 /* skip the right number of entries */
1599 for (i = 0; i < old_pos - 2; i++)
1601 if (!readdir( dir ))
1603 closedir( dir );
1604 io->u.Status = STATUS_NO_MORE_FILES;
1605 return;
1609 io->u.Status = STATUS_SUCCESS;
1611 for (;;)
1613 if (old_pos == 0)
1614 info = append_entry( buffer, io, length, ".", NULL, mask, class );
1615 else if (old_pos == 1)
1616 info = append_entry( buffer, io, length, "..", NULL, mask, class );
1617 else if ((de = readdir( dir )))
1619 if (strcmp( de->d_name, "." ) && strcmp( de->d_name, ".." ))
1620 info = append_entry( buffer, io, length, de->d_name, NULL, mask, class );
1621 else
1622 info = NULL;
1624 else
1625 break;
1626 old_pos++;
1627 if (info)
1629 last_info = info;
1630 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1632 old_pos--; /* restore pos to previous entry */
1633 break;
1635 if (single_entry) break;
1636 /* check if we still have enough space for the largest possible entry */
1637 if (io->Information + max_dir_info_size(class) > length) break;
1641 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
1642 closedir( dir );
1644 if (last_info) last_info->next = 0;
1645 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1648 /***********************************************************************
1649 * read_directory_stat
1651 * Read a single file from a directory by determining whether the file
1652 * identified by mask exists using stat.
1654 static int read_directory_stat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1655 BOOLEAN single_entry, const UNICODE_STRING *mask,
1656 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1658 int unix_len, ret, used_default;
1659 char *unix_name;
1660 struct stat st;
1662 TRACE("trying optimisation for file %s\n", debugstr_us( mask ));
1664 unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
1665 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
1667 io->u.Status = STATUS_NO_MEMORY;
1668 return 0;
1670 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
1671 NULL, &used_default );
1672 if (ret > 0 && !used_default)
1674 unix_name[ret] = 0;
1675 if (restart_scan)
1677 lseek( fd, 0, SEEK_SET );
1679 else if (lseek( fd, 0, SEEK_CUR ) != 0)
1681 io->u.Status = STATUS_NO_MORE_FILES;
1682 ret = 0;
1683 goto done;
1686 ret = stat( unix_name, &st );
1687 if (!ret)
1689 union file_directory_info *info = append_entry( buffer, io, length, unix_name, NULL, NULL, class );
1690 if (info)
1692 info->next = 0;
1693 if (io->u.Status != STATUS_BUFFER_OVERFLOW) lseek( fd, 1, SEEK_CUR );
1695 else io->u.Status = STATUS_NO_MORE_FILES;
1698 else ret = -1;
1700 done:
1701 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1703 TRACE("returning %d\n", ret);
1705 return ret;
1709 static inline WCHAR *mempbrkW( const WCHAR *ptr, const WCHAR *accept, size_t n )
1711 const WCHAR *end;
1712 for (end = ptr + n; ptr < end; ptr++) if (strchrW( accept, *ptr )) return (WCHAR *)ptr;
1713 return NULL;
1716 /******************************************************************************
1717 * NtQueryDirectoryFile [NTDLL.@]
1718 * ZwQueryDirectoryFile [NTDLL.@]
1720 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
1721 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
1722 PIO_STATUS_BLOCK io,
1723 PVOID buffer, ULONG length,
1724 FILE_INFORMATION_CLASS info_class,
1725 BOOLEAN single_entry,
1726 PUNICODE_STRING mask,
1727 BOOLEAN restart_scan )
1729 int cwd, fd, needs_close;
1730 static const WCHAR wszWildcards[] = { '*','?',0 };
1732 TRACE("(%p %p %p %p %p %p 0x%08x 0x%08x 0x%08x %s 0x%08x\n",
1733 handle, event, apc_routine, apc_context, io, buffer,
1734 length, info_class, single_entry, debugstr_us(mask),
1735 restart_scan);
1737 if (event || apc_routine)
1739 FIXME( "Unsupported yet option\n" );
1740 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1742 switch (info_class)
1744 case FileDirectoryInformation:
1745 case FileBothDirectoryInformation:
1746 case FileFullDirectoryInformation:
1747 case FileIdBothDirectoryInformation:
1748 case FileIdFullDirectoryInformation:
1749 if (length < dir_info_size( info_class, 1 )) return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
1750 break;
1751 default:
1752 FIXME( "Unsupported file info class %d\n", info_class );
1753 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1756 if ((io->u.Status = server_get_unix_fd( handle, FILE_LIST_DIRECTORY, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
1757 return io->u.Status;
1759 io->Information = 0;
1761 RtlEnterCriticalSection( &dir_section );
1763 if (show_dot_files == -1) init_options();
1765 cwd = open( ".", O_RDONLY );
1766 if (fchdir( fd ) != -1)
1768 struct stat st;
1769 fstat( fd, &st );
1770 curdir.dev = st.st_dev;
1771 curdir.ino = st.st_ino;
1772 #ifdef VFAT_IOCTL_READDIR_BOTH
1773 if ((read_directory_vfat( fd, io, buffer, length, single_entry,
1774 mask, restart_scan, info_class )) != -1) goto done;
1775 #endif
1776 if (mask && !mempbrkW( mask->Buffer, wszWildcards, mask->Length / sizeof(WCHAR) ) &&
1777 read_directory_stat( fd, io, buffer, length, single_entry,
1778 mask, restart_scan, info_class ) != -1) goto done;
1779 #ifdef USE_GETDENTS
1780 if ((read_directory_getdents( fd, io, buffer, length, single_entry,
1781 mask, restart_scan, info_class )) != -1) goto done;
1782 #elif defined HAVE_GETDIRENTRIES
1783 if ((read_directory_getdirentries( fd, io, buffer, length, single_entry,
1784 mask, restart_scan, info_class )) != -1) goto done;
1785 #endif
1786 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan, info_class );
1788 done:
1789 if (cwd == -1 || fchdir( cwd ) == -1) chdir( "/" );
1791 else io->u.Status = FILE_GetNtStatus();
1793 RtlLeaveCriticalSection( &dir_section );
1795 if (needs_close) close( fd );
1796 if (cwd != -1) close( cwd );
1797 TRACE( "=> %x (%ld)\n", io->u.Status, io->Information );
1798 return io->u.Status;
1802 /***********************************************************************
1803 * find_file_in_dir
1805 * Find a file in a directory the hard way, by doing a case-insensitive search.
1806 * The file found is appended to unix_name at pos.
1807 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
1809 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
1810 int check_case, int *is_win_dir )
1812 WCHAR buffer[MAX_DIR_ENTRY_LEN];
1813 UNICODE_STRING str;
1814 BOOLEAN spaces;
1815 DIR *dir;
1816 struct dirent *de;
1817 struct stat st;
1818 int ret, used_default, is_name_8_dot_3;
1820 /* try a shortcut for this directory */
1822 unix_name[pos++] = '/';
1823 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
1824 NULL, &used_default );
1825 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
1826 /* so it cannot match the file we are looking for */
1827 if (ret >= 0 && !used_default)
1829 unix_name[pos + ret] = 0;
1830 if (!stat( unix_name, &st ))
1832 if (is_win_dir) *is_win_dir = is_same_file( &windir, &st );
1833 return STATUS_SUCCESS;
1836 if (check_case) goto not_found; /* we want an exact match */
1838 if (pos > 1) unix_name[pos - 1] = 0;
1839 else unix_name[1] = 0; /* keep the initial slash */
1841 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
1843 str.Buffer = (WCHAR *)name;
1844 str.Length = length * sizeof(WCHAR);
1845 str.MaximumLength = str.Length;
1846 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
1848 /* now look for it through the directory */
1850 #ifdef VFAT_IOCTL_READDIR_BOTH
1851 if (is_name_8_dot_3)
1853 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
1854 if (fd != -1)
1856 KERNEL_DIRENT *de;
1858 RtlEnterCriticalSection( &dir_section );
1859 if ((de = start_vfat_ioctl( fd )))
1861 unix_name[pos - 1] = '/';
1862 while (de[0].d_reclen)
1864 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1865 size_t len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1866 de[0].d_name[len] = 0;
1867 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1868 de[1].d_name[len] = 0;
1870 if (de[1].d_name[0])
1872 ret = ntdll_umbstowcs( 0, de[1].d_name, strlen(de[1].d_name),
1873 buffer, MAX_DIR_ENTRY_LEN );
1874 if (ret == length && !memicmpW( buffer, name, length))
1876 strcpy( unix_name + pos, de[1].d_name );
1877 RtlLeaveCriticalSection( &dir_section );
1878 close( fd );
1879 goto success;
1882 ret = ntdll_umbstowcs( 0, de[0].d_name, strlen(de[0].d_name),
1883 buffer, MAX_DIR_ENTRY_LEN );
1884 if (ret == length && !memicmpW( buffer, name, length))
1886 strcpy( unix_name + pos,
1887 de[1].d_name[0] ? de[1].d_name : de[0].d_name );
1888 RtlLeaveCriticalSection( &dir_section );
1889 close( fd );
1890 goto success;
1892 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1)
1894 RtlLeaveCriticalSection( &dir_section );
1895 close( fd );
1896 goto not_found;
1900 RtlLeaveCriticalSection( &dir_section );
1901 close( fd );
1903 /* fall through to normal handling */
1905 #endif /* VFAT_IOCTL_READDIR_BOTH */
1907 if (!(dir = opendir( unix_name )))
1909 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
1910 else return FILE_GetNtStatus();
1912 unix_name[pos - 1] = '/';
1913 str.Buffer = buffer;
1914 str.MaximumLength = sizeof(buffer);
1915 while ((de = readdir( dir )))
1917 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
1918 if (ret == length && !memicmpW( buffer, name, length ))
1920 strcpy( unix_name + pos, de->d_name );
1921 closedir( dir );
1922 goto success;
1925 if (!is_name_8_dot_3) continue;
1927 str.Length = ret * sizeof(WCHAR);
1928 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1930 WCHAR short_nameW[12];
1931 ret = hash_short_file_name( &str, short_nameW );
1932 if (ret == length && !memicmpW( short_nameW, name, length ))
1934 strcpy( unix_name + pos, de->d_name );
1935 closedir( dir );
1936 goto success;
1940 closedir( dir );
1941 goto not_found; /* avoid warning */
1943 not_found:
1944 unix_name[pos - 1] = 0;
1945 return STATUS_OBJECT_PATH_NOT_FOUND;
1947 success:
1948 if (is_win_dir && !stat( unix_name, &st )) *is_win_dir = is_same_file( &windir, &st );
1949 return STATUS_SUCCESS;
1953 #ifndef _WIN64
1955 static const WCHAR catrootW[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t',0};
1956 static const WCHAR catroot2W[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t','2',0};
1957 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};
1958 static const WCHAR driversetcW[] = {'s','y','s','t','e','m','3','2','\\','d','r','i','v','e','r','s','\\','e','t','c',0};
1959 static const WCHAR logfilesW[] = {'s','y','s','t','e','m','3','2','\\','l','o','g','f','i','l','e','s',0};
1960 static const WCHAR spoolW[] = {'s','y','s','t','e','m','3','2','\\','s','p','o','o','l',0};
1961 static const WCHAR system32W[] = {'s','y','s','t','e','m','3','2',0};
1962 static const WCHAR syswow64W[] = {'s','y','s','w','o','w','6','4',0};
1963 static const WCHAR sysnativeW[] = {'s','y','s','n','a','t','i','v','e',0};
1964 static const WCHAR regeditW[] = {'r','e','g','e','d','i','t','.','e','x','e',0};
1965 static const WCHAR wow_regeditW[] = {'s','y','s','w','o','w','6','4','\\','r','e','g','e','d','i','t','.','e','x','e',0};
1967 static struct
1969 const WCHAR *source;
1970 const WCHAR *dos_target;
1971 const char *unix_target;
1972 } redirects[] =
1974 { catrootW, NULL, NULL },
1975 { catroot2W, NULL, NULL },
1976 { driversstoreW, NULL, NULL },
1977 { driversetcW, NULL, NULL },
1978 { logfilesW, NULL, NULL },
1979 { spoolW, NULL, NULL },
1980 { system32W, syswow64W, NULL },
1981 { sysnativeW, system32W, NULL },
1982 { regeditW, wow_regeditW, NULL }
1985 static unsigned int nb_redirects;
1988 /***********************************************************************
1989 * get_redirect_target
1991 * Find the target unix name for a redirected dir.
1993 static const char *get_redirect_target( const char *windows_dir, const WCHAR *name )
1995 int used_default, len, pos, win_len = strlen( windows_dir );
1996 char *unix_name, *unix_target = NULL;
1997 NTSTATUS status;
1999 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, win_len + MAX_DIR_ENTRY_LEN + 2 )))
2000 return NULL;
2001 memcpy( unix_name, windows_dir, win_len );
2002 pos = win_len;
2004 while (*name)
2006 const WCHAR *end, *next;
2008 for (end = name; *end; end++) if (IS_SEPARATOR(*end)) break;
2009 for (next = end; *next; next++) if (!IS_SEPARATOR(*next)) break;
2011 status = find_file_in_dir( unix_name, pos, name, end - name, FALSE, NULL );
2012 if (status == STATUS_OBJECT_PATH_NOT_FOUND && !*next) /* not finding last element is ok */
2014 len = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2015 MAX_DIR_ENTRY_LEN - (pos - win_len), NULL, &used_default );
2016 if (len > 0 && !used_default)
2018 unix_name[pos] = '/';
2019 pos += len + 1;
2020 unix_name[pos] = 0;
2021 break;
2024 if (status) goto done;
2025 pos += strlen( unix_name + pos );
2026 name = next;
2029 if ((unix_target = RtlAllocateHeap( GetProcessHeap(), 0, pos - win_len )))
2030 memcpy( unix_target, unix_name + win_len + 1, pos - win_len );
2032 done:
2033 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2034 return unix_target;
2038 /***********************************************************************
2039 * init_redirects
2041 static void init_redirects(void)
2043 UNICODE_STRING nt_name;
2044 ANSI_STRING unix_name;
2045 NTSTATUS status;
2046 struct stat st;
2047 unsigned int i;
2049 if (!RtlDosPathNameToNtPathName_U( windows_dir.Buffer, &nt_name, NULL, NULL ))
2051 ERR( "can't convert %s\n", debugstr_us(&windows_dir) );
2052 return;
2054 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
2055 RtlFreeUnicodeString( &nt_name );
2056 if (status)
2058 ERR( "cannot open %s (%x)\n", debugstr_us(&windows_dir), status );
2059 return;
2061 if (!stat( unix_name.Buffer, &st ))
2063 windir.dev = st.st_dev;
2064 windir.ino = st.st_ino;
2065 nb_redirects = sizeof(redirects) / sizeof(redirects[0]);
2066 for (i = 0; i < nb_redirects; i++)
2068 if (!redirects[i].dos_target) continue;
2069 redirects[i].unix_target = get_redirect_target( unix_name.Buffer, redirects[i].dos_target );
2070 TRACE( "%s -> %s\n", debugstr_w(redirects[i].source), redirects[i].unix_target );
2073 RtlFreeAnsiString( &unix_name );
2078 /***********************************************************************
2079 * match_redirect
2081 * Check if path matches a redirect name. If yes, return matched length.
2083 static int match_redirect( const WCHAR *path, int len, const WCHAR *redir, int check_case )
2085 int i = 0;
2087 while (i < len && *redir)
2089 if (IS_SEPARATOR(path[i]))
2091 if (*redir++ != '\\') return 0;
2092 while (i < len && IS_SEPARATOR(path[i])) i++;
2093 continue; /* move on to next path component */
2095 else if (check_case)
2097 if (path[i] != *redir) return 0;
2099 else
2101 if (tolowerW(path[i]) != tolowerW(*redir)) return 0;
2103 i++;
2104 redir++;
2106 if (*redir) return 0;
2107 if (i < len && !IS_SEPARATOR(path[i])) return 0;
2108 while (i < len && IS_SEPARATOR(path[i])) i++;
2109 return i;
2113 /***********************************************************************
2114 * get_redirect_path
2116 * Retrieve the Unix path corresponding to a redirected path if any.
2118 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, int check_case )
2120 unsigned int i;
2121 int len;
2123 for (i = 0; i < nb_redirects; i++)
2125 if ((len = match_redirect( name, length, redirects[i].source, check_case )))
2127 if (!redirects[i].unix_target) break;
2128 unix_name[pos++] = '/';
2129 strcpy( unix_name + pos, redirects[i].unix_target );
2130 return len;
2133 return 0;
2136 #else /* _WIN64 */
2138 /* there are no redirects on 64-bit */
2140 static const unsigned int nb_redirects = 0;
2142 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, int check_case )
2144 return 0;
2147 #endif
2149 /***********************************************************************
2150 * DIR_init_windows_dir
2152 void DIR_init_windows_dir( const WCHAR *win, const WCHAR *sys )
2154 /* FIXME: should probably store paths as NT file names */
2156 RtlCreateUnicodeString( &windows_dir, win );
2157 RtlCreateUnicodeString( &system_dir, sys );
2159 #ifndef _WIN64
2160 if (is_wow64) init_redirects();
2161 #endif
2165 /******************************************************************************
2166 * get_dos_device
2168 * Get the Unix path of a DOS device.
2170 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
2172 const char *config_dir = wine_get_config_dir();
2173 struct stat st;
2174 char *unix_name, *new_name, *dev;
2175 unsigned int i;
2176 int unix_len;
2178 /* make sure the device name is ASCII */
2179 for (i = 0; i < name_len; i++)
2180 if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
2182 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
2184 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2185 return STATUS_NO_MEMORY;
2187 strcpy( unix_name, config_dir );
2188 strcat( unix_name, "/dosdevices/" );
2189 dev = unix_name + strlen(unix_name);
2191 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
2192 dev[i] = 0;
2194 /* special case for drive devices */
2195 if (name_len == 2 && dev[1] == ':')
2197 dev[i++] = ':';
2198 dev[i] = 0;
2201 for (;;)
2203 if (!stat( unix_name, &st ))
2205 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
2206 unix_name_ret->Buffer = unix_name;
2207 unix_name_ret->Length = strlen(unix_name);
2208 unix_name_ret->MaximumLength = unix_len;
2209 return STATUS_SUCCESS;
2211 if (!dev) break;
2213 /* now try some defaults for it */
2214 if (!strcmp( dev, "aux" ))
2216 strcpy( dev, "com1" );
2217 continue;
2219 if (!strcmp( dev, "prn" ))
2221 strcpy( dev, "lpt1" );
2222 continue;
2224 if (!strcmp( dev, "nul" ))
2226 strcpy( unix_name, "/dev/null" );
2227 dev = NULL; /* last try */
2228 continue;
2231 new_name = NULL;
2232 if (dev[1] == ':' && dev[2] == ':') /* drive device */
2234 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
2235 new_name = get_default_drive_device( unix_name );
2237 else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( atoi(dev + 3 ));
2238 else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( atoi(dev + 3 ));
2240 if (!new_name) break;
2242 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2243 unix_name = new_name;
2244 unix_len = strlen(unix_name) + 1;
2245 dev = NULL; /* last try */
2247 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2248 return STATUS_BAD_DEVICE_TYPE;
2252 /* return the length of the DOS namespace prefix if any */
2253 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
2255 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
2256 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
2258 if (name->Length > sizeof(nt_prefixW) &&
2259 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
2260 return sizeof(nt_prefixW) / sizeof(WCHAR);
2262 if (name->Length > sizeof(dosdev_prefixW) &&
2263 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
2264 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
2266 return 0;
2270 /******************************************************************************
2271 * find_file_id
2273 * Recursively search directories from the dir queue for a given inode.
2275 static NTSTATUS find_file_id( ANSI_STRING *unix_name, ULONGLONG file_id, dev_t dev )
2277 unsigned int pos;
2278 DIR *dir;
2279 struct dirent *de;
2280 NTSTATUS status;
2281 struct stat st;
2283 while (!(status = next_dir_in_queue( unix_name->Buffer )))
2285 if (!(dir = opendir( unix_name->Buffer ))) continue;
2286 TRACE( "searching %s for %s\n", unix_name->Buffer, wine_dbgstr_longlong(file_id) );
2287 pos = strlen( unix_name->Buffer );
2288 if (pos + MAX_DIR_ENTRY_LEN >= unix_name->MaximumLength/sizeof(WCHAR))
2290 char *new = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name->Buffer,
2291 unix_name->MaximumLength * 2 );
2292 if (!new)
2294 closedir( dir );
2295 return STATUS_NO_MEMORY;
2297 unix_name->MaximumLength *= 2;
2298 unix_name->Buffer = new;
2300 unix_name->Buffer[pos++] = '/';
2301 while ((de = readdir( dir )))
2303 if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
2304 strcpy( unix_name->Buffer + pos, de->d_name );
2305 if (lstat( unix_name->Buffer, &st ) == -1) continue;
2306 if (st.st_dev != dev) continue;
2307 if (st.st_ino == file_id)
2309 closedir( dir );
2310 return STATUS_SUCCESS;
2312 if (!S_ISDIR( st.st_mode )) continue;
2313 if ((status = add_dir_to_queue( unix_name->Buffer )) != STATUS_SUCCESS)
2315 closedir( dir );
2316 return status;
2319 closedir( dir );
2321 return status;
2325 /******************************************************************************
2326 * file_id_to_unix_file_name
2328 * Lookup a file from its file id instead of its name.
2330 NTSTATUS file_id_to_unix_file_name( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name )
2332 enum server_fd_type type;
2333 int old_cwd, root_fd, needs_close;
2334 NTSTATUS status;
2335 ULONGLONG file_id;
2336 struct stat st, root_st;
2338 if (attr->ObjectName->Length != sizeof(ULONGLONG)) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2339 if (!attr->RootDirectory) return STATUS_INVALID_PARAMETER;
2340 memcpy( &file_id, attr->ObjectName->Buffer, sizeof(file_id) );
2342 unix_name->MaximumLength = 2 * MAX_DIR_ENTRY_LEN + 4;
2343 if (!(unix_name->Buffer = RtlAllocateHeap( GetProcessHeap(), 0, unix_name->MaximumLength )))
2344 return STATUS_NO_MEMORY;
2345 strcpy( unix_name->Buffer, "." );
2347 if ((status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
2348 goto done;
2350 if (type != FD_TYPE_DIR)
2352 status = STATUS_OBJECT_TYPE_MISMATCH;
2353 goto done;
2356 fstat( root_fd, &root_st );
2357 if (root_st.st_ino == file_id) /* shortcut for "." */
2359 status = STATUS_SUCCESS;
2360 goto done;
2363 RtlEnterCriticalSection( &dir_section );
2364 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2366 /* shortcut for ".." */
2367 if (!stat( "..", &st ) && st.st_dev == root_st.st_dev && st.st_ino == file_id)
2369 strcpy( unix_name->Buffer, ".." );
2370 status = STATUS_SUCCESS;
2372 else
2374 status = add_dir_to_queue( "." );
2375 if (!status)
2376 status = find_file_id( unix_name, file_id, root_st.st_dev );
2377 if (!status) /* get rid of "./" prefix */
2378 memmove( unix_name->Buffer, unix_name->Buffer + 2, strlen(unix_name->Buffer) - 1 );
2379 flush_dir_queue();
2381 if (fchdir( old_cwd ) == -1) chdir( "/" );
2383 else status = FILE_GetNtStatus();
2384 RtlLeaveCriticalSection( &dir_section );
2385 if (old_cwd != -1) close( old_cwd );
2387 done:
2388 if (status == STATUS_SUCCESS)
2390 TRACE( "%s -> %s\n", wine_dbgstr_longlong(file_id), debugstr_a(unix_name->Buffer) );
2391 unix_name->Length = strlen( unix_name->Buffer );
2393 else
2395 TRACE( "%s not found in dir %p\n", wine_dbgstr_longlong(file_id), attr->RootDirectory );
2396 RtlFreeHeap( GetProcessHeap(), 0, unix_name->Buffer );
2398 if (needs_close) close( root_fd );
2399 return status;
2403 /******************************************************************************
2404 * lookup_unix_name
2406 * Helper for nt_to_unix_file_name
2408 static NTSTATUS lookup_unix_name( const WCHAR *name, int name_len, char **buffer, int unix_len, int pos,
2409 UINT disposition, BOOLEAN check_case )
2411 NTSTATUS status;
2412 int ret, used_default, len;
2413 struct stat st;
2414 char *unix_name = *buffer;
2415 const BOOL redirect = nb_redirects && ntdll_get_thread_data()->wow64_redir;
2417 /* try a shortcut first */
2419 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
2420 NULL, &used_default );
2422 while (name_len && IS_SEPARATOR(*name))
2424 name++;
2425 name_len--;
2428 if (ret >= 0 && !used_default) /* if we used the default char the name didn't convert properly */
2430 char *p;
2431 unix_name[pos + ret] = 0;
2432 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
2433 if (!redirect || (!strstr( unix_name, "/windows/") && strncmp( unix_name, "windows/", 8 )))
2435 if (!stat( unix_name, &st ))
2437 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
2438 if (disposition == FILE_CREATE)
2439 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
2440 return STATUS_SUCCESS;
2445 if (!name_len) /* empty name -> drive root doesn't exist */
2446 return STATUS_OBJECT_PATH_NOT_FOUND;
2447 if (check_case && !redirect && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
2448 return STATUS_OBJECT_NAME_NOT_FOUND;
2450 /* now do it component by component */
2452 while (name_len)
2454 const WCHAR *end, *next;
2455 int is_win_dir = 0;
2457 end = name;
2458 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
2459 next = end;
2460 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
2461 name_len -= next - name;
2463 /* grow the buffer if needed */
2465 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
2467 char *new_name;
2468 unix_len += 2 * MAX_DIR_ENTRY_LEN;
2469 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
2470 return STATUS_NO_MEMORY;
2471 unix_name = *buffer = new_name;
2474 status = find_file_in_dir( unix_name, pos, name, end - name,
2475 check_case, redirect ? &is_win_dir : NULL );
2477 /* if this is the last element, not finding it is not necessarily fatal */
2478 if (!name_len)
2480 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
2482 status = STATUS_OBJECT_NAME_NOT_FOUND;
2483 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
2485 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2486 MAX_DIR_ENTRY_LEN, NULL, &used_default );
2487 if (ret > 0 && !used_default)
2489 unix_name[pos] = '/';
2490 unix_name[pos + 1 + ret] = 0;
2491 status = STATUS_NO_SUCH_FILE;
2492 break;
2496 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
2498 status = STATUS_OBJECT_NAME_COLLISION;
2502 if (status != STATUS_SUCCESS) break;
2504 pos += strlen( unix_name + pos );
2505 name = next;
2507 if (is_win_dir && (len = get_redirect_path( unix_name, pos, name, name_len, check_case )))
2509 name += len;
2510 name_len -= len;
2511 pos += strlen( unix_name + pos );
2512 TRACE( "redirecting -> %s + %s\n", debugstr_a(unix_name), debugstr_w(name) );
2516 return status;
2520 /******************************************************************************
2521 * nt_to_unix_file_name_attr
2523 NTSTATUS nt_to_unix_file_name_attr( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name_ret,
2524 UINT disposition )
2526 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2527 enum server_fd_type type;
2528 int old_cwd, root_fd, needs_close;
2529 const WCHAR *name, *p;
2530 char *unix_name;
2531 int name_len, unix_len;
2532 NTSTATUS status;
2533 BOOLEAN check_case = !(attr->Attributes & OBJ_CASE_INSENSITIVE);
2535 if (!attr->RootDirectory) /* without root dir fall back to normal lookup */
2536 return wine_nt_to_unix_file_name( attr->ObjectName, unix_name_ret, disposition, check_case );
2538 name = attr->ObjectName->Buffer;
2539 name_len = attr->ObjectName->Length / sizeof(WCHAR);
2541 if (name_len && IS_SEPARATOR(name[0])) return STATUS_INVALID_PARAMETER;
2543 /* check for invalid characters */
2544 for (p = name; p < name + name_len; p++)
2545 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2547 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
2548 unix_len += MAX_DIR_ENTRY_LEN + 3;
2549 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2550 return STATUS_NO_MEMORY;
2551 unix_name[0] = '.';
2553 if (!(status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
2555 if (type != FD_TYPE_DIR)
2557 if (needs_close) close( root_fd );
2558 status = STATUS_BAD_DEVICE_TYPE;
2560 else
2562 RtlEnterCriticalSection( &dir_section );
2563 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2565 status = lookup_unix_name( name, name_len, &unix_name, unix_len, 1,
2566 disposition, check_case );
2567 if (fchdir( old_cwd ) == -1) chdir( "/" );
2569 else status = FILE_GetNtStatus();
2570 RtlLeaveCriticalSection( &dir_section );
2571 if (old_cwd != -1) close( old_cwd );
2572 if (needs_close) close( root_fd );
2575 else if (status == STATUS_OBJECT_TYPE_MISMATCH) status = STATUS_BAD_DEVICE_TYPE;
2577 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
2579 TRACE( "%s -> %s\n", debugstr_us(attr->ObjectName), debugstr_a(unix_name) );
2580 unix_name_ret->Buffer = unix_name;
2581 unix_name_ret->Length = strlen(unix_name);
2582 unix_name_ret->MaximumLength = unix_len;
2584 else
2586 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
2587 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2589 return status;
2593 /******************************************************************************
2594 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
2596 * Convert a file name from NT namespace to Unix namespace.
2598 * If disposition is not FILE_OPEN or FILE_OVERWRITE, the last path
2599 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
2600 * returned, but the unix name is still filled in properly.
2602 NTSTATUS CDECL wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
2603 UINT disposition, BOOLEAN check_case )
2605 static const WCHAR unixW[] = {'u','n','i','x'};
2606 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2608 NTSTATUS status = STATUS_SUCCESS;
2609 const char *config_dir = wine_get_config_dir();
2610 const WCHAR *name, *p;
2611 struct stat st;
2612 char *unix_name;
2613 int pos, ret, name_len, unix_len, prefix_len, used_default;
2614 WCHAR prefix[MAX_DIR_ENTRY_LEN];
2615 BOOLEAN is_unix = FALSE;
2617 name = nameW->Buffer;
2618 name_len = nameW->Length / sizeof(WCHAR);
2620 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2622 if (!(pos = get_dos_prefix_len( nameW )))
2623 return STATUS_BAD_DEVICE_TYPE; /* no DOS prefix, assume NT native name */
2625 name += pos;
2626 name_len -= pos;
2628 /* check for sub-directory */
2629 for (pos = 0; pos < name_len; pos++)
2631 if (IS_SEPARATOR(name[pos])) break;
2632 if (name[pos] < 32 || strchrW( invalid_charsW, name[pos] ))
2633 return STATUS_OBJECT_NAME_INVALID;
2635 if (pos > MAX_DIR_ENTRY_LEN)
2636 return STATUS_OBJECT_NAME_INVALID;
2638 if (pos == name_len) /* no subdir, plain DOS device */
2639 return get_dos_device( name, name_len, unix_name_ret );
2641 for (prefix_len = 0; prefix_len < pos; prefix_len++)
2642 prefix[prefix_len] = tolowerW(name[prefix_len]);
2644 name += prefix_len;
2645 name_len -= prefix_len;
2647 /* check for invalid characters (all chars except 0 are valid for unix) */
2648 is_unix = (prefix_len == 4 && !memcmp( prefix, unixW, sizeof(unixW) ));
2649 if (is_unix)
2651 for (p = name; p < name + name_len; p++)
2652 if (!*p) return STATUS_OBJECT_NAME_INVALID;
2653 check_case = TRUE;
2655 else
2657 for (p = name; p < name + name_len; p++)
2658 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2661 unix_len = ntdll_wcstoumbs( 0, prefix, prefix_len, NULL, 0, NULL, NULL );
2662 unix_len += ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
2663 unix_len += MAX_DIR_ENTRY_LEN + 3;
2664 unix_len += strlen(config_dir) + sizeof("/dosdevices/");
2665 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2666 return STATUS_NO_MEMORY;
2667 strcpy( unix_name, config_dir );
2668 strcat( unix_name, "/dosdevices/" );
2669 pos = strlen(unix_name);
2671 ret = ntdll_wcstoumbs( 0, prefix, prefix_len, unix_name + pos, unix_len - pos - 1,
2672 NULL, &used_default );
2673 if (!ret || used_default)
2675 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2676 return STATUS_OBJECT_NAME_INVALID;
2678 pos += ret;
2680 /* check if prefix exists (except for DOS drives to avoid extra stat calls) */
2682 if (prefix_len != 2 || prefix[1] != ':')
2684 unix_name[pos] = 0;
2685 if (lstat( unix_name, &st ) == -1 && errno == ENOENT)
2687 if (!is_unix)
2689 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2690 return STATUS_BAD_DEVICE_TYPE;
2692 pos = 0; /* fall back to unix root */
2696 status = lookup_unix_name( name, name_len, &unix_name, unix_len, pos, disposition, check_case );
2697 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
2699 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
2700 unix_name_ret->Buffer = unix_name;
2701 unix_name_ret->Length = strlen(unix_name);
2702 unix_name_ret->MaximumLength = unix_len;
2704 else
2706 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
2707 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2709 return status;
2713 /******************************************************************
2714 * RtlWow64EnableFsRedirection (NTDLL.@)
2716 NTSTATUS WINAPI RtlWow64EnableFsRedirection( BOOLEAN enable )
2718 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
2719 ntdll_get_thread_data()->wow64_redir = enable;
2720 return STATUS_SUCCESS;
2724 /******************************************************************
2725 * RtlWow64EnableFsRedirectionEx (NTDLL.@)
2727 NTSTATUS WINAPI RtlWow64EnableFsRedirectionEx( ULONG disable, ULONG *old_value )
2729 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
2730 *old_value = !ntdll_get_thread_data()->wow64_redir;
2731 ntdll_get_thread_data()->wow64_redir = !disable;
2732 return STATUS_SUCCESS;
2736 /******************************************************************
2737 * RtlDoesFileExists_U (NTDLL.@)
2739 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
2741 UNICODE_STRING nt_name;
2742 FILE_BASIC_INFORMATION basic_info;
2743 OBJECT_ATTRIBUTES attr;
2744 BOOLEAN ret;
2746 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
2748 attr.Length = sizeof(attr);
2749 attr.RootDirectory = 0;
2750 attr.ObjectName = &nt_name;
2751 attr.Attributes = OBJ_CASE_INSENSITIVE;
2752 attr.SecurityDescriptor = NULL;
2753 attr.SecurityQualityOfService = NULL;
2755 ret = NtQueryAttributesFile(&attr, &basic_info) == STATUS_SUCCESS;
2757 RtlFreeUnicodeString( &nt_name );
2758 return ret;
2762 /***********************************************************************
2763 * DIR_unmount_device
2765 * Unmount the specified device.
2767 NTSTATUS DIR_unmount_device( HANDLE handle )
2769 NTSTATUS status;
2770 int unix_fd, needs_close;
2772 if (!(status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )))
2774 struct stat st;
2775 char *mount_point = NULL;
2777 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2778 status = STATUS_INVALID_PARAMETER;
2779 else
2781 if ((mount_point = get_device_mount_point( st.st_rdev )))
2783 #ifdef __APPLE__
2784 static const char umount[] = "diskutil unmount >/dev/null 2>&1 ";
2785 #else
2786 static const char umount[] = "umount >/dev/null 2>&1 ";
2787 #endif
2788 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
2789 if (cmd)
2791 strcpy( cmd, umount );
2792 strcat( cmd, mount_point );
2793 system( cmd );
2794 RtlFreeHeap( GetProcessHeap(), 0, cmd );
2795 #ifdef linux
2796 /* umount will fail to release the loop device since we still have
2797 a handle to it, so we release it here */
2798 if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
2799 #endif
2801 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
2804 if (needs_close) close( unix_fd );
2806 return status;
2810 /******************************************************************************
2811 * DIR_get_unix_cwd
2813 * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
2814 * Returned value must be freed by caller.
2816 NTSTATUS DIR_get_unix_cwd( char **cwd )
2818 int old_cwd, unix_fd, needs_close;
2819 CURDIR *curdir;
2820 HANDLE handle;
2821 NTSTATUS status;
2823 RtlAcquirePebLock();
2825 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
2826 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
2827 else
2828 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
2830 if (!(handle = curdir->Handle))
2832 UNICODE_STRING dirW;
2833 OBJECT_ATTRIBUTES attr;
2834 IO_STATUS_BLOCK io;
2836 if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
2838 status = STATUS_OBJECT_NAME_INVALID;
2839 goto done;
2841 attr.Length = sizeof(attr);
2842 attr.RootDirectory = 0;
2843 attr.Attributes = OBJ_CASE_INSENSITIVE;
2844 attr.ObjectName = &dirW;
2845 attr.SecurityDescriptor = NULL;
2846 attr.SecurityQualityOfService = NULL;
2848 status = NtOpenFile( &handle, 0, &attr, &io, 0,
2849 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
2850 RtlFreeUnicodeString( &dirW );
2851 if (status != STATUS_SUCCESS) goto done;
2854 if ((status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )) == STATUS_SUCCESS)
2856 RtlEnterCriticalSection( &dir_section );
2858 if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
2860 unsigned int size = 512;
2862 for (;;)
2864 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2866 status = STATUS_NO_MEMORY;
2867 break;
2869 if (getcwd( *cwd, size )) break;
2870 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
2871 if (errno != ERANGE)
2873 status = STATUS_OBJECT_PATH_INVALID;
2874 break;
2876 size *= 2;
2878 if (fchdir( old_cwd ) == -1) chdir( "/" );
2880 else status = FILE_GetNtStatus();
2882 RtlLeaveCriticalSection( &dir_section );
2883 if (old_cwd != -1) close( old_cwd );
2884 if (needs_close) close( unix_fd );
2886 if (!curdir->Handle) NtClose( handle );
2888 done:
2889 RtlReleasePebLock();
2890 return status;
2893 struct read_changes_info
2895 HANDLE FileHandle;
2896 PVOID Buffer;
2897 ULONG BufferSize;
2898 PIO_APC_ROUTINE apc;
2899 void *apc_arg;
2902 /* callback for ioctl user APC */
2903 static void WINAPI read_changes_user_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
2905 struct read_changes_info *info = arg;
2906 if (info->apc) info->apc( info->apc_arg, io, reserved );
2907 RtlFreeHeap( GetProcessHeap(), 0, info );
2910 static NTSTATUS read_changes_apc( void *user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
2912 struct read_changes_info *info = user;
2913 char path[PATH_MAX];
2914 NTSTATUS ret = STATUS_SUCCESS;
2915 int len, action, i;
2917 SERVER_START_REQ( read_change )
2919 req->handle = wine_server_obj_handle( info->FileHandle );
2920 wine_server_set_reply( req, path, PATH_MAX );
2921 ret = wine_server_call( req );
2922 action = reply->action;
2923 len = wine_server_reply_size( reply );
2925 SERVER_END_REQ;
2927 if (ret == STATUS_SUCCESS && info->Buffer &&
2928 (info->BufferSize > (sizeof (FILE_NOTIFY_INFORMATION) + len*sizeof(WCHAR))))
2930 PFILE_NOTIFY_INFORMATION pfni;
2932 pfni = info->Buffer;
2934 /* convert to an NT style path */
2935 for (i=0; i<len; i++)
2936 if (path[i] == '/')
2937 path[i] = '\\';
2939 len = ntdll_umbstowcs( 0, path, len, pfni->FileName,
2940 info->BufferSize - sizeof (*pfni) );
2942 pfni->NextEntryOffset = 0;
2943 pfni->Action = action;
2944 pfni->FileNameLength = len * sizeof (WCHAR);
2945 pfni->FileName[len] = 0;
2946 len = sizeof (*pfni) - sizeof (DWORD) + pfni->FileNameLength;
2948 else
2950 ret = STATUS_NOTIFY_ENUM_DIR;
2951 len = 0;
2954 iosb->u.Status = ret;
2955 iosb->Information = len;
2956 *apc = read_changes_user_apc;
2957 return ret;
2960 #define FILE_NOTIFY_ALL ( \
2961 FILE_NOTIFY_CHANGE_FILE_NAME | \
2962 FILE_NOTIFY_CHANGE_DIR_NAME | \
2963 FILE_NOTIFY_CHANGE_ATTRIBUTES | \
2964 FILE_NOTIFY_CHANGE_SIZE | \
2965 FILE_NOTIFY_CHANGE_LAST_WRITE | \
2966 FILE_NOTIFY_CHANGE_LAST_ACCESS | \
2967 FILE_NOTIFY_CHANGE_CREATION | \
2968 FILE_NOTIFY_CHANGE_SECURITY )
2970 /******************************************************************************
2971 * NtNotifyChangeDirectoryFile [NTDLL.@]
2973 NTSTATUS WINAPI
2974 NtNotifyChangeDirectoryFile( HANDLE FileHandle, HANDLE Event,
2975 PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext,
2976 PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer,
2977 ULONG BufferSize, ULONG CompletionFilter, BOOLEAN WatchTree )
2979 struct read_changes_info *info;
2980 NTSTATUS status;
2981 ULONG_PTR cvalue = ApcRoutine ? 0 : (ULONG_PTR)ApcContext;
2983 TRACE("%p %p %p %p %p %p %u %u %d\n",
2984 FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock,
2985 Buffer, BufferSize, CompletionFilter, WatchTree );
2987 if (!IoStatusBlock)
2988 return STATUS_ACCESS_VIOLATION;
2990 if (CompletionFilter == 0 || (CompletionFilter & ~FILE_NOTIFY_ALL))
2991 return STATUS_INVALID_PARAMETER;
2993 info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof *info );
2994 if (!info)
2995 return STATUS_NO_MEMORY;
2997 info->FileHandle = FileHandle;
2998 info->Buffer = Buffer;
2999 info->BufferSize = BufferSize;
3000 info->apc = ApcRoutine;
3001 info->apc_arg = ApcContext;
3003 SERVER_START_REQ( read_directory_changes )
3005 req->filter = CompletionFilter;
3006 req->want_data = (Buffer != NULL);
3007 req->subtree = WatchTree;
3008 req->async.handle = wine_server_obj_handle( FileHandle );
3009 req->async.callback = wine_server_client_ptr( read_changes_apc );
3010 req->async.iosb = wine_server_client_ptr( IoStatusBlock );
3011 req->async.arg = wine_server_client_ptr( info );
3012 req->async.event = wine_server_obj_handle( Event );
3013 req->async.cvalue = cvalue;
3014 status = wine_server_call( req );
3016 SERVER_END_REQ;
3018 if (status != STATUS_PENDING)
3019 RtlFreeHeap( GetProcessHeap(), 0, info );
3021 return status;