Debian Codegraph @

bypy/windows/eject.c

raw
1 /*
2 * eject.c
3 * Copyright (C) 2013 Kovid Goyal <kovid at kovidgoyal.net>
4 *
5 * Distributed under terms of the GPL3 license.
6 */
7
8 #include "Windows.h"
9 #include <stdio.h>
10 #include <wchar.h>
11 #include <winioctl.h>
12 #include <setupapi.h>
13 #include <devguid.h>
14 #include <cfgmgr32.h>
15
16 #define BUFSIZE 4096
17 #define LOCK_TIMEOUT 10000 // 10 Seconds
18 #define LOCK_RETRIES 20
19
20 #define BOOL2STR(x) ((x) ? L"True" : L"False")
21
22 // Error handling {{{
23
24 static void
25 show_error(LPCWSTR msg) {
26 MessageBeep(MB_ICONERROR);
27 MessageBoxW(NULL, msg, L"Error", MB_OK | MB_ICONERROR);
28 }
29
30 static void
31 show_detailed_error(LPCWSTR preamble, LPCWSTR msg, int code) {
32 LPWSTR buf;
33 buf = (LPWSTR)LocalAlloc(LMEM_ZEROINIT, sizeof(WCHAR) * (wcslen(msg) + wcslen(preamble) + 80));
34
35 _snwprintf_s(buf, LocalSize(buf) / sizeof(WCHAR), _TRUNCATE, L"%s\r\n %s (Error Code: %d)\r\n", preamble, msg, code);
36
37 show_error(buf);
38 LocalFree(buf);
39 }
40
41 static void
42 print_detailed_error(LPCWSTR preamble, LPCWSTR msg, int code) {
43 fwprintf_s(stderr, L"%s\r\n %s (Error Code: %d)\r\n", preamble, msg, code);
44 fflush(stderr);
45 }
46
47 static void
48 show_last_error_crt(LPCWSTR preamble) {
49 WCHAR buf[BUFSIZE];
50 int err = 0;
51
52 _get_errno(&err);
53 _wcserror_s(buf, BUFSIZE, err);
54 show_detailed_error(preamble, buf, err);
55 }
56
57 static void
58 show_last_error(LPCWSTR preamble) {
59 WCHAR *msg = NULL;
60 DWORD dw = GetLastError();
61
62 FormatMessageW(
63 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
64 NULL,
65 dw,
66 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
67 (LPWSTR)&msg,
68 0,
69 NULL);
70
71 show_detailed_error(preamble, msg, (int)dw);
72 }
73
74 static void
75 print_last_error(LPCWSTR preamble) {
76 WCHAR *msg = NULL;
77 DWORD dw = GetLastError();
78
79 FormatMessageW(
80 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
81 NULL,
82 dw,
83 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
84 (LPWSTR)&msg,
85 0,
86 NULL);
87
88 print_detailed_error(preamble, msg, (int)dw);
89 }
90
91 // }}}
92
93 static void
94 print_help() {
95 fwprintf_s(stderr, L"Usage: calibre-eject.exe drive-letter1 [drive-letter2 drive-letter3 ...]");
96 }
97
98 static LPWSTR root_path = L"X:\\", device_path = L"X:", volume_access_path = L"\\\\.\\X:";
99 static wchar_t dos_device_name[MAX_PATH];
100 static UINT drive_type = 0;
101 static long device_number = -1;
102 static DEVINST dev_inst = 0, dev_inst_parent = 0;
103
104 // Unmount and eject volumes (drives) {{{
105 static HANDLE
106 open_volume(wchar_t drive_letter) {
107 DWORD access_flags;
108
109 switch (drive_type) {
110 case DRIVE_REMOVABLE: access_flags = GENERIC_READ | GENERIC_WRITE; break;
111 case DRIVE_CDROM: access_flags = GENERIC_READ; break;
112 default:
113 fwprintf_s(stderr, L"Cannot eject %c: Drive type is incorrect.\r\n", drive_letter);
114 fflush(stderr);
115 return INVALID_HANDLE_VALUE;
116 }
117
118 return CreateFileW(volume_access_path, access_flags, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
119 }
120
121 static BOOL
122 lock_volume(HANDLE volume) {
123 DWORD bytes_returned;
124 DWORD sleep_amount = LOCK_TIMEOUT / LOCK_RETRIES;
125 int try_count;
126
127 // Do this in a loop until a timeout period has expired
128 for (try_count = 0; try_count < LOCK_RETRIES; try_count++) {
129 if (DeviceIoControl(volume, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &bytes_returned, NULL)) return TRUE;
130
131 Sleep(sleep_amount);
132 }
133
134 return FALSE;
135 }
136
137 static BOOL
138 dismount_volume(HANDLE volume) {
139 DWORD bytes_returned;
140
141 return DeviceIoControl(volume, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &bytes_returned, NULL);
142 }
143
144 static BOOL
145 disable_prevent_removal_of_volume(HANDLE volume) {
146 DWORD bytes_returned;
147 PREVENT_MEDIA_REMOVAL PMRBuffer;
148
149 PMRBuffer.PreventMediaRemoval = FALSE;
150
151 return DeviceIoControl(volume, IOCTL_STORAGE_MEDIA_REMOVAL, &PMRBuffer, sizeof(PREVENT_MEDIA_REMOVAL), NULL, 0, &bytes_returned, NULL);
152 }
153
154 static BOOL
155 auto_eject_volume(HANDLE volume) {
156 DWORD bytes_returned;
157
158 return DeviceIoControl(volume, IOCTL_STORAGE_EJECT_MEDIA, NULL, 0, NULL, 0, &bytes_returned, NULL);
159 }
160
161 static BOOL
162 unmount_drive(wchar_t drive_letter, BOOL *remove_safely, BOOL *auto_eject) {
163 // Unmount the drive identified by drive_letter. Code adapted from:
164 // http://support.microsoft.com/kb/165721
165 HANDLE volume;
166 *remove_safely = FALSE;
167 *auto_eject = FALSE;
168
169 volume = open_volume(drive_letter);
170 if (volume == INVALID_HANDLE_VALUE) return FALSE;
171
172 // Lock and dismount the volume.
173 if (lock_volume(volume) && dismount_volume(volume)) {
174 *remove_safely = TRUE;
175
176 // Set prevent removal to false and eject the volume.
177 if (disable_prevent_removal_of_volume(volume) && auto_eject_volume(volume)) *auto_eject = TRUE;
178 }
179 CloseHandle(volume);
180 return TRUE;
181 }
182 // }}}
183
184 // Eject USB device {{{
185 static void
186 get_device_number(wchar_t drive_letter) {
187 HANDLE volume;
188 DWORD bytes_returned = 0;
189 STORAGE_DEVICE_NUMBER sdn;
190
191 volume = CreateFileW(volume_access_path, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
192 if (volume == INVALID_HANDLE_VALUE) {
193 print_last_error(L"Failed to open volume while getting device number");
194 return;
195 }
196
197 if (DeviceIoControl(volume, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, &sdn, sizeof(sdn), &bytes_returned, NULL)) device_number = sdn.DeviceNumber;
198 CloseHandle(volume);
199 }
200
201 static DEVINST
202 get_dev_inst_by_device_number(long device_number, UINT drive_type, LPWSTR dos_device_name) {
203 GUID *guid;
204 HDEVINFO dev_info;
205 DWORD index, bytes_returned;
206 BOOL bRet, is_floppy;
207 BYTE Buf[1024];
208 PSP_DEVICE_INTERFACE_DETAIL_DATA pspdidd;
209 long res;
210 HANDLE drive;
211 STORAGE_DEVICE_NUMBER sdn;
212 SP_DEVICE_INTERFACE_DATA spdid;
213 SP_DEVINFO_DATA spdd;
214 DWORD size;
215
216 is_floppy = (wcsstr(dos_device_name, L"\\Floppy") != NULL); // is there a better way?
217
218 switch (drive_type) {
219 case DRIVE_REMOVABLE: guid = ((is_floppy) ? (GUID *)&GUID_DEVINTERFACE_FLOPPY : (GUID *)&GUID_DEVINTERFACE_DISK); break;
220 case DRIVE_FIXED: guid = (GUID *)&GUID_DEVINTERFACE_DISK; break;
221 case DRIVE_CDROM: guid = (GUID *)&GUID_DEVINTERFACE_CDROM; break;
222 default:
223 fwprintf_s(stderr, L"Invalid drive type at line: %d\r\n", __LINE__);
224 fflush(stderr);
225 return 0;
226 }
227
228 // Get device interface info set handle
229 // for all devices attached to system
230 dev_info = SetupDiGetClassDevs(guid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
231
232 if (dev_info == INVALID_HANDLE_VALUE) {
233 fwprintf_s(stderr, L"Failed to setup class devs at line: %d\r\n", __LINE__);
234 fflush(stderr);
235 return 0;
236 }
237
238 // Retrieve a context structure for a device interface
239 // of a device information set.
240 index = 0;
241 bRet = FALSE;
242
243 pspdidd = (PSP_DEVICE_INTERFACE_DETAIL_DATA)Buf;
244 spdid.cbSize = sizeof(spdid);
245
246 while (TRUE) {
247 bRet = SetupDiEnumDeviceInterfaces(dev_info, NULL, guid, index, &spdid);
248 if (!bRet) break;
249
250 size = 0;
251 SetupDiGetDeviceInterfaceDetail(dev_info, &spdid, NULL, 0, &size, NULL);
252
253 if (size != 0 && size <= sizeof(Buf)) {
254 pspdidd->cbSize = sizeof(*pspdidd); // 5 Bytes!
255
256 ZeroMemory((PVOID)&spdd, sizeof(spdd));
257 spdd.cbSize = sizeof(spdd);
258
259 res = SetupDiGetDeviceInterfaceDetail(dev_info, &spdid, pspdidd, size, &size, &spdd);
260 if (res) {
261 drive = CreateFile(pspdidd->DevicePath, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
262 if (drive != INVALID_HANDLE_VALUE) {
263 bytes_returned = 0;
264 res = DeviceIoControl(drive, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, &sdn, sizeof(sdn), &bytes_returned, NULL);
265 if (res) {
266 if (device_number == (long)sdn.DeviceNumber) {
267 CloseHandle(drive);
268 SetupDiDestroyDeviceInfoList(dev_info);
269 return spdd.DevInst;
270 }
271 }
272 CloseHandle(drive);
273 }
274 }
275 }
276 index++;
277 }
278
279 SetupDiDestroyDeviceInfoList(dev_info);
280 fwprintf_s(stderr, L"Invalid device number at line: %d\r\n", __LINE__);
281 fflush(stderr);
282
283 return 0;
284 }
285
286
287 static void
288 get_parent_device(wchar_t drive_letter) {
289 get_device_number(drive_letter);
290 if (device_number == -1) return;
291 if (QueryDosDeviceW(device_path, dos_device_name, MAX_PATH) == 0) {
292 print_last_error(L"Failed to query DOS device name");
293 return;
294 }
295
296 dev_inst = get_dev_inst_by_device_number(device_number, drive_type, dos_device_name);
297 if (dev_inst == 0) {
298 fwprintf_s(stderr, L"Failed to get device by device number");
299 fflush(stderr);
300 return;
301 }
302 if (CM_Get_Parent(&dev_inst_parent, dev_inst, 0) != CR_SUCCESS) {
303 fwprintf_s(stderr, L"Failed to get device parent from CM");
304 fflush(stderr);
305 return;
306 }
307 }
308
309 static int
310 eject_device() {
311 int tries;
312 CONFIGRET res;
313 PNP_VETO_TYPE VetoType;
314 WCHAR VetoNameW[MAX_PATH];
315 BOOL success;
316
317 for (tries = 0; tries < 3; tries++) {
318 VetoNameW[0] = 0;
319
320 res = CM_Request_Device_EjectW(dev_inst_parent, &VetoType, VetoNameW, MAX_PATH, 0);
321
322 success = (res == CR_SUCCESS && VetoType == PNP_VetoTypeUnknown);
323 if (success) { break; }
324
325 Sleep(500); // required to give the next tries a chance!
326 }
327 if (!success) {
328 fwprintf_s(stderr, L"CM_Request_Device_Eject failed after three tries\r\n");
329 fflush(stderr);
330 }
331
332 return (success) ? 0 : 1;
333 }
334
335 // }}}
336
337 int
338 wmain(int argc, wchar_t *argv[]) {
339 int i = 0;
340 wchar_t drive_letter;
341 BOOL remove_safely, auto_eject;
342
343 // Validate command line arguments
344 if (argc < 2) {
345 print_help();
346 return 1;
347 }
348 for (i = 1; i < argc; i++) {
349 if (wcsnlen_s(argv[i], 2) != 1) {
350 print_help();
351 return 1;
352 }
353 }
354
355 // Unmount all mounted volumes and eject volume media
356 for (i = 1; i < argc; i++) {
357 drive_letter = *argv[i];
358 root_path[0] = drive_letter;
359 device_path[0] = drive_letter;
360 volume_access_path[4] = drive_letter;
361 drive_type = GetDriveTypeW(root_path);
362 if (i == 1 && device_number == -1) { get_parent_device(drive_letter); }
363 if (device_number != -1) {
364 unmount_drive(drive_letter, &remove_safely, &auto_eject);
365 fwprintf_s(stdout, L"Unmounting: %c: Remove safely: %s Media Ejected: %s\r\n", drive_letter, BOOL2STR(remove_safely), BOOL2STR(auto_eject));
366 fflush(stdout);
367 }
368 }
369
370 // Eject the parent USB device
371 if (device_number == -1) {
372 fwprintf_s(stderr, L"Cannot eject, failed to get device number\r\n");
373 fflush(stderr);
374 return 1;
375 }
376
377 if (dev_inst_parent == 0) {
378 fwprintf_s(stderr, L"Cannot eject, failed to get device parent\r\n");
379 fflush(stderr);
380 return 1;
381 }
382
383 return eject_device();
384 }