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