includes: Fix alignment for 64-bits
[wine/wine64.git] / dlls / ntdll / directory.c
blobc2453f8934401e89c9a273669e7f9327c900ca90
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/library.h"
75 #include "wine/debug.h"
77 WINE_DEFAULT_DEBUG_CHANNEL(file);
79 /* just in case... */
80 #undef VFAT_IOCTL_READDIR_BOTH
81 #undef USE_GETDENTS
83 #ifdef linux
85 /* We want the real kernel dirent structure, not the libc one */
86 typedef struct
88 long d_ino;
89 long d_off;
90 unsigned short d_reclen;
91 char d_name[256];
92 } KERNEL_DIRENT;
94 /* Define the VFAT ioctl to get both short and long file names */
95 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
97 #ifndef O_DIRECTORY
98 # define O_DIRECTORY 0200000 /* must be directory */
99 #endif
101 #ifdef __i386__
103 typedef struct
105 ULONG64 d_ino;
106 LONG64 d_off;
107 unsigned short d_reclen;
108 unsigned char d_type;
109 char d_name[256];
110 } KERNEL_DIRENT64;
112 static inline int getdents64( int fd, char *de, unsigned int size )
114 int ret;
115 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
116 : "=a" (ret)
117 : "0" (220 /*NR_getdents64*/), "r" (fd), "c" (de), "d" (size)
118 : "memory" );
119 if (ret < 0)
121 errno = -ret;
122 ret = -1;
124 return ret;
126 #define USE_GETDENTS
128 #endif /* i386 */
130 #endif /* linux */
132 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
133 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
135 #define INVALID_NT_CHARS '*','?','<','>','|','"'
136 #define INVALID_DOS_CHARS INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
138 #define MAX_DIR_ENTRY_LEN 255 /* max length of a directory entry in chars */
140 #define MAX_IGNORED_FILES 4
142 static struct
144 dev_t dev;
145 ino_t ino;
146 } ignored_files[MAX_IGNORED_FILES];
147 static int ignored_files_count;
149 static const unsigned int max_dir_info_size = FIELD_OFFSET( FILE_BOTH_DIR_INFORMATION, FileName[MAX_DIR_ENTRY_LEN] );
151 static int show_dot_files = -1;
153 /* at some point we may want to allow Winelib apps to set this */
154 static const int is_case_sensitive = FALSE;
156 static RTL_CRITICAL_SECTION dir_section;
157 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
159 0, 0, &dir_section,
160 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
161 0, 0, { (DWORD_PTR)(__FILE__ ": dir_section") }
163 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
166 /* check if a given Unicode char is OK in a DOS short name */
167 static inline BOOL is_invalid_dos_char( WCHAR ch )
169 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
170 if (ch > 0x7f) return TRUE;
171 return strchrW( invalid_chars, ch ) != NULL;
174 /* check if the device can be a mounted volume */
175 static inline int is_valid_mounted_device( const struct stat *st )
177 #if defined(linux) || defined(__sun__)
178 return S_ISBLK( st->st_mode );
179 #else
180 /* disks are char devices on *BSD */
181 return S_ISCHR( st->st_mode );
182 #endif
185 static inline void ignore_file( const char *name )
187 struct stat st;
188 assert( ignored_files_count < MAX_IGNORED_FILES );
189 if (!stat( name, &st ))
191 ignored_files[ignored_files_count].dev = st.st_dev;
192 ignored_files[ignored_files_count].ino = st.st_ino;
193 ignored_files_count++;
197 static inline BOOL is_ignored_file( const struct stat *st )
199 unsigned int i;
201 for (i = 0; i < ignored_files_count; i++)
202 if (ignored_files[i].dev == st->st_dev && ignored_files[i].ino == st->st_ino)
203 return TRUE;
204 return FALSE;
207 /***********************************************************************
208 * get_default_com_device
210 * Return the default device to use for serial ports.
212 static char *get_default_com_device( int num )
214 char *ret = NULL;
216 if (!num || num > 9) return ret;
217 #ifdef linux
218 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
219 if (ret)
221 strcpy( ret, "/dev/ttyS0" );
222 ret[strlen(ret) - 1] = '0' + num - 1;
224 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
225 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuad0") );
226 if (ret)
228 strcpy( ret, "/dev/cuad0" );
229 ret[strlen(ret) - 1] = '0' + num - 1;
231 #else
232 FIXME( "no known default for device com%d\n", num );
233 #endif
234 return ret;
238 /***********************************************************************
239 * get_default_lpt_device
241 * Return the default device to use for parallel ports.
243 static char *get_default_lpt_device( int num )
245 char *ret = NULL;
247 if (!num || num > 9) return ret;
248 #ifdef linux
249 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
250 if (ret)
252 strcpy( ret, "/dev/lp0" );
253 ret[strlen(ret) - 1] = '0' + num - 1;
255 #else
256 FIXME( "no known default for device lpt%d\n", num );
257 #endif
258 return ret;
262 /***********************************************************************
263 * DIR_get_drives_info
265 * Retrieve device/inode number for all the drives. Helper for find_drive_root.
267 unsigned int DIR_get_drives_info( struct drive_info info[MAX_DOS_DRIVES] )
269 static struct drive_info cache[MAX_DOS_DRIVES];
270 static time_t last_update;
271 static unsigned int nb_drives;
272 unsigned int ret;
273 time_t now = time(NULL);
275 RtlEnterCriticalSection( &dir_section );
276 if (now != last_update)
278 const char *config_dir = wine_get_config_dir();
279 char *buffer, *p;
280 struct stat st;
281 unsigned int i;
283 if ((buffer = RtlAllocateHeap( GetProcessHeap(), 0,
284 strlen(config_dir) + sizeof("/dosdevices/a:") )))
286 strcpy( buffer, config_dir );
287 strcat( buffer, "/dosdevices/a:" );
288 p = buffer + strlen(buffer) - 2;
290 for (i = nb_drives = 0; i < MAX_DOS_DRIVES; i++)
292 *p = 'a' + i;
293 if (!stat( buffer, &st ))
295 cache[i].dev = st.st_dev;
296 cache[i].ino = st.st_ino;
297 nb_drives++;
299 else
301 cache[i].dev = 0;
302 cache[i].ino = 0;
305 RtlFreeHeap( GetProcessHeap(), 0, buffer );
307 last_update = now;
309 memcpy( info, cache, sizeof(cache) );
310 ret = nb_drives;
311 RtlLeaveCriticalSection( &dir_section );
312 return ret;
316 /***********************************************************************
317 * parse_mount_entries
319 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
322 #ifdef sun
323 #include <sys/vfstab.h>
324 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
326 struct vfstab entry;
327 struct stat st;
328 char *device;
330 while (! getvfsent( f, &entry ))
332 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
333 if (!strcmp( entry.vfs_fstype, "nfs" ) ||
334 !strcmp( entry.vfs_fstype, "smbfs" ) ||
335 !strcmp( entry.vfs_fstype, "ncpfs" )) continue;
337 if (stat( entry.vfs_mountp, &st ) == -1) continue;
338 if (st.st_dev != dev || st.st_ino != ino) continue;
339 if (!strcmp( entry.vfs_fstype, "fd" ))
341 if ((device = strstr( entry.vfs_mntopts, "dev=" )))
343 char *p = strchr( device + 4, ',' );
344 if (p) *p = 0;
345 return device + 4;
348 else
349 return entry.vfs_special;
351 return NULL;
353 #endif
355 #ifdef linux
356 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
358 struct mntent *entry;
359 struct stat st;
360 char *device;
362 while ((entry = getmntent( f )))
364 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
365 if (!strcmp( entry->mnt_type, "nfs" ) ||
366 !strcmp( entry->mnt_type, "smbfs" ) ||
367 !strcmp( entry->mnt_type, "ncpfs" )) continue;
369 if (stat( entry->mnt_dir, &st ) == -1) continue;
370 if (st.st_dev != dev || st.st_ino != ino) continue;
371 if (!strcmp( entry->mnt_type, "supermount" ))
373 if ((device = strstr( entry->mnt_opts, "dev=" )))
375 char *p = strchr( device + 4, ',' );
376 if (p) *p = 0;
377 return device + 4;
380 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
382 /* if device is a regular file check for a loop mount */
383 if ((device = strstr( entry->mnt_opts, "loop=" )))
385 char *p = strchr( device + 5, ',' );
386 if (p) *p = 0;
387 return device + 5;
390 else
391 return entry->mnt_fsname;
393 return NULL;
395 #endif
397 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
398 #include <fstab.h>
399 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
401 struct fstab *entry;
402 struct stat st;
404 while ((entry = getfsent()))
406 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
407 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
408 !strcmp( entry->fs_vfstype, "smbfs" ) ||
409 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
411 if (stat( entry->fs_file, &st ) == -1) continue;
412 if (st.st_dev != dev || st.st_ino != ino) continue;
413 return entry->fs_spec;
415 return NULL;
417 #endif
419 #ifdef sun
420 #include <sys/mnttab.h>
421 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
423 struct mnttab entry;
424 struct stat st;
425 char *device;
428 while (( ! getmntent( f, &entry) ))
430 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
431 if (!strcmp( entry.mnt_fstype, "nfs" ) ||
432 !strcmp( entry.mnt_fstype, "smbfs" ) ||
433 !strcmp( entry.mnt_fstype, "ncpfs" )) continue;
435 if (stat( entry.mnt_mountp, &st ) == -1) continue;
436 if (st.st_dev != dev || st.st_ino != ino) continue;
437 if (!strcmp( entry.mnt_fstype, "fd" ))
439 if ((device = strstr( entry.mnt_mntopts, "dev=" )))
441 char *p = strchr( device + 4, ',' );
442 if (p) *p = 0;
443 return device + 4;
446 else
447 return entry.mnt_special;
449 return NULL;
451 #endif
453 /***********************************************************************
454 * get_default_drive_device
456 * Return the default device to use for a given drive mount point.
458 static char *get_default_drive_device( const char *root )
460 char *ret = NULL;
462 #ifdef linux
463 FILE *f;
464 char *device = NULL;
465 int fd, res = -1;
466 struct stat st;
468 /* try to open it first to force it to get mounted */
469 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
471 res = fstat( fd, &st );
472 close( fd );
474 /* now try normal stat just in case */
475 if (res == -1) res = stat( root, &st );
476 if (res == -1) return NULL;
478 RtlEnterCriticalSection( &dir_section );
480 if ((f = fopen( "/etc/mtab", "r" )))
482 device = parse_mount_entries( f, st.st_dev, st.st_ino );
483 endmntent( f );
485 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
486 if (!device && (f = fopen( "/etc/fstab", "r" )))
488 device = parse_mount_entries( f, st.st_dev, st.st_ino );
489 endmntent( f );
491 if (device)
493 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
494 if (ret) strcpy( ret, device );
496 RtlLeaveCriticalSection( &dir_section );
498 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ )
499 char *device = NULL;
500 int fd, res = -1;
501 struct stat st;
503 /* try to open it first to force it to get mounted */
504 if ((fd = open( root, O_RDONLY )) != -1)
506 res = fstat( fd, &st );
507 close( fd );
509 /* now try normal stat just in case */
510 if (res == -1) res = stat( root, &st );
511 if (res == -1) return NULL;
513 RtlEnterCriticalSection( &dir_section );
515 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
516 * pass NULL. Leave the argument in for symmetry.
518 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
519 if (device)
521 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
522 if (ret) strcpy( ret, device );
524 RtlLeaveCriticalSection( &dir_section );
526 #elif defined( sun )
527 FILE *f;
528 char *device = NULL;
529 int fd, res = -1;
530 struct stat st;
532 /* try to open it first to force it to get mounted */
533 if ((fd = open( root, O_RDONLY )) != -1)
535 res = fstat( fd, &st );
536 close( fd );
538 /* now try normal stat just in case */
539 if (res == -1) res = stat( root, &st );
540 if (res == -1) return NULL;
542 RtlEnterCriticalSection( &dir_section );
544 if ((f = fopen( "/etc/mnttab", "r" )))
546 device = parse_mount_entries( f, st.st_dev, st.st_ino);
547 fclose( f );
549 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
550 if (!device && (f = fopen( "/etc/vfstab", "r" )))
552 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
553 fclose( f );
555 if (device)
557 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
558 if (ret) strcpy( ret, device );
560 RtlLeaveCriticalSection( &dir_section );
562 #elif defined(__APPLE__)
563 struct statfs *mntStat;
564 struct stat st;
565 int i;
566 int mntSize;
567 dev_t dev;
568 ino_t ino;
569 static const char path_bsd_device[] = "/dev/disk";
570 int res;
572 res = stat( root, &st );
573 if (res == -1) return NULL;
575 dev = st.st_dev;
576 ino = st.st_ino;
578 RtlEnterCriticalSection( &dir_section );
580 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
582 for (i = 0; i < mntSize && !ret; i++)
584 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
585 if (st.st_dev != dev || st.st_ino != ino) continue;
587 /* FIXME add support for mounted network drive */
588 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
590 /* set return value to the corresponding raw BSD node */
591 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
592 if (ret)
594 strcpy(ret, "/dev/r");
595 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
599 RtlLeaveCriticalSection( &dir_section );
600 #else
601 static int warned;
602 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
603 #endif
604 return ret;
608 /***********************************************************************
609 * get_device_mount_point
611 * Return the current mount point for a device.
613 static char *get_device_mount_point( dev_t dev )
615 char *ret = NULL;
617 #ifdef linux
618 FILE *f;
620 RtlEnterCriticalSection( &dir_section );
622 if ((f = fopen( "/etc/mtab", "r" )))
624 struct mntent *entry;
625 struct stat st;
626 char *p, *device;
628 while ((entry = getmntent( f )))
630 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
631 if (!strcmp( entry->mnt_type, "nfs" ) ||
632 !strcmp( entry->mnt_type, "smbfs" ) ||
633 !strcmp( entry->mnt_type, "ncpfs" )) continue;
635 if (!strcmp( entry->mnt_type, "supermount" ))
637 if ((device = strstr( entry->mnt_opts, "dev=" )))
639 device += 4;
640 if ((p = strchr( device, ',' ))) *p = 0;
643 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
645 /* if device is a regular file check for a loop mount */
646 if ((device = strstr( entry->mnt_opts, "loop=" )))
648 device += 5;
649 if ((p = strchr( device, ',' ))) *p = 0;
652 else device = entry->mnt_fsname;
654 if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
656 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
657 if (ret) strcpy( ret, entry->mnt_dir );
658 break;
661 endmntent( f );
663 RtlLeaveCriticalSection( &dir_section );
664 #elif defined(__APPLE__)
665 struct statfs *entry;
666 struct stat st;
667 int i, size;
669 RtlEnterCriticalSection( &dir_section );
671 size = getmntinfo( &entry, MNT_NOWAIT );
672 for (i = 0; i < size; i++)
674 if (stat( entry[i].f_mntfromname, &st ) == -1) continue;
675 if (S_ISBLK(st.st_mode) && st.st_rdev == dev)
677 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry[i].f_mntfromname) + 1 );
678 if (ret) strcpy( ret, entry[i].f_mntfromname );
679 break;
682 RtlLeaveCriticalSection( &dir_section );
683 #else
684 static int warned;
685 if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
686 #endif
687 return ret;
691 /***********************************************************************
692 * init_options
694 * Initialize the show_dot_files options.
696 static void init_options(void)
698 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
699 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
700 char tmp[80];
701 HANDLE root, hkey;
702 DWORD dummy;
703 OBJECT_ATTRIBUTES attr;
704 UNICODE_STRING nameW;
706 show_dot_files = 0;
708 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
709 attr.Length = sizeof(attr);
710 attr.RootDirectory = root;
711 attr.ObjectName = &nameW;
712 attr.Attributes = 0;
713 attr.SecurityDescriptor = NULL;
714 attr.SecurityQualityOfService = NULL;
715 RtlInitUnicodeString( &nameW, WineW );
717 /* @@ Wine registry key: HKCU\Software\Wine */
718 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
720 RtlInitUnicodeString( &nameW, ShowDotFilesW );
721 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
723 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
724 show_dot_files = IS_OPTION_TRUE( str[0] );
726 NtClose( hkey );
728 NtClose( root );
730 /* a couple of directories that we don't want to return in directory searches */
731 ignore_file( wine_get_config_dir() );
732 ignore_file( "/dev" );
733 ignore_file( "/proc" );
734 #ifdef linux
735 ignore_file( "/sys" );
736 #endif
740 /***********************************************************************
741 * DIR_is_hidden_file
743 * Check if the specified file should be hidden based on its name and the show dot files option.
745 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
747 WCHAR *p, *end;
749 if (show_dot_files == -1) init_options();
750 if (show_dot_files) return FALSE;
752 end = p = name->Buffer + name->Length/sizeof(WCHAR);
753 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
754 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
755 if (p == end || *p != '.') return FALSE;
756 /* make sure it isn't '.' or '..' */
757 if (p + 1 == end) return FALSE;
758 if (p[1] == '.' && p + 2 == end) return FALSE;
759 return TRUE;
763 /***********************************************************************
764 * hash_short_file_name
766 * Transform a Unix file name into a hashed DOS name. If the name is a valid
767 * DOS name, it is converted to upper-case; otherwise it is replaced by a
768 * hashed version that fits in 8.3 format.
769 * 'buffer' must be at least 12 characters long.
770 * Returns length of short name in bytes; short name is NOT null-terminated.
772 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
774 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
776 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
777 LPWSTR dst;
778 unsigned short hash;
779 int i;
781 /* Compute the hash code of the file name */
782 /* If you know something about hash functions, feel free to */
783 /* insert a better algorithm here... */
784 if (!is_case_sensitive)
786 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
787 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
788 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
790 else
792 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
793 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
794 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
797 /* Find last dot for start of the extension */
798 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
800 /* Copy first 4 chars, replacing invalid chars with '_' */
801 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
803 if (p == end || p == ext) break;
804 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
806 /* Pad to 5 chars with '~' */
807 while (i-- >= 0) *dst++ = '~';
809 /* Insert hash code converted to 3 ASCII chars */
810 *dst++ = hash_chars[(hash >> 10) & 0x1f];
811 *dst++ = hash_chars[(hash >> 5) & 0x1f];
812 *dst++ = hash_chars[hash & 0x1f];
814 /* Copy the first 3 chars of the extension (if any) */
815 if (ext)
817 *dst++ = '.';
818 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
819 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
821 return dst - buffer;
825 /***********************************************************************
826 * match_filename
828 * Check a long file name against a mask.
830 * Tests (done in W95 DOS shell - case insensitive):
831 * *.txt test1.test.txt *
832 * *st1* test1.txt *
833 * *.t??????.t* test1.ta.tornado.txt *
834 * *tornado* test1.ta.tornado.txt *
835 * t*t test1.ta.tornado.txt *
836 * ?est* test1.txt *
837 * ?est??? test1.txt -
838 * *test1.txt* test1.txt *
839 * h?l?o*t.dat hellothisisatest.dat *
841 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
843 int mismatch;
844 const WCHAR *name = name_str->Buffer;
845 const WCHAR *mask = mask_str->Buffer;
846 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
847 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
848 const WCHAR *lastjoker = NULL;
849 const WCHAR *next_to_retry = NULL;
851 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
853 while (name < name_end && mask < mask_end)
855 switch(*mask)
857 case '*':
858 mask++;
859 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
860 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
861 lastjoker = mask;
863 /* skip to the next match after the joker(s) */
864 if (is_case_sensitive)
865 while (name < name_end && (*name != *mask)) name++;
866 else
867 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
868 next_to_retry = name;
869 break;
870 case '?':
871 mask++;
872 name++;
873 break;
874 default:
875 if (is_case_sensitive) mismatch = (*mask != *name);
876 else mismatch = (toupperW(*mask) != toupperW(*name));
878 if (!mismatch)
880 mask++;
881 name++;
882 if (mask == mask_end)
884 if (name == name_end) return TRUE;
885 if (lastjoker) mask = lastjoker;
888 else /* mismatch ! */
890 if (lastjoker) /* we had an '*', so we can try unlimitedly */
892 mask = lastjoker;
894 /* this scan sequence was a mismatch, so restart
895 * 1 char after the first char we checked last time */
896 next_to_retry++;
897 name = next_to_retry;
899 else return FALSE; /* bad luck */
901 break;
904 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
905 mask++; /* Ignore trailing '.' or '*' in mask */
906 return (name == name_end && mask == mask_end);
910 /***********************************************************************
911 * append_entry
913 * helper for NtQueryDirectoryFile
915 static FILE_BOTH_DIR_INFORMATION *append_entry( void *info_ptr, ULONG_PTR *pos, ULONG max_length,
916 const char *long_name, const char *short_name,
917 const UNICODE_STRING *mask )
919 FILE_BOTH_DIR_INFORMATION *info;
920 int i, long_len, short_len, total_len;
921 struct stat st;
922 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
923 WCHAR short_nameW[12];
924 UNICODE_STRING str;
926 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
927 if (long_len == -1) return NULL;
929 str.Buffer = long_nameW;
930 str.Length = long_len * sizeof(WCHAR);
931 str.MaximumLength = sizeof(long_nameW);
933 if (short_name)
935 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
936 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
937 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
939 else /* generate a short name if necessary */
941 BOOLEAN spaces;
943 short_len = 0;
944 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
945 short_len = hash_short_file_name( &str, short_nameW );
948 TRACE( "long %s short %s mask %s\n",
949 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
951 if (mask && !match_filename( &str, mask ))
953 if (!short_len) return NULL; /* no short name to match */
954 str.Buffer = short_nameW;
955 str.Length = short_len * sizeof(WCHAR);
956 str.MaximumLength = sizeof(short_nameW);
957 if (!match_filename( &str, mask )) return NULL;
960 total_len = (sizeof(*info) - sizeof(info->FileName) + long_len*sizeof(WCHAR) + 3) & ~3;
961 info = (FILE_BOTH_DIR_INFORMATION *)((char *)info_ptr + *pos);
963 if (*pos + total_len > max_length) total_len = max_length - *pos;
965 info->FileAttributes = 0;
966 if (lstat( long_name, &st ) == -1) return NULL;
967 if (S_ISLNK( st.st_mode ))
969 if (stat( long_name, &st ) == -1) return NULL;
970 if (S_ISDIR( st.st_mode )) info->FileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT;
972 if (is_ignored_file( &st ))
974 TRACE( "ignoring file %s\n", long_name );
975 return NULL;
978 info->NextEntryOffset = total_len;
979 info->FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
981 RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
982 RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
983 RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
984 RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
986 if (S_ISDIR(st.st_mode))
988 info->EndOfFile.QuadPart = info->AllocationSize.QuadPart = 0;
989 info->FileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
991 else
993 info->EndOfFile.QuadPart = st.st_size;
994 info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
995 info->FileAttributes |= FILE_ATTRIBUTE_ARCHIVE;
998 if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
999 info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
1001 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
1002 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
1004 info->EaSize = 0; /* FIXME */
1005 info->ShortNameLength = short_len * sizeof(WCHAR);
1006 for (i = 0; i < short_len; i++) info->ShortName[i] = toupperW(short_nameW[i]);
1007 info->FileNameLength = long_len * sizeof(WCHAR);
1008 memcpy( info->FileName, long_nameW,
1009 min( info->FileNameLength, total_len-sizeof(*info)+sizeof(info->FileName) ));
1011 *pos += total_len;
1012 return info;
1016 #ifdef VFAT_IOCTL_READDIR_BOTH
1018 /***********************************************************************
1019 * start_vfat_ioctl
1021 * Wrapper for the VFAT ioctl to work around various kernel bugs.
1022 * dir_section must be held by caller.
1024 static KERNEL_DIRENT *start_vfat_ioctl( int fd )
1026 static KERNEL_DIRENT *de;
1027 int res;
1029 if (!de)
1031 const size_t page_size = getpagesize();
1032 SIZE_T size = 2 * sizeof(*de) + page_size;
1033 void *addr = NULL;
1035 if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_RESERVE, PAGE_READWRITE ))
1036 return NULL;
1037 /* commit only the size needed for the dir entries */
1038 /* this leaves an extra unaccessible page, which should make the kernel */
1039 /* fail with -EFAULT before it stomps all over our memory */
1040 de = addr;
1041 size = 2 * sizeof(*de);
1042 NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_COMMIT, PAGE_READWRITE );
1045 /* set d_reclen to 65535 to work around an AFS kernel bug */
1046 de[0].d_reclen = 65535;
1047 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
1048 if (res == -1)
1050 if (errno != ENOENT) return NULL; /* VFAT ioctl probably not supported */
1051 de[0].d_reclen = 0; /* eof */
1053 else if (!res && de[0].d_reclen == 65535) return NULL; /* AFS bug */
1055 return de;
1059 /***********************************************************************
1060 * read_directory_vfat
1062 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
1064 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1065 BOOLEAN single_entry, const UNICODE_STRING *mask,
1066 BOOLEAN restart_scan )
1069 size_t len;
1070 KERNEL_DIRENT *de;
1071 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
1073 io->u.Status = STATUS_SUCCESS;
1075 if (restart_scan) lseek( fd, 0, SEEK_SET );
1077 if (length < max_dir_info_size) /* we may have to return a partial entry here */
1079 off_t old_pos = lseek( fd, 0, SEEK_CUR );
1081 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1083 while (de[0].d_reclen)
1085 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1086 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1087 de[0].d_name[len] = 0;
1088 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1089 de[1].d_name[len] = 0;
1091 if (de[1].d_name[0])
1092 info = append_entry( buffer, &io->Information, length,
1093 de[1].d_name, de[0].d_name, mask );
1094 else
1095 info = append_entry( buffer, &io->Information, length,
1096 de[0].d_name, NULL, mask );
1097 if (info)
1099 last_info = info;
1100 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1102 io->u.Status = STATUS_BUFFER_OVERFLOW;
1103 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1105 break;
1107 old_pos = lseek( fd, 0, SEEK_CUR );
1108 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1111 else /* we'll only return full entries, no need to worry about overflow */
1113 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1115 while (de[0].d_reclen)
1117 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1118 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1119 de[0].d_name[len] = 0;
1120 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1121 de[1].d_name[len] = 0;
1123 if (de[1].d_name[0])
1124 info = append_entry( buffer, &io->Information, length,
1125 de[1].d_name, de[0].d_name, mask );
1126 else
1127 info = append_entry( buffer, &io->Information, length,
1128 de[0].d_name, NULL, mask );
1129 if (info)
1131 last_info = info;
1132 if (single_entry) break;
1133 /* check if we still have enough space for the largest possible entry */
1134 if (io->Information + max_dir_info_size > length) break;
1136 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1140 if (last_info) last_info->NextEntryOffset = 0;
1141 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1142 return 0;
1144 #endif /* VFAT_IOCTL_READDIR_BOTH */
1147 /***********************************************************************
1148 * read_directory_getdents
1150 * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
1152 #ifdef USE_GETDENTS
1153 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1154 BOOLEAN single_entry, const UNICODE_STRING *mask,
1155 BOOLEAN restart_scan )
1157 off_t old_pos = 0;
1158 size_t size = length;
1159 int res, fake_dot_dot = 1;
1160 char *data, local_buffer[8192];
1161 KERNEL_DIRENT64 *de;
1162 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
1164 if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1166 size = sizeof(local_buffer);
1167 data = local_buffer;
1170 if (restart_scan) lseek( fd, 0, SEEK_SET );
1171 else if (length < max_dir_info_size) /* we may have to return a partial entry here */
1173 old_pos = lseek( fd, 0, SEEK_CUR );
1174 if (old_pos == -1 && errno == ENOENT)
1176 io->u.Status = STATUS_NO_MORE_FILES;
1177 res = 0;
1178 goto done;
1182 io->u.Status = STATUS_SUCCESS;
1184 res = getdents64( fd, data, size );
1185 if (res == -1)
1187 if (errno != ENOSYS)
1189 io->u.Status = FILE_GetNtStatus();
1190 res = 0;
1192 goto done;
1195 de = (KERNEL_DIRENT64 *)data;
1197 if (restart_scan)
1199 /* check if we got . and .. from getdents */
1200 if (res > 0)
1202 if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1204 KERNEL_DIRENT64 *next_de = (KERNEL_DIRENT64 *)(data + de->d_reclen);
1205 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1208 /* make sure we have enough room for both entries */
1209 if (fake_dot_dot)
1211 static const ULONG min_info_size = (FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileName[1]) +
1212 FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileName[2]) + 3) & ~3;
1213 if (length < min_info_size || single_entry)
1215 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1216 fake_dot_dot = 0;
1220 if (fake_dot_dot)
1222 if ((info = append_entry( buffer, &io->Information, length, ".", NULL, mask )))
1223 last_info = info;
1224 if ((info = append_entry( buffer, &io->Information, length, "..", NULL, mask )))
1225 last_info = info;
1227 /* check if we still have enough space for the largest possible entry */
1228 if (last_info && io->Information + max_dir_info_size > length)
1230 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1231 res = 0;
1236 while (res > 0)
1238 res -= de->d_reclen;
1239 if (de->d_ino &&
1240 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1241 (info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask )))
1243 last_info = info;
1244 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1246 io->u.Status = STATUS_BUFFER_OVERFLOW;
1247 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1248 break;
1250 /* check if we still have enough space for the largest possible entry */
1251 if (single_entry || io->Information + max_dir_info_size > length)
1253 if (res > 0) lseek( fd, de->d_off, SEEK_SET ); /* set pos to next entry */
1254 break;
1257 old_pos = de->d_off;
1258 /* move on to the next entry */
1259 if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1260 else
1262 res = getdents64( fd, data, size );
1263 de = (KERNEL_DIRENT64 *)data;
1267 if (last_info) last_info->NextEntryOffset = 0;
1268 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1269 res = 0;
1270 done:
1271 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1272 return res;
1275 #elif defined HAVE_GETDIRENTRIES
1277 /***********************************************************************
1278 * wine_getdirentries
1280 * Wrapper for the BSD getdirentries system call to fix a bug in the
1281 * Mac OS X version. For some file systems (at least Apple Filing
1282 * Protocol a.k.a. AFP), getdirentries resets the file position to 0
1283 * when it's about to return 0 (no more entries). So, a subsequent
1284 * getdirentries call starts over at the beginning again, causing an
1285 * infinite loop.
1287 static inline int wine_getdirentries(int fd, char *buf, int nbytes, long *basep)
1289 int res = getdirentries(fd, buf, nbytes, basep);
1290 #ifdef __APPLE__
1291 if (res == 0)
1292 lseek(fd, *basep, SEEK_SET);
1293 #endif
1294 return res;
1297 /***********************************************************************
1298 * read_directory_getdirentries
1300 * Read a directory using the BSD getdirentries system call; helper for NtQueryDirectoryFile.
1302 static int read_directory_getdirentries( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1303 BOOLEAN single_entry, const UNICODE_STRING *mask,
1304 BOOLEAN restart_scan )
1306 long restart_pos;
1307 ULONG_PTR restart_info_pos = 0;
1308 size_t size, initial_size = length;
1309 int res, fake_dot_dot = 1;
1310 char *data, local_buffer[8192];
1311 struct dirent *de;
1312 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL, *restart_last_info = NULL;
1314 size = initial_size;
1315 data = local_buffer;
1316 if (size > sizeof(local_buffer) && !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1318 io->u.Status = STATUS_NO_MEMORY;
1319 return io->u.Status;
1322 if (restart_scan) lseek( fd, 0, SEEK_SET );
1324 io->u.Status = STATUS_SUCCESS;
1326 /* FIXME: should make sure size is larger than filesystem block size */
1327 res = wine_getdirentries( fd, data, size, &restart_pos );
1328 if (res == -1)
1330 io->u.Status = FILE_GetNtStatus();
1331 res = 0;
1332 goto done;
1335 de = (struct dirent *)data;
1337 if (restart_scan)
1339 /* check if we got . and .. from getdirentries */
1340 if (res > 0)
1342 if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1344 struct dirent *next_de = (struct dirent *)(data + de->d_reclen);
1345 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1348 /* make sure we have enough room for both entries */
1349 if (fake_dot_dot)
1351 static const ULONG min_info_size = (FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileName[1]) +
1352 FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileName[2]) + 3) & ~3;
1353 if (length < min_info_size || single_entry)
1355 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1356 fake_dot_dot = 0;
1360 if (fake_dot_dot)
1362 if ((info = append_entry( buffer, &io->Information, length, ".", NULL, mask )))
1363 last_info = info;
1364 if ((info = append_entry( buffer, &io->Information, length, "..", NULL, mask )))
1365 last_info = info;
1367 restart_last_info = last_info;
1368 restart_info_pos = io->Information;
1370 /* check if we still have enough space for the largest possible entry */
1371 if (last_info && io->Information + max_dir_info_size > length)
1373 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1374 res = 0;
1379 while (res > 0)
1381 res -= de->d_reclen;
1382 if (de->d_fileno &&
1383 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1384 ((info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask ))))
1386 last_info = info;
1387 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1389 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1390 if (restart_info_pos) /* if we have a complete read already, return it */
1392 io->Information = restart_info_pos;
1393 last_info = restart_last_info;
1394 break;
1396 /* otherwise restart from the start with a smaller size */
1397 size = (char *)de - data;
1398 if (!size)
1400 io->u.Status = STATUS_BUFFER_OVERFLOW;
1401 break;
1403 io->Information = 0;
1404 last_info = NULL;
1405 goto restart;
1407 /* if we have to return but the buffer contains more data, restart with a smaller size */
1408 if (res > 0 && (single_entry || io->Information + max_dir_info_size > length))
1410 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1411 size = (char *)de - data;
1412 io->Information = restart_info_pos;
1413 last_info = restart_last_info;
1414 goto restart;
1417 /* move on to the next entry */
1418 if (res > 0)
1420 de = (struct dirent *)((char *)de + de->d_reclen);
1421 continue;
1423 if (size < initial_size) break; /* already restarted once, give up now */
1424 size = min( size, length - io->Information );
1425 /* if size is too small don't bother to continue */
1426 if (size < max_dir_info_size && last_info) break;
1427 restart_last_info = last_info;
1428 restart_info_pos = io->Information;
1429 restart:
1430 res = wine_getdirentries( fd, data, size, &restart_pos );
1431 de = (struct dirent *)data;
1434 if (last_info) last_info->NextEntryOffset = 0;
1435 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1436 res = 0;
1437 done:
1438 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1439 return res;
1441 #endif /* HAVE_GETDIRENTRIES */
1444 /***********************************************************************
1445 * read_directory_readdir
1447 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1449 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1450 BOOLEAN single_entry, const UNICODE_STRING *mask,
1451 BOOLEAN restart_scan )
1453 DIR *dir;
1454 off_t i, old_pos = 0;
1455 struct dirent *de;
1456 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
1458 if (!(dir = opendir( "." )))
1460 io->u.Status = FILE_GetNtStatus();
1461 return;
1464 if (!restart_scan)
1466 old_pos = lseek( fd, 0, SEEK_CUR );
1467 /* skip the right number of entries */
1468 for (i = 0; i < old_pos - 2; i++)
1470 if (!readdir( dir ))
1472 closedir( dir );
1473 io->u.Status = STATUS_NO_MORE_FILES;
1474 return;
1478 io->u.Status = STATUS_SUCCESS;
1480 for (;;)
1482 if (old_pos == 0)
1483 info = append_entry( buffer, &io->Information, length, ".", NULL, mask );
1484 else if (old_pos == 1)
1485 info = append_entry( buffer, &io->Information, length, "..", NULL, mask );
1486 else if ((de = readdir( dir )))
1488 if (strcmp( de->d_name, "." ) && strcmp( de->d_name, ".." ))
1489 info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask );
1490 else
1491 info = NULL;
1493 else
1494 break;
1495 old_pos++;
1496 if (info)
1498 last_info = info;
1499 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1501 io->u.Status = STATUS_BUFFER_OVERFLOW;
1502 old_pos--; /* restore pos to previous entry */
1503 break;
1505 if (single_entry) break;
1506 /* check if we still have enough space for the largest possible entry */
1507 if (io->Information + max_dir_info_size > length) break;
1511 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
1512 closedir( dir );
1514 if (last_info) last_info->NextEntryOffset = 0;
1515 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1518 /***********************************************************************
1519 * read_directory_stat
1521 * Read a single file from a directory by determining whether the file
1522 * identified by mask exists using stat.
1524 static int read_directory_stat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1525 BOOLEAN single_entry, const UNICODE_STRING *mask,
1526 BOOLEAN restart_scan )
1528 int unix_len, ret, used_default;
1529 char *unix_name;
1530 struct stat st;
1532 TRACE("trying optimisation for file %s\n", debugstr_us( mask ));
1534 unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
1535 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
1537 io->u.Status = STATUS_NO_MEMORY;
1538 return 0;
1540 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
1541 NULL, &used_default );
1542 if (ret > 0 && !used_default)
1544 unix_name[ret] = 0;
1545 if (restart_scan)
1547 lseek( fd, 0, SEEK_SET );
1549 else if (lseek( fd, 0, SEEK_CUR ) != 0)
1551 io->u.Status = STATUS_NO_MORE_FILES;
1552 ret = 0;
1553 goto done;
1556 ret = stat( unix_name, &st );
1557 if (!ret)
1559 FILE_BOTH_DIR_INFORMATION *info = append_entry( buffer, &io->Information, length, unix_name, NULL, NULL );
1560 if (info)
1562 info->NextEntryOffset = 0;
1563 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1564 io->u.Status = STATUS_BUFFER_OVERFLOW;
1565 else
1566 lseek( fd, 1, SEEK_CUR );
1568 else io->u.Status = STATUS_NO_MORE_FILES;
1571 else ret = -1;
1573 done:
1574 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1576 TRACE("returning %d\n", ret);
1578 return ret;
1582 static inline WCHAR *mempbrkW( const WCHAR *ptr, const WCHAR *accept, size_t n )
1584 const WCHAR *end;
1585 for (end = ptr + n; ptr < end; ptr++) if (strchrW( accept, *ptr )) return (WCHAR *)ptr;
1586 return NULL;
1589 /******************************************************************************
1590 * NtQueryDirectoryFile [NTDLL.@]
1591 * ZwQueryDirectoryFile [NTDLL.@]
1593 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
1594 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
1595 PIO_STATUS_BLOCK io,
1596 PVOID buffer, ULONG length,
1597 FILE_INFORMATION_CLASS info_class,
1598 BOOLEAN single_entry,
1599 PUNICODE_STRING mask,
1600 BOOLEAN restart_scan )
1602 int cwd, fd, needs_close;
1603 static const WCHAR wszWildcards[] = { '*','?',0 };
1605 TRACE("(%p %p %p %p %p %p 0x%08x 0x%08x 0x%08x %s 0x%08x\n",
1606 handle, event, apc_routine, apc_context, io, buffer,
1607 length, info_class, single_entry, debugstr_us(mask),
1608 restart_scan);
1610 if (length < sizeof(FILE_BOTH_DIR_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
1612 if (event || apc_routine)
1614 FIXME( "Unsupported yet option\n" );
1615 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1617 if (info_class != FileBothDirectoryInformation)
1619 FIXME( "Unsupported file info class %d\n", info_class );
1620 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1623 if ((io->u.Status = server_get_unix_fd( handle, FILE_LIST_DIRECTORY, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
1624 return io->u.Status;
1626 io->Information = 0;
1628 RtlEnterCriticalSection( &dir_section );
1630 if (show_dot_files == -1) init_options();
1632 cwd = open( ".", O_RDONLY );
1633 if (fchdir( fd ) != -1)
1635 #ifdef VFAT_IOCTL_READDIR_BOTH
1636 if ((read_directory_vfat( fd, io, buffer, length, single_entry, mask, restart_scan )) != -1)
1637 goto done;
1638 #endif
1639 if (mask && !mempbrkW( mask->Buffer, wszWildcards, mask->Length / sizeof(WCHAR) ) &&
1640 read_directory_stat( fd, io, buffer, length, single_entry, mask, restart_scan ) != -1)
1641 goto done;
1642 #ifdef USE_GETDENTS
1643 if ((read_directory_getdents( fd, io, buffer, length, single_entry, mask, restart_scan )) != -1)
1644 goto done;
1645 #elif defined HAVE_GETDIRENTRIES
1646 if ((read_directory_getdirentries( fd, io, buffer, length, single_entry, mask, restart_scan )) != -1)
1647 goto done;
1648 #endif
1649 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan );
1651 done:
1652 if (cwd == -1 || fchdir( cwd ) == -1) chdir( "/" );
1654 else io->u.Status = FILE_GetNtStatus();
1656 RtlLeaveCriticalSection( &dir_section );
1658 if (needs_close) close( fd );
1659 if (cwd != -1) close( cwd );
1660 TRACE( "=> %x (%ld)\n", io->u.Status, io->Information );
1661 return io->u.Status;
1665 /***********************************************************************
1666 * find_file_in_dir
1668 * Find a file in a directory the hard way, by doing a case-insensitive search.
1669 * The file found is appended to unix_name at pos.
1670 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
1672 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
1673 int check_case )
1675 WCHAR buffer[MAX_DIR_ENTRY_LEN];
1676 UNICODE_STRING str;
1677 BOOLEAN spaces;
1678 DIR *dir;
1679 struct dirent *de;
1680 struct stat st;
1681 int ret, used_default, is_name_8_dot_3;
1683 /* try a shortcut for this directory */
1685 unix_name[pos++] = '/';
1686 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
1687 NULL, &used_default );
1688 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
1689 /* so it cannot match the file we are looking for */
1690 if (ret >= 0 && !used_default)
1692 unix_name[pos + ret] = 0;
1693 if (!stat( unix_name, &st )) return STATUS_SUCCESS;
1695 if (check_case) goto not_found; /* we want an exact match */
1697 if (pos > 1) unix_name[pos - 1] = 0;
1698 else unix_name[1] = 0; /* keep the initial slash */
1700 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
1702 str.Buffer = (WCHAR *)name;
1703 str.Length = length * sizeof(WCHAR);
1704 str.MaximumLength = str.Length;
1705 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
1707 /* now look for it through the directory */
1709 #ifdef VFAT_IOCTL_READDIR_BOTH
1710 if (is_name_8_dot_3)
1712 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
1713 if (fd != -1)
1715 KERNEL_DIRENT *de;
1717 RtlEnterCriticalSection( &dir_section );
1718 if ((de = start_vfat_ioctl( fd )))
1720 unix_name[pos - 1] = '/';
1721 while (de[0].d_reclen)
1723 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1724 size_t len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1725 de[0].d_name[len] = 0;
1726 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1727 de[1].d_name[len] = 0;
1729 if (de[1].d_name[0])
1731 ret = ntdll_umbstowcs( 0, de[1].d_name, strlen(de[1].d_name),
1732 buffer, MAX_DIR_ENTRY_LEN );
1733 if (ret == length && !memicmpW( buffer, name, length))
1735 strcpy( unix_name + pos, de[1].d_name );
1736 RtlLeaveCriticalSection( &dir_section );
1737 close( fd );
1738 return STATUS_SUCCESS;
1741 ret = ntdll_umbstowcs( 0, de[0].d_name, strlen(de[0].d_name),
1742 buffer, MAX_DIR_ENTRY_LEN );
1743 if (ret == length && !memicmpW( buffer, name, length))
1745 strcpy( unix_name + pos,
1746 de[1].d_name[0] ? de[1].d_name : de[0].d_name );
1747 RtlLeaveCriticalSection( &dir_section );
1748 close( fd );
1749 return STATUS_SUCCESS;
1751 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1)
1753 RtlLeaveCriticalSection( &dir_section );
1754 close( fd );
1755 goto not_found;
1759 RtlLeaveCriticalSection( &dir_section );
1760 close( fd );
1762 /* fall through to normal handling */
1764 #endif /* VFAT_IOCTL_READDIR_BOTH */
1766 if (!(dir = opendir( unix_name )))
1768 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
1769 else return FILE_GetNtStatus();
1771 unix_name[pos - 1] = '/';
1772 str.Buffer = buffer;
1773 str.MaximumLength = sizeof(buffer);
1774 while ((de = readdir( dir )))
1776 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
1777 if (ret == length && !memicmpW( buffer, name, length ))
1779 strcpy( unix_name + pos, de->d_name );
1780 closedir( dir );
1781 return STATUS_SUCCESS;
1784 if (!is_name_8_dot_3) continue;
1786 str.Length = ret * sizeof(WCHAR);
1787 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1789 WCHAR short_nameW[12];
1790 ret = hash_short_file_name( &str, short_nameW );
1791 if (ret == length && !memicmpW( short_nameW, name, length ))
1793 strcpy( unix_name + pos, de->d_name );
1794 closedir( dir );
1795 return STATUS_SUCCESS;
1799 closedir( dir );
1800 goto not_found; /* avoid warning */
1802 not_found:
1803 unix_name[pos - 1] = 0;
1804 return STATUS_OBJECT_PATH_NOT_FOUND;
1808 /******************************************************************************
1809 * get_dos_device
1811 * Get the Unix path of a DOS device.
1813 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
1815 const char *config_dir = wine_get_config_dir();
1816 struct stat st;
1817 char *unix_name, *new_name, *dev;
1818 unsigned int i;
1819 int unix_len;
1821 /* make sure the device name is ASCII */
1822 for (i = 0; i < name_len; i++)
1823 if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
1825 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
1827 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1828 return STATUS_NO_MEMORY;
1830 strcpy( unix_name, config_dir );
1831 strcat( unix_name, "/dosdevices/" );
1832 dev = unix_name + strlen(unix_name);
1834 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
1835 dev[i] = 0;
1837 /* special case for drive devices */
1838 if (name_len == 2 && dev[1] == ':')
1840 dev[i++] = ':';
1841 dev[i] = 0;
1844 for (;;)
1846 if (!stat( unix_name, &st ))
1848 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
1849 unix_name_ret->Buffer = unix_name;
1850 unix_name_ret->Length = strlen(unix_name);
1851 unix_name_ret->MaximumLength = unix_len;
1852 return STATUS_SUCCESS;
1854 if (!dev) break;
1856 /* now try some defaults for it */
1857 if (!strcmp( dev, "aux" ))
1859 strcpy( dev, "com1" );
1860 continue;
1862 if (!strcmp( dev, "prn" ))
1864 strcpy( dev, "lpt1" );
1865 continue;
1867 if (!strcmp( dev, "nul" ))
1869 strcpy( unix_name, "/dev/null" );
1870 dev = NULL; /* last try */
1871 continue;
1874 new_name = NULL;
1875 if (dev[1] == ':' && dev[2] == ':') /* drive device */
1877 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
1878 new_name = get_default_drive_device( unix_name );
1880 else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( atoi(dev + 3 ));
1881 else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( atoi(dev + 3 ));
1883 if (!new_name) break;
1885 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1886 unix_name = new_name;
1887 unix_len = strlen(unix_name) + 1;
1888 dev = NULL; /* last try */
1890 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1891 return STATUS_BAD_DEVICE_TYPE;
1895 /* return the length of the DOS namespace prefix if any */
1896 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
1898 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
1899 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
1901 if (name->Length > sizeof(nt_prefixW) &&
1902 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
1903 return sizeof(nt_prefixW) / sizeof(WCHAR);
1905 if (name->Length > sizeof(dosdev_prefixW) &&
1906 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
1907 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
1909 return 0;
1913 /******************************************************************************
1914 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
1916 * Convert a file name from NT namespace to Unix namespace.
1918 * If disposition is not FILE_OPEN or FILE_OVERWRITE, the last path
1919 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
1920 * returned, but the unix name is still filled in properly.
1922 NTSTATUS CDECL wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
1923 UINT disposition, BOOLEAN check_case )
1925 static const WCHAR unixW[] = {'u','n','i','x'};
1926 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
1928 NTSTATUS status = STATUS_SUCCESS;
1929 const char *config_dir = wine_get_config_dir();
1930 const WCHAR *name, *p;
1931 struct stat st;
1932 char *unix_name;
1933 int pos, ret, name_len, unix_len, prefix_len, used_default;
1934 WCHAR prefix[MAX_DIR_ENTRY_LEN];
1935 BOOLEAN is_unix = FALSE;
1937 name = nameW->Buffer;
1938 name_len = nameW->Length / sizeof(WCHAR);
1940 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
1942 if (!(pos = get_dos_prefix_len( nameW )))
1943 return STATUS_BAD_DEVICE_TYPE; /* no DOS prefix, assume NT native name */
1945 name += pos;
1946 name_len -= pos;
1948 /* check for sub-directory */
1949 for (pos = 0; pos < name_len; pos++)
1951 if (IS_SEPARATOR(name[pos])) break;
1952 if (name[pos] < 32 || strchrW( invalid_charsW, name[pos] ))
1953 return STATUS_OBJECT_NAME_INVALID;
1955 if (pos > MAX_DIR_ENTRY_LEN)
1956 return STATUS_OBJECT_NAME_INVALID;
1958 if (pos == name_len) /* no subdir, plain DOS device */
1959 return get_dos_device( name, name_len, unix_name_ret );
1961 for (prefix_len = 0; prefix_len < pos; prefix_len++)
1962 prefix[prefix_len] = tolowerW(name[prefix_len]);
1964 name += prefix_len;
1965 name_len -= prefix_len;
1967 /* check for invalid characters (all chars except 0 are valid for unix) */
1968 is_unix = (prefix_len == 4 && !memcmp( prefix, unixW, sizeof(unixW) ));
1969 if (is_unix)
1971 for (p = name; p < name + name_len; p++)
1972 if (!*p) return STATUS_OBJECT_NAME_INVALID;
1973 check_case = TRUE;
1975 else
1977 for (p = name; p < name + name_len; p++)
1978 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
1981 unix_len = ntdll_wcstoumbs( 0, prefix, prefix_len, NULL, 0, NULL, NULL );
1982 unix_len += ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1983 unix_len += MAX_DIR_ENTRY_LEN + 3;
1984 unix_len += strlen(config_dir) + sizeof("/dosdevices/");
1985 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1986 return STATUS_NO_MEMORY;
1987 strcpy( unix_name, config_dir );
1988 strcat( unix_name, "/dosdevices/" );
1989 pos = strlen(unix_name);
1991 ret = ntdll_wcstoumbs( 0, prefix, prefix_len, unix_name + pos, unix_len - pos - 1,
1992 NULL, &used_default );
1993 if (!ret || used_default)
1995 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1996 return STATUS_OBJECT_NAME_INVALID;
1998 pos += ret;
2000 /* check if prefix exists (except for DOS drives to avoid extra stat calls) */
2002 if (prefix_len != 2 || prefix[1] != ':')
2004 unix_name[pos] = 0;
2005 if (lstat( unix_name, &st ) == -1 && errno == ENOENT)
2007 if (!is_unix)
2009 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2010 return STATUS_BAD_DEVICE_TYPE;
2012 pos = 0; /* fall back to unix root */
2016 /* try a shortcut first */
2018 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
2019 NULL, &used_default );
2021 while (name_len && IS_SEPARATOR(*name))
2023 name++;
2024 name_len--;
2027 if (ret > 0 && !used_default) /* if we used the default char the name didn't convert properly */
2029 char *p;
2030 unix_name[pos + ret] = 0;
2031 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
2032 if (!stat( unix_name, &st ))
2034 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
2035 if (disposition == FILE_CREATE)
2037 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2038 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
2040 goto done;
2044 if (!name_len) /* empty name -> drive root doesn't exist */
2046 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2047 return STATUS_OBJECT_PATH_NOT_FOUND;
2049 if (check_case && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
2051 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2052 return STATUS_OBJECT_NAME_NOT_FOUND;
2055 /* now do it component by component */
2057 while (name_len)
2059 const WCHAR *end, *next;
2061 end = name;
2062 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
2063 next = end;
2064 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
2065 name_len -= next - name;
2067 /* grow the buffer if needed */
2069 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
2071 char *new_name;
2072 unix_len += 2 * MAX_DIR_ENTRY_LEN;
2073 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
2075 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2076 return STATUS_NO_MEMORY;
2078 unix_name = new_name;
2081 status = find_file_in_dir( unix_name, pos, name, end - name, check_case );
2083 /* if this is the last element, not finding it is not necessarily fatal */
2084 if (!name_len)
2086 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
2088 status = STATUS_OBJECT_NAME_NOT_FOUND;
2089 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
2091 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2092 MAX_DIR_ENTRY_LEN, NULL, &used_default );
2093 if (ret > 0 && !used_default)
2095 unix_name[pos] = '/';
2096 unix_name[pos + 1 + ret] = 0;
2097 status = STATUS_NO_SUCH_FILE;
2098 break;
2102 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
2104 status = STATUS_OBJECT_NAME_COLLISION;
2108 if (status != STATUS_SUCCESS)
2110 /* couldn't find it at all, fail */
2111 WARN( "%s not found in %s\n", debugstr_w(name), unix_name );
2112 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2113 return status;
2116 pos += strlen( unix_name + pos );
2117 name = next;
2120 WARN( "%s -> %s required a case-insensitive search\n",
2121 debugstr_us(nameW), debugstr_a(unix_name) );
2123 done:
2124 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
2125 unix_name_ret->Buffer = unix_name;
2126 unix_name_ret->Length = strlen(unix_name);
2127 unix_name_ret->MaximumLength = unix_len;
2128 return status;
2132 /******************************************************************
2133 * RtlDoesFileExists_U (NTDLL.@)
2135 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
2137 UNICODE_STRING nt_name;
2138 FILE_BASIC_INFORMATION basic_info;
2139 OBJECT_ATTRIBUTES attr;
2140 BOOLEAN ret;
2142 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
2144 attr.Length = sizeof(attr);
2145 attr.RootDirectory = 0;
2146 attr.ObjectName = &nt_name;
2147 attr.Attributes = OBJ_CASE_INSENSITIVE;
2148 attr.SecurityDescriptor = NULL;
2149 attr.SecurityQualityOfService = NULL;
2151 ret = NtQueryAttributesFile(&attr, &basic_info) == STATUS_SUCCESS;
2153 RtlFreeUnicodeString( &nt_name );
2154 return ret;
2158 /***********************************************************************
2159 * DIR_unmount_device
2161 * Unmount the specified device.
2163 NTSTATUS DIR_unmount_device( HANDLE handle )
2165 NTSTATUS status;
2166 int unix_fd, needs_close;
2168 if (!(status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )))
2170 struct stat st;
2171 char *mount_point = NULL;
2173 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2174 status = STATUS_INVALID_PARAMETER;
2175 else
2177 if ((mount_point = get_device_mount_point( st.st_rdev )))
2179 #ifdef __APPLE__
2180 static const char umount[] = "diskutil unmount >/dev/null 2>&1 ";
2181 #else
2182 static const char umount[] = "umount >/dev/null 2>&1 ";
2183 #endif
2184 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
2185 if (cmd)
2187 strcpy( cmd, umount );
2188 strcat( cmd, mount_point );
2189 system( cmd );
2190 RtlFreeHeap( GetProcessHeap(), 0, cmd );
2191 #ifdef linux
2192 /* umount will fail to release the loop device since we still have
2193 a handle to it, so we release it here */
2194 if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
2195 #endif
2197 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
2200 if (needs_close) close( unix_fd );
2202 return status;
2206 /******************************************************************************
2207 * DIR_get_unix_cwd
2209 * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
2210 * Returned value must be freed by caller.
2212 NTSTATUS DIR_get_unix_cwd( char **cwd )
2214 int old_cwd, unix_fd, needs_close;
2215 CURDIR *curdir;
2216 HANDLE handle;
2217 NTSTATUS status;
2219 RtlAcquirePebLock();
2221 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
2222 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
2223 else
2224 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
2226 if (!(handle = curdir->Handle))
2228 UNICODE_STRING dirW;
2229 OBJECT_ATTRIBUTES attr;
2230 IO_STATUS_BLOCK io;
2232 if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
2234 status = STATUS_OBJECT_NAME_INVALID;
2235 goto done;
2237 attr.Length = sizeof(attr);
2238 attr.RootDirectory = 0;
2239 attr.Attributes = OBJ_CASE_INSENSITIVE;
2240 attr.ObjectName = &dirW;
2241 attr.SecurityDescriptor = NULL;
2242 attr.SecurityQualityOfService = NULL;
2244 status = NtOpenFile( &handle, 0, &attr, &io, 0,
2245 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
2246 RtlFreeUnicodeString( &dirW );
2247 if (status != STATUS_SUCCESS) goto done;
2250 if ((status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )) == STATUS_SUCCESS)
2252 RtlEnterCriticalSection( &dir_section );
2254 if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
2256 unsigned int size = 512;
2258 for (;;)
2260 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2262 status = STATUS_NO_MEMORY;
2263 break;
2265 if (getcwd( *cwd, size )) break;
2266 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
2267 if (errno != ERANGE)
2269 status = STATUS_OBJECT_PATH_INVALID;
2270 break;
2272 size *= 2;
2274 if (fchdir( old_cwd ) == -1) chdir( "/" );
2276 else status = FILE_GetNtStatus();
2278 RtlLeaveCriticalSection( &dir_section );
2279 if (needs_close) close( unix_fd );
2281 if (!curdir->Handle) NtClose( handle );
2283 done:
2284 RtlReleasePebLock();
2285 return status;
2288 struct read_changes_info
2290 HANDLE FileHandle;
2291 PVOID Buffer;
2292 ULONG BufferSize;
2293 PIO_APC_ROUTINE apc;
2294 void *apc_arg;
2297 /* callback for ioctl user APC */
2298 static void WINAPI read_changes_user_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
2300 struct read_changes_info *info = arg;
2301 if (info->apc) info->apc( info->apc_arg, io, reserved );
2302 RtlFreeHeap( GetProcessHeap(), 0, info );
2305 static NTSTATUS read_changes_apc( void *user, PIO_STATUS_BLOCK iosb, NTSTATUS status, ULONG *total )
2307 struct read_changes_info *info = user;
2308 char path[PATH_MAX];
2309 NTSTATUS ret = STATUS_SUCCESS;
2310 int len, action, i;
2312 SERVER_START_REQ( read_change )
2314 req->handle = wine_server_obj_handle( info->FileHandle );
2315 wine_server_set_reply( req, path, PATH_MAX );
2316 ret = wine_server_call( req );
2317 action = reply->action;
2318 len = wine_server_reply_size( reply );
2320 SERVER_END_REQ;
2322 if (ret == STATUS_SUCCESS && info->Buffer &&
2323 (info->BufferSize > (sizeof (FILE_NOTIFY_INFORMATION) + len*sizeof(WCHAR))))
2325 PFILE_NOTIFY_INFORMATION pfni;
2327 pfni = (PFILE_NOTIFY_INFORMATION) info->Buffer;
2329 /* convert to an NT style path */
2330 for (i=0; i<len; i++)
2331 if (path[i] == '/')
2332 path[i] = '\\';
2334 len = ntdll_umbstowcs( 0, path, len, pfni->FileName,
2335 info->BufferSize - sizeof (*pfni) );
2337 pfni->NextEntryOffset = 0;
2338 pfni->Action = action;
2339 pfni->FileNameLength = len * sizeof (WCHAR);
2340 pfni->FileName[len] = 0;
2341 len = sizeof (*pfni) - sizeof (DWORD) + pfni->FileNameLength;
2343 else
2345 ret = STATUS_NOTIFY_ENUM_DIR;
2346 len = 0;
2349 iosb->u.Status = ret;
2350 iosb->Information = *total = len;
2351 return ret;
2354 #define FILE_NOTIFY_ALL ( \
2355 FILE_NOTIFY_CHANGE_FILE_NAME | \
2356 FILE_NOTIFY_CHANGE_DIR_NAME | \
2357 FILE_NOTIFY_CHANGE_ATTRIBUTES | \
2358 FILE_NOTIFY_CHANGE_SIZE | \
2359 FILE_NOTIFY_CHANGE_LAST_WRITE | \
2360 FILE_NOTIFY_CHANGE_LAST_ACCESS | \
2361 FILE_NOTIFY_CHANGE_CREATION | \
2362 FILE_NOTIFY_CHANGE_SECURITY )
2364 /******************************************************************************
2365 * NtNotifyChangeDirectoryFile [NTDLL.@]
2367 NTSTATUS WINAPI
2368 NtNotifyChangeDirectoryFile( HANDLE FileHandle, HANDLE Event,
2369 PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext,
2370 PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer,
2371 ULONG BufferSize, ULONG CompletionFilter, BOOLEAN WatchTree )
2373 struct read_changes_info *info;
2374 NTSTATUS status;
2375 ULONG_PTR cvalue = ApcRoutine ? 0 : (ULONG_PTR)ApcContext;
2377 TRACE("%p %p %p %p %p %p %u %u %d\n",
2378 FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock,
2379 Buffer, BufferSize, CompletionFilter, WatchTree );
2381 if (!IoStatusBlock)
2382 return STATUS_ACCESS_VIOLATION;
2384 if (CompletionFilter == 0 || (CompletionFilter & ~FILE_NOTIFY_ALL))
2385 return STATUS_INVALID_PARAMETER;
2387 info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof *info );
2388 if (!info)
2389 return STATUS_NO_MEMORY;
2391 info->FileHandle = FileHandle;
2392 info->Buffer = Buffer;
2393 info->BufferSize = BufferSize;
2394 info->apc = ApcRoutine;
2395 info->apc_arg = ApcContext;
2397 SERVER_START_REQ( read_directory_changes )
2399 req->filter = CompletionFilter;
2400 req->want_data = (Buffer != NULL);
2401 req->subtree = WatchTree;
2402 req->async.handle = wine_server_obj_handle( FileHandle );
2403 req->async.callback = read_changes_apc;
2404 req->async.iosb = IoStatusBlock;
2405 req->async.arg = info;
2406 req->async.apc = read_changes_user_apc;
2407 req->async.event = wine_server_obj_handle( Event );
2408 req->async.cvalue = cvalue;
2409 status = wine_server_call( req );
2411 SERVER_END_REQ;
2413 if (status != STATUS_PENDING)
2414 RtlFreeHeap( GetProcessHeap(), 0, info );
2416 return status;