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