Assorted C++11/formatting cleanups.
[dcpomatic.git] / src / lib / cross_windows.cc
1 /*
2     Copyright (C) 2012-2021 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
22 #include "cross.h"
23 #include "compose.hpp"
24 #include "log.h"
25 #include "dcpomatic_log.h"
26 #include "config.h"
27 #include "exceptions.h"
28 #include "dcpomatic_assert.h"
29 #include <dcp/raw_convert.h>
30 #include <glib.h>
31 extern "C" {
32 #include <libavformat/avio.h>
33 }
34 #include <boost/algorithm/string.hpp>
35 #include <boost/dll/runtime_symbol_info.hpp>
36 #include <windows.h>
37 #include <winternl.h>
38 #include <winioctl.h>
39 #include <ntdddisk.h>
40 #include <setupapi.h>
41 #include <fileapi.h>
42 #undef DATADIR
43 #include <shlwapi.h>
44 #include <shellapi.h>
45 #include <fcntl.h>
46 #include <fstream>
47 #include <map>
48
49 #include "i18n.h"
50
51
52 using std::pair;
53 using std::cerr;
54 using std::cout;
55 using std::ifstream;
56 using std::list;
57 using std::make_pair;
58 using std::map;
59 using std::runtime_error;
60 using std::shared_ptr;
61 using std::string;
62 using std::vector;
63 using std::wstring;
64 using boost::optional;
65
66
67 static std::vector<pair<HANDLE, string>> locked_volumes;
68
69
70 /** @param s Number of seconds to sleep for */
71 void
72 dcpomatic_sleep_seconds (int s)
73 {
74         Sleep (s * 1000);
75 }
76
77
78 void
79 dcpomatic_sleep_milliseconds (int ms)
80 {
81         Sleep (ms);
82 }
83
84
85 /** @return A string of CPU information (model name etc.) */
86 string
87 cpu_info ()
88 {
89         string info;
90
91         HKEY key;
92         if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &key) != ERROR_SUCCESS) {
93                 return info;
94         }
95
96         DWORD type;
97         DWORD data;
98         if (RegQueryValueEx (key, L"ProcessorNameString", 0, &type, 0, &data) != ERROR_SUCCESS) {
99                 return info;
100         }
101
102         if (type != REG_SZ) {
103                 return info;
104         }
105
106         wstring value (data / sizeof (wchar_t), L'\0');
107         if (RegQueryValueEx (key, L"ProcessorNameString", 0, 0, reinterpret_cast<LPBYTE> (&value[0]), &data) != ERROR_SUCCESS) {
108                 RegCloseKey (key);
109                 return info;
110         }
111
112         info = string (value.begin(), value.end());
113
114         RegCloseKey (key);
115
116         return info;
117 }
118
119
120 void
121 run_ffprobe (boost::filesystem::path content, boost::filesystem::path out)
122 {
123         SECURITY_ATTRIBUTES security;
124         security.nLength = sizeof (security);
125         security.bInheritHandle = TRUE;
126         security.lpSecurityDescriptor = 0;
127
128         HANDLE child_stderr_read;
129         HANDLE child_stderr_write;
130         if (!CreatePipe (&child_stderr_read, &child_stderr_write, &security, 0)) {
131                 LOG_ERROR_NC ("ffprobe call failed (could not CreatePipe)");
132                 return;
133         }
134
135         wchar_t dir[512];
136         MultiByteToWideChar (CP_UTF8, 0, directory_containing_executable().string().c_str(), -1, dir, sizeof(dir));
137
138         STARTUPINFO startup_info;
139         ZeroMemory (&startup_info, sizeof (startup_info));
140         startup_info.cb = sizeof (startup_info);
141         startup_info.hStdError = child_stderr_write;
142         startup_info.dwFlags |= STARTF_USESTDHANDLES;
143
144         wchar_t command[512];
145         wcscpy (command, L"ffprobe.exe \"");
146
147         wchar_t file[512];
148         MultiByteToWideChar (CP_UTF8, 0, content.string().c_str(), -1, file, sizeof(file));
149         wcscat (command, file);
150
151         wcscat (command, L"\"");
152
153         PROCESS_INFORMATION process_info;
154         ZeroMemory (&process_info, sizeof (process_info));
155         if (!CreateProcess (0, command, 0, 0, TRUE, CREATE_NO_WINDOW, 0, dir, &startup_info, &process_info)) {
156                 LOG_ERROR_NC (N_("ffprobe call failed (could not CreateProcess)"));
157                 return;
158         }
159
160         auto o = fopen_boost (out, "w");
161         if (!o) {
162                 LOG_ERROR_NC (N_("ffprobe call failed (could not create output file)"));
163                 return;
164         }
165
166         CloseHandle (child_stderr_write);
167
168         while (true) {
169                 char buffer[512];
170                 DWORD read;
171                 if (!ReadFile(child_stderr_read, buffer, sizeof(buffer), &read, 0) || read == 0) {
172                         break;
173                 }
174                 fwrite (buffer, read, 1, o);
175         }
176
177         fclose (o);
178
179         WaitForSingleObject (process_info.hProcess, INFINITE);
180         CloseHandle (process_info.hProcess);
181         CloseHandle (process_info.hThread);
182         CloseHandle (child_stderr_read);
183 }
184
185
186 list<pair<string, string>>
187 mount_info ()
188 {
189         return {};
190 }
191
192
193 boost::filesystem::path
194 directory_containing_executable ()
195 {
196         return boost::dll::program_location().parent_path();
197 }
198
199
200 boost::filesystem::path
201 resources_path ()
202 {
203         return directory_containing_executable().parent_path();
204 }
205
206
207 boost::filesystem::path
208 xsd_path ()
209 {
210         return directory_containing_executable().parent_path() / "xsd";
211 }
212
213
214 boost::filesystem::path
215 tags_path ()
216 {
217         return directory_containing_executable().parent_path() / "tags";
218 }
219
220
221 boost::filesystem::path
222 openssl_path ()
223 {
224         return directory_containing_executable() / "openssl.exe";
225 }
226
227
228 #ifdef DCPOMATIC_DISK
229 boost::filesystem::path
230 disk_writer_path ()
231 {
232         return directory_containing_executable() / "dcpomatic2_disk_writer.exe";
233 }
234 #endif
235
236
237 /* Apparently there is no way to create an ofstream using a UTF-8
238    filename under Windows.  We are hence reduced to using fopen
239    with this wrapper.
240 */
241 FILE *
242 fopen_boost (boost::filesystem::path p, string t)
243 {
244         wstring w (t.begin(), t.end());
245         /* c_str() here should give a UTF-16 string */
246         return _wfopen (p.c_str(), w.c_str ());
247 }
248
249
250 int
251 dcpomatic_fseek (FILE* stream, int64_t offset, int whence)
252 {
253         return _fseeki64 (stream, offset, whence);
254 }
255
256
257 void
258 Waker::nudge ()
259 {
260         boost::mutex::scoped_lock lm (_mutex);
261         SetThreadExecutionState (ES_SYSTEM_REQUIRED);
262 }
263
264
265 Waker::Waker ()
266 {
267
268 }
269
270
271 Waker::~Waker ()
272 {
273
274 }
275
276
277 void
278 start_tool (string executable)
279 {
280         auto batch = directory_containing_executable() / executable;
281
282         STARTUPINFO startup_info;
283         ZeroMemory (&startup_info, sizeof (startup_info));
284         startup_info.cb = sizeof (startup_info);
285
286         PROCESS_INFORMATION process_info;
287         ZeroMemory (&process_info, sizeof (process_info));
288
289         wchar_t cmd[512];
290         MultiByteToWideChar (CP_UTF8, 0, batch.string().c_str(), -1, cmd, sizeof(cmd));
291         CreateProcess (0, cmd, 0, 0, FALSE, 0, 0, 0, &startup_info, &process_info);
292 }
293
294
295 void
296 start_batch_converter ()
297 {
298         start_tool ("dcpomatic2_batch");
299 }
300
301
302 void
303 start_player ()
304 {
305         start_tool ("dcpomatic2_player");
306 }
307
308
309 uint64_t
310 thread_id ()
311 {
312         return (uint64_t) GetCurrentThreadId ();
313 }
314
315
316 static string
317 wchar_to_utf8 (wchar_t const * s)
318 {
319         int const length = (wcslen(s) + 1) * 2;
320         char* utf8 = new char[length];
321         WideCharToMultiByte (CP_UTF8, 0, s, -1, utf8, length, 0, 0);
322         string u (utf8);
323         delete[] utf8;
324         return u;
325 }
326
327
328 int
329 avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags)
330 {
331         return avio_open (s, wchar_to_utf8(file.c_str()).c_str(), flags);
332 }
333
334
335 void
336 maybe_open_console ()
337 {
338         if (Config::instance()->win32_console ()) {
339                 AllocConsole();
340
341                 auto handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
342                 int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
343                 auto hf_out = _fdopen(hCrt, "w");
344                 setvbuf(hf_out, NULL, _IONBF, 1);
345                 *stdout = *hf_out;
346
347                 auto handle_in = GetStdHandle(STD_INPUT_HANDLE);
348                 hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
349                 auto hf_in = _fdopen(hCrt, "r");
350                 setvbuf(hf_in, NULL, _IONBF, 128);
351                 *stdin = *hf_in;
352         }
353 }
354
355
356 boost::filesystem::path
357 home_directory ()
358 {
359         return boost::filesystem::path(getenv("HOMEDRIVE")) / boost::filesystem::path(getenv("HOMEPATH"));
360 }
361
362
363 /** @return true if this process is a 32-bit one running on a 64-bit-capable OS */
364 bool
365 running_32_on_64 ()
366 {
367         BOOL p;
368         IsWow64Process (GetCurrentProcess(), &p);
369         return p;
370 }
371
372
373 static optional<string>
374 get_friendly_name (HDEVINFO device_info, SP_DEVINFO_DATA* device_info_data)
375 {
376         wchar_t buffer[MAX_PATH];
377         ZeroMemory (&buffer, sizeof(buffer));
378         bool r = SetupDiGetDeviceRegistryPropertyW (
379                         device_info, device_info_data, SPDRP_FRIENDLYNAME, 0, reinterpret_cast<PBYTE>(buffer), sizeof(buffer), 0
380                         );
381         if (!r) {
382                 return optional<string>();
383         }
384         return wchar_to_utf8 (buffer);
385 }
386
387
388 static const GUID GUID_DEVICE_INTERFACE_DISK = {
389         0x53F56307L, 0xB6BF, 0x11D0, { 0x94, 0xF2, 0x00, 0xA0, 0xC9, 0x1E, 0xFB, 0x8B }
390 };
391
392
393 static optional<int>
394 get_device_number (HDEVINFO device_info, SP_DEVINFO_DATA* device_info_data)
395 {
396         /* Find the Windows path to the device */
397
398         SP_DEVICE_INTERFACE_DATA device_interface_data;
399         device_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
400
401         auto r = SetupDiEnumDeviceInterfaces (device_info, device_info_data, &GUID_DEVICE_INTERFACE_DISK, 0, &device_interface_data);
402         if (!r) {
403                 LOG_DISK("SetupDiEnumDeviceInterfaces failed (%1)", GetLastError());
404                 return optional<int>();
405         }
406
407         /* Find out how much space we need for our SP_DEVICE_INTERFACE_DETAIL_DATA_W */
408         DWORD size;
409         r = SetupDiGetDeviceInterfaceDetailW(device_info, &device_interface_data, 0, 0, &size, 0);
410         PSP_DEVICE_INTERFACE_DETAIL_DATA_W device_detail_data = static_cast<PSP_DEVICE_INTERFACE_DETAIL_DATA_W> (malloc(size));
411         if (!device_detail_data) {
412                 LOG_DISK_NC("malloc failed");
413                 return optional<int>();
414         }
415
416         device_detail_data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W);
417
418         /* And get the path */
419         r = SetupDiGetDeviceInterfaceDetailW (device_info, &device_interface_data, device_detail_data, size, &size, 0);
420         if (!r) {
421                 LOG_DISK_NC("SetupDiGetDeviceInterfaceDetailW failed");
422                 free (device_detail_data);
423                 return optional<int>();
424         }
425
426         /* Open it.  We would not be allowed GENERIC_READ access here but specifying 0 for
427            dwDesiredAccess allows us to query some metadata.
428         */
429         auto device = CreateFileW (
430                         device_detail_data->DevicePath, 0,
431                         FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
432                         OPEN_EXISTING, 0, 0
433                         );
434
435         free (device_detail_data);
436
437         if (device == INVALID_HANDLE_VALUE) {
438                 LOG_DISK("CreateFileW failed with %1", GetLastError());
439                 return optional<int>();
440         }
441
442         /* Get the device number */
443         STORAGE_DEVICE_NUMBER device_number;
444         r = DeviceIoControl (
445                         device, IOCTL_STORAGE_GET_DEVICE_NUMBER, 0, 0,
446                         &device_number, sizeof(device_number), &size, 0
447                         );
448
449         CloseHandle (device);
450
451         if (!r) {
452                 return {};
453         }
454
455         return device_number.DeviceNumber;
456 }
457
458
459 typedef map<int, vector<boost::filesystem::path>> MountPoints;
460
461
462 /** Take a volume path (with a trailing \) and add any disk numbers related to that volume
463  *  to @ref disks.
464  */
465 static void
466 add_volume_mount_points (wchar_t* volume, MountPoints& mount_points)
467 {
468         LOG_DISK("Looking at %1", wchar_to_utf8(volume));
469
470         wchar_t volume_path_names[512];
471         vector<boost::filesystem::path> mp;
472         DWORD returned;
473         if (GetVolumePathNamesForVolumeNameW(volume, volume_path_names, sizeof(volume_path_names) / sizeof(wchar_t), &returned)) {
474                 wchar_t* p = volume_path_names;
475                 while (*p != L'\0') {
476                         mp.push_back (wchar_to_utf8(p));
477                         LOG_DISK ("Found mount point %1", wchar_to_utf8(p));
478                         p += wcslen(p) + 1;
479                 }
480         }
481
482         /* Strip trailing \ */
483         size_t const len = wcslen (volume);
484         DCPOMATIC_ASSERT (len > 0);
485         volume[len - 1] = L'\0';
486
487         auto handle = CreateFileW (
488                         volume, 0,
489                         FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
490                         OPEN_EXISTING, 0, 0
491                         );
492
493         DCPOMATIC_ASSERT (handle != INVALID_HANDLE_VALUE);
494
495         VOLUME_DISK_EXTENTS extents;
496         DWORD size;
497         BOOL r = DeviceIoControl (handle, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, 0, 0, &extents, sizeof(extents), &size, 0);
498         CloseHandle (handle);
499         if (!r) {
500                 return;
501         }
502         DCPOMATIC_ASSERT (extents.NumberOfDiskExtents == 1);
503
504         mount_points[extents.Extents[0].DiskNumber] = mp;
505 }
506
507
508 MountPoints
509 find_mount_points ()
510 {
511         MountPoints mount_points;
512
513         wchar_t volume_name[512];
514         auto volume = FindFirstVolumeW (volume_name, sizeof(volume_name) / sizeof(wchar_t));
515         if (volume == INVALID_HANDLE_VALUE) {
516                 return MountPoints();
517         }
518
519         add_volume_mount_points (volume_name, mount_points);
520         while (true) {
521                 if (!FindNextVolumeW(volume, volume_name, sizeof(volume_name) / sizeof(wchar_t))) {
522                         break;
523                 }
524                 add_volume_mount_points (volume_name, mount_points);
525         }
526         FindVolumeClose (volume);
527
528         return mount_points;
529 }
530
531
532 vector<Drive>
533 Drive::get ()
534 {
535         vector<Drive> drives;
536
537         auto mount_points = find_mount_points ();
538
539         /* Get a `device information set' containing information about all disks */
540         auto device_info = SetupDiGetClassDevsA (&GUID_DEVICE_INTERFACE_DISK, 0, 0, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
541         if (device_info == INVALID_HANDLE_VALUE) {
542                 LOG_DISK_NC ("SetupDiClassDevsA failed");
543                 return drives;
544         }
545
546         int i = 0;
547         while (true) {
548                 /* Find out about the next disk */
549                 SP_DEVINFO_DATA device_info_data;
550                 device_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
551                 if (!SetupDiEnumDeviceInfo(device_info, i, &device_info_data)) {
552                         DWORD e = GetLastError();
553                         if (e != ERROR_NO_MORE_ITEMS) {
554                                 LOG_DISK ("SetupDiEnumDeviceInfo failed (%1)", GetLastError());
555                         }
556                         break;
557                 }
558                 ++i;
559
560                 auto const friendly_name = get_friendly_name (device_info, &device_info_data);
561                 auto device_number = get_device_number (device_info, &device_info_data);
562                 if (!device_number) {
563                         continue;
564                 }
565
566                 string const physical_drive = String::compose("\\\\.\\PHYSICALDRIVE%1", *device_number);
567
568                 HANDLE device = CreateFileA (
569                                 physical_drive.c_str(), 0,
570                                 FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
571                                 OPEN_EXISTING, 0, 0
572                                 );
573
574                 if (device == INVALID_HANDLE_VALUE) {
575                         LOG_DISK_NC("Could not open PHYSICALDRIVE");
576                         continue;
577                 }
578
579                 DISK_GEOMETRY geom;
580                 DWORD returned;
581                 BOOL r = DeviceIoControl (
582                                 device, IOCTL_DISK_GET_DRIVE_GEOMETRY, 0, 0,
583                                 &geom, sizeof(geom), &returned, 0
584                                 );
585
586                 LOG_DISK("Having a look through %1 locked volumes", locked_volumes.size());
587                 bool locked = false;
588                 for (auto const& i: locked_volumes) {
589                         if (i.second == physical_drive) {
590                                 locked = true;
591                         }
592                 }
593
594                 if (r) {
595                         uint64_t const disk_size = geom.Cylinders.QuadPart * geom.TracksPerCylinder * geom.SectorsPerTrack * geom.BytesPerSector;
596                         drives.push_back (Drive(physical_drive, locked ? vector<boost::filesystem::path>() : mount_points[*device_number], disk_size, friendly_name, optional<string>()));
597                         LOG_DISK("Added drive %1%2", drives.back().log_summary(), locked ? "(locked by us)" : "");
598                 }
599
600                 CloseHandle (device);
601         }
602
603         return drives;
604 }
605
606
607 bool
608 Drive::unmount ()
609 {
610         LOG_DISK("Unmounting %1 with %2 mount points", _device, _mount_points.size());
611         DCPOMATIC_ASSERT (_mount_points.size() == 1);
612         string const device_name = String::compose ("\\\\.\\%1", _mount_points.front());
613         string const truncated = device_name.substr (0, device_name.length() - 1);
614         //LOG_DISK("Actually opening %1", _device);
615         //HANDLE device = CreateFileA (_device.c_str(), (GENERIC_READ | GENERIC_WRITE), FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
616         LOG_DISK("Actually opening %1", truncated);
617         HANDLE device = CreateFileA (truncated.c_str(), (GENERIC_READ | GENERIC_WRITE), FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
618         if (device == INVALID_HANDLE_VALUE) {
619                 LOG_DISK("Could not open %1 for unmount (%2)", truncated, GetLastError());
620                 return false;
621         }
622         DWORD returned;
623         BOOL r = DeviceIoControl (device, FSCTL_LOCK_VOLUME, 0, 0, 0, 0, &returned, 0);
624         if (!r) {
625                 LOG_DISK("Unmount of %1 failed (%2)", truncated, GetLastError());
626                 return false;
627         }
628
629         LOG_DISK("Unmount of %1 succeeded", _device);
630         locked_volumes.push_back (make_pair(device, _device));
631
632         return true;
633 }
634
635
636 boost::filesystem::path
637 config_path ()
638 {
639         boost::filesystem::path p;
640         p /= g_get_user_config_dir ();
641         p /= "dcpomatic2";
642         return p;
643 }
644
645
646 void
647 disk_write_finished ()
648 {
649         for (auto const& i: locked_volumes) {
650                 CloseHandle (i.first);
651         }
652 }
653
654
655 string
656 dcpomatic::get_process_id ()
657 {
658         return dcp::raw_convert<string>(GetCurrentProcessId());
659 }
660