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