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