comctl32: Add implementation of LVS_EX_ONECLICKACTIVATE.
[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_device; /* unix device path */
71     char                 *unix_mount;  /* unix mount point path */
72 };
73
74 static struct list drives_list = LIST_INIT(drives_list);
75
76 static DRIVER_OBJECT *harddisk_driver;
77
78 static char *get_dosdevices_path( char **drive )
79 {
80     const char *config_dir = wine_get_config_dir();
81     size_t len = strlen(config_dir) + sizeof("/dosdevices/a::");
82     char *path = HeapAlloc( GetProcessHeap(), 0, len );
83     if (path)
84     {
85         strcpy( path, config_dir );
86         strcat( path, "/dosdevices/a::" );
87         *drive = path + len - 4;
88     }
89     return path;
90 }
91
92 static char *strdupA( const char *str )
93 {
94     char *ret;
95
96     if (!str) return NULL;
97     if ((ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(str) + 1 ))) strcpy( ret, str );
98     return ret;
99 }
100
101 /* read a Unix symlink; returned buffer must be freed by caller */
102 static char *read_symlink( const char *path )
103 {
104     char *buffer;
105     int ret, size = 128;
106
107     for (;;)
108     {
109         if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size )))
110         {
111             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
112             return 0;
113         }
114         ret = readlink( path, buffer, size );
115         if (ret == -1)
116         {
117             RtlFreeHeap( GetProcessHeap(), 0, buffer );
118             return 0;
119         }
120         if (ret != size)
121         {
122             buffer[ret] = 0;
123             return buffer;
124         }
125         RtlFreeHeap( GetProcessHeap(), 0, buffer );
126         size *= 2;
127     }
128 }
129
130 /* send notification about a change to a given drive */
131 static void send_notify( int drive, int code )
132 {
133     DWORD_PTR result;
134     DEV_BROADCAST_VOLUME info;
135
136     info.dbcv_size       = sizeof(info);
137     info.dbcv_devicetype = DBT_DEVTYP_VOLUME;
138     info.dbcv_reserved   = 0;
139     info.dbcv_unitmask   = 1 << drive;
140     info.dbcv_flags      = DBTF_MEDIA;
141     result = BroadcastSystemMessageW( BSF_FORCEIFHUNG|BSF_QUERY, NULL,
142                                       WM_DEVICECHANGE, code, (LPARAM)&info );
143 }
144
145 /* create the disk device for a given drive */
146 static NTSTATUS create_disk_device( const char *udi, DWORD type, struct dos_drive **drive_ret )
147 {
148     static const WCHAR harddiskvolW[] = {'\\','D','e','v','i','c','e',
149                                          '\\','H','a','r','d','d','i','s','k','V','o','l','u','m','e','%','u',0};
150     static const WCHAR harddiskW[] = {'\\','D','e','v','i','c','e','\\','H','a','r','d','d','i','s','k','%','u',0};
151     static const WCHAR cdromW[] = {'\\','D','e','v','i','c','e','\\','C','d','R','o','m','%','u',0};
152     static const WCHAR floppyW[] = {'\\','D','e','v','i','c','e','\\','F','l','o','p','p','y','%','u',0};
153     static const WCHAR physdriveW[] = {'\\','?','?','\\','P','h','y','s','i','c','a','l','D','r','i','v','e','%','u',0};
154
155     UINT i, first = 0;
156     NTSTATUS status = 0;
157     const WCHAR *format;
158     UNICODE_STRING name;
159     DEVICE_OBJECT *dev_obj;
160     struct dos_drive *drive;
161
162     switch(type)
163     {
164     case DRIVE_REMOVABLE:
165         format = floppyW;
166         break;
167     case DRIVE_CDROM:
168         format = cdromW;
169         break;
170     case DRIVE_FIXED:
171     default:  /* FIXME */
172         if (udi) format = harddiskW;
173         else
174         {
175             format = harddiskvolW;
176             first = 1;  /* harddisk volumes start counting from 1 */
177         }
178         break;
179     }
180
181     name.MaximumLength = (strlenW(format) + 10) * sizeof(WCHAR);
182     name.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, name.MaximumLength );
183     for (i = first; i < 32; i++)
184     {
185         sprintfW( name.Buffer, format, i );
186         name.Length = strlenW(name.Buffer) * sizeof(WCHAR);
187         status = IoCreateDevice( harddisk_driver, sizeof(*drive), &name, 0, 0, FALSE, &dev_obj );
188         if (status != STATUS_OBJECT_NAME_COLLISION) break;
189     }
190     if (!status)
191     {
192         drive = dev_obj->DeviceExtension;
193         drive->drive  = -1;
194         drive->device = dev_obj;
195         drive->name   = name;
196         drive->type   = type;
197         drive->dosdev = NULL;
198         drive->volume = NULL;
199         drive->unix_device = NULL;
200         drive->unix_mount  = NULL;
201         drive->symlink.Buffer = NULL;
202         if (udi)
203         {
204             if (!(drive->udi = HeapAlloc( GetProcessHeap(), 0, strlen(udi)+1 )))
205             {
206                 RtlFreeUnicodeString( &name );
207                 IoDeleteDevice( drive->device );
208                 return STATUS_NO_MEMORY;
209             }
210             strcpy( drive->udi, udi );
211         }
212         switch (type)
213         {
214         case DRIVE_REMOVABLE:
215             drive->devnum.DeviceType = FILE_DEVICE_DISK;
216             drive->devnum.DeviceNumber = i;
217             drive->devnum.PartitionNumber = ~0u;
218             break;
219         case DRIVE_CDROM:
220             drive->devnum.DeviceType = FILE_DEVICE_CD_ROM;
221             drive->devnum.DeviceNumber = i;
222             drive->devnum.PartitionNumber = ~0u;
223             break;
224         case DRIVE_FIXED:
225         default:  /* FIXME */
226             drive->devnum.DeviceType = FILE_DEVICE_DISK;
227             if (udi)
228             {
229                 UNICODE_STRING symlink;
230
231                 symlink.MaximumLength = sizeof(physdriveW) + 10 * sizeof(WCHAR);
232                 if ((symlink.Buffer = RtlAllocateHeap( GetProcessHeap(), 0, symlink.MaximumLength)))
233                 {
234                     sprintfW( symlink.Buffer, physdriveW, i );
235                     symlink.Length = strlenW(symlink.Buffer) * sizeof(WCHAR);
236                     if (!IoCreateSymbolicLink( &symlink, &name )) drive->symlink = symlink;
237                 }
238                 drive->devnum.DeviceNumber = i;
239                 drive->devnum.PartitionNumber = 0;
240             }
241             else
242             {
243                 drive->devnum.DeviceNumber = 0;
244                 drive->devnum.PartitionNumber = i;
245             }
246             break;
247         }
248         list_add_tail( &drives_list, &drive->entry );
249         *drive_ret = drive;
250         TRACE( "created device %s\n", debugstr_w(name.Buffer) );
251     }
252     else
253     {
254         FIXME( "IoCreateDevice %s got %x\n", debugstr_w(name.Buffer), status );
255         RtlFreeUnicodeString( &name );
256     }
257     return status;
258 }
259
260 /* delete the disk device for a given drive */
261 static void delete_disk_device( struct dos_drive *drive )
262 {
263     TRACE( "deleting device %s\n", debugstr_w(drive->name.Buffer) );
264     list_remove( &drive->entry );
265     if (drive->dosdev) delete_mount_point( drive->dosdev );
266     if (drive->volume) delete_mount_point( drive->volume );
267     if (drive->symlink.Buffer)
268     {
269         IoDeleteSymbolicLink( &drive->symlink );
270         RtlFreeUnicodeString( &drive->symlink );
271     }
272     RtlFreeHeap( GetProcessHeap(), 0, drive->unix_device );
273     RtlFreeHeap( GetProcessHeap(), 0, drive->unix_mount );
274     RtlFreeHeap( GetProcessHeap(), 0, drive->udi );
275     RtlFreeUnicodeString( &drive->name );
276     IoDeleteDevice( drive->device );
277 }
278
279 /* set or change the drive letter for an existing drive */
280 static void set_drive_letter( struct dos_drive *drive, int letter )
281 {
282     void *id = NULL;
283     unsigned int id_len = 0;
284
285     if (drive->drive == letter) return;
286     if (drive->dosdev) delete_mount_point( drive->dosdev );
287     if (drive->volume) delete_mount_point( drive->volume );
288     drive->drive = letter;
289     if (letter == -1) return;
290     if (drive->unix_mount)
291     {
292         id = drive->unix_mount;
293         id_len = strlen( drive->unix_mount ) + 1;
294     }
295     drive->dosdev = add_dosdev_mount_point( drive->device, &drive->name, letter, id, id_len );
296     drive->volume = add_volume_mount_point( drive->device, &drive->name, letter, id, id_len );
297 }
298
299 static inline int is_valid_device( struct stat *st )
300 {
301 #if defined(linux) || defined(__sun__)
302     return S_ISBLK( st->st_mode );
303 #else
304     /* disks are char devices on *BSD */
305     return S_ISCHR( st->st_mode );
306 #endif
307 }
308
309 /* find or create a DOS drive for the corresponding device */
310 static int add_drive( const char *device, DWORD type )
311 {
312     char *path, *p;
313     char in_use[26];
314     struct stat dev_st, drive_st;
315     int drive, first, last, avail = 0;
316
317     if (stat( device, &dev_st ) == -1 || !is_valid_device( &dev_st )) return -1;
318
319     if (!(path = get_dosdevices_path( &p ))) return -1;
320
321     memset( in_use, 0, sizeof(in_use) );
322
323     first = 2;
324     last = 26;
325     if (type == DRIVE_REMOVABLE)
326     {
327         first = 0;
328         last = 2;
329     }
330
331     while (avail != -1)
332     {
333         avail = -1;
334         for (drive = first; drive < last; drive++)
335         {
336             if (in_use[drive]) continue;  /* already checked */
337             *p = 'a' + drive;
338             if (stat( path, &drive_st ) == -1)
339             {
340                 if (lstat( path, &drive_st ) == -1 && errno == ENOENT)  /* this is a candidate */
341                 {
342                     if (avail == -1)
343                     {
344                         p[2] = 0;
345                         /* if mount point symlink doesn't exist either, it's available */
346                         if (lstat( path, &drive_st ) == -1 && errno == ENOENT) avail = drive;
347                         p[2] = ':';
348                     }
349                 }
350                 else in_use[drive] = 1;
351             }
352             else
353             {
354                 in_use[drive] = 1;
355                 if (!is_valid_device( &drive_st )) continue;
356                 if (dev_st.st_rdev == drive_st.st_rdev) goto done;
357             }
358         }
359         if (avail != -1)
360         {
361             /* try to use the one we found */
362             drive = avail;
363             *p = 'a' + drive;
364             if (symlink( device, path ) != -1) goto done;
365             /* failed, retry the search */
366         }
367     }
368     drive = -1;
369
370 done:
371     HeapFree( GetProcessHeap(), 0, path );
372     return drive;
373 }
374
375 static BOOL set_unix_mount_point( struct dos_drive *drive, const char *mount_point )
376 {
377     char *path, *p;
378     BOOL modified = FALSE;
379
380     if (!(path = get_dosdevices_path( &p ))) return FALSE;
381     p[0] = 'a' + drive->drive;
382     p[2] = 0;
383
384     if (mount_point && mount_point[0])
385     {
386         /* try to avoid unlinking if already set correctly */
387         if (!drive->unix_mount || strcmp( drive->unix_mount, mount_point ))
388         {
389             unlink( path );
390             symlink( mount_point, path );
391             modified = TRUE;
392         }
393         RtlFreeHeap( GetProcessHeap(), 0, drive->unix_mount );
394         drive->unix_mount = strdupA( mount_point );
395         if (drive->dosdev) set_mount_point_id( drive->dosdev, mount_point, strlen(mount_point) + 1 );
396         if (drive->volume) set_mount_point_id( drive->volume, mount_point, strlen(mount_point) + 1 );
397     }
398     else
399     {
400         if (unlink( path ) != -1) modified = TRUE;
401         RtlFreeHeap( GetProcessHeap(), 0, drive->unix_mount );
402         drive->unix_mount = NULL;
403         if (drive->dosdev) set_mount_point_id( drive->dosdev, NULL, 0 );
404         if (drive->volume) set_mount_point_id( drive->volume, NULL, 0 );
405     }
406
407     HeapFree( GetProcessHeap(), 0, path );
408     return modified;
409 }
410
411 /* create devices for mapped drives */
412 static void create_drive_devices(void)
413 {
414     char *path, *p, *link, *device;
415     struct dos_drive *drive;
416     unsigned int i;
417     HKEY drives_key;
418     DWORD drive_type;
419     WCHAR driveW[] = {'a',':',0};
420
421     if (!(path = get_dosdevices_path( &p ))) return;
422     if (RegOpenKeyW( HKEY_LOCAL_MACHINE, drives_keyW, &drives_key )) drives_key = 0;
423
424     for (i = 0; i < MAX_DOS_DRIVES; i++)
425     {
426         p[0] = 'a' + i;
427         p[2] = 0;
428         if (!(link = read_symlink( path ))) continue;
429         p[2] = ':';
430         device = read_symlink( path );
431
432         drive_type = i < 2 ? DRIVE_REMOVABLE : DRIVE_FIXED;
433         if (drives_key)
434         {
435             WCHAR buffer[32];
436             DWORD j, type, size = sizeof(buffer);
437
438             driveW[0] = 'a' + i;
439             if (!RegQueryValueExW( drives_key, driveW, NULL, &type, (BYTE *)buffer, &size ) &&
440                 type == REG_SZ)
441             {
442                 for (j = 0; j < sizeof(drive_types)/sizeof(drive_types[0]); j++)
443                     if (drive_types[j][0] && !strcmpiW( buffer, drive_types[j] ))
444                     {
445                         drive_type = j;
446                         break;
447                     }
448             }
449         }
450
451         if (!create_disk_device( NULL, drive_type, &drive ))
452         {
453             drive->unix_mount = link;
454             drive->unix_device = device;
455             set_drive_letter( drive, i );
456         }
457         else
458         {
459             RtlFreeHeap( GetProcessHeap(), 0, link );
460             RtlFreeHeap( GetProcessHeap(), 0, device );
461         }
462     }
463     RegCloseKey( drives_key );
464     RtlFreeHeap( GetProcessHeap(), 0, path );
465 }
466
467 /* create a new dos drive */
468 NTSTATUS add_dos_device( int letter, const char *udi, const char *device,
469                          const char *mount_point, DWORD type )
470 {
471     struct dos_drive *drive, *next;
472
473     if (letter == -1)  /* auto-assign a letter */
474     {
475         letter = add_drive( device, type );
476         if (letter == -1) return STATUS_OBJECT_NAME_COLLISION;
477     }
478     else  /* simply reset the device symlink */
479     {
480         char *path, *p;
481
482         if (!(path = get_dosdevices_path( &p ))) return STATUS_NO_MEMORY;
483         *p = 'a' + letter;
484         unlink( path );
485         if (device) symlink( device, path );
486     }
487
488     LIST_FOR_EACH_ENTRY_SAFE( drive, next, &drives_list, struct dos_drive, entry )
489     {
490         if (udi && drive->udi && !strcmp( udi, drive->udi ))
491         {
492             if (type == drive->type) goto found;
493             delete_disk_device( drive );
494             continue;
495         }
496         if (drive->drive == letter) delete_disk_device( drive );
497     }
498
499     if (create_disk_device( udi, type, &drive )) return STATUS_NO_MEMORY;
500
501 found:
502     RtlFreeHeap( GetProcessHeap(), 0, drive->unix_device );
503     drive->unix_device = strdupA( device );
504     set_drive_letter( drive, letter );
505     set_unix_mount_point( drive, mount_point );
506
507     if (drive->drive != -1)
508     {
509         HKEY hkey;
510
511         TRACE( "added device %c: udi %s for %s on %s type %u\n",
512                     'a' + drive->drive, wine_dbgstr_a(udi), wine_dbgstr_a(device),
513                     wine_dbgstr_a(mount_point), type );
514
515         /* hack: force the drive type in the registry */
516         if (!RegCreateKeyW( HKEY_LOCAL_MACHINE, drives_keyW, &hkey ))
517         {
518             const WCHAR *type_name = drive_types[type];
519             WCHAR name[3] = {'a',':',0};
520
521             name[0] += drive->drive;
522             if (type_name[0])
523                 RegSetValueExW( hkey, name, 0, REG_SZ, (const BYTE *)type_name,
524                                 (strlenW(type_name) + 1) * sizeof(WCHAR) );
525             else
526                 RegDeleteValueW( hkey, name );
527             RegCloseKey( hkey );
528         }
529
530         if (udi) send_notify( drive->drive, DBT_DEVICEARRIVAL );
531     }
532     return STATUS_SUCCESS;
533 }
534
535 /* remove an existing dos drive, by letter or udi */
536 NTSTATUS remove_dos_device( int letter, const char *udi )
537 {
538     HKEY hkey;
539     struct dos_drive *drive;
540
541     LIST_FOR_EACH_ENTRY( drive, &drives_list, struct dos_drive, entry )
542     {
543         if (letter != -1 && drive->drive != letter) continue;
544         if (udi)
545         {
546             if (!drive->udi) continue;
547             if (strcmp( udi, drive->udi )) continue;
548         }
549
550         if (drive->drive != -1)
551         {
552             BOOL modified = set_unix_mount_point( drive, NULL );
553
554             /* clear the registry key too */
555             if (!RegOpenKeyW( HKEY_LOCAL_MACHINE, drives_keyW, &hkey ))
556             {
557                 WCHAR name[3] = {'a',':',0};
558                 name[0] += drive->drive;
559                 RegDeleteValueW( hkey, name );
560                 RegCloseKey( hkey );
561             }
562
563             if (modified && udi) send_notify( drive->drive, DBT_DEVICEREMOVECOMPLETE );
564         }
565         delete_disk_device( drive );
566         return STATUS_SUCCESS;
567     }
568     return STATUS_NO_SUCH_DEVICE;
569 }
570
571 /* query information about an existing dos drive, by letter or udi */
572 NTSTATUS query_dos_device( int letter, DWORD *type, const char **device, const char **mount_point )
573 {
574     struct dos_drive *drive;
575
576     LIST_FOR_EACH_ENTRY( drive, &drives_list, struct dos_drive, entry )
577     {
578         if (drive->drive != letter) continue;
579         if (type) *type = drive->type;
580         if (device) *device = drive->unix_device;
581         if (mount_point) *mount_point = drive->unix_mount;
582         return STATUS_SUCCESS;
583     }
584     return STATUS_NO_SUCH_DEVICE;
585 }
586
587 /* handler for ioctls on the harddisk device */
588 static NTSTATUS WINAPI harddisk_ioctl( DEVICE_OBJECT *device, IRP *irp )
589 {
590     IO_STACK_LOCATION *irpsp = irp->Tail.Overlay.s.u.CurrentStackLocation;
591     struct dos_drive *drive = device->DeviceExtension;
592
593     TRACE( "ioctl %x insize %u outsize %u\n",
594            irpsp->Parameters.DeviceIoControl.IoControlCode,
595            irpsp->Parameters.DeviceIoControl.InputBufferLength,
596            irpsp->Parameters.DeviceIoControl.OutputBufferLength );
597
598     switch(irpsp->Parameters.DeviceIoControl.IoControlCode)
599     {
600     case IOCTL_DISK_GET_DRIVE_GEOMETRY:
601     {
602         DISK_GEOMETRY info;
603         DWORD len = min( sizeof(info), irpsp->Parameters.DeviceIoControl.OutputBufferLength );
604
605         info.Cylinders.QuadPart = 10000;
606         info.MediaType = (drive->devnum.DeviceType == FILE_DEVICE_DISK) ? FixedMedia : RemovableMedia;
607         info.TracksPerCylinder = 255;
608         info.SectorsPerTrack = 63;
609         info.BytesPerSector = 512;
610         memcpy( irp->MdlAddress->StartVa, &info, len );
611         irp->IoStatus.Information = len;
612         irp->IoStatus.u.Status = STATUS_SUCCESS;
613         break;
614     }
615     case IOCTL_STORAGE_GET_DEVICE_NUMBER:
616     {
617         DWORD len = min( sizeof(drive->devnum), irpsp->Parameters.DeviceIoControl.OutputBufferLength );
618
619         memcpy( irp->MdlAddress->StartVa, &drive->devnum, len );
620         irp->IoStatus.Information = len;
621         irp->IoStatus.u.Status = STATUS_SUCCESS;
622         break;
623     }
624     case IOCTL_CDROM_READ_TOC:
625         irp->IoStatus.u.Status = STATUS_INVALID_DEVICE_REQUEST;
626         break;
627     default:
628         FIXME( "unsupported ioctl %x\n", irpsp->Parameters.DeviceIoControl.IoControlCode );
629         irp->IoStatus.u.Status = STATUS_NOT_SUPPORTED;
630         break;
631     }
632     return irp->IoStatus.u.Status;
633 }
634
635 /* driver entry point for the harddisk driver */
636 NTSTATUS WINAPI harddisk_driver_entry( DRIVER_OBJECT *driver, UNICODE_STRING *path )
637 {
638     struct dos_drive *drive;
639
640     harddisk_driver = driver;
641     driver->MajorFunction[IRP_MJ_DEVICE_CONTROL] = harddisk_ioctl;
642
643     /* create a harddisk0 device that isn't assigned to any drive */
644     create_disk_device( "harddisk0 placeholder", DRIVE_FIXED, &drive );
645
646     create_drive_devices();
647
648     return STATUS_SUCCESS;
649 }