crypt32: Fix incorrect casts in X509_CERT and friends.
[wine/wine64.git] / dlls / ntdll / directory.c
blob894d3365cdf605518775b6c4834768c892266dea
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 <sys/types.h>
27 #include <dirent.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <stdarg.h>
31 #include <string.h>
32 #include <stdlib.h>
33 #include <stdio.h>
34 #include <limits.h>
35 #ifdef HAVE_MNTENT_H
36 #include <mntent.h>
37 #endif
38 #ifdef HAVE_SYS_STAT_H
39 # include <sys/stat.h>
40 #endif
41 #ifdef HAVE_SYS_IOCTL_H
42 #include <sys/ioctl.h>
43 #endif
44 #ifdef HAVE_LINUX_IOCTL_H
45 #include <linux/ioctl.h>
46 #endif
47 #ifdef HAVE_LINUX_MAJOR_H
48 # include <linux/major.h>
49 #endif
50 #ifdef HAVE_SYS_PARAM_H
51 #include <sys/param.h>
52 #endif
53 #ifdef HAVE_SYS_MOUNT_H
54 #include <sys/mount.h>
55 #endif
56 #include <time.h>
57 #ifdef HAVE_UNISTD_H
58 # include <unistd.h>
59 #endif
61 #define NONAMELESSUNION
62 #define NONAMELESSSTRUCT
63 #include "ntstatus.h"
64 #define WIN32_NO_STATUS
65 #include "windef.h"
66 #include "winnt.h"
67 #include "thread.h"
68 #include "winternl.h"
69 #include "ntdll_misc.h"
70 #include "wine/unicode.h"
71 #include "wine/server.h"
72 #include "wine/library.h"
73 #include "wine/debug.h"
75 WINE_DEFAULT_DEBUG_CHANNEL(file);
77 /* just in case... */
78 #undef VFAT_IOCTL_READDIR_BOTH
79 #undef USE_GETDENTS
81 #ifdef linux
83 /* We want the real kernel dirent structure, not the libc one */
84 typedef struct
86 long d_ino;
87 long d_off;
88 unsigned short d_reclen;
89 char d_name[256];
90 } KERNEL_DIRENT;
92 /* Define the VFAT ioctl to get both short and long file names */
93 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
95 #ifndef O_DIRECTORY
96 # define O_DIRECTORY 0200000 /* must be directory */
97 #endif
99 #ifdef __i386__
101 typedef struct
103 ULONG64 d_ino;
104 LONG64 d_off;
105 unsigned short d_reclen;
106 unsigned char d_type;
107 char d_name[256];
108 } KERNEL_DIRENT64;
110 static inline int getdents64( int fd, char *de, unsigned int size )
112 int ret;
113 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
114 : "=a" (ret)
115 : "0" (220 /*NR_getdents64*/), "r" (fd), "c" (de), "d" (size)
116 : "memory" );
117 if (ret < 0)
119 errno = -ret;
120 ret = -1;
122 return ret;
124 #define USE_GETDENTS
126 #endif /* i386 */
128 #endif /* linux */
130 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
131 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
133 #define INVALID_NT_CHARS '*','?','<','>','|','"'
134 #define INVALID_DOS_CHARS INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
136 #define MAX_DIR_ENTRY_LEN 255 /* max length of a directory entry in chars */
138 static const unsigned int max_dir_info_size = FIELD_OFFSET( FILE_BOTH_DIR_INFORMATION, FileName[MAX_DIR_ENTRY_LEN] );
140 static int show_dot_files = -1;
142 /* at some point we may want to allow Winelib apps to set this */
143 static const int is_case_sensitive = FALSE;
145 static RTL_CRITICAL_SECTION dir_section;
146 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
148 0, 0, &dir_section,
149 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
150 0, 0, { (DWORD_PTR)(__FILE__ ": dir_section") }
152 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
155 /* check if a given Unicode char is OK in a DOS short name */
156 static inline BOOL is_invalid_dos_char( WCHAR ch )
158 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
159 if (ch > 0x7f) return TRUE;
160 return strchrW( invalid_chars, ch ) != NULL;
163 /* check if the device can be a mounted volume */
164 static inline int is_valid_mounted_device( const struct stat *st )
166 #if defined(linux) || defined(__sun__)
167 return S_ISBLK( st->st_mode );
168 #else
169 /* disks are char devices on *BSD */
170 return S_ISCHR( st->st_mode );
171 #endif
174 /***********************************************************************
175 * get_default_com_device
177 * Return the default device to use for serial ports.
179 static char *get_default_com_device( int num )
181 char *ret = NULL;
183 if (!num || num > 9) return ret;
184 #ifdef linux
185 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
186 if (ret)
188 strcpy( ret, "/dev/ttyS0" );
189 ret[strlen(ret) - 1] = '0' + num - 1;
191 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
192 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuad0") );
193 if (ret)
195 strcpy( ret, "/dev/cuad0" );
196 ret[strlen(ret) - 1] = '0' + num - 1;
198 #else
199 FIXME( "no known default for device com%d\n", num );
200 #endif
201 return ret;
205 /***********************************************************************
206 * get_default_lpt_device
208 * Return the default device to use for parallel ports.
210 static char *get_default_lpt_device( int num )
212 char *ret = NULL;
214 if (!num || num > 9) return ret;
215 #ifdef linux
216 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
217 if (ret)
219 strcpy( ret, "/dev/lp0" );
220 ret[strlen(ret) - 1] = '0' + num - 1;
222 #else
223 FIXME( "no known default for device lpt%d\n", num );
224 #endif
225 return ret;
229 /***********************************************************************
230 * parse_mount_entries
232 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
235 #ifdef sun
236 #include <sys/vfstab.h>
237 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
239 struct vfstab entry;
240 struct stat st;
241 char *device;
243 while (! getvfsent( f, &entry ))
245 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
246 if (!strcmp( entry.vfs_fstype, "nfs" ) ||
247 !strcmp( entry.vfs_fstype, "smbfs" ) ||
248 !strcmp( entry.vfs_fstype, "ncpfs" )) continue;
250 if (stat( entry.vfs_mountp, &st ) == -1) continue;
251 if (st.st_dev != dev || st.st_ino != ino) continue;
252 if (!strcmp( entry.vfs_fstype, "fd" ))
254 if ((device = strstr( entry.vfs_mntopts, "dev=" )))
256 char *p = strchr( device + 4, ',' );
257 if (p) *p = 0;
258 return device + 4;
261 else
262 return entry.vfs_special;
264 return NULL;
266 #endif
268 #ifdef linux
269 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
271 struct mntent *entry;
272 struct stat st;
273 char *device;
275 while ((entry = getmntent( f )))
277 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
278 if (!strcmp( entry->mnt_type, "nfs" ) ||
279 !strcmp( entry->mnt_type, "smbfs" ) ||
280 !strcmp( entry->mnt_type, "ncpfs" )) continue;
282 if (stat( entry->mnt_dir, &st ) == -1) continue;
283 if (st.st_dev != dev || st.st_ino != ino) continue;
284 if (!strcmp( entry->mnt_type, "supermount" ))
286 if ((device = strstr( entry->mnt_opts, "dev=" )))
288 char *p = strchr( device + 4, ',' );
289 if (p) *p = 0;
290 return device + 4;
293 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
295 /* if device is a regular file check for a loop mount */
296 if ((device = strstr( entry->mnt_opts, "loop=" )))
298 char *p = strchr( device + 5, ',' );
299 if (p) *p = 0;
300 return device + 5;
303 else
304 return entry->mnt_fsname;
306 return NULL;
308 #endif
310 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
311 #include <fstab.h>
312 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
314 struct fstab *entry;
315 struct stat st;
317 while ((entry = getfsent()))
319 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
320 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
321 !strcmp( entry->fs_vfstype, "smbfs" ) ||
322 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
324 if (stat( entry->fs_file, &st ) == -1) continue;
325 if (st.st_dev != dev || st.st_ino != ino) continue;
326 return entry->fs_spec;
328 return NULL;
330 #endif
332 #ifdef sun
333 #include <sys/mnttab.h>
334 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
336 struct mnttab entry;
337 struct stat st;
338 char *device;
341 while (( ! getmntent( f, &entry) ))
343 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
344 if (!strcmp( entry.mnt_fstype, "nfs" ) ||
345 !strcmp( entry.mnt_fstype, "smbfs" ) ||
346 !strcmp( entry.mnt_fstype, "ncpfs" )) continue;
348 if (stat( entry.mnt_mountp, &st ) == -1) continue;
349 if (st.st_dev != dev || st.st_ino != ino) continue;
350 if (!strcmp( entry.mnt_fstype, "fd" ))
352 if ((device = strstr( entry.mnt_mntopts, "dev=" )))
354 char *p = strchr( device + 4, ',' );
355 if (p) *p = 0;
356 return device + 4;
359 else
360 return entry.mnt_special;
362 return NULL;
364 #endif
366 /***********************************************************************
367 * get_default_drive_device
369 * Return the default device to use for a given drive mount point.
371 static char *get_default_drive_device( const char *root )
373 char *ret = NULL;
375 #ifdef linux
376 FILE *f;
377 char *device = NULL;
378 int fd, res = -1;
379 struct stat st;
381 /* try to open it first to force it to get mounted */
382 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
384 res = fstat( fd, &st );
385 close( fd );
387 /* now try normal stat just in case */
388 if (res == -1) res = stat( root, &st );
389 if (res == -1) return NULL;
391 RtlEnterCriticalSection( &dir_section );
393 if ((f = fopen( "/etc/mtab", "r" )))
395 device = parse_mount_entries( f, st.st_dev, st.st_ino );
396 endmntent( f );
398 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
399 if (!device && (f = fopen( "/etc/fstab", "r" )))
401 device = parse_mount_entries( f, st.st_dev, st.st_ino );
402 endmntent( f );
404 if (device)
406 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
407 if (ret) strcpy( ret, device );
409 RtlLeaveCriticalSection( &dir_section );
411 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ )
412 char *device = NULL;
413 int fd, res = -1;
414 struct stat st;
416 /* try to open it first to force it to get mounted */
417 if ((fd = open( root, O_RDONLY )) != -1)
419 res = fstat( fd, &st );
420 close( fd );
422 /* now try normal stat just in case */
423 if (res == -1) res = stat( root, &st );
424 if (res == -1) return NULL;
426 RtlEnterCriticalSection( &dir_section );
428 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
429 * pass NULL. Leave the argument in for symmetry.
431 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
432 if (device)
434 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
435 if (ret) strcpy( ret, device );
437 RtlLeaveCriticalSection( &dir_section );
439 #elif defined( sun )
440 FILE *f;
441 char *device = NULL;
442 int fd, res = -1;
443 struct stat st;
445 /* try to open it first to force it to get mounted */
446 if ((fd = open( root, O_RDONLY )) != -1)
448 res = fstat( fd, &st );
449 close( fd );
451 /* now try normal stat just in case */
452 if (res == -1) res = stat( root, &st );
453 if (res == -1) return NULL;
455 RtlEnterCriticalSection( &dir_section );
457 if ((f = fopen( "/etc/mnttab", "r" )))
459 device = parse_mount_entries( f, st.st_dev, st.st_ino);
460 fclose( f );
462 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
463 if (!device && (f = fopen( "/etc/vfstab", "r" )))
465 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
466 fclose( f );
468 if (device)
470 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
471 if (ret) strcpy( ret, device );
473 RtlLeaveCriticalSection( &dir_section );
475 #elif defined(__APPLE__)
476 struct statfs *mntStat;
477 struct stat st;
478 int i;
479 int mntSize;
480 dev_t dev;
481 ino_t ino;
482 static const char path_bsd_device[] = "/dev/disk";
483 int res;
485 res = stat( root, &st );
486 if (res == -1) return NULL;
488 dev = st.st_dev;
489 ino = st.st_ino;
491 RtlEnterCriticalSection( &dir_section );
493 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
495 for (i = 0; i < mntSize && !ret; i++)
497 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
498 if (st.st_dev != dev || st.st_ino != ino) continue;
500 /* FIXME add support for mounted network drive */
501 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
503 /* set return value to the corresponding raw BSD node */
504 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
505 if (ret)
507 strcpy(ret, "/dev/r");
508 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
512 RtlLeaveCriticalSection( &dir_section );
513 #else
514 static int warned;
515 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
516 #endif
517 return ret;
521 /***********************************************************************
522 * get_device_mount_point
524 * Return the current mount point for a device.
526 static char *get_device_mount_point( dev_t dev )
528 char *ret = NULL;
530 #ifdef linux
531 FILE *f;
533 RtlEnterCriticalSection( &dir_section );
535 if ((f = fopen( "/etc/mtab", "r" )))
537 struct mntent *entry;
538 struct stat st;
539 char *p, *device;
541 while ((entry = getmntent( f )))
543 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
544 if (!strcmp( entry->mnt_type, "nfs" ) ||
545 !strcmp( entry->mnt_type, "smbfs" ) ||
546 !strcmp( entry->mnt_type, "ncpfs" )) continue;
548 if (!strcmp( entry->mnt_type, "supermount" ))
550 if ((device = strstr( entry->mnt_opts, "dev=" )))
552 device += 4;
553 if ((p = strchr( device, ',' ))) *p = 0;
556 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
558 /* if device is a regular file check for a loop mount */
559 if ((device = strstr( entry->mnt_opts, "loop=" )))
561 device += 5;
562 if ((p = strchr( device, ',' ))) *p = 0;
565 else device = entry->mnt_fsname;
567 if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
569 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
570 if (ret) strcpy( ret, entry->mnt_dir );
571 break;
574 endmntent( f );
576 RtlLeaveCriticalSection( &dir_section );
577 #elif defined(__APPLE__)
578 struct statfs *entry;
579 struct stat st;
580 int i, size;
582 RtlEnterCriticalSection( &dir_section );
584 size = getmntinfo( &entry, MNT_NOWAIT );
585 for (i = 0; i < size; i++)
587 if (stat( entry[i].f_mntfromname, &st ) == -1) continue;
588 if (S_ISBLK(st.st_mode) && st.st_rdev == dev)
590 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry[i].f_mntfromname) + 1 );
591 if (ret) strcpy( ret, entry[i].f_mntfromname );
592 break;
595 RtlLeaveCriticalSection( &dir_section );
596 #else
597 static int warned;
598 if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
599 #endif
600 return ret;
604 /***********************************************************************
605 * init_options
607 * Initialize the show_dot_files options.
609 static void init_options(void)
611 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
612 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
613 char tmp[80];
614 HANDLE root, hkey;
615 DWORD dummy;
616 OBJECT_ATTRIBUTES attr;
617 UNICODE_STRING nameW;
619 show_dot_files = 0;
621 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
622 attr.Length = sizeof(attr);
623 attr.RootDirectory = root;
624 attr.ObjectName = &nameW;
625 attr.Attributes = 0;
626 attr.SecurityDescriptor = NULL;
627 attr.SecurityQualityOfService = NULL;
628 RtlInitUnicodeString( &nameW, WineW );
630 /* @@ Wine registry key: HKCU\Software\Wine */
631 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
633 RtlInitUnicodeString( &nameW, ShowDotFilesW );
634 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
636 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
637 show_dot_files = IS_OPTION_TRUE( str[0] );
639 NtClose( hkey );
641 NtClose( root );
645 /***********************************************************************
646 * DIR_is_hidden_file
648 * Check if the specified file should be hidden based on its name and the show dot files option.
650 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
652 WCHAR *p, *end;
654 if (show_dot_files == -1) init_options();
655 if (show_dot_files) return FALSE;
657 end = p = name->Buffer + name->Length/sizeof(WCHAR);
658 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
659 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
660 if (p == end || *p != '.') return FALSE;
661 /* make sure it isn't '.' or '..' */
662 if (p + 1 == end) return FALSE;
663 if (p[1] == '.' && p + 2 == end) return FALSE;
664 return TRUE;
668 /***********************************************************************
669 * hash_short_file_name
671 * Transform a Unix file name into a hashed DOS name. If the name is a valid
672 * DOS name, it is converted to upper-case; otherwise it is replaced by a
673 * hashed version that fits in 8.3 format.
674 * 'buffer' must be at least 12 characters long.
675 * Returns length of short name in bytes; short name is NOT null-terminated.
677 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
679 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
681 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
682 LPWSTR dst;
683 unsigned short hash;
684 int i;
686 /* Compute the hash code of the file name */
687 /* If you know something about hash functions, feel free to */
688 /* insert a better algorithm here... */
689 if (!is_case_sensitive)
691 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
692 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
693 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
695 else
697 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
698 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
699 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
702 /* Find last dot for start of the extension */
703 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
705 /* Copy first 4 chars, replacing invalid chars with '_' */
706 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
708 if (p == end || p == ext) break;
709 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
711 /* Pad to 5 chars with '~' */
712 while (i-- >= 0) *dst++ = '~';
714 /* Insert hash code converted to 3 ASCII chars */
715 *dst++ = hash_chars[(hash >> 10) & 0x1f];
716 *dst++ = hash_chars[(hash >> 5) & 0x1f];
717 *dst++ = hash_chars[hash & 0x1f];
719 /* Copy the first 3 chars of the extension (if any) */
720 if (ext)
722 *dst++ = '.';
723 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
724 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
726 return dst - buffer;
730 /***********************************************************************
731 * match_filename
733 * Check a long file name against a mask.
735 * Tests (done in W95 DOS shell - case insensitive):
736 * *.txt test1.test.txt *
737 * *st1* test1.txt *
738 * *.t??????.t* test1.ta.tornado.txt *
739 * *tornado* test1.ta.tornado.txt *
740 * t*t test1.ta.tornado.txt *
741 * ?est* test1.txt *
742 * ?est??? test1.txt -
743 * *test1.txt* test1.txt *
744 * h?l?o*t.dat hellothisisatest.dat *
746 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
748 int mismatch;
749 const WCHAR *name = name_str->Buffer;
750 const WCHAR *mask = mask_str->Buffer;
751 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
752 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
753 const WCHAR *lastjoker = NULL;
754 const WCHAR *next_to_retry = NULL;
756 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
758 while (name < name_end && mask < mask_end)
760 switch(*mask)
762 case '*':
763 mask++;
764 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
765 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
766 lastjoker = mask;
768 /* skip to the next match after the joker(s) */
769 if (is_case_sensitive)
770 while (name < name_end && (*name != *mask)) name++;
771 else
772 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
773 next_to_retry = name;
774 break;
775 case '?':
776 mask++;
777 name++;
778 break;
779 default:
780 if (is_case_sensitive) mismatch = (*mask != *name);
781 else mismatch = (toupperW(*mask) != toupperW(*name));
783 if (!mismatch)
785 mask++;
786 name++;
787 if (mask == mask_end)
789 if (name == name_end) return TRUE;
790 if (lastjoker) mask = lastjoker;
793 else /* mismatch ! */
795 if (lastjoker) /* we had an '*', so we can try unlimitedly */
797 mask = lastjoker;
799 /* this scan sequence was a mismatch, so restart
800 * 1 char after the first char we checked last time */
801 next_to_retry++;
802 name = next_to_retry;
804 else return FALSE; /* bad luck */
806 break;
809 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
810 mask++; /* Ignore trailing '.' or '*' in mask */
811 return (name == name_end && mask == mask_end);
815 /***********************************************************************
816 * append_entry
818 * helper for NtQueryDirectoryFile
820 static FILE_BOTH_DIR_INFORMATION *append_entry( void *info_ptr, ULONG_PTR *pos, ULONG max_length,
821 const char *long_name, const char *short_name,
822 const UNICODE_STRING *mask )
824 FILE_BOTH_DIR_INFORMATION *info;
825 int i, long_len, short_len, total_len;
826 struct stat st;
827 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
828 WCHAR short_nameW[12];
829 UNICODE_STRING str;
831 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
832 if (long_len == -1) return NULL;
834 str.Buffer = long_nameW;
835 str.Length = long_len * sizeof(WCHAR);
836 str.MaximumLength = sizeof(long_nameW);
838 if (short_name)
840 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
841 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
842 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
844 else /* generate a short name if necessary */
846 BOOLEAN spaces;
848 short_len = 0;
849 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
850 short_len = hash_short_file_name( &str, short_nameW );
853 TRACE( "long %s short %s mask %s\n",
854 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
856 if (mask && !match_filename( &str, mask ))
858 if (!short_len) return NULL; /* no short name to match */
859 str.Buffer = short_nameW;
860 str.Length = short_len * sizeof(WCHAR);
861 str.MaximumLength = sizeof(short_nameW);
862 if (!match_filename( &str, mask )) return NULL;
865 total_len = (sizeof(*info) - sizeof(info->FileName) + long_len*sizeof(WCHAR) + 3) & ~3;
866 info = (FILE_BOTH_DIR_INFORMATION *)((char *)info_ptr + *pos);
868 if (*pos + total_len > max_length) total_len = max_length - *pos;
870 info->FileAttributes = 0;
871 if (lstat( long_name, &st ) == -1) return NULL;
872 if (S_ISLNK( st.st_mode ))
874 if (stat( long_name, &st ) == -1) return NULL;
875 if (S_ISDIR( st.st_mode )) info->FileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT;
878 info->NextEntryOffset = total_len;
879 info->FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
881 RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
882 RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
883 RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
884 RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
886 if (S_ISDIR(st.st_mode))
888 info->EndOfFile.QuadPart = info->AllocationSize.QuadPart = 0;
889 info->FileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
891 else
893 info->EndOfFile.QuadPart = st.st_size;
894 info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
895 info->FileAttributes |= FILE_ATTRIBUTE_ARCHIVE;
898 if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
899 info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
901 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
902 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
904 info->EaSize = 0; /* FIXME */
905 info->ShortNameLength = short_len * sizeof(WCHAR);
906 for (i = 0; i < short_len; i++) info->ShortName[i] = toupperW(short_nameW[i]);
907 info->FileNameLength = long_len * sizeof(WCHAR);
908 memcpy( info->FileName, long_nameW,
909 min( info->FileNameLength, total_len-sizeof(*info)+sizeof(info->FileName) ));
911 *pos += total_len;
912 return info;
916 #ifdef VFAT_IOCTL_READDIR_BOTH
918 /***********************************************************************
919 * start_vfat_ioctl
921 * Wrapper for the VFAT ioctl to work around various kernel bugs.
922 * dir_section must be held by caller.
924 static KERNEL_DIRENT *start_vfat_ioctl( int fd )
926 static KERNEL_DIRENT *de;
927 int res;
929 if (!de)
931 const size_t page_size = getpagesize();
932 SIZE_T size = 2 * sizeof(*de) + page_size;
933 void *addr = NULL;
935 if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_RESERVE, PAGE_READWRITE ))
936 return NULL;
937 /* commit only the size needed for the dir entries */
938 /* this leaves an extra unaccessible page, which should make the kernel */
939 /* fail with -EFAULT before it stomps all over our memory */
940 de = addr;
941 size = 2 * sizeof(*de);
942 NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_COMMIT, PAGE_READWRITE );
945 /* set d_reclen to 65535 to work around an AFS kernel bug */
946 de[0].d_reclen = 65535;
947 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
948 if (res == -1)
950 if (errno != ENOENT) return NULL; /* VFAT ioctl probably not supported */
951 de[0].d_reclen = 0; /* eof */
953 else if (!res && de[0].d_reclen == 65535) return NULL; /* AFS bug */
955 return de;
959 /***********************************************************************
960 * read_directory_vfat
962 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
964 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
965 BOOLEAN single_entry, const UNICODE_STRING *mask,
966 BOOLEAN restart_scan )
969 size_t len;
970 KERNEL_DIRENT *de;
971 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
973 io->u.Status = STATUS_SUCCESS;
975 if (restart_scan) lseek( fd, 0, SEEK_SET );
977 if (length < max_dir_info_size) /* we may have to return a partial entry here */
979 off_t old_pos = lseek( fd, 0, SEEK_CUR );
981 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
983 while (de[0].d_reclen)
985 /* make sure names are null-terminated to work around an x86-64 kernel bug */
986 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
987 de[0].d_name[len] = 0;
988 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
989 de[1].d_name[len] = 0;
991 if (de[1].d_name[0])
992 info = append_entry( buffer, &io->Information, length,
993 de[1].d_name, de[0].d_name, mask );
994 else
995 info = append_entry( buffer, &io->Information, length,
996 de[0].d_name, NULL, mask );
997 if (info)
999 last_info = info;
1000 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1002 io->u.Status = STATUS_BUFFER_OVERFLOW;
1003 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1005 break;
1007 old_pos = lseek( fd, 0, SEEK_CUR );
1008 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1011 else /* we'll only return full entries, no need to worry about overflow */
1013 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1015 while (de[0].d_reclen)
1017 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1018 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1019 de[0].d_name[len] = 0;
1020 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1021 de[1].d_name[len] = 0;
1023 if (de[1].d_name[0])
1024 info = append_entry( buffer, &io->Information, length,
1025 de[1].d_name, de[0].d_name, mask );
1026 else
1027 info = append_entry( buffer, &io->Information, length,
1028 de[0].d_name, NULL, mask );
1029 if (info)
1031 last_info = info;
1032 if (single_entry) break;
1033 /* check if we still have enough space for the largest possible entry */
1034 if (io->Information + max_dir_info_size > length) break;
1036 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1040 if (last_info) last_info->NextEntryOffset = 0;
1041 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1042 return 0;
1044 #endif /* VFAT_IOCTL_READDIR_BOTH */
1047 /***********************************************************************
1048 * read_directory_getdents
1050 * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
1052 #ifdef USE_GETDENTS
1053 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1054 BOOLEAN single_entry, const UNICODE_STRING *mask,
1055 BOOLEAN restart_scan )
1057 off_t old_pos = 0;
1058 size_t size = length;
1059 int res, fake_dot_dot = 1;
1060 char *data, local_buffer[8192];
1061 KERNEL_DIRENT64 *de;
1062 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
1064 if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1066 size = sizeof(local_buffer);
1067 data = local_buffer;
1070 if (restart_scan) lseek( fd, 0, SEEK_SET );
1071 else if (length < max_dir_info_size) /* we may have to return a partial entry here */
1073 old_pos = lseek( fd, 0, SEEK_CUR );
1074 if (old_pos == -1 && errno == ENOENT)
1076 io->u.Status = STATUS_NO_MORE_FILES;
1077 res = 0;
1078 goto done;
1082 io->u.Status = STATUS_SUCCESS;
1084 res = getdents64( fd, data, size );
1085 if (res == -1)
1087 if (errno != ENOSYS)
1089 io->u.Status = FILE_GetNtStatus();
1090 res = 0;
1092 goto done;
1095 de = (KERNEL_DIRENT64 *)data;
1097 if (restart_scan)
1099 /* check if we got . and .. from getdents */
1100 if (res > 0)
1102 if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1104 KERNEL_DIRENT64 *next_de = (KERNEL_DIRENT64 *)(data + de->d_reclen);
1105 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1108 /* make sure we have enough room for both entries */
1109 if (fake_dot_dot)
1111 static const ULONG min_info_size = (FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileName[1]) +
1112 FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileName[2]) + 3) & ~3;
1113 if (length < min_info_size || single_entry)
1115 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1116 fake_dot_dot = 0;
1120 if (fake_dot_dot)
1122 if ((info = append_entry( buffer, &io->Information, length, ".", NULL, mask )))
1123 last_info = info;
1124 if ((info = append_entry( buffer, &io->Information, length, "..", NULL, mask )))
1125 last_info = info;
1127 /* check if we still have enough space for the largest possible entry */
1128 if (last_info && io->Information + max_dir_info_size > length)
1130 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1131 res = 0;
1136 while (res > 0)
1138 res -= de->d_reclen;
1139 if (!(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1140 (info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask )))
1142 last_info = info;
1143 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1145 io->u.Status = STATUS_BUFFER_OVERFLOW;
1146 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1147 break;
1149 /* check if we still have enough space for the largest possible entry */
1150 if (single_entry || io->Information + max_dir_info_size > length)
1152 if (res > 0) lseek( fd, de->d_off, SEEK_SET ); /* set pos to next entry */
1153 break;
1156 old_pos = de->d_off;
1157 /* move on to the next entry */
1158 if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1159 else
1161 res = getdents64( fd, data, size );
1162 de = (KERNEL_DIRENT64 *)data;
1166 if (last_info) last_info->NextEntryOffset = 0;
1167 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1168 res = 0;
1169 done:
1170 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1171 return res;
1174 #elif defined HAVE_GETDIRENTRIES
1176 /***********************************************************************
1177 * wine_getdirentries
1179 * Wrapper for the BSD getdirentries system call to fix a bug in the
1180 * Mac OS X version. For some file systems (at least Apple Filing
1181 * Protocol a.k.a. AFP), getdirentries resets the file position to 0
1182 * when it's about to return 0 (no more entries). So, a subsequent
1183 * getdirentries call starts over at the beginning again, causing an
1184 * infinite loop.
1186 static inline int wine_getdirentries(int fd, char *buf, int nbytes, long *basep)
1188 int res = getdirentries(fd, buf, nbytes, basep);
1189 #ifdef __APPLE__
1190 if (res == 0)
1191 lseek(fd, *basep, SEEK_SET);
1192 #endif
1193 return res;
1196 /***********************************************************************
1197 * read_directory_getdirentries
1199 * Read a directory using the BSD getdirentries system call; helper for NtQueryDirectoryFile.
1201 static int read_directory_getdirentries( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1202 BOOLEAN single_entry, const UNICODE_STRING *mask,
1203 BOOLEAN restart_scan )
1205 long restart_pos;
1206 ULONG_PTR restart_info_pos = 0;
1207 size_t size, initial_size = length;
1208 int res, fake_dot_dot = 1;
1209 char *data, local_buffer[8192];
1210 struct dirent *de;
1211 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL, *restart_last_info = NULL;
1213 size = initial_size;
1214 data = local_buffer;
1215 if (size > sizeof(local_buffer) && !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1217 io->u.Status = STATUS_NO_MEMORY;
1218 return io->u.Status;
1221 if (restart_scan) lseek( fd, 0, SEEK_SET );
1223 io->u.Status = STATUS_SUCCESS;
1225 /* FIXME: should make sure size is larger than filesystem block size */
1226 res = wine_getdirentries( fd, data, size, &restart_pos );
1227 if (res == -1)
1229 io->u.Status = FILE_GetNtStatus();
1230 res = 0;
1231 goto done;
1234 de = (struct dirent *)data;
1236 if (restart_scan)
1238 /* check if we got . and .. from getdirentries */
1239 if (res > 0)
1241 if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1243 struct dirent *next_de = (struct dirent *)(data + de->d_reclen);
1244 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1247 /* make sure we have enough room for both entries */
1248 if (fake_dot_dot)
1250 static const ULONG min_info_size = (FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileName[1]) +
1251 FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileName[2]) + 3) & ~3;
1252 if (length < min_info_size || single_entry)
1254 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1255 fake_dot_dot = 0;
1259 if (fake_dot_dot)
1261 if ((info = append_entry( buffer, &io->Information, length, ".", NULL, mask )))
1262 last_info = info;
1263 if ((info = append_entry( buffer, &io->Information, length, "..", NULL, mask )))
1264 last_info = info;
1266 restart_last_info = last_info;
1267 restart_info_pos = io->Information;
1269 /* check if we still have enough space for the largest possible entry */
1270 if (last_info && io->Information + max_dir_info_size > length)
1272 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1273 res = 0;
1278 while (res > 0)
1280 res -= de->d_reclen;
1281 if (de->d_fileno &&
1282 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1283 ((info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask ))))
1285 last_info = info;
1286 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1288 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1289 if (restart_info_pos) /* if we have a complete read already, return it */
1291 io->Information = restart_info_pos;
1292 last_info = restart_last_info;
1293 break;
1295 /* otherwise restart from the start with a smaller size */
1296 size = (char *)de - data;
1297 if (!size)
1299 io->u.Status = STATUS_BUFFER_OVERFLOW;
1300 break;
1302 io->Information = 0;
1303 last_info = NULL;
1304 goto restart;
1306 /* if we have to return but the buffer contains more data, restart with a smaller size */
1307 if (res > 0 && (single_entry || io->Information + max_dir_info_size > length))
1309 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1310 size = (char *)de - data;
1311 io->Information = restart_info_pos;
1312 last_info = restart_last_info;
1313 goto restart;
1316 /* move on to the next entry */
1317 if (res > 0)
1319 de = (struct dirent *)((char *)de + de->d_reclen);
1320 continue;
1322 if (size < initial_size) break; /* already restarted once, give up now */
1323 size = min( size, length - io->Information );
1324 /* if size is too small don't bother to continue */
1325 if (size < max_dir_info_size && last_info) break;
1326 restart_last_info = last_info;
1327 restart_info_pos = io->Information;
1328 restart:
1329 res = wine_getdirentries( fd, data, size, &restart_pos );
1330 de = (struct dirent *)data;
1333 if (last_info) last_info->NextEntryOffset = 0;
1334 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1335 res = 0;
1336 done:
1337 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1338 return res;
1340 #endif /* HAVE_GETDIRENTRIES */
1343 /***********************************************************************
1344 * read_directory_readdir
1346 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1348 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1349 BOOLEAN single_entry, const UNICODE_STRING *mask,
1350 BOOLEAN restart_scan )
1352 DIR *dir;
1353 off_t i, old_pos = 0;
1354 struct dirent *de;
1355 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
1357 if (!(dir = opendir( "." )))
1359 io->u.Status = FILE_GetNtStatus();
1360 return;
1363 if (!restart_scan)
1365 old_pos = lseek( fd, 0, SEEK_CUR );
1366 /* skip the right number of entries */
1367 for (i = 0; i < old_pos - 2; i++)
1369 if (!readdir( dir ))
1371 closedir( dir );
1372 io->u.Status = STATUS_NO_MORE_FILES;
1373 return;
1377 io->u.Status = STATUS_SUCCESS;
1379 for (;;)
1381 if (old_pos == 0)
1382 info = append_entry( buffer, &io->Information, length, ".", NULL, mask );
1383 else if (old_pos == 1)
1384 info = append_entry( buffer, &io->Information, length, "..", NULL, mask );
1385 else if ((de = readdir( dir )))
1387 if (strcmp( de->d_name, "." ) && strcmp( de->d_name, ".." ))
1388 info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask );
1389 else
1390 info = NULL;
1392 else
1393 break;
1394 old_pos++;
1395 if (info)
1397 last_info = info;
1398 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1400 io->u.Status = STATUS_BUFFER_OVERFLOW;
1401 old_pos--; /* restore pos to previous entry */
1402 break;
1404 if (single_entry) break;
1405 /* check if we still have enough space for the largest possible entry */
1406 if (io->Information + max_dir_info_size > length) break;
1410 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
1411 closedir( dir );
1413 if (last_info) last_info->NextEntryOffset = 0;
1414 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1417 /***********************************************************************
1418 * read_directory_stat
1420 * Read a single file from a directory by determining whether the file
1421 * identified by mask exists using stat.
1423 static int read_directory_stat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1424 BOOLEAN single_entry, const UNICODE_STRING *mask,
1425 BOOLEAN restart_scan )
1427 int unix_len, ret, used_default;
1428 char *unix_name;
1429 struct stat st;
1431 TRACE("trying optimisation for file %s\n", debugstr_us( mask ));
1433 unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
1434 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
1436 io->u.Status = STATUS_NO_MEMORY;
1437 return 0;
1439 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
1440 NULL, &used_default );
1441 if (ret > 0 && !used_default)
1443 unix_name[ret] = 0;
1444 if (restart_scan)
1446 lseek( fd, 0, SEEK_SET );
1448 else if (lseek( fd, 0, SEEK_CUR ) != 0)
1450 io->u.Status = STATUS_NO_MORE_FILES;
1451 ret = 0;
1452 goto done;
1455 ret = stat( unix_name, &st );
1456 if (!ret)
1458 FILE_BOTH_DIR_INFORMATION *info = append_entry( buffer, &io->Information, length, unix_name, NULL, mask );
1459 if (info)
1461 info->NextEntryOffset = 0;
1462 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1463 io->u.Status = STATUS_BUFFER_OVERFLOW;
1464 else
1465 lseek( fd, 1, SEEK_CUR );
1469 else ret = -1;
1471 done:
1472 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1474 TRACE("returning %d\n", ret);
1476 return ret;
1480 static inline WCHAR *mempbrkW( const WCHAR *ptr, const WCHAR *accept, size_t n )
1482 const WCHAR *end;
1483 for (end = ptr + n; ptr < end; ptr++) if (strchrW( accept, *ptr )) return (WCHAR *)ptr;
1484 return NULL;
1487 /******************************************************************************
1488 * NtQueryDirectoryFile [NTDLL.@]
1489 * ZwQueryDirectoryFile [NTDLL.@]
1491 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
1492 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
1493 PIO_STATUS_BLOCK io,
1494 PVOID buffer, ULONG length,
1495 FILE_INFORMATION_CLASS info_class,
1496 BOOLEAN single_entry,
1497 PUNICODE_STRING mask,
1498 BOOLEAN restart_scan )
1500 int cwd, fd, needs_close;
1501 static const WCHAR wszWildcards[] = { '*','?',0 };
1503 TRACE("(%p %p %p %p %p %p 0x%08x 0x%08x 0x%08x %s 0x%08x\n",
1504 handle, event, apc_routine, apc_context, io, buffer,
1505 length, info_class, single_entry, debugstr_us(mask),
1506 restart_scan);
1508 if (length < sizeof(FILE_BOTH_DIR_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
1510 if (event || apc_routine)
1512 FIXME( "Unsupported yet option\n" );
1513 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1515 if (info_class != FileBothDirectoryInformation)
1517 FIXME( "Unsupported file info class %d\n", info_class );
1518 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1521 if ((io->u.Status = server_get_unix_fd( handle, FILE_LIST_DIRECTORY, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
1522 return io->u.Status;
1524 io->Information = 0;
1526 RtlEnterCriticalSection( &dir_section );
1528 if (show_dot_files == -1) init_options();
1530 cwd = open( ".", O_RDONLY );
1531 if (fchdir( fd ) != -1)
1533 #ifdef VFAT_IOCTL_READDIR_BOTH
1534 if ((read_directory_vfat( fd, io, buffer, length, single_entry, mask, restart_scan )) != -1)
1535 goto done;
1536 #endif
1537 if (mask && !mempbrkW( mask->Buffer, wszWildcards, mask->Length / sizeof(WCHAR) ) &&
1538 read_directory_stat( fd, io, buffer, length, single_entry, mask, restart_scan ) != -1)
1539 goto done;
1540 #ifdef USE_GETDENTS
1541 if ((read_directory_getdents( fd, io, buffer, length, single_entry, mask, restart_scan )) != -1)
1542 goto done;
1543 #elif defined HAVE_GETDIRENTRIES
1544 if ((read_directory_getdirentries( fd, io, buffer, length, single_entry, mask, restart_scan )) != -1)
1545 goto done;
1546 #endif
1547 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan );
1549 done:
1550 if (cwd == -1 || fchdir( cwd ) == -1) chdir( "/" );
1552 else io->u.Status = FILE_GetNtStatus();
1554 RtlLeaveCriticalSection( &dir_section );
1556 if (needs_close) close( fd );
1557 if (cwd != -1) close( cwd );
1558 TRACE( "=> %x (%ld)\n", io->u.Status, io->Information );
1559 return io->u.Status;
1563 /***********************************************************************
1564 * find_file_in_dir
1566 * Find a file in a directory the hard way, by doing a case-insensitive search.
1567 * The file found is appended to unix_name at pos.
1568 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
1570 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
1571 int check_case )
1573 WCHAR buffer[MAX_DIR_ENTRY_LEN];
1574 UNICODE_STRING str;
1575 BOOLEAN spaces;
1576 DIR *dir;
1577 struct dirent *de;
1578 struct stat st;
1579 int ret, used_default, is_name_8_dot_3;
1581 /* try a shortcut for this directory */
1583 unix_name[pos++] = '/';
1584 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
1585 NULL, &used_default );
1586 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
1587 /* so it cannot match the file we are looking for */
1588 if (ret >= 0 && !used_default)
1590 unix_name[pos + ret] = 0;
1591 if (!stat( unix_name, &st )) return STATUS_SUCCESS;
1593 if (check_case) goto not_found; /* we want an exact match */
1595 if (pos > 1) unix_name[pos - 1] = 0;
1596 else unix_name[1] = 0; /* keep the initial slash */
1598 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
1600 str.Buffer = (WCHAR *)name;
1601 str.Length = length * sizeof(WCHAR);
1602 str.MaximumLength = str.Length;
1603 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
1605 /* now look for it through the directory */
1607 #ifdef VFAT_IOCTL_READDIR_BOTH
1608 if (is_name_8_dot_3)
1610 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
1611 if (fd != -1)
1613 KERNEL_DIRENT *de;
1615 RtlEnterCriticalSection( &dir_section );
1616 if ((de = start_vfat_ioctl( fd )))
1618 unix_name[pos - 1] = '/';
1619 while (de[0].d_reclen)
1621 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1622 size_t len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1623 de[0].d_name[len] = 0;
1624 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1625 de[1].d_name[len] = 0;
1627 if (de[1].d_name[0])
1629 ret = ntdll_umbstowcs( 0, de[1].d_name, strlen(de[1].d_name),
1630 buffer, MAX_DIR_ENTRY_LEN );
1631 if (ret == length && !memicmpW( buffer, name, length))
1633 strcpy( unix_name + pos, de[1].d_name );
1634 RtlLeaveCriticalSection( &dir_section );
1635 close( fd );
1636 return STATUS_SUCCESS;
1639 ret = ntdll_umbstowcs( 0, de[0].d_name, strlen(de[0].d_name),
1640 buffer, MAX_DIR_ENTRY_LEN );
1641 if (ret == length && !memicmpW( buffer, name, length))
1643 strcpy( unix_name + pos,
1644 de[1].d_name[0] ? de[1].d_name : de[0].d_name );
1645 RtlLeaveCriticalSection( &dir_section );
1646 close( fd );
1647 return STATUS_SUCCESS;
1649 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1)
1651 RtlLeaveCriticalSection( &dir_section );
1652 close( fd );
1653 goto not_found;
1657 RtlLeaveCriticalSection( &dir_section );
1658 close( fd );
1660 /* fall through to normal handling */
1662 #endif /* VFAT_IOCTL_READDIR_BOTH */
1664 if (!(dir = opendir( unix_name )))
1666 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
1667 else return FILE_GetNtStatus();
1669 unix_name[pos - 1] = '/';
1670 str.Buffer = buffer;
1671 str.MaximumLength = sizeof(buffer);
1672 while ((de = readdir( dir )))
1674 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
1675 if (ret == length && !memicmpW( buffer, name, length ))
1677 strcpy( unix_name + pos, de->d_name );
1678 closedir( dir );
1679 return STATUS_SUCCESS;
1682 if (!is_name_8_dot_3) continue;
1684 str.Length = ret * sizeof(WCHAR);
1685 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1687 WCHAR short_nameW[12];
1688 ret = hash_short_file_name( &str, short_nameW );
1689 if (ret == length && !memicmpW( short_nameW, name, length ))
1691 strcpy( unix_name + pos, de->d_name );
1692 closedir( dir );
1693 return STATUS_SUCCESS;
1697 closedir( dir );
1698 goto not_found; /* avoid warning */
1700 not_found:
1701 unix_name[pos - 1] = 0;
1702 return STATUS_OBJECT_PATH_NOT_FOUND;
1706 /******************************************************************************
1707 * get_dos_device
1709 * Get the Unix path of a DOS device.
1711 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
1713 const char *config_dir = wine_get_config_dir();
1714 struct stat st;
1715 char *unix_name, *new_name, *dev;
1716 unsigned int i;
1717 int unix_len;
1719 /* make sure the device name is ASCII */
1720 for (i = 0; i < name_len; i++)
1721 if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
1723 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
1725 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1726 return STATUS_NO_MEMORY;
1728 strcpy( unix_name, config_dir );
1729 strcat( unix_name, "/dosdevices/" );
1730 dev = unix_name + strlen(unix_name);
1732 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
1733 dev[i] = 0;
1735 /* special case for drive devices */
1736 if (name_len == 2 && dev[1] == ':')
1738 dev[i++] = ':';
1739 dev[i] = 0;
1742 for (;;)
1744 if (!stat( unix_name, &st ))
1746 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
1747 unix_name_ret->Buffer = unix_name;
1748 unix_name_ret->Length = strlen(unix_name);
1749 unix_name_ret->MaximumLength = unix_len;
1750 return STATUS_SUCCESS;
1752 if (!dev) break;
1754 /* now try some defaults for it */
1755 if (!strcmp( dev, "aux" ))
1757 strcpy( dev, "com1" );
1758 continue;
1760 if (!strcmp( dev, "prn" ))
1762 strcpy( dev, "lpt1" );
1763 continue;
1765 if (!strcmp( dev, "nul" ))
1767 strcpy( unix_name, "/dev/null" );
1768 dev = NULL; /* last try */
1769 continue;
1772 new_name = NULL;
1773 if (dev[1] == ':' && dev[2] == ':') /* drive device */
1775 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
1776 new_name = get_default_drive_device( unix_name );
1778 else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( dev[3] - '0' );
1779 else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( dev[3] - '0' );
1781 if (!new_name) break;
1783 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1784 unix_name = new_name;
1785 unix_len = strlen(unix_name) + 1;
1786 dev = NULL; /* last try */
1788 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1789 return STATUS_BAD_DEVICE_TYPE;
1793 /* return the length of the DOS namespace prefix if any */
1794 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
1796 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
1797 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
1799 if (name->Length > sizeof(nt_prefixW) &&
1800 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
1801 return sizeof(nt_prefixW) / sizeof(WCHAR);
1803 if (name->Length > sizeof(dosdev_prefixW) &&
1804 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
1805 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
1807 return 0;
1811 /******************************************************************************
1812 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
1814 * Convert a file name from NT namespace to Unix namespace.
1816 * If disposition is not FILE_OPEN or FILE_OVERWRITTE, the last path
1817 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
1818 * returned, but the unix name is still filled in properly.
1820 NTSTATUS wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
1821 UINT disposition, BOOLEAN check_case )
1823 static const WCHAR unixW[] = {'u','n','i','x'};
1824 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
1826 NTSTATUS status = STATUS_SUCCESS;
1827 const char *config_dir = wine_get_config_dir();
1828 const WCHAR *name, *p;
1829 struct stat st;
1830 char *unix_name;
1831 int pos, ret, name_len, unix_len, prefix_len, used_default;
1832 WCHAR prefix[MAX_DIR_ENTRY_LEN];
1833 BOOLEAN is_unix = FALSE;
1835 name = nameW->Buffer;
1836 name_len = nameW->Length / sizeof(WCHAR);
1838 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
1840 if (!(pos = get_dos_prefix_len( nameW )))
1841 return STATUS_BAD_DEVICE_TYPE; /* no DOS prefix, assume NT native name */
1843 name += pos;
1844 name_len -= pos;
1846 /* check for sub-directory */
1847 for (pos = 0; pos < name_len; pos++)
1849 if (IS_SEPARATOR(name[pos])) break;
1850 if (name[pos] < 32 || strchrW( invalid_charsW, name[pos] ))
1851 return STATUS_OBJECT_NAME_INVALID;
1853 if (pos > MAX_DIR_ENTRY_LEN)
1854 return STATUS_OBJECT_NAME_INVALID;
1856 if (pos == name_len) /* no subdir, plain DOS device */
1857 return get_dos_device( name, name_len, unix_name_ret );
1859 for (prefix_len = 0; prefix_len < pos; prefix_len++)
1860 prefix[prefix_len] = tolowerW(name[prefix_len]);
1862 name += prefix_len;
1863 name_len -= prefix_len;
1865 /* check for invalid characters (all chars except 0 are valid for unix) */
1866 is_unix = (prefix_len == 4 && !memcmp( prefix, unixW, sizeof(unixW) ));
1867 if (is_unix)
1869 for (p = name; p < name + name_len; p++)
1870 if (!*p) return STATUS_OBJECT_NAME_INVALID;
1871 check_case = TRUE;
1873 else
1875 for (p = name; p < name + name_len; p++)
1876 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
1879 unix_len = ntdll_wcstoumbs( 0, prefix, prefix_len, NULL, 0, NULL, NULL );
1880 unix_len += ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1881 unix_len += MAX_DIR_ENTRY_LEN + 3;
1882 unix_len += strlen(config_dir) + sizeof("/dosdevices/");
1883 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1884 return STATUS_NO_MEMORY;
1885 strcpy( unix_name, config_dir );
1886 strcat( unix_name, "/dosdevices/" );
1887 pos = strlen(unix_name);
1889 ret = ntdll_wcstoumbs( 0, prefix, prefix_len, unix_name + pos, unix_len - pos - 1,
1890 NULL, &used_default );
1891 if (!ret || used_default)
1893 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1894 return STATUS_OBJECT_NAME_INVALID;
1896 pos += ret;
1898 /* check if prefix exists (except for DOS drives to avoid extra stat calls) */
1900 if (prefix_len != 2 || prefix[1] != ':')
1902 unix_name[pos] = 0;
1903 if (lstat( unix_name, &st ) == -1 && errno == ENOENT)
1905 if (!is_unix)
1907 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1908 return STATUS_BAD_DEVICE_TYPE;
1910 pos = 0; /* fall back to unix root */
1914 /* try a shortcut first */
1916 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
1917 NULL, &used_default );
1919 while (name_len && IS_SEPARATOR(*name))
1921 name++;
1922 name_len--;
1925 if (ret > 0 && !used_default) /* if we used the default char the name didn't convert properly */
1927 char *p;
1928 unix_name[pos + ret] = 0;
1929 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
1930 if (!stat( unix_name, &st ))
1932 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
1933 if (disposition == FILE_CREATE)
1935 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1936 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
1938 goto done;
1942 if (!name_len) /* empty name -> drive root doesn't exist */
1944 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1945 return STATUS_OBJECT_PATH_NOT_FOUND;
1947 if (check_case && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
1949 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1950 return STATUS_OBJECT_NAME_NOT_FOUND;
1953 /* now do it component by component */
1955 while (name_len)
1957 const WCHAR *end, *next;
1959 end = name;
1960 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
1961 next = end;
1962 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
1963 name_len -= next - name;
1965 /* grow the buffer if needed */
1967 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
1969 char *new_name;
1970 unix_len += 2 * MAX_DIR_ENTRY_LEN;
1971 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
1973 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1974 return STATUS_NO_MEMORY;
1976 unix_name = new_name;
1979 status = find_file_in_dir( unix_name, pos, name, end - name, check_case );
1981 /* if this is the last element, not finding it is not necessarily fatal */
1982 if (!name_len)
1984 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
1986 status = STATUS_OBJECT_NAME_NOT_FOUND;
1987 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
1989 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
1990 MAX_DIR_ENTRY_LEN, NULL, &used_default );
1991 if (ret > 0 && !used_default)
1993 unix_name[pos] = '/';
1994 unix_name[pos + 1 + ret] = 0;
1995 status = STATUS_NO_SUCH_FILE;
1996 break;
2000 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
2002 status = STATUS_OBJECT_NAME_COLLISION;
2006 if (status != STATUS_SUCCESS)
2008 /* couldn't find it at all, fail */
2009 WARN( "%s not found in %s\n", debugstr_w(name), unix_name );
2010 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2011 return status;
2014 pos += strlen( unix_name + pos );
2015 name = next;
2018 WARN( "%s -> %s required a case-insensitive search\n",
2019 debugstr_us(nameW), debugstr_a(unix_name) );
2021 done:
2022 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
2023 unix_name_ret->Buffer = unix_name;
2024 unix_name_ret->Length = strlen(unix_name);
2025 unix_name_ret->MaximumLength = unix_len;
2026 return status;
2030 /******************************************************************
2031 * RtlDoesFileExists_U (NTDLL.@)
2033 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
2035 UNICODE_STRING nt_name;
2036 FILE_BASIC_INFORMATION basic_info;
2037 OBJECT_ATTRIBUTES attr;
2038 BOOLEAN ret;
2040 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
2042 attr.Length = sizeof(attr);
2043 attr.RootDirectory = 0;
2044 attr.ObjectName = &nt_name;
2045 attr.Attributes = OBJ_CASE_INSENSITIVE;
2046 attr.SecurityDescriptor = NULL;
2047 attr.SecurityQualityOfService = NULL;
2049 ret = NtQueryAttributesFile(&attr, &basic_info) == STATUS_SUCCESS;
2051 RtlFreeUnicodeString( &nt_name );
2052 return ret;
2056 /***********************************************************************
2057 * DIR_unmount_device
2059 * Unmount the specified device.
2061 NTSTATUS DIR_unmount_device( HANDLE handle )
2063 NTSTATUS status;
2064 int unix_fd, needs_close;
2066 if (!(status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )))
2068 struct stat st;
2069 char *mount_point = NULL;
2071 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2072 status = STATUS_INVALID_PARAMETER;
2073 else
2075 if ((mount_point = get_device_mount_point( st.st_rdev )))
2077 #ifdef __APPLE__
2078 static const char umount[] = "diskutil unmount >/dev/null 2>&1 ";
2079 #else
2080 static const char umount[] = "umount >/dev/null 2>&1 ";
2081 #endif
2082 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
2083 if (cmd)
2085 strcpy( cmd, umount );
2086 strcat( cmd, mount_point );
2087 system( cmd );
2088 RtlFreeHeap( GetProcessHeap(), 0, cmd );
2089 #ifdef linux
2090 /* umount will fail to release the loop device since we still have
2091 a handle to it, so we release it here */
2092 if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
2093 #endif
2095 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
2098 if (needs_close) close( unix_fd );
2100 return status;
2104 /******************************************************************************
2105 * DIR_get_unix_cwd
2107 * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
2108 * Returned value must be freed by caller.
2110 NTSTATUS DIR_get_unix_cwd( char **cwd )
2112 int old_cwd, unix_fd, needs_close;
2113 CURDIR *curdir;
2114 HANDLE handle;
2115 NTSTATUS status;
2117 RtlAcquirePebLock();
2119 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
2120 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
2121 else
2122 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
2124 if (!(handle = curdir->Handle))
2126 UNICODE_STRING dirW;
2127 OBJECT_ATTRIBUTES attr;
2128 IO_STATUS_BLOCK io;
2130 if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
2132 status = STATUS_OBJECT_NAME_INVALID;
2133 goto done;
2135 attr.Length = sizeof(attr);
2136 attr.RootDirectory = 0;
2137 attr.Attributes = OBJ_CASE_INSENSITIVE;
2138 attr.ObjectName = &dirW;
2139 attr.SecurityDescriptor = NULL;
2140 attr.SecurityQualityOfService = NULL;
2142 status = NtOpenFile( &handle, 0, &attr, &io, 0,
2143 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
2144 RtlFreeUnicodeString( &dirW );
2145 if (status != STATUS_SUCCESS) goto done;
2148 if ((status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )) == STATUS_SUCCESS)
2150 RtlEnterCriticalSection( &dir_section );
2152 if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
2154 unsigned int size = 512;
2156 for (;;)
2158 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2160 status = STATUS_NO_MEMORY;
2161 break;
2163 if (getcwd( *cwd, size )) break;
2164 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
2165 if (errno != ERANGE)
2167 status = STATUS_OBJECT_PATH_INVALID;
2168 break;
2170 size *= 2;
2172 if (fchdir( old_cwd ) == -1) chdir( "/" );
2174 else status = FILE_GetNtStatus();
2176 RtlLeaveCriticalSection( &dir_section );
2177 if (needs_close) close( unix_fd );
2179 if (!curdir->Handle) NtClose( handle );
2181 done:
2182 RtlReleasePebLock();
2183 return status;
2186 struct read_changes_info
2188 HANDLE FileHandle;
2189 PVOID Buffer;
2190 ULONG BufferSize;
2191 PIO_APC_ROUTINE apc;
2192 void *apc_arg;
2195 /* callback for ioctl user APC */
2196 static void WINAPI read_changes_user_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
2198 struct read_changes_info *info = arg;
2199 if (info->apc) info->apc( info->apc_arg, io, reserved );
2200 RtlFreeHeap( GetProcessHeap(), 0, info );
2203 static NTSTATUS read_changes_apc( void *user, PIO_STATUS_BLOCK iosb, NTSTATUS status )
2205 struct read_changes_info *info = user;
2206 char path[PATH_MAX];
2207 NTSTATUS ret = STATUS_SUCCESS;
2208 int len, action, i;
2210 SERVER_START_REQ( read_change )
2212 req->handle = info->FileHandle;
2213 wine_server_set_reply( req, path, PATH_MAX );
2214 ret = wine_server_call( req );
2215 action = reply->action;
2216 len = wine_server_reply_size( reply );
2218 SERVER_END_REQ;
2220 if (ret == STATUS_SUCCESS && info->Buffer &&
2221 (info->BufferSize > (sizeof (FILE_NOTIFY_INFORMATION) + len*sizeof(WCHAR))))
2223 PFILE_NOTIFY_INFORMATION pfni;
2225 pfni = (PFILE_NOTIFY_INFORMATION) info->Buffer;
2227 /* convert to an NT style path */
2228 for (i=0; i<len; i++)
2229 if (path[i] == '/')
2230 path[i] = '\\';
2232 len = ntdll_umbstowcs( 0, path, len, pfni->FileName,
2233 info->BufferSize - sizeof (*pfni) );
2235 pfni->NextEntryOffset = 0;
2236 pfni->Action = action;
2237 pfni->FileNameLength = len * sizeof (WCHAR);
2238 pfni->FileName[len] = 0;
2239 len = sizeof (*pfni) - sizeof (DWORD) + pfni->FileNameLength;
2241 else
2243 ret = STATUS_NOTIFY_ENUM_DIR;
2244 len = 0;
2247 iosb->u.Status = ret;
2248 iosb->Information = len;
2249 return ret;
2252 #define FILE_NOTIFY_ALL ( \
2253 FILE_NOTIFY_CHANGE_FILE_NAME | \
2254 FILE_NOTIFY_CHANGE_DIR_NAME | \
2255 FILE_NOTIFY_CHANGE_ATTRIBUTES | \
2256 FILE_NOTIFY_CHANGE_SIZE | \
2257 FILE_NOTIFY_CHANGE_LAST_WRITE | \
2258 FILE_NOTIFY_CHANGE_LAST_ACCESS | \
2259 FILE_NOTIFY_CHANGE_CREATION | \
2260 FILE_NOTIFY_CHANGE_SECURITY )
2262 /******************************************************************************
2263 * NtNotifyChangeDirectoryFile [NTDLL.@]
2265 NTSTATUS WINAPI
2266 NtNotifyChangeDirectoryFile( HANDLE FileHandle, HANDLE Event,
2267 PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext,
2268 PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer,
2269 ULONG BufferSize, ULONG CompletionFilter, BOOLEAN WatchTree )
2271 struct read_changes_info *info;
2272 NTSTATUS status;
2274 TRACE("%p %p %p %p %p %p %u %u %d\n",
2275 FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock,
2276 Buffer, BufferSize, CompletionFilter, WatchTree );
2278 if (!IoStatusBlock)
2279 return STATUS_ACCESS_VIOLATION;
2281 if (CompletionFilter == 0 || (CompletionFilter & ~FILE_NOTIFY_ALL))
2282 return STATUS_INVALID_PARAMETER;
2284 info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof *info );
2285 if (!info)
2286 return STATUS_NO_MEMORY;
2288 info->FileHandle = FileHandle;
2289 info->Buffer = Buffer;
2290 info->BufferSize = BufferSize;
2291 info->apc = ApcRoutine;
2292 info->apc_arg = ApcContext;
2294 SERVER_START_REQ( read_directory_changes )
2296 req->handle = FileHandle;
2297 req->filter = CompletionFilter;
2298 req->want_data = (Buffer != NULL);
2299 req->subtree = WatchTree;
2300 req->async.callback = read_changes_apc;
2301 req->async.iosb = IoStatusBlock;
2302 req->async.arg = info;
2303 req->async.apc = read_changes_user_apc;
2304 req->async.event = Event;
2305 status = wine_server_call( req );
2307 SERVER_END_REQ;
2309 if (status != STATUS_PENDING)
2310 RtlFreeHeap( GetProcessHeap(), 0, info );
2312 return status;