mountmgr: Reuse create_disk_device to create the initial harddisk0 device.
[wine] / dlls / mountmgr.sys / device.c
1 /*
2  * Dynamic devices support
3  *
4  * Copyright 2006 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <errno.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <sys/time.h>
29
30 #include "mountmgr.h"
31 #include "winreg.h"
32 #include "winuser.h"
33 #include "dbt.h"
34
35 #include "wine/library.h"
36 #include "wine/list.h"
37 #include "wine/unicode.h"
38 #include "wine/debug.h"
39
40 WINE_DEFAULT_DEBUG_CHANNEL(mountmgr);
41
42 #define MAX_DOS_DRIVES 26
43
44 static const WCHAR drive_types[][8] =
45 {
46     { 0 }, /* DRIVE_UNKNOWN */
47     { 0 }, /* DRIVE_NO_ROOT_DIR */
48     {'f','l','o','p','p','y',0}, /* DRIVE_REMOVABLE */
49     {'h','d',0}, /* DRIVE_FIXED */
50     {'n','e','t','w','o','r','k',0}, /* DRIVE_REMOTE */
51     {'c','d','r','o','m',0}, /* DRIVE_CDROM */
52     {'r','a','m','d','i','s','k',0} /* DRIVE_RAMDISK */
53 };
54
55 static const WCHAR drives_keyW[] = {'S','o','f','t','w','a','r','e','\\',
56                                     'W','i','n','e','\\','D','r','i','v','e','s',0};
57
58 struct dos_drive
59 {
60     struct list           entry;       /* entry in drives list */
61     char                 *udi;         /* unique identifier for dynamic drives */
62     int                   drive;       /* drive letter (0 = A: etc.) */
63     DWORD                 type;        /* drive type */
64     DEVICE_OBJECT        *device;      /* disk device allocated for this drive */
65     UNICODE_STRING        name;        /* device name */
66     UNICODE_STRING        symlink;     /* device symlink if any */
67     STORAGE_DEVICE_NUMBER devnum;      /* device number info */
68     struct mount_point   *dosdev;      /* DosDevices mount point */
69     struct mount_point   *volume;      /* Volume{xxx} mount point */
70     char                 *unix_mount;  /* unix mount point path */
71 };
72
73 static struct list drives_list = LIST_INIT(drives_list);
74
75 static DRIVER_OBJECT *harddisk_driver;
76
77 static char *get_dosdevices_path( char **drive )
78 {
79     const char *config_dir = wine_get_config_dir();
80     size_t len = strlen(config_dir) + sizeof("/dosdevices/a::");
81     char *path = HeapAlloc( GetProcessHeap(), 0, len );
82     if (path)
83     {
84         strcpy( path, config_dir );
85         strcat( path, "/dosdevices/a::" );
86         *drive = path + len - 4;
87     }
88     return path;
89 }
90
91 /* read a Unix symlink; returned buffer must be freed by caller */
92 static char *read_symlink( const char *path )
93 {
94     char *buffer;
95     int ret, size = 128;
96
97     for (;;)
98     {
99         if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size )))
100         {
101             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
102             return 0;
103         }
104         ret = readlink( path, buffer, size );
105         if (ret == -1)
106         {
107             RtlFreeHeap( GetProcessHeap(), 0, buffer );
108             return 0;
109         }
110         if (ret != size)
111         {
112             buffer[ret] = 0;
113             return buffer;
114         }
115         RtlFreeHeap( GetProcessHeap(), 0, buffer );
116         size *= 2;
117     }
118 }
119
120 /* send notification about a change to a given drive */
121 static void send_notify( int drive, int code )
122 {
123     DWORD_PTR result;
124     DEV_BROADCAST_VOLUME info;
125
126     info.dbcv_size       = sizeof(info);
127     info.dbcv_devicetype = DBT_DEVTYP_VOLUME;
128     info.dbcv_reserved   = 0;
129     info.dbcv_unitmask   = 1 << drive;
130     info.dbcv_flags      = DBTF_MEDIA;
131     result = BroadcastSystemMessageW( BSF_FORCEIFHUNG|BSF_QUERY, NULL,
132                                       WM_DEVICECHANGE, code, (LPARAM)&info );
133 }
134
135 /* create the disk device for a given drive */
136 static NTSTATUS create_disk_device( const char *udi, DWORD type, struct dos_drive **drive_ret )
137 {
138     static const WCHAR harddiskvolW[] = {'\\','D','e','v','i','c','e',
139                                          '\\','H','a','r','d','d','i','s','k','V','o','l','u','m','e','%','u',0};
140     static const WCHAR harddiskW[] = {'\\','D','e','v','i','c','e','\\','H','a','r','d','d','i','s','k','%','u',0};
141     static const WCHAR cdromW[] = {'\\','D','e','v','i','c','e','\\','C','d','R','o','m','%','u',0};
142     static const WCHAR floppyW[] = {'\\','D','e','v','i','c','e','\\','F','l','o','p','p','y','%','u',0};
143     static const WCHAR physdriveW[] = {'\\','?','?','\\','P','h','y','s','i','c','a','l','D','r','i','v','e','%','u',0};
144
145     UINT i, first = 0;
146     NTSTATUS status = 0;
147     const WCHAR *format;
148     UNICODE_STRING name;
149     DEVICE_OBJECT *dev_obj;
150     struct dos_drive *drive;
151
152     switch(type)
153     {
154     case DRIVE_REMOVABLE:
155         format = floppyW;
156         break;
157     case DRIVE_CDROM:
158         format = cdromW;
159         break;
160     case DRIVE_FIXED:
161     default:  /* FIXME */
162         if (udi) format = harddiskW;
163         else
164         {
165             format = harddiskvolW;
166             first = 1;  /* harddisk volumes start counting from 1 */
167         }
168         break;
169     }
170
171     name.MaximumLength = (strlenW(format) + 10) * sizeof(WCHAR);
172     name.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, name.MaximumLength );
173     for (i = first; i < 32; i++)
174     {
175         sprintfW( name.Buffer, format, i );
176         name.Length = strlenW(name.Buffer) * sizeof(WCHAR);
177         status = IoCreateDevice( harddisk_driver, sizeof(*drive), &name, 0, 0, FALSE, &dev_obj );
178         if (status != STATUS_OBJECT_NAME_COLLISION) break;
179     }
180     if (!status)
181     {
182         drive = dev_obj->DeviceExtension;
183         drive->drive  = -1;
184         drive->device = dev_obj;
185         drive->name   = name;
186         drive->type   = type;
187         drive->dosdev = NULL;
188         drive->volume = NULL;
189         drive->unix_mount = NULL;
190         drive->symlink.Buffer = NULL;
191         if (udi)
192         {
193             if (!(drive->udi = HeapAlloc( GetProcessHeap(), 0, strlen(udi)+1 )))
194             {
195                 RtlFreeUnicodeString( &name );
196                 IoDeleteDevice( drive->device );
197                 return STATUS_NO_MEMORY;
198             }
199             strcpy( drive->udi, udi );
200         }
201         switch (type)
202         {
203         case DRIVE_REMOVABLE:
204             drive->devnum.DeviceType = FILE_DEVICE_DISK;
205             drive->devnum.DeviceNumber = i;
206             drive->devnum.PartitionNumber = ~0u;
207             break;
208         case DRIVE_CDROM:
209             drive->devnum.DeviceType = FILE_DEVICE_CD_ROM;
210             drive->devnum.DeviceNumber = i;
211             drive->devnum.PartitionNumber = ~0u;
212             break;
213         case DRIVE_FIXED:
214         default:  /* FIXME */
215             drive->devnum.DeviceType = FILE_DEVICE_DISK;
216             if (udi)
217             {
218                 UNICODE_STRING symlink;
219
220                 symlink.MaximumLength = sizeof(physdriveW) + 10 * sizeof(WCHAR);
221                 if ((symlink.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, symlink.MaximumLength)))
222                 {
223                     sprintfW( symlink.Buffer, physdriveW, i );
224                     symlink.Length = strlenW(symlink.Buffer) * sizeof(WCHAR);
225                     if (!IoCreateSymbolicLink( &symlink, &name )) drive->symlink = symlink;
226                 }
227                 drive->devnum.DeviceNumber = i;
228                 drive->devnum.PartitionNumber = 0;
229             }
230             else
231             {
232                 drive->devnum.DeviceNumber = 0;
233                 drive->devnum.PartitionNumber = i;
234             }
235             break;
236         }
237         list_add_tail( &drives_list, &drive->entry );
238         *drive_ret = drive;
239         TRACE( "created device %s\n", debugstr_w(name.Buffer) );
240     }
241     else
242     {
243         FIXME( "IoCreateDevice %s got %x\n", debugstr_w(name.Buffer), status );
244         RtlFreeUnicodeString( &name );
245     }
246     return status;
247 }
248
249 /* delete the disk device for a given drive */
250 static void delete_disk_device( struct dos_drive *drive )
251 {
252     TRACE( "deleting device %s\n", debugstr_w(drive->name.Buffer) );
253     list_remove( &drive->entry );
254     if (drive->dosdev) delete_mount_point( drive->dosdev );
255     if (drive->volume) delete_mount_point( drive->volume );
256     if (drive->symlink.Buffer)
257     {
258         IoDeleteSymbolicLink( &drive->symlink );
259         RtlFreeUnicodeString( &drive->symlink );
260     }
261     RtlFreeHeap( GetProcessHeap(), 0, drive->unix_mount );
262     RtlFreeHeap( GetProcessHeap(), 0, drive->udi );
263     RtlFreeUnicodeString( &drive->name );
264     IoDeleteDevice( drive->device );
265 }
266
267 /* set or change the drive letter for an existing drive */
268 static void set_drive_letter( struct dos_drive *drive, int letter )
269 {
270     void *id = NULL;
271     unsigned int id_len = 0;
272
273     if (drive->drive == letter) return;
274     if (drive->dosdev) delete_mount_point( drive->dosdev );
275     if (drive->volume) delete_mount_point( drive->volume );
276     drive->drive = letter;
277     if (letter == -1) return;
278     if (drive->unix_mount)
279     {
280         id = drive->unix_mount;
281         id_len = strlen( drive->unix_mount ) + 1;
282     }
283     drive->dosdev = add_dosdev_mount_point( drive->device, &drive->name, letter, id, id_len );
284     drive->volume = add_volume_mount_point( drive->device, &drive->name, letter, id, id_len );
285 }
286
287 static inline int is_valid_device( struct stat *st )
288 {
289 #if defined(linux) || defined(__sun__)
290     return S_ISBLK( st->st_mode );
291 #else
292     /* disks are char devices on *BSD */
293     return S_ISCHR( st->st_mode );
294 #endif
295 }
296
297 /* find or create a DOS drive for the corresponding device */
298 static int add_drive( const char *device, DWORD type )
299 {
300     char *path, *p;
301     char in_use[26];
302     struct stat dev_st, drive_st;
303     int drive, first, last, avail = 0;
304
305     if (stat( device, &dev_st ) == -1 || !is_valid_device( &dev_st )) return -1;
306
307     if (!(path = get_dosdevices_path( &p ))) return -1;
308
309     memset( in_use, 0, sizeof(in_use) );
310
311     first = 2;
312     last = 26;
313     if (type == DRIVE_REMOVABLE)
314     {
315         first = 0;
316         last = 2;
317     }
318
319     while (avail != -1)
320     {
321         avail = -1;
322         for (drive = first; drive < last; drive++)
323         {
324             if (in_use[drive]) continue;  /* already checked */
325             *p = 'a' + drive;
326             if (stat( path, &drive_st ) == -1)
327             {
328                 if (lstat( path, &drive_st ) == -1 && errno == ENOENT)  /* this is a candidate */
329                 {
330                     if (avail == -1)
331                     {
332                         p[2] = 0;
333                         /* if mount point symlink doesn't exist either, it's available */
334                         if (lstat( path, &drive_st ) == -1 && errno == ENOENT) avail = drive;
335                         p[2] = ':';
336                     }
337                 }
338                 else in_use[drive] = 1;
339             }
340             else
341             {
342                 in_use[drive] = 1;
343                 if (!is_valid_device( &drive_st )) continue;
344                 if (dev_st.st_rdev == drive_st.st_rdev) goto done;
345             }
346         }
347         if (avail != -1)
348         {
349             /* try to use the one we found */
350             drive = avail;
351             *p = 'a' + drive;
352             if (symlink( device, path ) != -1) goto done;
353             /* failed, retry the search */
354         }
355     }
356     drive = -1;
357
358 done:
359     HeapFree( GetProcessHeap(), 0, path );
360     return drive;
361 }
362
363 static BOOL set_unix_mount_point( struct dos_drive *drive, const char *mount_point )
364 {
365     char *path, *p;
366     BOOL modified = FALSE;
367
368     if (!(path = get_dosdevices_path( &p ))) return FALSE;
369     p[0] = 'a' + drive->drive;
370     p[2] = 0;
371
372     if (mount_point && mount_point[0])
373     {
374         /* try to avoid unlinking if already set correctly */
375         if (!drive->unix_mount || strcmp( drive->unix_mount, mount_point ))
376         {
377             unlink( path );
378             symlink( mount_point, path );
379             modified = TRUE;
380         }
381         RtlFreeHeap( GetProcessHeap(), 0, drive->unix_mount );
382         if ((drive->unix_mount = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point) + 1 )))
383             strcpy( drive->unix_mount, mount_point );
384         if (drive->dosdev) set_mount_point_id( drive->dosdev, mount_point, strlen(mount_point) + 1 );
385         if (drive->volume) set_mount_point_id( drive->volume, mount_point, strlen(mount_point) + 1 );
386     }
387     else
388     {
389         if (unlink( path ) != -1) modified = TRUE;
390         RtlFreeHeap( GetProcessHeap(), 0, drive->unix_mount );
391         drive->unix_mount = NULL;
392         if (drive->dosdev) set_mount_point_id( drive->dosdev, NULL, 0 );
393         if (drive->volume) set_mount_point_id( drive->volume, NULL, 0 );
394     }
395
396     HeapFree( GetProcessHeap(), 0, path );
397     return modified;
398 }
399
400 /* create devices for mapped drives */
401 static void create_drive_devices(void)
402 {
403     char *path, *p, *link;
404     struct dos_drive *drive;
405     unsigned int i;
406     HKEY drives_key;
407     DWORD drive_type;
408     WCHAR driveW[] = {'a',':',0};
409
410     if (!(path = get_dosdevices_path( &p ))) return;
411     if (RegOpenKeyW( HKEY_LOCAL_MACHINE, drives_keyW, &drives_key )) drives_key = 0;
412
413     for (i = 0; i < MAX_DOS_DRIVES; i++)
414     {
415         p[0] = 'a' + i;
416         p[2] = 0;
417         if (!(link = read_symlink( path ))) continue;
418
419         drive_type = i < 2 ? DRIVE_REMOVABLE : DRIVE_FIXED;
420         if (drives_key)
421         {
422             WCHAR buffer[32];
423             DWORD j, type, size = sizeof(buffer);
424
425             driveW[0] = 'a' + i;
426             if (!RegQueryValueExW( drives_key, driveW, NULL, &type, (BYTE *)buffer, &size ) &&
427                 type == REG_SZ)
428             {
429                 for (j = 0; j < sizeof(drive_types)/sizeof(drive_types[0]); j++)
430                     if (drive_types[j][0] && !strcmpiW( buffer, drive_types[j] ))
431                     {
432                         drive_type = j;
433                         break;
434                     }
435             }
436         }
437
438         if (!create_disk_device( NULL, drive_type, &drive ))
439         {
440             drive->unix_mount = link;
441             set_drive_letter( drive, i );
442         }
443         else RtlFreeHeap( GetProcessHeap(), 0, link );
444     }
445     RegCloseKey( drives_key );
446     RtlFreeHeap( GetProcessHeap(), 0, path );
447 }
448
449 BOOL add_dos_device( const char *udi, const char *device, const char *mount_point, DWORD type )
450 {
451     struct dos_drive *drive, *next;
452     int letter = add_drive( device, type );
453
454     if (letter == -1) return FALSE;
455
456     LIST_FOR_EACH_ENTRY_SAFE( drive, next, &drives_list, struct dos_drive, entry )
457     {
458         if (drive->udi && !strcmp( udi, drive->udi ))
459         {
460             if (type == drive->type) goto found;
461             delete_disk_device( drive );
462             continue;
463         }
464         if (drive->drive == letter) delete_disk_device( drive );
465     }
466
467     if (create_disk_device( udi, type, &drive )) return FALSE;
468
469 found:
470     set_drive_letter( drive, letter );
471     set_unix_mount_point( drive, mount_point );
472
473     if (drive->drive != -1)
474     {
475         HKEY hkey;
476
477         TRACE( "added device %c: udi %s for %s on %s type %u\n",
478                     'a' + drive->drive, wine_dbgstr_a(udi), wine_dbgstr_a(device),
479                     wine_dbgstr_a(mount_point), type );
480
481         /* hack: force the drive type in the registry */
482         if (!RegCreateKeyW( HKEY_LOCAL_MACHINE, drives_keyW, &hkey ))
483         {
484             const WCHAR *type_name = drive_types[type];
485             WCHAR name[3] = {'a',':',0};
486
487             name[0] += drive->drive;
488             if (type_name[0])
489                 RegSetValueExW( hkey, name, 0, REG_SZ, (const BYTE *)type_name,
490                                 (strlenW(type_name) + 1) * sizeof(WCHAR) );
491             else
492                 RegDeleteValueW( hkey, name );
493             RegCloseKey( hkey );
494         }
495
496         send_notify( drive->drive, DBT_DEVICEARRIVAL );
497     }
498     return TRUE;
499 }
500
501 BOOL remove_dos_device( const char *udi )
502 {
503     HKEY hkey;
504     struct dos_drive *drive;
505
506     LIST_FOR_EACH_ENTRY( drive, &drives_list, struct dos_drive, entry )
507     {
508         if (!drive->udi || strcmp( udi, drive->udi )) continue;
509
510         if (drive->drive != -1)
511         {
512             BOOL modified = set_unix_mount_point( drive, NULL );
513
514             /* clear the registry key too */
515             if (!RegOpenKeyW( HKEY_LOCAL_MACHINE, drives_keyW, &hkey ))
516             {
517                 WCHAR name[3] = {'a',':',0};
518                 name[0] += drive->drive;
519                 RegDeleteValueW( hkey, name );
520                 RegCloseKey( hkey );
521             }
522
523             if (modified) send_notify( drive->drive, DBT_DEVICEREMOVECOMPLETE );
524         }
525         delete_disk_device( drive );
526         return TRUE;
527     }
528     return FALSE;
529 }
530
531 /* handler for ioctls on the harddisk device */
532 static NTSTATUS WINAPI harddisk_ioctl( DEVICE_OBJECT *device, IRP *irp )
533 {
534     IO_STACK_LOCATION *irpsp = irp->Tail.Overlay.s.u.CurrentStackLocation;
535     struct dos_drive *drive = device->DeviceExtension;
536
537     TRACE( "ioctl %x insize %u outsize %u\n",
538            irpsp->Parameters.DeviceIoControl.IoControlCode,
539            irpsp->Parameters.DeviceIoControl.InputBufferLength,
540            irpsp->Parameters.DeviceIoControl.OutputBufferLength );
541
542     switch(irpsp->Parameters.DeviceIoControl.IoControlCode)
543     {
544     case IOCTL_DISK_GET_DRIVE_GEOMETRY:
545     {
546         DISK_GEOMETRY info;
547         DWORD len = min( sizeof(info), irpsp->Parameters.DeviceIoControl.OutputBufferLength );
548
549         info.Cylinders.QuadPart = 10000;
550         info.MediaType = (drive->devnum.DeviceType == FILE_DEVICE_DISK) ? FixedMedia : RemovableMedia;
551         info.TracksPerCylinder = 255;
552         info.SectorsPerTrack = 63;
553         info.BytesPerSector = 512;
554         memcpy( irp->MdlAddress->StartVa, &info, len );
555         irp->IoStatus.Information = len;
556         irp->IoStatus.u.Status = STATUS_SUCCESS;
557         break;
558     }
559     case IOCTL_STORAGE_GET_DEVICE_NUMBER:
560     {
561         DWORD len = min( sizeof(drive->devnum), irpsp->Parameters.DeviceIoControl.OutputBufferLength );
562
563         memcpy( irp->MdlAddress->StartVa, &drive->devnum, len );
564         irp->IoStatus.Information = len;
565         irp->IoStatus.u.Status = STATUS_SUCCESS;
566         break;
567     }
568     case IOCTL_CDROM_READ_TOC:
569         irp->IoStatus.u.Status = STATUS_INVALID_DEVICE_REQUEST;
570         break;
571     default:
572         FIXME( "unsupported ioctl %x\n", irpsp->Parameters.DeviceIoControl.IoControlCode );
573         irp->IoStatus.u.Status = STATUS_NOT_SUPPORTED;
574         break;
575     }
576     return irp->IoStatus.u.Status;
577 }
578
579 /* driver entry point for the harddisk driver */
580 NTSTATUS WINAPI harddisk_driver_entry( DRIVER_OBJECT *driver, UNICODE_STRING *path )
581 {
582     struct dos_drive *drive;
583
584     harddisk_driver = driver;
585     driver->MajorFunction[IRP_MJ_DEVICE_CONTROL] = harddisk_ioctl;
586
587     /* create a harddisk0 device that isn't assigned to any drive */
588     create_disk_device( "harddisk0 placeholder", DRIVE_FIXED, &drive );
589
590     create_drive_devices();
591
592     return STATUS_SUCCESS;
593 }