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