Return correct error on name collision when creating new named
[wine] / dlls / ntdll / directory.c
1 /*
2  * NTDLL directory functions
3  *
4  * Copyright 1993 Erik Bos
5  * Copyright 2003 Eric Pouech
6  * Copyright 1996, 2004 Alexandre Julliard
7  *
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.
12  *
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.
17  *
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
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 #ifdef HAVE_MNTENT_H
35 #include <mntent.h>
36 #endif
37 #ifdef HAVE_SYS_STAT_H
38 # include <sys/stat.h>
39 #endif
40 #ifdef HAVE_SYS_IOCTL_H
41 #include <sys/ioctl.h>
42 #endif
43 #ifdef HAVE_LINUX_IOCTL_H
44 #include <linux/ioctl.h>
45 #endif
46 #ifdef HAVE_LINUX_MAJOR_H
47 # include <linux/major.h>
48 #endif
49 #ifdef HAVE_SYS_PARAM_H
50 #include <sys/param.h>
51 #endif
52 #ifdef HAVE_SYS_MOUNT_H
53 #include <sys/mount.h>
54 #endif
55 #include <time.h>
56 #ifdef HAVE_UNISTD_H
57 # include <unistd.h>
58 #endif
59
60 #define NONAMELESSUNION
61 #define NONAMELESSSTRUCT
62 #include "windef.h"
63 #include "winnt.h"
64 #include "ntstatus.h"
65 #include "thread.h"
66 #include "winternl.h"
67 #include "ntdll_misc.h"
68 #include "wine/unicode.h"
69 #include "wine/server.h"
70 #include "wine/library.h"
71 #include "wine/debug.h"
72
73 WINE_DEFAULT_DEBUG_CHANNEL(file);
74
75 /* just in case... */
76 #undef VFAT_IOCTL_READDIR_BOTH
77 #undef USE_GETDENTS
78
79 #ifdef linux
80
81 /* We want the real kernel dirent structure, not the libc one */
82 typedef struct
83 {
84     long d_ino;
85     long d_off;
86     unsigned short d_reclen;
87     char d_name[256];
88 } KERNEL_DIRENT;
89
90 /* Define the VFAT ioctl to get both short and long file names */
91 #define VFAT_IOCTL_READDIR_BOTH  _IOR('r', 1, KERNEL_DIRENT [2] )
92
93 #ifndef O_DIRECTORY
94 # define O_DIRECTORY 0200000 /* must be directory */
95 #endif
96
97 #ifdef __i386__
98
99 typedef struct
100 {
101     ULONG64        d_ino;
102     LONG64         d_off;
103     unsigned short d_reclen;
104     unsigned char  d_type;
105     char           d_name[256];
106 } KERNEL_DIRENT64;
107
108 static inline int getdents64( int fd, KERNEL_DIRENT64 *de, unsigned int size )
109 {
110     int ret;
111     __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
112              : "=a" (ret)
113              : "0" (220 /*NR_getdents64*/), "r" (fd), "c" (de), "d" (size)
114              : "memory" );
115     if (ret < 0)
116     {
117         errno = -ret;
118         ret = -1;
119     }
120     return ret;
121 }
122 #define USE_GETDENTS
123
124 #endif  /* i386 */
125
126 #endif  /* linux */
127
128 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
129 #define IS_SEPARATOR(ch)   ((ch) == '\\' || (ch) == '/')
130
131 #define INVALID_NT_CHARS   '*','?','<','>','|','"'
132 #define INVALID_DOS_CHARS  INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
133
134 #define MAX_DIR_ENTRY_LEN 255  /* max length of a directory entry in chars */
135
136 static int show_dot_files = -1;
137
138 /* at some point we may want to allow Winelib apps to set this */
139 static const int is_case_sensitive = FALSE;
140
141 static RTL_CRITICAL_SECTION dir_section;
142 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
143 {
144     0, 0, &dir_section,
145     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
146       0, 0, { (DWORD_PTR)(__FILE__ ": dir_section") }
147 };
148 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
149
150
151 /* check if a given Unicode char is OK in a DOS short name */
152 static inline BOOL is_invalid_dos_char( WCHAR ch )
153 {
154     static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
155     if (ch > 0x7f) return TRUE;
156     return strchrW( invalid_chars, ch ) != NULL;
157 }
158
159 /***********************************************************************
160  *           get_default_com_device
161  *
162  * Return the default device to use for serial ports.
163  */
164 static char *get_default_com_device( int num )
165 {
166     char *ret = NULL;
167
168     if (!num || num > 9) return ret;
169 #ifdef linux
170     ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
171     if (ret)
172     {
173         strcpy( ret, "/dev/ttyS0" );
174         ret[strlen(ret) - 1] = '0' + num - 1;
175     }
176 #else
177     FIXME( "no known default for device com%d\n", num );
178 #endif
179     return ret;
180 }
181
182
183 /***********************************************************************
184  *           get_default_lpt_device
185  *
186  * Return the default device to use for parallel ports.
187  */
188 static char *get_default_lpt_device( int num )
189 {
190     char *ret = NULL;
191
192     if (!num || num > 9) return ret;
193 #ifdef linux
194     ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
195     if (ret)
196     {
197         strcpy( ret, "/dev/lp0" );
198         ret[strlen(ret) - 1] = '0' + num - 1;
199     }
200 #else
201     FIXME( "no known default for device lpt%d\n", num );
202 #endif
203     return ret;
204 }
205
206
207 /***********************************************************************
208  *           parse_mount_entries
209  *
210  * Parse mount entries looking for a given device. Helper for get_default_drive_device.
211  */
212
213 #ifdef sun
214 #include <sys/vfstab.h>
215 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
216 {
217
218     struct vfstab vfs_entry;
219     struct vfstab *entry=&vfs_entry;
220     struct stat st;
221     char *device;
222
223     while (! getvfsent( f, entry ))
224     {
225         /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
226         if (!strcmp( entry->vfs_fstype, "nfs" ) ||
227             !strcmp( entry->vfs_fstype, "smbfs" ) ||
228             !strcmp( entry->vfs_fstype, "ncpfs" )) continue;
229
230         if (stat( entry->vfs_mountp, &st ) == -1) continue;
231         if (st.st_dev != dev || st.st_ino != ino) continue;
232         if (!strcmp( entry->vfs_fstype, "fd" ))
233         {
234             if ((device = strstr( entry->vfs_mntopts, "dev=" )))
235             {
236                 char *p = strchr( device + 4, ',' );
237                 if (p) *p = 0;
238                 return device + 4;
239             }
240         }
241         else
242             return entry->vfs_special;
243     }
244     return NULL;
245 }
246 #endif
247
248 #ifdef linux
249 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
250 {
251     struct mntent *entry;
252     struct stat st;
253     char *device;
254
255     while ((entry = getmntent( f )))
256     {
257         /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
258         if (!strcmp( entry->mnt_type, "nfs" ) ||
259             !strcmp( entry->mnt_type, "smbfs" ) ||
260             !strcmp( entry->mnt_type, "ncpfs" )) continue;
261
262         if (stat( entry->mnt_dir, &st ) == -1) continue;
263         if (st.st_dev != dev || st.st_ino != ino) continue;
264         if (!strcmp( entry->mnt_type, "supermount" ))
265         {
266             if ((device = strstr( entry->mnt_opts, "dev=" )))
267             {
268                 char *p = strchr( device + 4, ',' );
269                 if (p) *p = 0;
270                 return device + 4;
271             }
272         }
273         else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
274         {
275             /* if device is a regular file check for a loop mount */
276             if ((device = strstr( entry->mnt_opts, "loop=" )))
277             {
278                 char *p = strchr( device + 5, ',' );
279                 if (p) *p = 0;
280                 return device + 5;
281             }
282         }
283         else
284             return entry->mnt_fsname;
285     }
286     return NULL;
287 }
288 #endif
289
290 #ifdef __FreeBSD__
291 #include <fstab.h>
292 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
293 {
294     struct fstab *entry;
295     struct stat st;
296
297     while ((entry = getfsent()))
298     {
299         /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
300         if (!strcmp( entry->fs_vfstype, "nfs" ) ||
301             !strcmp( entry->fs_vfstype, "smbfs" ) ||
302             !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
303
304         if (stat( entry->fs_file, &st ) == -1) continue;
305         if (st.st_dev != dev || st.st_ino != ino) continue;
306         return entry->fs_spec;
307     }
308     return NULL;
309 }
310 #endif
311
312 #ifdef sun
313 #include <sys/mnttab.h>
314 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
315 {
316
317     volatile struct mnttab mntentry;
318     struct mnttab *entry=&mntentry;
319     struct stat st;
320     char *device;
321
322
323     while (( ! getmntent( f , entry) ))
324     {
325         /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
326         if (!strcmp( entry->mnt_fstype, "nfs" ) ||
327             !strcmp( entry->mnt_fstype, "smbfs" ) ||
328             !strcmp( entry->mnt_fstype, "ncpfs" )) continue;
329
330         if (stat( entry->mnt_mountp, &st ) == -1) continue;
331         if (st.st_dev != dev || st.st_ino != ino) continue;
332         if (!strcmp( entry->mnt_fstype, "fd" ))
333         {
334             if ((device = strstr( entry->mnt_mntopts, "dev=" )))
335             {
336                 char *p = strchr( device + 4, ',' );
337                 if (p) *p = 0;
338                 return device + 4;
339             }
340         }
341         else
342             return entry->mnt_special;
343     }
344     return NULL;
345 }
346 #endif
347
348 /***********************************************************************
349  *           get_default_drive_device
350  *
351  * Return the default device to use for a given drive mount point.
352  */
353 static char *get_default_drive_device( const char *root )
354 {
355     char *ret = NULL;
356
357 #ifdef linux
358     FILE *f;
359     char *device = NULL;
360     int fd, res = -1;
361     struct stat st;
362
363     /* try to open it first to force it to get mounted */
364     if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
365     {
366         res = fstat( fd, &st );
367         close( fd );
368     }
369     /* now try normal stat just in case */
370     if (res == -1) res = stat( root, &st );
371     if (res == -1) return NULL;
372
373     RtlEnterCriticalSection( &dir_section );
374
375     if ((f = fopen( "/etc/mtab", "r" )))
376     {
377         device = parse_mount_entries( f, st.st_dev, st.st_ino );
378         endmntent( f );
379     }
380     /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
381     if (!device && (f = fopen( "/etc/fstab", "r" )))
382     {
383         device = parse_mount_entries( f, st.st_dev, st.st_ino );
384         endmntent( f );
385     }
386     if (device)
387     {
388         ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
389         if (ret) strcpy( ret, device );
390     }
391     RtlLeaveCriticalSection( &dir_section );
392
393 #elif defined( __FreeBSD__ )
394     char *device = NULL;
395     int fd, res = -1;
396     struct stat st;
397
398     /* try to open it first to force it to get mounted */
399     if ((fd = open( root, O_RDONLY )) != -1)
400     {
401         res = fstat( fd, &st );
402         close( fd );
403     }
404     /* now try normal stat just in case */
405     if (res == -1) res = stat( root, &st );
406     if (res == -1) return NULL;
407
408     RtlEnterCriticalSection( &dir_section );
409
410     /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
411      * pass NULL.  Leave the argument in for symmetry.
412      */
413     device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
414     if (device)
415     {
416         ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
417         if (ret) strcpy( ret, device );
418     }
419     RtlLeaveCriticalSection( &dir_section );
420
421 #elif defined( sun )
422     FILE *f;
423     char *device = NULL;
424     int fd, res = -1;
425     struct stat st;
426
427     /* try to open it first to force it to get mounted */
428     if ((fd = open( root, O_RDONLY )) != -1)
429     {
430         res = fstat( fd, &st );
431         close( fd );
432     }
433     /* now try normal stat just in case */
434     if (res == -1) res = stat( root, &st );
435     if (res == -1) return NULL;
436
437     RtlEnterCriticalSection( &dir_section );
438
439     if ((f = fopen( "/etc/mnttab", "r" )))
440     {
441         device = parse_mount_entries( f, st.st_dev, st.st_ino);
442         fclose( f );
443     }
444     /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
445     if (!device && (f = fopen( "/etc/vfstab", "r" )))
446     {
447         device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
448         fclose( f );
449     }
450     if (device)
451     {
452         ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
453         if (ret) strcpy( ret, device );
454     }
455     RtlLeaveCriticalSection( &dir_section );
456
457 #elif defined(__APPLE__)
458     struct statfs *mntStat;
459     struct stat st;
460     int i;
461     int mntSize;
462     dev_t dev;
463     ino_t ino;
464     static const char path_bsd_device[] = "/dev/disk";
465     int res;
466
467     res = stat( root, &st );
468     if (res == -1) return NULL;
469
470     dev = st.st_dev;
471     ino = st.st_ino;
472
473     RtlEnterCriticalSection( &dir_section );
474
475     mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
476
477     for (i = 0; i < mntSize && !ret; i++)
478     {
479         if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
480         if (st.st_dev != dev || st.st_ino != ino) continue;
481
482         /* FIXME add support for mounted network drive */
483         if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
484         {
485             /* set return value to the corresponding raw BSD node */
486             ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
487             if (ret)
488             {
489                 strcpy(ret, "/dev/r");
490                 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
491             }
492         }
493     }
494     RtlLeaveCriticalSection( &dir_section );
495 #else
496     static int warned;
497     if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
498 #endif
499     return ret;
500 }
501
502
503 /***********************************************************************
504  *           get_device_mount_point
505  *
506  * Return the current mount point for a device.
507  */
508 static char *get_device_mount_point( dev_t dev )
509 {
510     char *ret = NULL;
511
512 #ifdef linux
513     FILE *f;
514
515     RtlEnterCriticalSection( &dir_section );
516
517     if ((f = fopen( "/etc/mtab", "r" )))
518     {
519         struct mntent *entry;
520         struct stat st;
521         char *p, *device;
522
523         while ((entry = getmntent( f )))
524         {
525             /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
526             if (!strcmp( entry->mnt_type, "nfs" ) ||
527                 !strcmp( entry->mnt_type, "smbfs" ) ||
528                 !strcmp( entry->mnt_type, "ncpfs" )) continue;
529
530             if (!strcmp( entry->mnt_type, "supermount" ))
531             {
532                 if ((device = strstr( entry->mnt_opts, "dev=" )))
533                 {
534                     device += 4;
535                     if ((p = strchr( device, ',' ))) *p = 0;
536                 }
537             }
538             else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
539             {
540                 /* if device is a regular file check for a loop mount */
541                 if ((device = strstr( entry->mnt_opts, "loop=" )))
542                 {
543                     device += 5;
544                     if ((p = strchr( device, ',' ))) *p = 0;
545                 }
546             }
547             else device = entry->mnt_fsname;
548
549             if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
550             {
551                 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
552                 if (ret) strcpy( ret, entry->mnt_dir );
553                 break;
554             }
555         }
556         endmntent( f );
557     }
558     RtlLeaveCriticalSection( &dir_section );
559 #else
560     static int warned;
561     if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
562 #endif
563     return ret;
564 }
565
566
567 /***********************************************************************
568  *           init_options
569  *
570  * Initialize the show_dot_files options.
571  */
572 static void init_options(void)
573 {
574     static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
575     static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
576     char tmp[80];
577     HANDLE root, hkey;
578     DWORD dummy;
579     OBJECT_ATTRIBUTES attr;
580     UNICODE_STRING nameW;
581
582     show_dot_files = 0;
583
584     RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
585     attr.Length = sizeof(attr);
586     attr.RootDirectory = root;
587     attr.ObjectName = &nameW;
588     attr.Attributes = 0;
589     attr.SecurityDescriptor = NULL;
590     attr.SecurityQualityOfService = NULL;
591     RtlInitUnicodeString( &nameW, WineW );
592
593     /* @@ Wine registry key: HKCU\Software\Wine */
594     if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
595     {
596         RtlInitUnicodeString( &nameW, ShowDotFilesW );
597         if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
598         {
599             WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
600             show_dot_files = IS_OPTION_TRUE( str[0] );
601         }
602         NtClose( hkey );
603     }
604     NtClose( root );
605 }
606
607
608 /***********************************************************************
609  *           DIR_is_hidden_file
610  *
611  * Check if the specified file should be hidden based on its name and the show dot files option.
612  */
613 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
614 {
615     WCHAR *p, *end;
616
617     if (show_dot_files == -1) init_options();
618     if (show_dot_files) return FALSE;
619
620     end = p = name->Buffer + name->Length/sizeof(WCHAR);
621     while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
622     while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
623     if (p == end || *p != '.') return FALSE;
624     /* make sure it isn't '.' or '..' */
625     if (p + 1 == end) return FALSE;
626     if (p[1] == '.' && p + 2 == end) return FALSE;
627     return TRUE;
628 }
629
630
631 /***********************************************************************
632  *           hash_short_file_name
633  *
634  * Transform a Unix file name into a hashed DOS name. If the name is a valid
635  * DOS name, it is converted to upper-case; otherwise it is replaced by a
636  * hashed version that fits in 8.3 format.
637  * 'buffer' must be at least 12 characters long.
638  * Returns length of short name in bytes; short name is NOT null-terminated.
639  */
640 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
641 {
642     static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
643
644     LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
645     LPWSTR dst;
646     unsigned short hash;
647     int i;
648
649     /* Compute the hash code of the file name */
650     /* If you know something about hash functions, feel free to */
651     /* insert a better algorithm here... */
652     if (!is_case_sensitive)
653     {
654         for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
655             hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
656         hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
657     }
658     else
659     {
660         for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
661             hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
662         hash = (hash << 3) ^ (hash >> 5) ^ *p;  /* Last character */
663     }
664
665     /* Find last dot for start of the extension */
666     for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
667
668     /* Copy first 4 chars, replacing invalid chars with '_' */
669     for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
670     {
671         if (p == end || p == ext) break;
672         *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
673     }
674     /* Pad to 5 chars with '~' */
675     while (i-- >= 0) *dst++ = '~';
676
677     /* Insert hash code converted to 3 ASCII chars */
678     *dst++ = hash_chars[(hash >> 10) & 0x1f];
679     *dst++ = hash_chars[(hash >> 5) & 0x1f];
680     *dst++ = hash_chars[hash & 0x1f];
681
682     /* Copy the first 3 chars of the extension (if any) */
683     if (ext)
684     {
685         *dst++ = '.';
686         for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
687             *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
688     }
689     return dst - buffer;
690 }
691
692
693 /***********************************************************************
694  *           match_filename
695  *
696  * Check a long file name against a mask.
697  *
698  * Tests (done in W95 DOS shell - case insensitive):
699  * *.txt                        test1.test.txt                          *
700  * *st1*                        test1.txt                               *
701  * *.t??????.t*                 test1.ta.tornado.txt                    *
702  * *tornado*                    test1.ta.tornado.txt                    *
703  * t*t                          test1.ta.tornado.txt                    *
704  * ?est*                        test1.txt                               *
705  * ?est???                      test1.txt                               -
706  * *test1.txt*                  test1.txt                               *
707  * h?l?o*t.dat                  hellothisisatest.dat                    *
708  */
709 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
710 {
711     int mismatch;
712     const WCHAR *name = name_str->Buffer;
713     const WCHAR *mask = mask_str->Buffer;
714     const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
715     const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
716     const WCHAR *lastjoker = NULL;
717     const WCHAR *next_to_retry = NULL;
718
719     TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
720
721     while (name < name_end && mask < mask_end)
722     {
723         switch(*mask)
724         {
725         case '*':
726             mask++;
727             while (mask < mask_end && *mask == '*') mask++;  /* Skip consecutive '*' */
728             if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
729             lastjoker = mask;
730
731             /* skip to the next match after the joker(s) */
732             if (is_case_sensitive)
733                 while (name < name_end && (*name != *mask)) name++;
734             else
735                 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
736             next_to_retry = name;
737             break;
738         case '?':
739             mask++;
740             name++;
741             break;
742         default:
743             if (is_case_sensitive) mismatch = (*mask != *name);
744             else mismatch = (toupperW(*mask) != toupperW(*name));
745
746             if (!mismatch)
747             {
748                 mask++;
749                 name++;
750                 if (mask == mask_end)
751                 {
752                     if (name == name_end) return TRUE;
753                     if (lastjoker) mask = lastjoker;
754                 }
755             }
756             else /* mismatch ! */
757             {
758                 if (lastjoker) /* we had an '*', so we can try unlimitedly */
759                 {
760                     mask = lastjoker;
761
762                     /* this scan sequence was a mismatch, so restart
763                      * 1 char after the first char we checked last time */
764                     next_to_retry++;
765                     name = next_to_retry;
766                 }
767                 else return FALSE; /* bad luck */
768             }
769             break;
770         }
771     }
772     while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
773         mask++;  /* Ignore trailing '.' or '*' in mask */
774     return (name == name_end && mask == mask_end);
775 }
776
777
778 /***********************************************************************
779  *           append_entry
780  *
781  * helper for NtQueryDirectoryFile
782  */
783 static FILE_BOTH_DIR_INFORMATION *append_entry( void *info_ptr, ULONG_PTR *pos, ULONG max_length,
784                                                 const char *long_name, const char *short_name,
785                                                 const UNICODE_STRING *mask )
786 {
787     FILE_BOTH_DIR_INFORMATION *info;
788     int i, long_len, short_len, total_len;
789     struct stat st;
790     WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
791     WCHAR short_nameW[12];
792     UNICODE_STRING str;
793
794     long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
795     if (long_len == -1) return NULL;
796
797     str.Buffer = long_nameW;
798     str.Length = long_len * sizeof(WCHAR);
799     str.MaximumLength = sizeof(long_nameW);
800
801     if (short_name)
802     {
803         short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
804                                      short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
805         if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
806     }
807     else  /* generate a short name if necessary */
808     {
809         BOOLEAN spaces;
810
811         short_len = 0;
812         if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
813             short_len = hash_short_file_name( &str, short_nameW );
814     }
815
816     TRACE( "long %s short %s mask %s\n",
817            debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
818
819     if (mask && !match_filename( &str, mask ))
820     {
821         if (!short_len) return NULL;  /* no short name to match */
822         str.Buffer = short_nameW;
823         str.Length = short_len * sizeof(WCHAR);
824         str.MaximumLength = sizeof(short_nameW);
825         if (!match_filename( &str, mask )) return NULL;
826     }
827
828     total_len = (sizeof(*info) - sizeof(info->FileName) + long_len*sizeof(WCHAR) + 3) & ~3;
829     info = (FILE_BOTH_DIR_INFORMATION *)((char *)info_ptr + *pos);
830
831     if (*pos + total_len > max_length) total_len = max_length - *pos;
832
833     info->FileAttributes = 0;
834     if (lstat( long_name, &st ) == -1) return NULL;
835     if (S_ISLNK( st.st_mode ))
836     {
837         if (stat( long_name, &st ) == -1) return NULL;
838         if (S_ISDIR( st.st_mode )) info->FileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT;
839     }
840
841     info->NextEntryOffset = total_len;
842     info->FileIndex = 0;  /* NTFS always has 0 here, so let's not bother with it */
843
844     RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
845     RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
846     RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
847     RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
848
849     if (S_ISDIR(st.st_mode))
850     {
851         info->EndOfFile.QuadPart = info->AllocationSize.QuadPart = 0;
852         info->FileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
853     }
854     else
855     {
856         info->EndOfFile.QuadPart = st.st_size;
857         info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
858         info->FileAttributes |= FILE_ATTRIBUTE_ARCHIVE;
859     }
860
861     if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
862         info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
863
864     if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
865         info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
866
867     info->EaSize = 0; /* FIXME */
868     info->ShortNameLength = short_len * sizeof(WCHAR);
869     for (i = 0; i < short_len; i++) info->ShortName[i] = toupperW(short_nameW[i]);
870     info->FileNameLength = long_len * sizeof(WCHAR);
871     memcpy( info->FileName, long_nameW,
872             min( info->FileNameLength, total_len-sizeof(*info)+sizeof(info->FileName) ));
873
874     *pos += total_len;
875     return info;
876 }
877
878
879 /***********************************************************************
880  *           read_directory_vfat
881  *
882  * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
883  */
884 #ifdef VFAT_IOCTL_READDIR_BOTH
885 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
886                                 BOOLEAN single_entry, const UNICODE_STRING *mask,
887                                 BOOLEAN restart_scan )
888
889 {
890     int res;
891     KERNEL_DIRENT de[2];
892     FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
893     static const unsigned int max_dir_info_size = sizeof(*info) + (MAX_DIR_ENTRY_LEN-1) * sizeof(WCHAR);
894
895     io->u.Status = STATUS_SUCCESS;
896
897     if (restart_scan) lseek( fd, 0, SEEK_SET );
898
899     if (length < max_dir_info_size)  /* we may have to return a partial entry here */
900     {
901         off_t old_pos = lseek( fd, 0, SEEK_CUR );
902
903         /* Set d_reclen to 65535 to work around an AFS kernel bug */
904         de[0].d_reclen = 65535;
905         res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
906         if (res == -1 && errno != ENOENT) return -1;  /* VFAT ioctl probably not supported */
907         if (!res && de[0].d_reclen == 65535) return -1;  /* AFS bug */
908
909         while (res != -1)
910         {
911             if (!de[0].d_reclen) break;
912             if (de[1].d_name[0])
913                 info = append_entry( buffer, &io->Information, length,
914                                      de[1].d_name, de[0].d_name, mask );
915             else
916                 info = append_entry( buffer, &io->Information, length,
917                                      de[0].d_name, NULL, mask );
918             if (info)
919             {
920                 last_info = info;
921                 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
922                 {
923                     io->u.Status = STATUS_BUFFER_OVERFLOW;
924                     lseek( fd, old_pos, SEEK_SET );  /* restore pos to previous entry */
925                 }
926                 break;
927             }
928             old_pos = lseek( fd, 0, SEEK_CUR );
929             res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
930         }
931     }
932     else  /* we'll only return full entries, no need to worry about overflow */
933     {
934         /* Set d_reclen to 65535 to work around an AFS kernel bug */
935         de[0].d_reclen = 65535;
936         res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
937         if (res == -1 && errno != ENOENT) return -1;  /* VFAT ioctl probably not supported */
938         if (!res && de[0].d_reclen == 65535) return -1;  /* AFS bug */
939
940         while (res != -1)
941         {
942             if (!de[0].d_reclen) break;
943             if (de[1].d_name[0])
944                 info = append_entry( buffer, &io->Information, length,
945                                      de[1].d_name, de[0].d_name, mask );
946             else
947                 info = append_entry( buffer, &io->Information, length,
948                                      de[0].d_name, NULL, mask );
949             if (info)
950             {
951                 last_info = info;
952                 if (single_entry) break;
953                 /* check if we still have enough space for the largest possible entry */
954                 if (io->Information + max_dir_info_size > length) break;
955             }
956             res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
957         }
958     }
959
960     if (last_info) last_info->NextEntryOffset = 0;
961     else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
962     return 0;
963 }
964 #endif /* VFAT_IOCTL_READDIR_BOTH */
965
966
967 /***********************************************************************
968  *           read_directory_getdents
969  *
970  * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
971  */
972 #ifdef USE_GETDENTS
973 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
974                                     BOOLEAN single_entry, const UNICODE_STRING *mask,
975                                     BOOLEAN restart_scan )
976 {
977     off_t old_pos = 0;
978     size_t size = length;
979     int res;
980     char local_buffer[8192];
981     KERNEL_DIRENT64 *data, *de;
982     FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
983     static const unsigned int max_dir_info_size = sizeof(*info) + (MAX_DIR_ENTRY_LEN-1) * sizeof(WCHAR);
984
985     if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
986     {
987         size = sizeof(local_buffer);
988         data = (KERNEL_DIRENT64 *)local_buffer;
989     }
990
991     if (restart_scan) lseek( fd, 0, SEEK_SET );
992     else if (length < max_dir_info_size)  /* we may have to return a partial entry here */
993     {
994         old_pos = lseek( fd, 0, SEEK_CUR );
995         if (old_pos == -1 && errno == ENOENT)
996         {
997             io->u.Status = STATUS_NO_MORE_FILES;
998             res = 0;
999             goto done;
1000         }
1001     }
1002
1003     io->u.Status = STATUS_SUCCESS;
1004
1005     res = getdents64( fd, data, size );
1006     if (res == -1)
1007     {
1008         if (errno != ENOSYS)
1009         {
1010             io->u.Status = FILE_GetNtStatus();
1011             res = 0;
1012         }
1013         goto done;
1014     }
1015
1016     de = data;
1017
1018     while (res > 0)
1019     {
1020         res -= de->d_reclen;
1021         info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask );
1022         if (info)
1023         {
1024             last_info = info;
1025             if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1026             {
1027                 io->u.Status = STATUS_BUFFER_OVERFLOW;
1028                 lseek( fd, old_pos, SEEK_SET );  /* restore pos to previous entry */
1029                 break;
1030             }
1031             /* check if we still have enough space for the largest possible entry */
1032             if (single_entry || io->Information + max_dir_info_size > length)
1033             {
1034                 if (res > 0) lseek( fd, de->d_off, SEEK_SET );  /* set pos to next entry */
1035                 break;
1036             }
1037         }
1038         old_pos = de->d_off;
1039         /* move on to the next entry */
1040         if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1041         else
1042         {
1043             res = getdents64( fd, data, size );
1044             de = data;
1045         }
1046     }
1047
1048     if (last_info) last_info->NextEntryOffset = 0;
1049     else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1050     res = 0;
1051 done:
1052     if ((char *)data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1053     return res;
1054 }
1055 #endif  /* USE_GETDENTS */
1056
1057
1058 /***********************************************************************
1059  *           read_directory_readdir
1060  *
1061  * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1062  */
1063 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1064                                     BOOLEAN single_entry, const UNICODE_STRING *mask,
1065                                     BOOLEAN restart_scan )
1066 {
1067     DIR *dir;
1068     off_t i, old_pos = 0;
1069     struct dirent *de;
1070     FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
1071     static const unsigned int max_dir_info_size = sizeof(*info) + (MAX_DIR_ENTRY_LEN-1) * sizeof(WCHAR);
1072
1073     if (!(dir = opendir( "." )))
1074     {
1075         io->u.Status = FILE_GetNtStatus();
1076         return;
1077     }
1078
1079     if (!restart_scan)
1080     {
1081         old_pos = lseek( fd, 0, SEEK_CUR );
1082         /* skip the right number of entries */
1083         for (i = 0; i < old_pos; i++)
1084         {
1085             if (!readdir( dir ))
1086             {
1087                 closedir( dir );
1088                 io->u.Status = STATUS_NO_MORE_FILES;
1089                 return;
1090             }
1091         }
1092     }
1093     io->u.Status = STATUS_SUCCESS;
1094
1095     while ((de = readdir( dir )))
1096     {
1097         old_pos++;
1098         info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask );
1099         if (info)
1100         {
1101             last_info = info;
1102             if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1103             {
1104                 io->u.Status = STATUS_BUFFER_OVERFLOW;
1105                 old_pos--;  /* restore pos to previous entry */
1106                 break;
1107             }
1108             if (single_entry) break;
1109             /* check if we still have enough space for the largest possible entry */
1110             if (io->Information + max_dir_info_size > length) break;
1111         }
1112     }
1113
1114     lseek( fd, old_pos, SEEK_SET );  /* store dir offset as filepos for fd */
1115     closedir( dir );
1116
1117     if (last_info) last_info->NextEntryOffset = 0;
1118     else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1119 }
1120
1121
1122 /******************************************************************************
1123  *  NtQueryDirectoryFile        [NTDLL.@]
1124  *  ZwQueryDirectoryFile        [NTDLL.@]
1125  */
1126 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
1127                                       PIO_APC_ROUTINE apc_routine, PVOID apc_context,
1128                                       PIO_STATUS_BLOCK io,
1129                                       PVOID buffer, ULONG length,
1130                                       FILE_INFORMATION_CLASS info_class,
1131                                       BOOLEAN single_entry,
1132                                       PUNICODE_STRING mask,
1133                                       BOOLEAN restart_scan )
1134 {
1135     int cwd, fd;
1136
1137     TRACE("(%p %p %p %p %p %p 0x%08lx 0x%08x 0x%08x %s 0x%08x\n",
1138           handle, event, apc_routine, apc_context, io, buffer,
1139           length, info_class, single_entry, debugstr_us(mask),
1140           restart_scan);
1141
1142     if (length < sizeof(FILE_BOTH_DIR_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
1143
1144     if (event || apc_routine)
1145     {
1146         FIXME( "Unsupported yet option\n" );
1147         return io->u.Status = STATUS_NOT_IMPLEMENTED;
1148     }
1149     if (info_class != FileBothDirectoryInformation)
1150     {
1151         FIXME( "Unsupported file info class %d\n", info_class );
1152         return io->u.Status = STATUS_NOT_IMPLEMENTED;
1153     }
1154
1155     if ((io->u.Status = wine_server_handle_to_fd( handle, GENERIC_READ, &fd, NULL )) != STATUS_SUCCESS)
1156         return io->u.Status;
1157
1158     io->Information = 0;
1159
1160     RtlEnterCriticalSection( &dir_section );
1161
1162     if (show_dot_files == -1) init_options();
1163
1164     if ((cwd = open(".", O_RDONLY)) != -1 && fchdir( fd ) != -1)
1165     {
1166 #ifdef VFAT_IOCTL_READDIR_BOTH
1167         if ((read_directory_vfat( fd, io, buffer, length, single_entry, mask, restart_scan )) == -1)
1168 #endif
1169 #ifdef USE_GETDENTS
1170             if ((read_directory_getdents( fd, io, buffer, length, single_entry, mask, restart_scan )) == -1)
1171 #endif
1172                 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan );
1173
1174         if (fchdir( cwd ) == -1) chdir( "/" );
1175     }
1176     else io->u.Status = FILE_GetNtStatus();
1177
1178     RtlLeaveCriticalSection( &dir_section );
1179
1180     wine_server_release_fd( handle, fd );
1181     if (cwd != -1) close( cwd );
1182     TRACE( "=> %lx (%ld)\n", io->u.Status, io->Information );
1183     return io->u.Status;
1184 }
1185
1186
1187 /***********************************************************************
1188  *           find_file_in_dir
1189  *
1190  * Find a file in a directory the hard way, by doing a case-insensitive search.
1191  * The file found is appended to unix_name at pos.
1192  * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
1193  */
1194 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
1195                                   int check_case )
1196 {
1197     WCHAR buffer[MAX_DIR_ENTRY_LEN];
1198     UNICODE_STRING str;
1199     BOOLEAN spaces;
1200     DIR *dir;
1201     struct dirent *de;
1202     struct stat st;
1203     int ret, used_default, is_name_8_dot_3;
1204
1205     /* try a shortcut for this directory */
1206
1207     unix_name[pos++] = '/';
1208     ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
1209                            NULL, &used_default );
1210     /* if we used the default char, the Unix name won't round trip properly back to Unicode */
1211     /* so it cannot match the file we are looking for */
1212     if (ret >= 0 && !used_default)
1213     {
1214         unix_name[pos + ret] = 0;
1215         if (!stat( unix_name, &st )) return STATUS_SUCCESS;
1216     }
1217     if (check_case) goto not_found;  /* we want an exact match */
1218
1219     if (pos > 1) unix_name[pos - 1] = 0;
1220     else unix_name[1] = 0;  /* keep the initial slash */
1221
1222     /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
1223
1224     str.Buffer = (WCHAR *)name;
1225     str.Length = length * sizeof(WCHAR);
1226     str.MaximumLength = str.Length;
1227     is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
1228
1229     /* now look for it through the directory */
1230
1231 #ifdef VFAT_IOCTL_READDIR_BOTH
1232     if (is_name_8_dot_3)
1233     {
1234         int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
1235         if (fd != -1)
1236         {
1237             KERNEL_DIRENT de[2];
1238
1239             /* Set d_reclen to 65535 to work around an AFS kernel bug */
1240             de[0].d_reclen = 65535;
1241             if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) != -1 &&
1242                 de[0].d_reclen != 65535)
1243             {
1244                 unix_name[pos - 1] = '/';
1245                 for (;;)
1246                 {
1247                     if (!de[0].d_reclen) break;
1248
1249                     if (de[1].d_name[0])
1250                     {
1251                         ret = ntdll_umbstowcs( 0, de[1].d_name, strlen(de[1].d_name),
1252                                                buffer, MAX_DIR_ENTRY_LEN );
1253                         if (ret == length && !memicmpW( buffer, name, length))
1254                         {
1255                             strcpy( unix_name + pos, de[1].d_name );
1256                             close( fd );
1257                             return STATUS_SUCCESS;
1258                         }
1259                     }
1260                     ret = ntdll_umbstowcs( 0, de[0].d_name, strlen(de[0].d_name),
1261                                            buffer, MAX_DIR_ENTRY_LEN );
1262                     if (ret == length && !memicmpW( buffer, name, length))
1263                     {
1264                         strcpy( unix_name + pos,
1265                                 de[1].d_name[0] ? de[1].d_name : de[0].d_name );
1266                         close( fd );
1267                         return STATUS_SUCCESS;
1268                     }
1269                     if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1)
1270                     {
1271                         close( fd );
1272                         goto not_found;
1273                     }
1274                 }
1275             }
1276             close( fd );
1277         }
1278         /* fall through to normal handling */
1279     }
1280 #endif /* VFAT_IOCTL_READDIR_BOTH */
1281
1282     if (!(dir = opendir( unix_name )))
1283     {
1284         if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
1285         else return FILE_GetNtStatus();
1286     }
1287     unix_name[pos - 1] = '/';
1288     str.Buffer = buffer;
1289     str.MaximumLength = sizeof(buffer);
1290     while ((de = readdir( dir )))
1291     {
1292         ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
1293         if (ret == length && !memicmpW( buffer, name, length ))
1294         {
1295             strcpy( unix_name + pos, de->d_name );
1296             closedir( dir );
1297             return STATUS_SUCCESS;
1298         }
1299
1300         if (!is_name_8_dot_3) continue;
1301
1302         str.Length = ret * sizeof(WCHAR);
1303         if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1304         {
1305             WCHAR short_nameW[12];
1306             ret = hash_short_file_name( &str, short_nameW );
1307             if (ret == length && !memicmpW( short_nameW, name, length ))
1308             {
1309                 strcpy( unix_name + pos, de->d_name );
1310                 closedir( dir );
1311                 return STATUS_SUCCESS;
1312             }
1313         }
1314     }
1315     closedir( dir );
1316     goto not_found;  /* avoid warning */
1317
1318 not_found:
1319     unix_name[pos - 1] = 0;
1320     return STATUS_OBJECT_PATH_NOT_FOUND;
1321 }
1322
1323
1324 /******************************************************************************
1325  *           get_dos_device
1326  *
1327  * Get the Unix path of a DOS device.
1328  */
1329 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
1330 {
1331     const char *config_dir = wine_get_config_dir();
1332     struct stat st;
1333     char *unix_name, *new_name, *dev;
1334     unsigned int i;
1335     int unix_len;
1336
1337     /* make sure the device name is ASCII */
1338     for (i = 0; i < name_len; i++)
1339         if (name[i] <= 32 || name[i] >= 127) return STATUS_OBJECT_NAME_NOT_FOUND;
1340
1341     unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
1342
1343     if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1344         return STATUS_NO_MEMORY;
1345
1346     strcpy( unix_name, config_dir );
1347     strcat( unix_name, "/dosdevices/" );
1348     dev = unix_name + strlen(unix_name);
1349
1350     for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
1351     dev[i] = 0;
1352
1353     /* special case for drive devices */
1354     if (name_len == 2 && dev[1] == ':')
1355     {
1356         dev[i++] = ':';
1357         dev[i] = 0;
1358     }
1359
1360     for (;;)
1361     {
1362         if (!stat( unix_name, &st ))
1363         {
1364             TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
1365             unix_name_ret->Buffer = unix_name;
1366             unix_name_ret->Length = strlen(unix_name);
1367             unix_name_ret->MaximumLength = unix_len;
1368             return STATUS_SUCCESS;
1369         }
1370         if (!dev) break;
1371
1372         /* now try some defaults for it */
1373         if (!strcmp( dev, "aux" ))
1374         {
1375             strcpy( dev, "com1" );
1376             continue;
1377         }
1378         if (!strcmp( dev, "prn" ))
1379         {
1380             strcpy( dev, "lpt1" );
1381             continue;
1382         }
1383         if (!strcmp( dev, "nul" ))
1384         {
1385             strcpy( unix_name, "/dev/null" );
1386             dev = NULL; /* last try */
1387             continue;
1388         }
1389
1390         new_name = NULL;
1391         if (dev[1] == ':' && dev[2] == ':')  /* drive device */
1392         {
1393             dev[2] = 0;  /* remove last ':' to get the drive mount point symlink */
1394             new_name = get_default_drive_device( unix_name );
1395         }
1396         else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( dev[3] - '0' );
1397         else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( dev[3] - '0' );
1398
1399         if (!new_name) break;
1400
1401         RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1402         unix_name = new_name;
1403         unix_len = strlen(unix_name) + 1;
1404         dev = NULL; /* last try */
1405     }
1406     RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1407     return STATUS_OBJECT_NAME_NOT_FOUND;
1408 }
1409
1410
1411 /* return the length of the DOS namespace prefix if any */
1412 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
1413 {
1414     static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
1415     static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
1416
1417     if (name->Length > sizeof(nt_prefixW) &&
1418         !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
1419         return sizeof(nt_prefixW) / sizeof(WCHAR);
1420
1421     if (name->Length > sizeof(dosdev_prefixW) &&
1422         !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
1423         return sizeof(dosdev_prefixW) / sizeof(WCHAR);
1424
1425     return 0;
1426 }
1427
1428
1429 /******************************************************************************
1430  *           wine_nt_to_unix_file_name  (NTDLL.@) Not a Windows API
1431  *
1432  * Convert a file name from NT namespace to Unix namespace.
1433  *
1434  * If disposition is not FILE_OPEN or FILE_OVERWRITTE, the last path
1435  * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
1436  * returned, but the unix name is still filled in properly.
1437  */
1438 NTSTATUS wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
1439                                     UINT disposition, BOOLEAN check_case )
1440 {
1441     static const WCHAR uncW[] = {'U','N','C','\\'};
1442     static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
1443
1444     NTSTATUS status = STATUS_SUCCESS;
1445     const char *config_dir = wine_get_config_dir();
1446     const WCHAR *name, *p;
1447     struct stat st;
1448     char *unix_name;
1449     int pos, ret, name_len, unix_len, used_default;
1450
1451     name     = nameW->Buffer;
1452     name_len = nameW->Length / sizeof(WCHAR);
1453
1454     if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
1455
1456     if ((pos = get_dos_prefix_len( nameW )))
1457     {
1458         BOOLEAN is_unc = FALSE;
1459
1460         name += pos;
1461         name_len -= pos;
1462
1463         /* check for UNC prefix */
1464         if (name_len > 4 && !memicmpW( name, uncW, 4 ))
1465         {
1466             name += 3;
1467             name_len -= 3;
1468             is_unc = TRUE;
1469         }
1470         else
1471         {
1472             /* check for a drive letter with path */
1473             if (name_len < 3 || !isalphaW(name[0]) || name[1] != ':' || !IS_SEPARATOR(name[2]))
1474             {
1475                 /* not a drive with path, try other DOS devices */
1476                 return get_dos_device( name, name_len, unix_name_ret );
1477             }
1478             name += 2;  /* skip drive letter */
1479             name_len -= 2;
1480         }
1481
1482         /* check for invalid characters */
1483         for (p = name; p < name + name_len; p++)
1484             if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
1485
1486         unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1487         unix_len += MAX_DIR_ENTRY_LEN + 3;
1488         unix_len += strlen(config_dir) + sizeof("/dosdevices/") + 3;
1489         if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1490             return STATUS_NO_MEMORY;
1491         strcpy( unix_name, config_dir );
1492         strcat( unix_name, "/dosdevices/" );
1493         pos = strlen(unix_name);
1494         if (is_unc)
1495         {
1496             strcpy( unix_name + pos, "unc" );
1497             pos += 3;
1498         }
1499         else
1500         {
1501             unix_name[pos++] = tolowerW( name[-2] );
1502             unix_name[pos++] = ':';
1503             unix_name[pos] = 0;
1504         }
1505     }
1506     else  /* no DOS prefix, assume NT native name, map directly to Unix */
1507     {
1508         if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_NAME_INVALID;
1509         unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1510         unix_len += MAX_DIR_ENTRY_LEN + 3;
1511         if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1512             return STATUS_NO_MEMORY;
1513         pos = 0;
1514     }
1515
1516     /* try a shortcut first */
1517
1518     ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
1519                            NULL, &used_default );
1520
1521     while (name_len && IS_SEPARATOR(*name))
1522     {
1523         name++;
1524         name_len--;
1525     }
1526
1527     if (ret > 0 && !used_default)  /* if we used the default char the name didn't convert properly */
1528     {
1529         char *p;
1530         unix_name[pos + ret] = 0;
1531         for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
1532         if (!stat( unix_name, &st ))
1533         {
1534             /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
1535             if (disposition == FILE_CREATE)
1536                 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
1537             goto done;
1538         }
1539     }
1540
1541     if (!name_len)  /* empty name -> drive root doesn't exist */
1542     {
1543         RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1544         return STATUS_OBJECT_PATH_NOT_FOUND;
1545     }
1546     if (check_case && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
1547     {
1548         RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1549         return STATUS_OBJECT_NAME_NOT_FOUND;
1550     }
1551
1552     /* now do it component by component */
1553
1554     while (name_len)
1555     {
1556         const WCHAR *end, *next;
1557
1558         end = name;
1559         while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
1560         next = end;
1561         while (next < name + name_len && IS_SEPARATOR(*next)) next++;
1562         name_len -= next - name;
1563
1564         /* grow the buffer if needed */
1565
1566         if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
1567         {
1568             char *new_name;
1569             unix_len += 2 * MAX_DIR_ENTRY_LEN;
1570             if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
1571             {
1572                 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1573                 return STATUS_NO_MEMORY;
1574             }
1575             unix_name = new_name;
1576         }
1577
1578         status = find_file_in_dir( unix_name, pos, name, end - name, check_case );
1579
1580         /* if this is the last element, not finding it is not necessarily fatal */
1581         if (!name_len)
1582         {
1583             if (status == STATUS_OBJECT_PATH_NOT_FOUND)
1584             {
1585                 status = STATUS_OBJECT_NAME_NOT_FOUND;
1586                 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
1587                 {
1588                     ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
1589                                            MAX_DIR_ENTRY_LEN, NULL, &used_default );
1590                     if (ret > 0 && !used_default)
1591                     {
1592                         unix_name[pos] = '/';
1593                         unix_name[pos + 1 + ret] = 0;
1594                         status = STATUS_NO_SUCH_FILE;
1595                         break;
1596                     }
1597                 }
1598             }
1599             else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
1600             {
1601                 status = STATUS_OBJECT_NAME_COLLISION;
1602             }
1603         }
1604
1605         if (status != STATUS_SUCCESS)
1606         {
1607             /* couldn't find it at all, fail */
1608             WARN( "%s not found in %s\n", debugstr_w(name), unix_name );
1609             RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1610             return status;
1611         }
1612
1613         pos += strlen( unix_name + pos );
1614         name = next;
1615     }
1616
1617     WARN( "%s -> %s required a case-insensitive search\n",
1618           debugstr_us(nameW), debugstr_a(unix_name) );
1619
1620 done:
1621     TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
1622     unix_name_ret->Buffer = unix_name;
1623     unix_name_ret->Length = strlen(unix_name);
1624     unix_name_ret->MaximumLength = unix_len;
1625     return status;
1626 }
1627
1628
1629 /******************************************************************
1630  *              RtlDoesFileExists_U   (NTDLL.@)
1631  */
1632 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
1633 {
1634     UNICODE_STRING nt_name;
1635     ANSI_STRING unix_name;
1636     BOOLEAN ret;
1637
1638     if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
1639     ret = (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ) == STATUS_SUCCESS);
1640     if (ret) RtlFreeAnsiString( &unix_name );
1641     RtlFreeUnicodeString( &nt_name );
1642     return ret;
1643 }
1644
1645
1646 /***********************************************************************
1647  *           DIR_unmount_device
1648  *
1649  * Unmount the specified device.
1650  */
1651 NTSTATUS DIR_unmount_device( HANDLE handle )
1652 {
1653     NTSTATUS status;
1654     int unix_fd;
1655
1656     SERVER_START_REQ( unmount_device )
1657     {
1658         req->handle = handle;
1659         status = wine_server_call( req );
1660     }
1661     SERVER_END_REQ;
1662     if (status) return status;
1663
1664     if (!(status = wine_server_handle_to_fd( handle, 0, &unix_fd, NULL )))
1665     {
1666         struct stat st;
1667         char *mount_point = NULL;
1668
1669         if (fstat( unix_fd, &st ) == -1 || !S_ISBLK(st.st_mode))
1670             status = STATUS_INVALID_PARAMETER;
1671         else
1672         {
1673             if ((mount_point = get_device_mount_point( st.st_rdev )))
1674             {
1675                 static const char umount[] = "umount >/dev/null 2>&1 ";
1676                 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
1677                 if (cmd)
1678                 {
1679                     strcpy( cmd, umount );
1680                     strcat( cmd, mount_point );
1681                     system( cmd );
1682                     RtlFreeHeap( GetProcessHeap(), 0, cmd );
1683 #ifdef linux
1684                     /* umount will fail to release the loop device since we still have
1685                        a handle to it, so we release it here */
1686                     if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
1687 #endif
1688                 }
1689                 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
1690             }
1691         }
1692         wine_server_release_fd( handle, unix_fd );
1693     }
1694     return status;
1695 }
1696
1697
1698 /******************************************************************************
1699  *           DIR_get_unix_cwd
1700  *
1701  * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
1702  * Returned value must be freed by caller.
1703  */
1704 NTSTATUS DIR_get_unix_cwd( char **cwd )
1705 {
1706     int old_cwd, unix_fd;
1707     CURDIR *curdir;
1708     HANDLE handle;
1709     NTSTATUS status;
1710
1711     RtlAcquirePebLock();
1712
1713     if (NtCurrentTeb()->Tib.SubSystemTib)  /* FIXME: hack */
1714         curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
1715     else
1716         curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
1717
1718     if (!(handle = curdir->Handle))
1719     {
1720         UNICODE_STRING dirW;
1721         OBJECT_ATTRIBUTES attr;
1722         IO_STATUS_BLOCK io;
1723
1724         if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
1725         {
1726             status = STATUS_OBJECT_NAME_INVALID;
1727             goto done;
1728         }
1729         attr.Length = sizeof(attr);
1730         attr.RootDirectory = 0;
1731         attr.Attributes = OBJ_CASE_INSENSITIVE;
1732         attr.ObjectName = &dirW;
1733         attr.SecurityDescriptor = NULL;
1734         attr.SecurityQualityOfService = NULL;
1735
1736         status = NtOpenFile( &handle, 0, &attr, &io, 0,
1737                              FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1738         RtlFreeUnicodeString( &dirW );
1739         if (status != STATUS_SUCCESS) goto done;
1740     }
1741
1742     if ((status = wine_server_handle_to_fd( handle, 0, &unix_fd, NULL )) == STATUS_SUCCESS)
1743     {
1744         RtlEnterCriticalSection( &dir_section );
1745
1746         if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
1747         {
1748             unsigned int size = 512;
1749
1750             for (;;)
1751             {
1752                 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1753                 {
1754                     status = STATUS_NO_MEMORY;
1755                     break;
1756                 }
1757                 if (getcwd( *cwd, size )) break;
1758                 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
1759                 if (errno != ERANGE)
1760                 {
1761                     status = STATUS_OBJECT_PATH_INVALID;
1762                     break;
1763                 }
1764                 size *= 2;
1765             }
1766             if (fchdir( old_cwd ) == -1) chdir( "/" );
1767         }
1768         else status = FILE_GetNtStatus();
1769
1770         RtlLeaveCriticalSection( &dir_section );
1771         wine_server_release_fd( handle, unix_fd );
1772     }
1773     if (!curdir->Handle) NtClose( handle );
1774
1775 done:
1776     RtlReleasePebLock();
1777     return status;
1778 }