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