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