Various Windows drive scanning hacks.
[dcpomatic.git] / src / lib / cross_windows.cc
1 /*
2     Copyright (C) 2012-2020 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic 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
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "cross.h"
22 #include "compose.hpp"
23 #include "log.h"
24 #include "dcpomatic_log.h"
25 #include "config.h"
26 #include "exceptions.h"
27 #include <dcp/raw_convert.h>
28 #include <glib.h>
29 extern "C" {
30 #include <libavformat/avio.h>
31 }
32 #include <boost/algorithm/string.hpp>
33 #include <boost/foreach.hpp>
34 #include <windows.h>
35 #include <winternl.h>
36 #include <winioctl.h>
37 #include <ntdddisk.h>
38 #include <setupapi.h>
39 #undef DATADIR
40 #include <shlwapi.h>
41 #include <shellapi.h>
42 #include <fcntl.h>
43 #include <fstream>
44
45 #include "i18n.h"
46
47 using std::pair;
48 using std::list;
49 using std::ifstream;
50 using std::string;
51 using std::wstring;
52 using std::make_pair;
53 using std::vector;
54 using std::cerr;
55 using std::cout;
56 using std::runtime_error;
57 using boost::shared_ptr;
58 using boost::optional;
59
60 /** @param s Number of seconds to sleep for */
61 void
62 dcpomatic_sleep_seconds (int s)
63 {
64         Sleep (s * 1000);
65 }
66
67 void
68 dcpomatic_sleep_milliseconds (int ms)
69 {
70         Sleep (ms);
71 }
72
73 /** @return A string of CPU information (model name etc.) */
74 string
75 cpu_info ()
76 {
77         string info;
78
79         HKEY key;
80         if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &key) != ERROR_SUCCESS) {
81                 return info;
82         }
83
84         DWORD type;
85         DWORD data;
86         if (RegQueryValueEx (key, L"ProcessorNameString", 0, &type, 0, &data) != ERROR_SUCCESS) {
87                 return info;
88         }
89
90         if (type != REG_SZ) {
91                 return info;
92         }
93
94         wstring value (data / sizeof (wchar_t), L'\0');
95         if (RegQueryValueEx (key, L"ProcessorNameString", 0, 0, reinterpret_cast<LPBYTE> (&value[0]), &data) != ERROR_SUCCESS) {
96                 RegCloseKey (key);
97                 return info;
98         }
99
100         info = string (value.begin(), value.end());
101
102         RegCloseKey (key);
103
104         return info;
105 }
106
107 boost::filesystem::path
108 shared_path ()
109 {
110         wchar_t dir[512];
111         GetModuleFileName (GetModuleHandle (0), dir, sizeof (dir));
112         PathRemoveFileSpec (dir);
113         boost::filesystem::path path = dir;
114         return path.parent_path();
115 }
116
117 void
118 run_ffprobe (boost::filesystem::path content, boost::filesystem::path out)
119 {
120         SECURITY_ATTRIBUTES security;
121         security.nLength = sizeof (security);
122         security.bInheritHandle = TRUE;
123         security.lpSecurityDescriptor = 0;
124
125         HANDLE child_stderr_read;
126         HANDLE child_stderr_write;
127         if (!CreatePipe (&child_stderr_read, &child_stderr_write, &security, 0)) {
128                 LOG_ERROR_NC ("ffprobe call failed (could not CreatePipe)");
129                 return;
130         }
131
132         wchar_t dir[512];
133         GetModuleFileName (GetModuleHandle (0), dir, sizeof (dir));
134         PathRemoveFileSpec (dir);
135         SetCurrentDirectory (dir);
136
137         STARTUPINFO startup_info;
138         ZeroMemory (&startup_info, sizeof (startup_info));
139         startup_info.cb = sizeof (startup_info);
140         startup_info.hStdError = child_stderr_write;
141         startup_info.dwFlags |= STARTF_USESTDHANDLES;
142
143         wchar_t command[512];
144         wcscpy (command, L"ffprobe.exe \"");
145
146         wchar_t file[512];
147         MultiByteToWideChar (CP_UTF8, 0, content.string().c_str(), -1, file, sizeof(file));
148         wcscat (command, file);
149
150         wcscat (command, L"\"");
151
152         PROCESS_INFORMATION process_info;
153         ZeroMemory (&process_info, sizeof (process_info));
154         if (!CreateProcess (0, command, 0, 0, TRUE, CREATE_NO_WINDOW, 0, 0, &startup_info, &process_info)) {
155                 LOG_ERROR_NC (N_("ffprobe call failed (could not CreateProcess)"));
156                 return;
157         }
158
159         FILE* o = fopen_boost (out, "w");
160         if (!o) {
161                 LOG_ERROR_NC (N_("ffprobe call failed (could not create output file)"));
162                 return;
163         }
164
165         CloseHandle (child_stderr_write);
166
167         while (true) {
168                 char buffer[512];
169                 DWORD read;
170                 if (!ReadFile(child_stderr_read, buffer, sizeof(buffer), &read, 0) || read == 0) {
171                         break;
172                 }
173                 fwrite (buffer, read, 1, o);
174         }
175
176         fclose (o);
177
178         WaitForSingleObject (process_info.hProcess, INFINITE);
179         CloseHandle (process_info.hProcess);
180         CloseHandle (process_info.hThread);
181         CloseHandle (child_stderr_read);
182 }
183
184 list<pair<string, string> >
185 mount_info ()
186 {
187         list<pair<string, string> > m;
188         return m;
189 }
190
191 boost::filesystem::path
192 openssl_path ()
193 {
194         wchar_t dir[512];
195         GetModuleFileName (GetModuleHandle (0), dir, sizeof (dir));
196         PathRemoveFileSpec (dir);
197
198         boost::filesystem::path path = dir;
199         path /= "openssl.exe";
200         return path;
201
202 }
203
204 /* Apparently there is no way to create an ofstream using a UTF-8
205    filename under Windows.  We are hence reduced to using fopen
206    with this wrapper.
207 */
208 FILE *
209 fopen_boost (boost::filesystem::path p, string t)
210 {
211         wstring w (t.begin(), t.end());
212         /* c_str() here should give a UTF-16 string */
213         return _wfopen (p.c_str(), w.c_str ());
214 }
215
216 int
217 dcpomatic_fseek (FILE* stream, int64_t offset, int whence)
218 {
219         return _fseeki64 (stream, offset, whence);
220 }
221
222 void
223 Waker::nudge ()
224 {
225         boost::mutex::scoped_lock lm (_mutex);
226         SetThreadExecutionState (ES_SYSTEM_REQUIRED);
227 }
228
229 Waker::Waker ()
230 {
231
232 }
233
234 Waker::~Waker ()
235 {
236
237 }
238
239 void
240 start_tool (boost::filesystem::path dcpomatic, string executable, string)
241 {
242         boost::filesystem::path batch = dcpomatic.parent_path() / executable;
243
244         STARTUPINFO startup_info;
245         ZeroMemory (&startup_info, sizeof (startup_info));
246         startup_info.cb = sizeof (startup_info);
247
248         PROCESS_INFORMATION process_info;
249         ZeroMemory (&process_info, sizeof (process_info));
250
251         wchar_t cmd[512];
252         MultiByteToWideChar (CP_UTF8, 0, batch.string().c_str(), -1, cmd, sizeof(cmd));
253         CreateProcess (0, cmd, 0, 0, FALSE, 0, 0, 0, &startup_info, &process_info);
254 }
255
256 void
257 start_batch_converter (boost::filesystem::path dcpomatic)
258 {
259         start_tool (dcpomatic, "dcpomatic2_batch", "DCP-o-matic\\ 2\\ Batch\\ Converter.app");
260 }
261
262 void
263 start_player (boost::filesystem::path dcpomatic)
264 {
265         start_tool (dcpomatic, "dcpomatic2_player", "DCP-o-matic\\ 2\\ Player.app");
266 }
267
268 uint64_t
269 thread_id ()
270 {
271         return (uint64_t) GetCurrentThreadId ();
272 }
273
274 static string
275 wchar_to_utf8 (wchar_t const * s)
276 {
277         int const length = (wcslen(s) + 1) * 2;
278         char* utf8 = new char[length];
279         WideCharToMultiByte (CP_UTF8, 0, s, -1, utf8, length, 0, 0);
280         string u (utf8);
281         delete[] utf8;
282         return u;
283 }
284
285 int
286 avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags)
287 {
288         return avio_open (s, wchar_to_utf8(file.c_str()).c_str(), flags);
289 }
290
291 void
292 maybe_open_console ()
293 {
294         if (Config::instance()->win32_console ()) {
295                 AllocConsole();
296
297                 HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
298                 int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
299                 FILE* hf_out = _fdopen(hCrt, "w");
300                 setvbuf(hf_out, NULL, _IONBF, 1);
301                 *stdout = *hf_out;
302
303                 HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
304                 hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
305                 FILE* hf_in = _fdopen(hCrt, "r");
306                 setvbuf(hf_in, NULL, _IONBF, 128);
307                 *stdin = *hf_in;
308         }
309 }
310
311 boost::filesystem::path
312 home_directory ()
313 {
314         return boost::filesystem::path(getenv("HOMEDRIVE")) / boost::filesystem::path(getenv("HOMEPATH"));
315 }
316
317 string
318 command_and_read (string)
319 {
320         return "";
321 }
322
323 /** @return true if this process is a 32-bit one running on a 64-bit-capable OS */
324 bool
325 running_32_on_64 ()
326 {
327         BOOL p;
328         IsWow64Process (GetCurrentProcess(), &p);
329         return p;
330 }
331
332 static optional<string>
333 get_friendly_name (HDEVINFO device_info, SP_DEVINFO_DATA* device_info_data)
334 {
335         wchar_t buffer[MAX_PATH];
336         ZeroMemory (&buffer, sizeof(buffer));
337         bool r = SetupDiGetDeviceRegistryPropertyW (
338                         device_info, device_info_data, SPDRP_FRIENDLYNAME, 0, reinterpret_cast<PBYTE>(buffer), sizeof(buffer), 0
339                         );
340         if (!r) {
341                 return optional<string>();
342         }
343         return wchar_to_utf8 (buffer);
344 }
345
346 static const GUID GUID_DEVICE_INTERFACE_DISK = {
347         0x53F56307L, 0xB6BF, 0x11D0, { 0x94, 0xF2, 0x00, 0xA0, 0xC9, 0x1E, 0xFB, 0x8B }
348 };
349
350 static optional<int>
351 get_device_number (HDEVINFO device_info, SP_DEVINFO_DATA* device_info_data)
352 {
353         /* Find the Windows path to the device */
354
355         SP_DEVICE_INTERFACE_DATA device_interface_data;
356         device_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
357
358         BOOL r = SetupDiEnumDeviceInterfaces (device_info, device_info_data, &GUID_DEVICE_INTERFACE_DISK, 0, &device_interface_data);
359         if (!r) {
360                 LOG_DIST("SetupDiEnumDeviceInterfaces failed (%1)", GetLastError());
361                 return optional<int>();
362         }
363
364         /* Find out how much space we need for our SP_DEVICE_INTERFACE_DETAIL_DATA_W */
365         DWORD size;
366         r = SetupDiGetDeviceInterfaceDetailW(device_info, &device_interface_data, 0, 0, &size, 0);
367         PSP_DEVICE_INTERFACE_DETAIL_DATA_W device_detail_data = static_cast<PSP_DEVICE_INTERFACE_DETAIL_DATA_W> (malloc(size));
368         if (!device_detail_data) {
369                 LOG_DIST_NC("malloc failed");
370                 return optional<int>();
371         }
372
373         device_detail_data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W);
374
375         /* And get the path */
376         r = SetupDiGetDeviceInterfaceDetailW (device_info, &device_interface_data, device_detail_data, size, &size, 0);
377         if (!r) {
378                 LOG_DIST_NC("SetupDiGetDeviceInterfaceDetailW failed");
379                 free (device_detail_data);
380                 return optional<int>();
381         }
382
383         /* Open it.  We would not be allowed GENERIC_READ access here but specifying 0 for
384            dwDesiredAccess allows us to query some metadata.
385         */
386         HANDLE device = CreateFileW (
387                         device_detail_data->DevicePath, 0,
388                         FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
389                         OPEN_EXISTING, 0, 0
390                         );
391
392         free (device_detail_data);
393
394         if (device == INVALID_HANDLE_VALUE) {
395                 LOG_DIST("CreateFileW failed with %1", GetLastError());
396                 return optional<int>();
397         }
398
399         /* Get the device number */
400         STORAGE_DEVICE_NUMBER device_number;
401         r = DeviceIoControl (
402                         device, IOCTL_STORAGE_GET_DEVICE_NUMBER, 0, 0,
403                         &device_number, sizeof(device_number), &size, 0
404                         );
405
406         CloseHandle (device);
407
408         if (!r) {
409                 return optional<int>();
410         }
411
412         return device_number.DeviceNumber;
413 }
414
415 vector<Drive>
416 get_drives ()
417 {
418         vector<Drive> drives;
419
420         /* Get a `device information set' containing information about all disks */
421         HDEVINFO device_info = SetupDiGetClassDevsA (&GUID_DEVICE_INTERFACE_DISK, 0, 0, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
422         if (device_info == INVALID_HANDLE_VALUE) {
423                 LOG_DIST_NC ("SetupDiClassDevsA failed");
424                 return drives;
425         }
426
427         int i = 0;
428         while (true) {
429                 /* Find out about the next disk */
430                 SP_DEVINFO_DATA device_info_data;
431                 device_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
432                 if (!SetupDiEnumDeviceInfo(device_info, i, &device_info_data)) {
433                         DWORD e = GetLastError();
434                         if (e != ERROR_NO_MORE_ITEMS) {
435                                 LOG_DIST ("SetupDiEnumDeviceInfo failed (%1)", GetLastError());
436                         }
437                         break;
438                 }
439                 ++i;
440
441                 optional<string> const friendly_name = get_friendly_name (device_info, &device_info_data);
442                 optional<int> device_number = get_device_number (device_info, &device_info_data);
443                 if (!device_number) {
444                         continue;
445                 }
446
447                 string const physical_drive = String::compose("\\\\.\\PHYSICALDRIVE%1", *device_number);
448
449                 HANDLE device = CreateFileA (
450                                 physical_drive.c_str(), 0,
451                                 FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
452                                 OPEN_EXISTING, 0, 0
453                                 );
454
455                 if (device == INVALID_HANDLE_VALUE) {
456                         LOG_DIST_NC("Could not open PHYSICALDRIVE");
457                 }
458
459                 DISK_GEOMETRY geom;
460                 DWORD returned;
461                 BOOL r = DeviceIoControl (
462                                 device, IOCTL_DISK_GET_DRIVE_GEOMETRY, 0, 0,
463                                 &geom, sizeof(geom), &returned, 0
464                                 );
465
466                 if (r) {
467                         uint64_t const disk_size = geom.Cylinders.QuadPart * geom.TracksPerCylinder * geom.SectorsPerTrack * geom.BytesPerSector;
468                         drives.push_back (Drive(physical_drive, disk_size, false, friendly_name, optional<string>()));
469                 } else {
470                         LOG_DIST("Error %1", GetLastError());
471                 }
472
473                 CloseHandle (device);
474         }
475
476         return drives;
477 }
478
479 string
480 Drive::description () const
481 {
482         char gb[64];
483         snprintf(gb, 64, "%.1f", _size / 1000000000.0);
484
485         string name;
486         if (_vendor) {
487                 name += *_vendor;
488         }
489         if (_model) {
490                 if (name.size() > 0) {
491                         name += " " + *_model;
492                 }
493         }
494         if (name.size() == 0) {
495                 name = _("Unknown");
496         }
497
498         return String::compose("%1 (%2 GB) [%3]", name, gb, _internal_name);
499 }
500
501 boost::filesystem::path
502 config_path ()
503 {
504         boost::filesystem::path p;
505         p /= g_get_user_config_dir ();
506         p /= "dcpomatic2";
507         return p;
508 }