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