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