kernel32: Load USERNAME and USERPROFILE from the volatile environment.
[wine] / dlls / kernel32 / volume.c
1 /*
2  * Volume management functions
3  *
4  * Copyright 1993 Erik Bos
5  * Copyright 1996, 2004 Alexandre Julliard
6  * Copyright 1999 Petr Tomasek
7  * Copyright 2000 Andreas Mohr
8  * Copyright 2003 Eric Pouech
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24
25 #include "config.h"
26 #include "wine/port.h"
27
28 #include <stdarg.h>
29 #include <stdlib.h>
30 #include <stdio.h>
31
32 #include "ntstatus.h"
33 #define WIN32_NO_STATUS
34 #include "windef.h"
35 #include "winbase.h"
36 #include "winnls.h"
37 #include "winternl.h"
38 #include "winioctl.h"
39 #include "ntddcdrm.h"
40 #define WINE_MOUNTMGR_EXTENSIONS
41 #include "ddk/mountmgr.h"
42 #include "kernel_private.h"
43 #include "wine/library.h"
44 #include "wine/unicode.h"
45 #include "wine/debug.h"
46
47 WINE_DEFAULT_DEBUG_CHANNEL(volume);
48
49 #define SUPERBLOCK_SIZE 2048
50 #define SYMBOLIC_LINK_QUERY 0x0001
51
52 #define CDFRAMES_PERSEC         75
53 #define CDFRAMES_PERMIN         (CDFRAMES_PERSEC * 60)
54 #define FRAME_OF_ADDR(a)        ((a)[1] * CDFRAMES_PERMIN + (a)[2] * CDFRAMES_PERSEC + (a)[3])
55 #define FRAME_OF_TOC(toc, idx)  FRAME_OF_ADDR((toc)->TrackData[(idx) - (toc)->FirstTrack].Address)
56
57 #define GETWORD(buf,off)  MAKEWORD(buf[(off)],buf[(off+1)])
58 #define GETLONG(buf,off)  MAKELONG(GETWORD(buf,off),GETWORD(buf,off+2))
59
60 enum fs_type
61 {
62     FS_ERROR,    /* error accessing the device */
63     FS_UNKNOWN,  /* unknown file system */
64     FS_FAT1216,
65     FS_FAT32,
66     FS_ISO9660
67 };
68
69 /* read a Unix symlink; returned buffer must be freed by caller */
70 static char *read_symlink( const char *path )
71 {
72     char *buffer;
73     int ret, size = 128;
74
75     for (;;)
76     {
77         if (!(buffer = HeapAlloc( GetProcessHeap(), 0, size )))
78         {
79             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
80             return 0;
81         }
82         ret = readlink( path, buffer, size );
83         if (ret == -1)
84         {
85             FILE_SetDosError();
86             HeapFree( GetProcessHeap(), 0, buffer );
87             return 0;
88         }
89         if (ret != size)
90         {
91             buffer[ret] = 0;
92             return buffer;
93         }
94         HeapFree( GetProcessHeap(), 0, buffer );
95         size *= 2;
96     }
97 }
98
99 /* get the path of a dos device symlink in the $WINEPREFIX/dosdevices directory */
100 static char *get_dos_device_path( LPCWSTR name )
101 {
102     const char *config_dir = wine_get_config_dir();
103     char *buffer, *dev;
104     int i;
105
106     if (!(buffer = HeapAlloc( GetProcessHeap(), 0,
107                               strlen(config_dir) + sizeof("/dosdevices/") + 5 )))
108     {
109         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
110         return NULL;
111     }
112     strcpy( buffer, config_dir );
113     strcat( buffer, "/dosdevices/" );
114     dev = buffer + strlen(buffer);
115     /* no codepage conversion, DOS device names are ASCII anyway */
116     for (i = 0; i < 5; i++)
117         if (!(dev[i] = (char)tolowerW(name[i]))) break;
118     dev[5] = 0;
119     return buffer;
120 }
121
122 /* read the contents of an NT symlink object */
123 static NTSTATUS read_nt_symlink( const WCHAR *name, WCHAR *target, DWORD size )
124 {
125     NTSTATUS status;
126     OBJECT_ATTRIBUTES attr;
127     UNICODE_STRING nameW;
128     HANDLE handle;
129
130     attr.Length = sizeof(attr);
131     attr.RootDirectory = 0;
132     attr.Attributes = OBJ_CASE_INSENSITIVE;
133     attr.ObjectName = &nameW;
134     attr.SecurityDescriptor = NULL;
135     attr.SecurityQualityOfService = NULL;
136     RtlInitUnicodeString( &nameW, name );
137
138     if (!(status = NtOpenSymbolicLinkObject( &handle, SYMBOLIC_LINK_QUERY, &attr )))
139     {
140         UNICODE_STRING targetW;
141         targetW.Buffer = target;
142         targetW.MaximumLength = (size - 1) * sizeof(WCHAR);
143         status = NtQuerySymbolicLinkObject( handle, &targetW, NULL );
144         if (!status) target[targetW.Length / sizeof(WCHAR)] = 0;
145         NtClose( handle );
146     }
147     return status;
148 }
149
150 /* open a handle to a device root */
151 static BOOL open_device_root( LPCWSTR root, HANDLE *handle )
152 {
153     static const WCHAR default_rootW[] = {'\\',0};
154     UNICODE_STRING nt_name;
155     OBJECT_ATTRIBUTES attr;
156     IO_STATUS_BLOCK io;
157     NTSTATUS status;
158
159     if (!root) root = default_rootW;
160     if (!RtlDosPathNameToNtPathName_U( root, &nt_name, NULL, NULL ))
161     {
162         SetLastError( ERROR_PATH_NOT_FOUND );
163         return FALSE;
164     }
165     attr.Length = sizeof(attr);
166     attr.RootDirectory = 0;
167     attr.Attributes = OBJ_CASE_INSENSITIVE;
168     attr.ObjectName = &nt_name;
169     attr.SecurityDescriptor = NULL;
170     attr.SecurityQualityOfService = NULL;
171
172     status = NtOpenFile( handle, 0, &attr, &io, 0,
173                          FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
174     RtlFreeUnicodeString( &nt_name );
175     if (status != STATUS_SUCCESS)
176     {
177         SetLastError( RtlNtStatusToDosError(status) );
178         return FALSE;
179     }
180     return TRUE;
181 }
182
183 /* query the type of a drive from the mount manager */
184 static DWORD get_mountmgr_drive_type( LPCWSTR root )
185 {
186     HANDLE mgr;
187     struct mountmgr_unix_drive data;
188
189     memset( &data, 0, sizeof(data) );
190     if (root) data.letter = root[0];
191     else
192     {
193         WCHAR curdir[MAX_PATH];
194         GetCurrentDirectoryW( MAX_PATH, curdir );
195         if (curdir[1] != ':' || curdir[2] != '\\') return DRIVE_UNKNOWN;
196         data.letter = curdir[0];
197     }
198
199     mgr = CreateFileW( MOUNTMGR_DOS_DEVICE_NAME, GENERIC_READ,
200                        FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0 );
201     if (mgr == INVALID_HANDLE_VALUE) return DRIVE_UNKNOWN;
202
203     if (!DeviceIoControl( mgr, IOCTL_MOUNTMGR_QUERY_UNIX_DRIVE, &data, sizeof(data), &data,
204                           sizeof(data), NULL, NULL ) && GetLastError() != ERROR_MORE_DATA)
205         data.type = DRIVE_UNKNOWN;
206
207     CloseHandle( mgr );
208     return data.type;
209 }
210
211 /* get the label by reading it from a file at the root of the filesystem */
212 static void get_filesystem_label( const WCHAR *device, WCHAR *label, DWORD len )
213 {
214     HANDLE handle;
215     WCHAR labelW[] = {'A',':','\\','.','w','i','n','d','o','w','s','-','l','a','b','e','l',0};
216
217     labelW[0] = device[4];
218     handle = CreateFileW( labelW, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
219                           OPEN_EXISTING, 0, 0 );
220     if (handle != INVALID_HANDLE_VALUE)
221     {
222         char buffer[256], *p;
223         DWORD size;
224
225         if (!ReadFile( handle, buffer, sizeof(buffer)-1, &size, NULL )) size = 0;
226         CloseHandle( handle );
227         p = buffer + size;
228         while (p > buffer && (p[-1] == ' ' || p[-1] == '\r' || p[-1] == '\n')) p--;
229         *p = 0;
230         if (!MultiByteToWideChar( CP_UNIXCP, 0, buffer, -1, label, len ))
231             label[len-1] = 0;
232     }
233     else label[0] = 0;
234 }
235
236 /* get the serial number by reading it from a file at the root of the filesystem */
237 static DWORD get_filesystem_serial( const WCHAR *device )
238 {
239     HANDLE handle;
240     WCHAR serialW[] = {'A',':','\\','.','w','i','n','d','o','w','s','-','s','e','r','i','a','l',0};
241
242     serialW[0] = device[4];
243     handle = CreateFileW( serialW, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
244                           OPEN_EXISTING, 0, 0 );
245     if (handle != INVALID_HANDLE_VALUE)
246     {
247         char buffer[32];
248         DWORD size;
249
250         if (!ReadFile( handle, buffer, sizeof(buffer)-1, &size, NULL )) size = 0;
251         CloseHandle( handle );
252         buffer[size] = 0;
253         return strtoul( buffer, NULL, 16 );
254     }
255     else return 0;
256 }
257
258
259 /******************************************************************
260  *              VOLUME_FindCdRomDataBestVoldesc
261  */
262 static DWORD VOLUME_FindCdRomDataBestVoldesc( HANDLE handle )
263 {
264     BYTE cur_vd_type, max_vd_type = 0;
265     BYTE buffer[0x800];
266     DWORD size, offs, best_offs = 0, extra_offs = 0;
267
268     for (offs = 0x8000; offs <= 0x9800; offs += 0x800)
269     {
270         /* if 'CDROM' occurs at position 8, this is a pre-iso9660 cd, and
271          * the volume label is displaced forward by 8
272          */
273         if (SetFilePointer( handle, offs, NULL, FILE_BEGIN ) != offs) break;
274         if (!ReadFile( handle, buffer, sizeof(buffer), &size, NULL )) break;
275         if (size != sizeof(buffer)) break;
276         /* check for non-ISO9660 signature */
277         if (!memcmp( buffer + 11, "ROM", 3 )) extra_offs = 8;
278         cur_vd_type = buffer[extra_offs];
279         if (cur_vd_type == 0xff) /* voldesc set terminator */
280             break;
281         if (cur_vd_type > max_vd_type)
282         {
283             max_vd_type = cur_vd_type;
284             best_offs = offs + extra_offs;
285         }
286     }
287     return best_offs;
288 }
289
290
291 /***********************************************************************
292  *           VOLUME_ReadFATSuperblock
293  */
294 static enum fs_type VOLUME_ReadFATSuperblock( HANDLE handle, BYTE *buff )
295 {
296     DWORD size;
297
298     /* try a fixed disk, with a FAT partition */
299     if (SetFilePointer( handle, 0, NULL, FILE_BEGIN ) != 0 ||
300         !ReadFile( handle, buff, SUPERBLOCK_SIZE, &size, NULL ))
301     {
302         if (GetLastError() == ERROR_BAD_DEV_TYPE) return FS_UNKNOWN;  /* not a real device */
303         return FS_ERROR;
304     }
305
306     if (size < SUPERBLOCK_SIZE) return FS_UNKNOWN;
307
308     /* FIXME: do really all FAT have their name beginning with
309      * "FAT" ? (At least FAT12, FAT16 and FAT32 have :)
310      */
311     if (!memcmp(buff+0x36, "FAT", 3) || !memcmp(buff+0x52, "FAT", 3))
312     {
313         /* guess which type of FAT we have */
314         int reasonable;
315         unsigned int sectors,
316                      sect_per_fat,
317                      total_sectors,
318                      num_boot_sectors,
319                      num_fats,
320                      num_root_dir_ents,
321                      bytes_per_sector,
322                      sectors_per_cluster,
323                      nclust;
324         sect_per_fat = GETWORD(buff, 0x16);
325         if (!sect_per_fat) sect_per_fat = GETLONG(buff, 0x24);
326         total_sectors = GETWORD(buff, 0x13);
327         if (!total_sectors)
328             total_sectors = GETLONG(buff, 0x20);
329         num_boot_sectors = GETWORD(buff, 0x0e);
330         num_fats =  buff[0x10];
331         num_root_dir_ents = GETWORD(buff, 0x11);
332         bytes_per_sector = GETWORD(buff, 0x0b);
333         sectors_per_cluster = buff[0x0d];
334         /* check if the parameters are reasonable and will not cause
335          * arithmetic errors in the calculation */
336         reasonable = num_boot_sectors < total_sectors &&
337                      num_fats < 16 &&
338                      bytes_per_sector >= 512 && bytes_per_sector % 512 == 0 &&
339                      sectors_per_cluster > 1;
340         if (!reasonable) return FS_UNKNOWN;
341         sectors =  total_sectors - num_boot_sectors - num_fats * sect_per_fat -
342             (num_root_dir_ents * 32 + bytes_per_sector - 1) / bytes_per_sector;
343         nclust = sectors / sectors_per_cluster;
344         if ((buff[0x42] == 0x28 || buff[0x42] == 0x29) &&
345                 !memcmp(buff+0x52, "FAT", 3)) return FS_FAT32;
346         if (nclust < 65525)
347         {
348             if ((buff[0x26] == 0x28 || buff[0x26] == 0x29) &&
349                     !memcmp(buff+0x36, "FAT", 3))
350                 return FS_FAT1216;
351         }
352     }
353     return FS_UNKNOWN;
354 }
355
356
357 /***********************************************************************
358  *           VOLUME_ReadCDSuperblock
359  */
360 static enum fs_type VOLUME_ReadCDSuperblock( HANDLE handle, BYTE *buff )
361 {
362     DWORD size, offs = VOLUME_FindCdRomDataBestVoldesc( handle );
363
364     if (!offs) return FS_UNKNOWN;
365
366     if (SetFilePointer( handle, offs, NULL, FILE_BEGIN ) != offs ||
367         !ReadFile( handle, buff, SUPERBLOCK_SIZE, &size, NULL ) ||
368         size != SUPERBLOCK_SIZE)
369         return FS_ERROR;
370
371     /* check for iso9660 present */
372     if (!memcmp(&buff[1], "CD001", 5)) return FS_ISO9660;
373     return FS_UNKNOWN;
374 }
375
376
377 /**************************************************************************
378  *                              VOLUME_GetSuperblockLabel
379  */
380 static void VOLUME_GetSuperblockLabel( const WCHAR *device, enum fs_type type, const BYTE *superblock,
381                                        WCHAR *label, DWORD len )
382 {
383     const BYTE *label_ptr = NULL;
384     DWORD label_len;
385
386     switch(type)
387     {
388     case FS_ERROR:
389         label_len = 0;
390         break;
391     case FS_UNKNOWN:
392         get_filesystem_label( device, label, len );
393         return;
394     case FS_FAT1216:
395         label_ptr = superblock + 0x2b;
396         label_len = 11;
397         break;
398     case FS_FAT32:
399         label_ptr = superblock + 0x47;
400         label_len = 11;
401         break;
402     case FS_ISO9660:
403         {
404             BYTE ver = superblock[0x5a];
405
406             if (superblock[0x58] == 0x25 && superblock[0x59] == 0x2f &&  /* Unicode ID */
407                 ((ver == 0x40) || (ver == 0x43) || (ver == 0x45)))
408             { /* yippee, unicode */
409                 unsigned int i;
410
411                 if (len > 17) len = 17;
412                 for (i = 0; i < len-1; i++)
413                     label[i] = (superblock[40+2*i] << 8) | superblock[41+2*i];
414                 label[i] = 0;
415                 while (i && label[i-1] == ' ') label[--i] = 0;
416                 return;
417             }
418             label_ptr = superblock + 40;
419             label_len = 32;
420             break;
421         }
422     }
423     if (label_len) RtlMultiByteToUnicodeN( label, (len-1) * sizeof(WCHAR),
424                                            &label_len, (LPCSTR)label_ptr, label_len );
425     label_len /= sizeof(WCHAR);
426     label[label_len] = 0;
427     while (label_len && label[label_len-1] == ' ') label[--label_len] = 0;
428 }
429
430
431 /**************************************************************************
432  *                              VOLUME_GetSuperblockSerial
433  */
434 static DWORD VOLUME_GetSuperblockSerial( const WCHAR *device, enum fs_type type, const BYTE *superblock )
435 {
436     switch(type)
437     {
438     case FS_ERROR:
439         break;
440     case FS_UNKNOWN:
441         return get_filesystem_serial( device );
442     case FS_FAT1216:
443         return GETLONG( superblock, 0x27 );
444     case FS_FAT32:
445         return GETLONG( superblock, 0x33 );
446     case FS_ISO9660:
447         {
448             BYTE sum[4];
449             int i;
450
451             sum[0] = sum[1] = sum[2] = sum[3] = 0;
452             for (i = 0; i < 2048; i += 4)
453             {
454                 /* DON'T optimize this into DWORD !! (breaks overflow) */
455                 sum[0] += superblock[i+0];
456                 sum[1] += superblock[i+1];
457                 sum[2] += superblock[i+2];
458                 sum[3] += superblock[i+3];
459             }
460             /*
461              * OK, another braindead one... argh. Just believe it.
462              * Me$$ysoft chose to reverse the serial number in NT4/W2K.
463              * It's true and nobody will ever be able to change it.
464              */
465             if (GetVersion() & 0x80000000)
466                 return (sum[3] << 24) | (sum[2] << 16) | (sum[1] << 8) | sum[0];
467             else
468                 return (sum[0] << 24) | (sum[1] << 16) | (sum[2] << 8) | sum[3];
469         }
470     }
471     return 0;
472 }
473
474
475 /**************************************************************************
476  *                              VOLUME_GetAudioCDSerial
477  */
478 static DWORD VOLUME_GetAudioCDSerial( const CDROM_TOC *toc )
479 {
480     DWORD serial = 0;
481     int i;
482
483     for (i = 0; i <= toc->LastTrack - toc->FirstTrack; i++)
484         serial += ((toc->TrackData[i].Address[1] << 16) |
485                    (toc->TrackData[i].Address[2] << 8) |
486                    toc->TrackData[i].Address[3]);
487
488     /*
489      * dwStart, dwEnd collect the beginning and end of the disc respectively, in
490      * frames.
491      * There it is collected for correcting the serial when there are less than
492      * 3 tracks.
493      */
494     if (toc->LastTrack - toc->FirstTrack + 1 < 3)
495     {
496         DWORD dwStart = FRAME_OF_TOC(toc, toc->FirstTrack);
497         DWORD dwEnd = FRAME_OF_TOC(toc, toc->LastTrack + 1);
498         serial += dwEnd - dwStart;
499     }
500     return serial;
501 }
502
503
504 /***********************************************************************
505  *           GetVolumeInformationW   (KERNEL32.@)
506  */
507 BOOL WINAPI GetVolumeInformationW( LPCWSTR root, LPWSTR label, DWORD label_len,
508                                    DWORD *serial, DWORD *filename_len, DWORD *flags,
509                                    LPWSTR fsname, DWORD fsname_len )
510 {
511     static const WCHAR audiocdW[] = {'A','u','d','i','o',' ','C','D',0};
512     static const WCHAR fatW[] = {'F','A','T',0};
513     static const WCHAR fat32W[] = {'F','A','T','3','2',0};
514     static const WCHAR ntfsW[] = {'N','T','F','S',0};
515     static const WCHAR cdfsW[] = {'C','D','F','S',0};
516
517     WCHAR device[] = {'\\','\\','.','\\','A',':',0};
518     HANDLE handle;
519     enum fs_type type = FS_UNKNOWN;
520
521     if (!root)
522     {
523         WCHAR path[MAX_PATH];
524         GetCurrentDirectoryW( MAX_PATH, path );
525         device[4] = path[0];
526     }
527     else
528     {
529         if (!root[0] || root[1] != ':' || root[lstrlenW(root)-1] != '\\' )
530         {
531             SetLastError( ERROR_INVALID_NAME );
532             return FALSE;
533         }
534         device[4] = root[0];
535     }
536
537     /* try to open the device */
538
539     handle = CreateFileW( device, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE,
540                           NULL, OPEN_EXISTING, 0, 0 );
541     if (handle != INVALID_HANDLE_VALUE)
542     {
543         BYTE superblock[SUPERBLOCK_SIZE];
544         CDROM_TOC toc;
545         DWORD br;
546
547         /* check for audio CD */
548         /* FIXME: we only check the first track for now */
549         if (DeviceIoControl( handle, IOCTL_CDROM_READ_TOC, NULL, 0, &toc, sizeof(toc), &br, 0 ))
550         {
551             if (!(toc.TrackData[0].Control & 0x04))  /* audio track */
552             {
553                 TRACE( "%s: found audio CD\n", debugstr_w(device) );
554                 if (label) lstrcpynW( label, audiocdW, label_len );
555                 if (serial) *serial = VOLUME_GetAudioCDSerial( &toc );
556                 CloseHandle( handle );
557                 type = FS_ISO9660;
558                 goto fill_fs_info;
559             }
560             type = VOLUME_ReadCDSuperblock( handle, superblock );
561         }
562         else
563         {
564             type = VOLUME_ReadFATSuperblock( handle, superblock );
565             if (type == FS_UNKNOWN) type = VOLUME_ReadCDSuperblock( handle, superblock );
566         }
567         CloseHandle( handle );
568         TRACE( "%s: found fs type %d\n", debugstr_w(device), type );
569         if (type == FS_ERROR) return FALSE;
570
571         if (label && label_len) VOLUME_GetSuperblockLabel( device, type, superblock, label, label_len );
572         if (serial) *serial = VOLUME_GetSuperblockSerial( device, type, superblock );
573         goto fill_fs_info;
574     }
575     else TRACE( "cannot open device %s: err %d\n", debugstr_w(device), GetLastError() );
576
577     /* we couldn't open the device, fallback to default strategy */
578
579     switch(GetDriveTypeW( root ))
580     {
581     case DRIVE_UNKNOWN:
582     case DRIVE_NO_ROOT_DIR:
583         SetLastError( ERROR_NOT_READY );
584         return FALSE;
585     case DRIVE_REMOVABLE:
586     case DRIVE_FIXED:
587     case DRIVE_REMOTE:
588     case DRIVE_RAMDISK:
589         type = FS_UNKNOWN;
590         break;
591     case DRIVE_CDROM:
592         type = FS_ISO9660;
593         break;
594     }
595
596     if (label && label_len) get_filesystem_label( device, label, label_len );
597     if (serial) *serial = get_filesystem_serial( device );
598
599 fill_fs_info:  /* now fill in the information that depends on the file system type */
600
601     switch(type)
602     {
603     case FS_ISO9660:
604         if (fsname) lstrcpynW( fsname, cdfsW, fsname_len );
605         if (filename_len) *filename_len = 221;
606         if (flags) *flags = FILE_READ_ONLY_VOLUME;
607         break;
608     case FS_FAT1216:
609         if (fsname) lstrcpynW( fsname, fatW, fsname_len );
610     case FS_FAT32:
611         if (type == FS_FAT32 && fsname) lstrcpynW( fsname, fat32W, fsname_len );
612         if (filename_len) *filename_len = 255;
613         if (flags) *flags = FILE_CASE_PRESERVED_NAMES;  /* FIXME */
614         break;
615     default:
616         if (fsname) lstrcpynW( fsname, ntfsW, fsname_len );
617         if (filename_len) *filename_len = 255;
618         if (flags) *flags = FILE_CASE_PRESERVED_NAMES;
619         break;
620     }
621     return TRUE;
622 }
623
624
625 /***********************************************************************
626  *           GetVolumeInformationA   (KERNEL32.@)
627  */
628 BOOL WINAPI GetVolumeInformationA( LPCSTR root, LPSTR label,
629                                    DWORD label_len, DWORD *serial,
630                                    DWORD *filename_len, DWORD *flags,
631                                    LPSTR fsname, DWORD fsname_len )
632 {
633     WCHAR *rootW = NULL;
634     LPWSTR labelW, fsnameW;
635     BOOL ret;
636
637     if (root && !(rootW = FILE_name_AtoW( root, FALSE ))) return FALSE;
638
639     labelW = label ? HeapAlloc(GetProcessHeap(), 0, label_len * sizeof(WCHAR)) : NULL;
640     fsnameW = fsname ? HeapAlloc(GetProcessHeap(), 0, fsname_len * sizeof(WCHAR)) : NULL;
641
642     if ((ret = GetVolumeInformationW(rootW, labelW, label_len, serial,
643                                     filename_len, flags, fsnameW, fsname_len)))
644     {
645         if (label) FILE_name_WtoA( labelW, -1, label, label_len );
646         if (fsname) FILE_name_WtoA( fsnameW, -1, fsname, fsname_len );
647     }
648
649     HeapFree( GetProcessHeap(), 0, labelW );
650     HeapFree( GetProcessHeap(), 0, fsnameW );
651     return ret;
652 }
653
654
655
656 /***********************************************************************
657  *           SetVolumeLabelW   (KERNEL32.@)
658  */
659 BOOL WINAPI SetVolumeLabelW( LPCWSTR root, LPCWSTR label )
660 {
661     WCHAR device[] = {'\\','\\','.','\\','A',':',0};
662     HANDLE handle;
663     enum fs_type type = FS_UNKNOWN;
664
665     if (!root)
666     {
667         WCHAR path[MAX_PATH];
668         GetCurrentDirectoryW( MAX_PATH, path );
669         device[4] = path[0];
670     }
671     else
672     {
673         if (!root[0] || root[1] != ':')
674         {
675             SetLastError( ERROR_INVALID_NAME );
676             return FALSE;
677         }
678         device[4] = root[0];
679     }
680
681     /* try to open the device */
682
683     handle = CreateFileW( device, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE,
684                           NULL, OPEN_EXISTING, 0, 0 );
685     if (handle != INVALID_HANDLE_VALUE)
686     {
687         BYTE superblock[SUPERBLOCK_SIZE];
688
689         type = VOLUME_ReadFATSuperblock( handle, superblock );
690         if (type == FS_UNKNOWN) type = VOLUME_ReadCDSuperblock( handle, superblock );
691         CloseHandle( handle );
692         if (type != FS_UNKNOWN)
693         {
694             /* we can't set the label on FAT or CDROM file systems */
695             TRACE( "cannot set label on device %s type %d\n", debugstr_w(device), type );
696             SetLastError( ERROR_ACCESS_DENIED );
697             return FALSE;
698         }
699     }
700     else
701     {
702         TRACE( "cannot open device %s: err %d\n", debugstr_w(device), GetLastError() );
703         if (GetLastError() == ERROR_ACCESS_DENIED) return FALSE;
704     }
705
706     /* we couldn't open the device, fallback to default strategy */
707
708     switch(GetDriveTypeW( root ))
709     {
710     case DRIVE_UNKNOWN:
711     case DRIVE_NO_ROOT_DIR:
712         SetLastError( ERROR_NOT_READY );
713         break;
714     case DRIVE_REMOVABLE:
715     case DRIVE_FIXED:
716         {
717             WCHAR labelW[] = {'A',':','\\','.','w','i','n','d','o','w','s','-','l','a','b','e','l',0};
718
719             labelW[0] = device[4];
720
721             if (!label[0])  /* delete label file when setting an empty label */
722                 return DeleteFileW( labelW ) || GetLastError() == ERROR_FILE_NOT_FOUND;
723
724             handle = CreateFileW( labelW, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
725                                   CREATE_ALWAYS, 0, 0 );
726             if (handle != INVALID_HANDLE_VALUE)
727             {
728                 char buffer[64];
729                 DWORD size;
730
731                 if (!WideCharToMultiByte( CP_UNIXCP, 0, label, -1, buffer, sizeof(buffer)-1, NULL, NULL ))
732                     buffer[sizeof(buffer)-2] = 0;
733                 strcat( buffer, "\n" );
734                 WriteFile( handle, buffer, strlen(buffer), &size, NULL );
735                 CloseHandle( handle );
736                 return TRUE;
737             }
738             break;
739         }
740     case DRIVE_REMOTE:
741     case DRIVE_RAMDISK:
742     case DRIVE_CDROM:
743         SetLastError( ERROR_ACCESS_DENIED );
744         break;
745     }
746     return FALSE;
747 }
748
749 /***********************************************************************
750  *           SetVolumeLabelA   (KERNEL32.@)
751  */
752 BOOL WINAPI SetVolumeLabelA(LPCSTR root, LPCSTR volname)
753 {
754     WCHAR *rootW = NULL, *volnameW = NULL;
755     BOOL ret;
756
757     if (root && !(rootW = FILE_name_AtoW( root, FALSE ))) return FALSE;
758     if (volname && !(volnameW = FILE_name_AtoW( volname, TRUE ))) return FALSE;
759     ret = SetVolumeLabelW( rootW, volnameW );
760     HeapFree( GetProcessHeap(), 0, volnameW );
761     return ret;
762 }
763
764
765 /***********************************************************************
766  *           GetVolumeNameForVolumeMountPointA   (KERNEL32.@)
767  */
768 BOOL WINAPI GetVolumeNameForVolumeMountPointA( LPCSTR path, LPSTR volume, DWORD size )
769 {
770     BOOL ret;
771     WCHAR volumeW[50], *pathW = NULL;
772     DWORD len = min( sizeof(volumeW) / sizeof(WCHAR), size );
773
774     TRACE("(%s, %p, %x)\n", debugstr_a(path), volume, size);
775
776     if (!path || !(pathW = FILE_name_AtoW( path, TRUE )))
777         return FALSE;
778
779     if ((ret = GetVolumeNameForVolumeMountPointW( pathW, volumeW, len )))
780         FILE_name_WtoA( volumeW, -1, volume, len );
781
782     HeapFree( GetProcessHeap(), 0, pathW );
783     return ret;
784 }
785
786 /***********************************************************************
787  *           GetVolumeNameForVolumeMountPointW   (KERNEL32.@)
788  */
789 BOOL WINAPI GetVolumeNameForVolumeMountPointW( LPCWSTR path, LPWSTR volume, DWORD size )
790 {
791     static const WCHAR prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\',0};
792     static const WCHAR volumeW[] = {'\\','?','?','\\','V','o','l','u','m','e','{',0};
793     static const WCHAR trailingW[] = {'\\',0};
794
795     MOUNTMGR_MOUNT_POINT *input = NULL, *o1;
796     MOUNTMGR_MOUNT_POINTS *output = NULL;
797     WCHAR *p;
798     char *r;
799     DWORD i, i_size = 1024, o_size = 1024;
800     WCHAR *nonpersist_name;
801     WCHAR symlink_name[MAX_PATH];
802     NTSTATUS status;
803     HANDLE mgr = INVALID_HANDLE_VALUE;
804     BOOL ret = FALSE;
805
806     TRACE("(%s, %p, %x)\n", debugstr_w(path), volume, size);
807     if (path[lstrlenW(path)-1] != '\\')
808     {
809         SetLastError( ERROR_INVALID_NAME );
810         return FALSE;
811     }
812
813     if (size < 50)
814     {
815         SetLastError( ERROR_FILENAME_EXCED_RANGE );
816         return FALSE;
817     }
818     /* if length of input is > 3 then it must be a mounted folder */
819     if (lstrlenW(path) > 3)
820     {
821         FIXME("Mounted Folders are not yet supported\n");
822         SetLastError( ERROR_NOT_A_REPARSE_POINT );
823         return FALSE;
824     }
825
826     mgr = CreateFileW( MOUNTMGR_DOS_DEVICE_NAME, 0, FILE_SHARE_READ,
827                         NULL, OPEN_EXISTING, 0, 0 );
828     if (mgr == INVALID_HANDLE_VALUE) return FALSE;
829
830     if (!(input = HeapAlloc( GetProcessHeap(), 0, i_size )))
831     {
832         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
833         goto err_ret;
834     }
835
836     if (!(output = HeapAlloc( GetProcessHeap(), 0, o_size )))
837     {
838         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
839         goto err_ret;
840     }
841
842     /* construct the symlink name as "\DosDevices\C:" */
843     lstrcpyW( symlink_name, prefixW );
844     lstrcatW( symlink_name, path );
845     symlink_name[lstrlenW(symlink_name)-1] = 0;
846
847     /* Take the mount point and get the "nonpersistent name" */
848     /* We will then take that and get the volume name        */
849     nonpersist_name = (WCHAR *)(input + 1);
850     status = read_nt_symlink( symlink_name, nonpersist_name, i_size - sizeof(*input) );
851     TRACE("read_nt_symlink got stat=%x, for %s, got <%s>\n", status,
852             debugstr_w(symlink_name), debugstr_w(nonpersist_name));
853     if (status != STATUS_SUCCESS)
854     {
855         SetLastError( ERROR_FILE_NOT_FOUND );
856         goto err_ret;
857     }
858
859     /* Now take the "nonpersistent name" and ask the mountmgr  */
860     /* to give us all the mount points.  One of them will be   */
861     /* the volume name  (format of \??\Volume{).               */
862     memset( input, 0, sizeof(*input) );  /* clear all input parameters */
863     input->DeviceNameOffset = sizeof(*input);
864     input->DeviceNameLength = lstrlenW( nonpersist_name) * sizeof(WCHAR);
865     i_size = input->DeviceNameOffset + input->DeviceNameLength;
866
867     output->Size = o_size;
868
869     /* now get the true volume name from the mountmgr   */
870     if (!DeviceIoControl( mgr, IOCTL_MOUNTMGR_QUERY_POINTS, input, i_size,
871                         output, o_size, NULL, NULL ))
872         goto err_ret;
873
874     /* Verify and return the data, note string is not null terminated  */
875     TRACE("found %d matching mount points\n", output->NumberOfMountPoints);
876     if (output->NumberOfMountPoints < 1)
877     {
878         SetLastError( ERROR_NO_VOLUME_ID );
879         goto err_ret;
880     }
881     o1 = &output->MountPoints[0];
882
883     /* look for the volume name in returned values  */
884     for(i=0;i<output->NumberOfMountPoints;i++)
885     {
886         p = (WCHAR*)((char *)output + o1->SymbolicLinkNameOffset);
887         r = (char *)output + o1->UniqueIdOffset;
888         TRACE("found symlink=%s, unique=%s, devname=%s\n",
889             debugstr_wn(p, o1->SymbolicLinkNameLength/sizeof(WCHAR)),
890             debugstr_an(r, o1->UniqueIdLength),
891             debugstr_wn((WCHAR*)((char *)output + o1->DeviceNameOffset),
892                             o1->DeviceNameLength/sizeof(WCHAR)));
893
894         if (!strncmpW( p, volumeW, (sizeof(volumeW)-1)/sizeof(WCHAR) ))
895         {
896             /* is there space in the return variable ?? */
897             if ((o1->SymbolicLinkNameLength/sizeof(WCHAR))+2 > size)
898             {
899                 SetLastError( ERROR_FILENAME_EXCED_RANGE );
900                 goto err_ret;
901             }
902             memcpy( volume, p, o1->SymbolicLinkNameLength );
903             volume[o1->SymbolicLinkNameLength / sizeof(WCHAR)] = 0;
904             lstrcatW( volume, trailingW );
905             /* change second char from '?' to '\'  */
906             volume[1] = '\\';
907             ret = TRUE;
908             break;
909         }
910         o1++;
911     }
912
913 err_ret:
914     HeapFree( GetProcessHeap(), 0, input );
915     HeapFree( GetProcessHeap(), 0, output );
916     CloseHandle( mgr );
917     return ret;
918 }
919
920 /***********************************************************************
921  *           DefineDosDeviceW       (KERNEL32.@)
922  */
923 BOOL WINAPI DefineDosDeviceW( DWORD flags, LPCWSTR devname, LPCWSTR targetpath )
924 {
925     DWORD len, dosdev;
926     BOOL ret = FALSE;
927     char *path = NULL, *target, *p;
928
929     TRACE("%x, %s, %s\n", flags, debugstr_w(devname), debugstr_w(targetpath));
930
931     if (!(flags & DDD_REMOVE_DEFINITION))
932     {
933         if (!(flags & DDD_RAW_TARGET_PATH))
934         {
935             FIXME( "(0x%08x,%s,%s) DDD_RAW_TARGET_PATH flag not set, not supported yet\n",
936                    flags, debugstr_w(devname), debugstr_w(targetpath) );
937             SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
938             return FALSE;
939         }
940
941         len = WideCharToMultiByte( CP_UNIXCP, 0, targetpath, -1, NULL, 0, NULL, NULL );
942         if ((target = HeapAlloc( GetProcessHeap(), 0, len )))
943         {
944             WideCharToMultiByte( CP_UNIXCP, 0, targetpath, -1, target, len, NULL, NULL );
945             for (p = target; *p; p++) if (*p == '\\') *p = '/';
946         }
947         else
948         {
949             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
950             return FALSE;
951         }
952     }
953     else target = NULL;
954
955     /* first check for a DOS device */
956
957     if ((dosdev = RtlIsDosDeviceName_U( devname )))
958     {
959         WCHAR name[5];
960
961         memcpy( name, devname + HIWORD(dosdev)/sizeof(WCHAR), LOWORD(dosdev) );
962         name[LOWORD(dosdev)/sizeof(WCHAR)] = 0;
963         path = get_dos_device_path( name );
964     }
965     else if (isalphaW(devname[0]) && devname[1] == ':' && !devname[2])  /* drive mapping */
966     {
967         path = get_dos_device_path( devname );
968     }
969     else SetLastError( ERROR_FILE_NOT_FOUND );
970
971     if (path)
972     {
973         if (target)
974         {
975             TRACE( "creating symlink %s -> %s\n", path, target );
976             unlink( path );
977             if (!symlink( target, path )) ret = TRUE;
978             else FILE_SetDosError();
979         }
980         else
981         {
982             TRACE( "removing symlink %s\n", path );
983             if (!unlink( path )) ret = TRUE;
984             else FILE_SetDosError();
985         }
986         HeapFree( GetProcessHeap(), 0, path );
987     }
988     HeapFree( GetProcessHeap(), 0, target );
989     return ret;
990 }
991
992
993 /***********************************************************************
994  *           DefineDosDeviceA       (KERNEL32.@)
995  */
996 BOOL WINAPI DefineDosDeviceA(DWORD flags, LPCSTR devname, LPCSTR targetpath)
997 {
998     WCHAR *devW, *targetW = NULL;
999     BOOL ret;
1000
1001     if (!(devW = FILE_name_AtoW( devname, FALSE ))) return FALSE;
1002     if (targetpath && !(targetW = FILE_name_AtoW( targetpath, TRUE ))) return FALSE;
1003     ret = DefineDosDeviceW(flags, devW, targetW);
1004     HeapFree( GetProcessHeap(), 0, targetW );
1005     return ret;
1006 }
1007
1008
1009 /***********************************************************************
1010  *           QueryDosDeviceW   (KERNEL32.@)
1011  *
1012  * returns array of strings terminated by \0, terminated by \0
1013  */
1014 DWORD WINAPI QueryDosDeviceW( LPCWSTR devname, LPWSTR target, DWORD bufsize )
1015 {
1016     static const WCHAR auxW[] = {'A','U','X',0};
1017     static const WCHAR nulW[] = {'N','U','L',0};
1018     static const WCHAR prnW[] = {'P','R','N',0};
1019     static const WCHAR comW[] = {'C','O','M',0};
1020     static const WCHAR lptW[] = {'L','P','T',0};
1021     static const WCHAR com0W[] = {'\\','?','?','\\','C','O','M','0',0};
1022     static const WCHAR com1W[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\','C','O','M','1',0,0};
1023     static const WCHAR lpt1W[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\','L','P','T','1',0,0};
1024     static const WCHAR dosdevW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\',0};
1025
1026     UNICODE_STRING nt_name;
1027     ANSI_STRING unix_name;
1028     WCHAR nt_buffer[10];
1029     NTSTATUS status;
1030
1031     if (!bufsize)
1032     {
1033         SetLastError( ERROR_INSUFFICIENT_BUFFER );
1034         return 0;
1035     }
1036
1037     if (devname)
1038     {
1039         WCHAR *p, name[5];
1040         char *path, *link;
1041         DWORD dosdev, ret = 0;
1042
1043         if ((dosdev = RtlIsDosDeviceName_U( devname )))
1044         {
1045             memcpy( name, devname + HIWORD(dosdev)/sizeof(WCHAR), LOWORD(dosdev) );
1046             name[LOWORD(dosdev)/sizeof(WCHAR)] = 0;
1047         }
1048         else
1049         {
1050             NTSTATUS status;
1051             WCHAR *buffer;
1052
1053             if (!(buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(dosdevW) + strlenW(devname)*sizeof(WCHAR) )))
1054             {
1055                 SetLastError( ERROR_OUTOFMEMORY );
1056                 return 0;
1057             }
1058             memcpy( buffer, dosdevW, sizeof(dosdevW) );
1059             strcatW( buffer, devname );
1060             status = read_nt_symlink( buffer, target, bufsize );
1061             HeapFree( GetProcessHeap(), 0, buffer );
1062             if (status)
1063             {
1064                 SetLastError( RtlNtStatusToDosError(status) );
1065                 return 0;
1066             }
1067             ret = strlenW( target ) + 1;
1068             goto done;
1069         }
1070
1071         /* FIXME: should read NT symlink for all devices */
1072
1073         if (!(path = get_dos_device_path( name ))) return 0;
1074         link = read_symlink( path );
1075         HeapFree( GetProcessHeap(), 0, path );
1076
1077         if (link)
1078         {
1079             ret = MultiByteToWideChar( CP_UNIXCP, 0, link, -1, target, bufsize );
1080             HeapFree( GetProcessHeap(), 0, link );
1081         }
1082         else if (dosdev)  /* look for device defaults */
1083         {
1084             if (!strcmpiW( name, auxW ))
1085             {
1086                 if (bufsize >= sizeof(com1W)/sizeof(WCHAR))
1087                 {
1088                     memcpy( target, com1W, sizeof(com1W) );
1089                     ret = sizeof(com1W)/sizeof(WCHAR);
1090                 }
1091                 else SetLastError( ERROR_INSUFFICIENT_BUFFER );
1092                 return ret;
1093             }
1094             if (!strcmpiW( name, prnW ))
1095             {
1096                 if (bufsize >= sizeof(lpt1W)/sizeof(WCHAR))
1097                 {
1098                     memcpy( target, lpt1W, sizeof(lpt1W) );
1099                     ret = sizeof(lpt1W)/sizeof(WCHAR);
1100                 }
1101                 else SetLastError( ERROR_INSUFFICIENT_BUFFER );
1102                 return ret;
1103             }
1104
1105             nt_buffer[0] = '\\';
1106             nt_buffer[1] = '?';
1107             nt_buffer[2] = '?';
1108             nt_buffer[3] = '\\';
1109             strcpyW( nt_buffer + 4, name );
1110             RtlInitUnicodeString( &nt_name, nt_buffer );
1111             status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, TRUE );
1112             if (status) SetLastError( RtlNtStatusToDosError(status) );
1113             else
1114             {
1115                 ret = MultiByteToWideChar( CP_UNIXCP, 0, unix_name.Buffer, -1, target, bufsize );
1116                 RtlFreeAnsiString( &unix_name );
1117             }
1118         }
1119     done:
1120         if (ret)
1121         {
1122             if (ret < bufsize) target[ret++] = 0;  /* add an extra null */
1123             for (p = target; *p; p++) if (*p == '/') *p = '\\';
1124         }
1125
1126         return ret;
1127     }
1128     else  /* return a list of all devices */
1129     {
1130         OBJECT_ATTRIBUTES attr;
1131         HANDLE handle;
1132         WCHAR *p = target;
1133         int i;
1134
1135         if (bufsize <= (sizeof(auxW)+sizeof(nulW)+sizeof(prnW))/sizeof(WCHAR))
1136         {
1137             SetLastError( ERROR_INSUFFICIENT_BUFFER );
1138             return 0;
1139         }
1140
1141         /* FIXME: these should be NT symlinks too */
1142
1143         memcpy( p, auxW, sizeof(auxW) );
1144         p += sizeof(auxW) / sizeof(WCHAR);
1145         memcpy( p, nulW, sizeof(nulW) );
1146         p += sizeof(nulW) / sizeof(WCHAR);
1147         memcpy( p, prnW, sizeof(prnW) );
1148         p += sizeof(prnW) / sizeof(WCHAR);
1149
1150         strcpyW( nt_buffer, com0W );
1151         RtlInitUnicodeString( &nt_name, nt_buffer );
1152
1153         for (i = 1; i <= 9; i++)
1154         {
1155             nt_buffer[7] = '0' + i;
1156             if (!wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, TRUE ))
1157             {
1158                 RtlFreeAnsiString( &unix_name );
1159                 if (p + 5 >= target + bufsize)
1160                 {
1161                     SetLastError( ERROR_INSUFFICIENT_BUFFER );
1162                     return 0;
1163                 }
1164                 strcpyW( p, comW );
1165                 p[3] = '0' + i;
1166                 p[4] = 0;
1167                 p += 5;
1168             }
1169         }
1170         strcpyW( nt_buffer + 4, lptW );
1171         for (i = 1; i <= 9; i++)
1172         {
1173             nt_buffer[7] = '0' + i;
1174             if (!wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, TRUE ))
1175             {
1176                 RtlFreeAnsiString( &unix_name );
1177                 if (p + 5 >= target + bufsize)
1178                 {
1179                     SetLastError( ERROR_INSUFFICIENT_BUFFER );
1180                     return 0;
1181                 }
1182                 strcpyW( p, lptW );
1183                 p[3] = '0' + i;
1184                 p[4] = 0;
1185                 p += 5;
1186             }
1187         }
1188
1189         RtlInitUnicodeString( &nt_name, dosdevW );
1190         nt_name.Length -= sizeof(WCHAR);  /* without trailing slash */
1191         attr.Length = sizeof(attr);
1192         attr.RootDirectory = 0;
1193         attr.ObjectName = &nt_name;
1194         attr.Attributes = OBJ_CASE_INSENSITIVE;
1195         attr.SecurityDescriptor = NULL;
1196         attr.SecurityQualityOfService = NULL;
1197         status = NtOpenDirectoryObject( &handle, FILE_LIST_DIRECTORY, &attr );
1198         if (!status)
1199         {
1200             char data[1024];
1201             DIRECTORY_BASIC_INFORMATION *info = (DIRECTORY_BASIC_INFORMATION *)data;
1202             ULONG ctx = 0, len;
1203
1204             while (!NtQueryDirectoryObject( handle, info, sizeof(data), 1, 0, &ctx, &len ))
1205             {
1206                 if (p + info->ObjectName.Length/sizeof(WCHAR) + 1 >= target + bufsize)
1207                 {
1208                     SetLastError( ERROR_INSUFFICIENT_BUFFER );
1209                     NtClose( handle );
1210                     return 0;
1211                 }
1212                 memcpy( p, info->ObjectName.Buffer, info->ObjectName.Length );
1213                 p += info->ObjectName.Length/sizeof(WCHAR);
1214                 *p++ = 0;
1215             }
1216             NtClose( handle );
1217         }
1218
1219         *p++ = 0;  /* terminating null */
1220         return p - target;
1221     }
1222 }
1223
1224
1225 /***********************************************************************
1226  *           QueryDosDeviceA   (KERNEL32.@)
1227  *
1228  * returns array of strings terminated by \0, terminated by \0
1229  */
1230 DWORD WINAPI QueryDosDeviceA( LPCSTR devname, LPSTR target, DWORD bufsize )
1231 {
1232     DWORD ret = 0, retW;
1233     WCHAR *devnameW = NULL;
1234     LPWSTR targetW;
1235
1236     if (devname && !(devnameW = FILE_name_AtoW( devname, FALSE ))) return 0;
1237
1238     targetW = HeapAlloc( GetProcessHeap(),0, bufsize * sizeof(WCHAR) );
1239     if (!targetW)
1240     {
1241         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1242         return 0;
1243     }
1244
1245     retW = QueryDosDeviceW(devnameW, targetW, bufsize);
1246
1247     ret = FILE_name_WtoA( targetW, retW, target, bufsize );
1248
1249     HeapFree(GetProcessHeap(), 0, targetW);
1250     return ret;
1251 }
1252
1253
1254 /***********************************************************************
1255  *           GetLogicalDrives   (KERNEL32.@)
1256  */
1257 DWORD WINAPI GetLogicalDrives(void)
1258 {
1259     const char *config_dir = wine_get_config_dir();
1260     struct stat st;
1261     char *buffer, *dev;
1262     DWORD ret = 0;
1263     int i;
1264
1265     if (!(buffer = HeapAlloc( GetProcessHeap(), 0, strlen(config_dir) + sizeof("/dosdevices/a:") )))
1266     {
1267         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1268         return 0;
1269     }
1270     strcpy( buffer, config_dir );
1271     strcat( buffer, "/dosdevices/a:" );
1272     dev = buffer + strlen(buffer) - 2;
1273
1274     for (i = 0; i < 26; i++)
1275     {
1276         *dev = 'a' + i;
1277         if (!stat( buffer, &st )) ret |= (1 << i);
1278     }
1279     HeapFree( GetProcessHeap(), 0, buffer );
1280     return ret;
1281 }
1282
1283
1284 /***********************************************************************
1285  *           GetLogicalDriveStringsA   (KERNEL32.@)
1286  */
1287 UINT WINAPI GetLogicalDriveStringsA( UINT len, LPSTR buffer )
1288 {
1289     DWORD drives = GetLogicalDrives();
1290     UINT drive, count;
1291
1292     for (drive = count = 0; drive < 26; drive++) if (drives & (1 << drive)) count++;
1293     if ((count * 4) + 1 > len) return count * 4 + 1;
1294
1295     for (drive = 0; drive < 26; drive++)
1296     {
1297         if (drives & (1 << drive))
1298         {
1299             *buffer++ = 'A' + drive;
1300             *buffer++ = ':';
1301             *buffer++ = '\\';
1302             *buffer++ = 0;
1303         }
1304     }
1305     *buffer = 0;
1306     return count * 4;
1307 }
1308
1309
1310 /***********************************************************************
1311  *           GetLogicalDriveStringsW   (KERNEL32.@)
1312  */
1313 UINT WINAPI GetLogicalDriveStringsW( UINT len, LPWSTR buffer )
1314 {
1315     DWORD drives = GetLogicalDrives();
1316     UINT drive, count;
1317
1318     for (drive = count = 0; drive < 26; drive++) if (drives & (1 << drive)) count++;
1319     if ((count * 4) + 1 > len) return count * 4 + 1;
1320
1321     for (drive = 0; drive < 26; drive++)
1322     {
1323         if (drives & (1 << drive))
1324         {
1325             *buffer++ = 'A' + drive;
1326             *buffer++ = ':';
1327             *buffer++ = '\\';
1328             *buffer++ = 0;
1329         }
1330     }
1331     *buffer = 0;
1332     return count * 4;
1333 }
1334
1335
1336 /***********************************************************************
1337  *           GetDriveTypeW   (KERNEL32.@)
1338  *
1339  * Returns the type of the disk drive specified. If root is NULL the
1340  * root of the current directory is used.
1341  *
1342  * RETURNS
1343  *
1344  *  Type of drive (from Win32 SDK):
1345  *
1346  *   DRIVE_UNKNOWN     unable to find out anything about the drive
1347  *   DRIVE_NO_ROOT_DIR nonexistent root dir
1348  *   DRIVE_REMOVABLE   the disk can be removed from the machine
1349  *   DRIVE_FIXED       the disk cannot be removed from the machine
1350  *   DRIVE_REMOTE      network disk
1351  *   DRIVE_CDROM       CDROM drive
1352  *   DRIVE_RAMDISK     virtual disk in RAM
1353  */
1354 UINT WINAPI GetDriveTypeW(LPCWSTR root) /* [in] String describing drive */
1355 {
1356     FILE_FS_DEVICE_INFORMATION info;
1357     IO_STATUS_BLOCK io;
1358     NTSTATUS status;
1359     HANDLE handle;
1360     UINT ret;
1361
1362     if (!open_device_root( root, &handle )) return DRIVE_NO_ROOT_DIR;
1363
1364     status = NtQueryVolumeInformationFile( handle, &io, &info, sizeof(info), FileFsDeviceInformation );
1365     NtClose( handle );
1366     if (status != STATUS_SUCCESS)
1367     {
1368         SetLastError( RtlNtStatusToDosError(status) );
1369         ret = DRIVE_UNKNOWN;
1370     }
1371     else
1372     {
1373         switch (info.DeviceType)
1374         {
1375         case FILE_DEVICE_CD_ROM_FILE_SYSTEM:  ret = DRIVE_CDROM; break;
1376         case FILE_DEVICE_VIRTUAL_DISK:        ret = DRIVE_RAMDISK; break;
1377         case FILE_DEVICE_NETWORK_FILE_SYSTEM: ret = DRIVE_REMOTE; break;
1378         case FILE_DEVICE_DISK_FILE_SYSTEM:
1379             if (info.Characteristics & FILE_REMOTE_DEVICE) ret = DRIVE_REMOTE;
1380             else if (info.Characteristics & FILE_REMOVABLE_MEDIA) ret = DRIVE_REMOVABLE;
1381             else if ((ret = get_mountmgr_drive_type( root )) == DRIVE_UNKNOWN) ret = DRIVE_FIXED;
1382             break;
1383         default:
1384             ret = DRIVE_UNKNOWN;
1385             break;
1386         }
1387     }
1388     TRACE( "%s -> %d\n", debugstr_w(root), ret );
1389     return ret;
1390 }
1391
1392
1393 /***********************************************************************
1394  *           GetDriveTypeA   (KERNEL32.@)
1395  *
1396  * See GetDriveTypeW.
1397  */
1398 UINT WINAPI GetDriveTypeA( LPCSTR root )
1399 {
1400     WCHAR *rootW = NULL;
1401
1402     if (root && !(rootW = FILE_name_AtoW( root, FALSE ))) return DRIVE_NO_ROOT_DIR;
1403     return GetDriveTypeW( rootW );
1404 }
1405
1406
1407 /***********************************************************************
1408  *           GetDiskFreeSpaceExW   (KERNEL32.@)
1409  *
1410  *  This function is used to acquire the size of the available and
1411  *  total space on a logical volume.
1412  *
1413  * RETURNS
1414  *
1415  *  Zero on failure, nonzero upon success. Use GetLastError to obtain
1416  *  detailed error information.
1417  *
1418  */
1419 BOOL WINAPI GetDiskFreeSpaceExW( LPCWSTR root, PULARGE_INTEGER avail,
1420                                  PULARGE_INTEGER total, PULARGE_INTEGER totalfree )
1421 {
1422     FILE_FS_SIZE_INFORMATION info;
1423     IO_STATUS_BLOCK io;
1424     NTSTATUS status;
1425     HANDLE handle;
1426     UINT units;
1427
1428     TRACE( "%s,%p,%p,%p\n", debugstr_w(root), avail, total, totalfree );
1429
1430     if (!open_device_root( root, &handle )) return FALSE;
1431
1432     status = NtQueryVolumeInformationFile( handle, &io, &info, sizeof(info), FileFsSizeInformation );
1433     NtClose( handle );
1434     if (status != STATUS_SUCCESS)
1435     {
1436         SetLastError( RtlNtStatusToDosError(status) );
1437         return FALSE;
1438     }
1439
1440     units = info.SectorsPerAllocationUnit * info.BytesPerSector;
1441     if (total) total->QuadPart = info.TotalAllocationUnits.QuadPart * units;
1442     if (totalfree) totalfree->QuadPart = info.AvailableAllocationUnits.QuadPart * units;
1443     /* FIXME: this one should take quotas into account */
1444     if (avail) avail->QuadPart = info.AvailableAllocationUnits.QuadPart * units;
1445     return TRUE;
1446 }
1447
1448
1449 /***********************************************************************
1450  *           GetDiskFreeSpaceExA   (KERNEL32.@)
1451  *
1452  * See GetDiskFreeSpaceExW.
1453  */
1454 BOOL WINAPI GetDiskFreeSpaceExA( LPCSTR root, PULARGE_INTEGER avail,
1455                                  PULARGE_INTEGER total, PULARGE_INTEGER totalfree )
1456 {
1457     WCHAR *rootW = NULL;
1458
1459     if (root && !(rootW = FILE_name_AtoW( root, FALSE ))) return FALSE;
1460     return GetDiskFreeSpaceExW( rootW, avail, total, totalfree );
1461 }
1462
1463
1464 /***********************************************************************
1465  *           GetDiskFreeSpaceW   (KERNEL32.@)
1466  */
1467 BOOL WINAPI GetDiskFreeSpaceW( LPCWSTR root, LPDWORD cluster_sectors,
1468                                LPDWORD sector_bytes, LPDWORD free_clusters,
1469                                LPDWORD total_clusters )
1470 {
1471     FILE_FS_SIZE_INFORMATION info;
1472     IO_STATUS_BLOCK io;
1473     NTSTATUS status;
1474     HANDLE handle;
1475     UINT units;
1476
1477     TRACE( "%s,%p,%p,%p,%p\n", debugstr_w(root),
1478            cluster_sectors, sector_bytes, free_clusters, total_clusters );
1479
1480     if (!open_device_root( root, &handle )) return FALSE;
1481
1482     status = NtQueryVolumeInformationFile( handle, &io, &info, sizeof(info), FileFsSizeInformation );
1483     NtClose( handle );
1484     if (status != STATUS_SUCCESS)
1485     {
1486         SetLastError( RtlNtStatusToDosError(status) );
1487         return FALSE;
1488     }
1489
1490     units = info.SectorsPerAllocationUnit * info.BytesPerSector;
1491
1492     if( GetVersion() & 0x80000000) {    /* win3.x, 9x, ME */
1493         /* cap the size and available at 2GB as per specs */
1494         if (info.TotalAllocationUnits.QuadPart * units > 0x7fffffff) {
1495             info.TotalAllocationUnits.QuadPart = 0x7fffffff / units;
1496             if (info.AvailableAllocationUnits.QuadPart * units > 0x7fffffff)
1497                 info.AvailableAllocationUnits.QuadPart = 0x7fffffff / units;
1498         }
1499         /* nr. of clusters is always <= 65335 */
1500         while( info.TotalAllocationUnits.QuadPart > 65535 ) {
1501             info.TotalAllocationUnits.QuadPart /= 2;
1502             info.AvailableAllocationUnits.QuadPart /= 2;
1503             info.SectorsPerAllocationUnit *= 2;
1504         }
1505     }
1506
1507     if (cluster_sectors) *cluster_sectors = info.SectorsPerAllocationUnit;
1508     if (sector_bytes) *sector_bytes = info.BytesPerSector;
1509     if (free_clusters) *free_clusters = info.AvailableAllocationUnits.u.LowPart;
1510     if (total_clusters) *total_clusters = info.TotalAllocationUnits.u.LowPart;
1511     return TRUE;
1512 }
1513
1514
1515 /***********************************************************************
1516  *           GetDiskFreeSpaceA   (KERNEL32.@)
1517  */
1518 BOOL WINAPI GetDiskFreeSpaceA( LPCSTR root, LPDWORD cluster_sectors,
1519                                LPDWORD sector_bytes, LPDWORD free_clusters,
1520                                LPDWORD total_clusters )
1521 {
1522     WCHAR *rootW = NULL;
1523
1524     if (root && !(rootW = FILE_name_AtoW( root, FALSE ))) return FALSE;
1525     return GetDiskFreeSpaceW( rootW, cluster_sectors, sector_bytes, free_clusters, total_clusters );
1526 }
1527
1528 /***********************************************************************
1529  *           GetVolumePathNameA   (KERNEL32.@)
1530  */
1531 BOOL WINAPI GetVolumePathNameA(LPCSTR filename, LPSTR volumepathname, DWORD buflen)
1532 {
1533     BOOL ret;
1534     WCHAR *filenameW = NULL, *volumeW;
1535
1536     FIXME("(%s, %p, %d), stub!\n", debugstr_a(filename), volumepathname, buflen);
1537
1538     if (filename && !(filenameW = FILE_name_AtoW( filename, FALSE ))) return FALSE;
1539     if (!(volumeW = HeapAlloc( GetProcessHeap(), 0, buflen * sizeof(WCHAR) ))) return FALSE;
1540
1541     if ((ret = GetVolumePathNameW( filenameW, volumeW, buflen )))
1542         FILE_name_WtoA( volumeW, -1, volumepathname, buflen );
1543
1544     HeapFree( GetProcessHeap(), 0, volumeW );
1545     return ret;
1546 }
1547
1548 /***********************************************************************
1549  *           GetVolumePathNameW   (KERNEL32.@)
1550  */
1551 BOOL WINAPI GetVolumePathNameW(LPCWSTR filename, LPWSTR volumepathname, DWORD buflen)
1552 {
1553     const WCHAR *p = filename;
1554
1555     FIXME("(%s, %p, %d), stub!\n", debugstr_w(filename), volumepathname, buflen);
1556
1557     if (p && tolowerW(p[0]) >= 'a' && tolowerW(p[0]) <= 'z' && p[1] ==':' && p[2] == '\\' && buflen >= 4)
1558     {
1559         volumepathname[0] = p[0];
1560         volumepathname[1] = ':';
1561         volumepathname[2] = '\\';
1562         volumepathname[3] = 0;
1563         return TRUE;
1564     }
1565     return FALSE;
1566 }
1567
1568 /***********************************************************************
1569  *           GetVolumePathNamesForVolumeNameW   (KERNEL32.@)
1570  */
1571 BOOL WINAPI GetVolumePathNamesForVolumeNameW(LPCWSTR volumename, LPWSTR volumepathname, DWORD buflen, PDWORD returnlen)
1572 {
1573     FIXME("(%s, %p, %d, %p), stub!\n", debugstr_w(volumename), volumepathname, buflen, returnlen);
1574     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1575     return FALSE;
1576 }
1577
1578 /***********************************************************************
1579  *           FindFirstVolumeA   (KERNEL32.@)
1580  */
1581 HANDLE WINAPI FindFirstVolumeA(LPSTR volume, DWORD len)
1582 {
1583     WCHAR *buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
1584     HANDLE handle = FindFirstVolumeW( buffer, len );
1585
1586     if (handle != INVALID_HANDLE_VALUE)
1587     {
1588         if (!WideCharToMultiByte( CP_ACP, 0, buffer, -1, volume, len, NULL, NULL ))
1589         {
1590             FindVolumeClose( handle );
1591             handle = INVALID_HANDLE_VALUE;
1592         }
1593     }
1594     HeapFree( GetProcessHeap(), 0, buffer );
1595     return handle;
1596 }
1597
1598 /***********************************************************************
1599  *           FindFirstVolumeW   (KERNEL32.@)
1600  */
1601 HANDLE WINAPI FindFirstVolumeW( LPWSTR volume, DWORD len )
1602 {
1603     DWORD size = 1024;
1604     HANDLE mgr = CreateFileW( MOUNTMGR_DOS_DEVICE_NAME, 0, FILE_SHARE_READ|FILE_SHARE_WRITE,
1605                               NULL, OPEN_EXISTING, 0, 0 );
1606     if (mgr == INVALID_HANDLE_VALUE) return INVALID_HANDLE_VALUE;
1607
1608     for (;;)
1609     {
1610         MOUNTMGR_MOUNT_POINT input;
1611         MOUNTMGR_MOUNT_POINTS *output;
1612
1613         if (!(output = HeapAlloc( GetProcessHeap(), 0, size )))
1614         {
1615             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1616             break;
1617         }
1618         memset( &input, 0, sizeof(input) );
1619
1620         if (!DeviceIoControl( mgr, IOCTL_MOUNTMGR_QUERY_POINTS, &input, sizeof(input),
1621                               output, size, NULL, NULL ))
1622         {
1623             if (GetLastError() != ERROR_MORE_DATA) break;
1624             size = output->Size;
1625             HeapFree( GetProcessHeap(), 0, output );
1626             continue;
1627         }
1628         CloseHandle( mgr );
1629         /* abuse the Size field to store the current index */
1630         output->Size = 0;
1631         if (!FindNextVolumeW( output, volume, len ))
1632         {
1633             HeapFree( GetProcessHeap(), 0, output );
1634             return INVALID_HANDLE_VALUE;
1635         }
1636         return output;
1637     }
1638     CloseHandle( mgr );
1639     return INVALID_HANDLE_VALUE;
1640 }
1641
1642 /***********************************************************************
1643  *           FindNextVolumeA   (KERNEL32.@)
1644  */
1645 BOOL WINAPI FindNextVolumeA( HANDLE handle, LPSTR volume, DWORD len )
1646 {
1647     WCHAR *buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
1648     BOOL ret;
1649
1650     if ((ret = FindNextVolumeW( handle, buffer, len )))
1651     {
1652         if (!WideCharToMultiByte( CP_ACP, 0, buffer, -1, volume, len, NULL, NULL )) ret = FALSE;
1653     }
1654     HeapFree( GetProcessHeap(), 0, buffer );
1655     return ret;
1656 }
1657
1658 /***********************************************************************
1659  *           FindNextVolumeW   (KERNEL32.@)
1660  */
1661 BOOL WINAPI FindNextVolumeW( HANDLE handle, LPWSTR volume, DWORD len )
1662 {
1663     MOUNTMGR_MOUNT_POINTS *data = handle;
1664
1665     while (data->Size < data->NumberOfMountPoints)
1666     {
1667         static const WCHAR volumeW[] = {'\\','?','?','\\','V','o','l','u','m','e','{',};
1668         WCHAR *link = (WCHAR *)((char *)data + data->MountPoints[data->Size].SymbolicLinkNameOffset);
1669         DWORD size = data->MountPoints[data->Size].SymbolicLinkNameLength;
1670         data->Size++;
1671         /* skip non-volumes */
1672         if (size < sizeof(volumeW) || memcmp( link, volumeW, sizeof(volumeW) )) continue;
1673         if (size + sizeof(WCHAR) >= len * sizeof(WCHAR))
1674         {
1675             SetLastError( ERROR_FILENAME_EXCED_RANGE );
1676             return FALSE;
1677         }
1678         memcpy( volume, link, size );
1679         volume[1] = '\\';  /* map \??\ to \\?\ */
1680         volume[size / sizeof(WCHAR)] = '\\';  /* Windows appends a backslash */
1681         volume[size / sizeof(WCHAR) + 1] = 0;
1682         TRACE( "returning entry %u %s\n", data->Size - 1, debugstr_w(volume) );
1683         return TRUE;
1684     }
1685     SetLastError( ERROR_NO_MORE_FILES );
1686     return FALSE;
1687 }
1688
1689 /***********************************************************************
1690  *           FindVolumeClose   (KERNEL32.@)
1691  */
1692 BOOL WINAPI FindVolumeClose(HANDLE handle)
1693 {
1694     return HeapFree( GetProcessHeap(), 0, handle );
1695 }
1696
1697 /***********************************************************************
1698  *           FindFirstVolumeMountPointA   (KERNEL32.@)
1699  */
1700 HANDLE WINAPI FindFirstVolumeMountPointA(LPCSTR root, LPSTR mount_point, DWORD len)
1701 {
1702     FIXME("(%s, %p, %d), stub!\n", debugstr_a(root), mount_point, len);
1703     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1704     return INVALID_HANDLE_VALUE;
1705 }
1706
1707 /***********************************************************************
1708  *           FindFirstVolumeMountPointW   (KERNEL32.@)
1709  */
1710 HANDLE WINAPI FindFirstVolumeMountPointW(LPCWSTR root, LPWSTR mount_point, DWORD len)
1711 {
1712     FIXME("(%s, %p, %d), stub!\n", debugstr_w(root), mount_point, len);
1713     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1714     return INVALID_HANDLE_VALUE;
1715 }
1716
1717 /***********************************************************************
1718  *           FindVolumeMountPointClose   (KERNEL32.@)
1719  */
1720 BOOL WINAPI FindVolumeMountPointClose(HANDLE h)
1721 {
1722     FIXME("(%p), stub!\n", h);
1723     return FALSE;
1724 }