4990f53eecb3f1634f81545919b6f34fc55c8678
[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         auto o = fopen_boost (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                 fwrite (buffer, read, 1, o);
180         }
181
182         fclose (o);
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 xsd_path ()
214 {
215         return directory_containing_executable().parent_path() / "xsd";
216 }
217
218
219 boost::filesystem::path
220 tags_path ()
221 {
222         return directory_containing_executable().parent_path() / "tags";
223 }
224
225
226 boost::filesystem::path
227 openssl_path ()
228 {
229         return directory_containing_executable() / "openssl.exe";
230 }
231
232
233 #ifdef DCPOMATIC_DISK
234 boost::filesystem::path
235 disk_writer_path ()
236 {
237         return directory_containing_executable() / "dcpomatic2_disk_writer.exe";
238 }
239 #endif
240
241
242 /** Windows can't "by default" cope with paths longer than 260 characters, so if you pass such a path to
243  *  any boost::filesystem method it will fail.  There is a "fix" for this, which is to prepend
244  *  the string \\?\ to the path.  This will make it work, so long as:
245  *  - the path is absolute.
246  *  - the path only uses backslashes.
247  *  - individual path components are "short enough" (probably less than 255 characters)
248  *
249  *  See https://www.boost.org/doc/libs/1_57_0/libs/filesystem/doc/reference.html under
250  *  "Warning: Long paths on Windows" for some details.
251  *
252  *  Our fopen_boost uses this method to get this fix, but any other calls to boost::filesystem
253  *  will not unless this method is explicitly called to pre-process the pathname.
254  */
255 boost::filesystem::path
256 fix_long_path (boost::filesystem::path long_path)
257 {
258         using namespace boost::filesystem;
259
260         if (boost::algorithm::starts_with(long_path.string(), "\\\\")) {
261                 /* This could mean it starts with \\ (i.e. a SMB path) or \\?\ (a long path)
262                  * or a variety of other things... anyway, we'll leave it alone.
263                  */
264                 return long_path;
265         }
266
267         /* We have to make the path canonical but we can't call canonical() on the long path
268          * as it will fail.  So we'll sort of do it ourselves (possibly badly).
269          */
270         path fixed = "\\\\?\\";
271         if (long_path.is_absolute()) {
272                 fixed += long_path.make_preferred();
273         } else {
274                 fixed += boost::filesystem::current_path() / long_path.make_preferred();
275         }
276         return fixed;
277 }
278
279
280 /* Apparently there is no way to create an ofstream using a UTF-8
281    filename under Windows.  We are hence reduced to using fopen
282    with this wrapper.
283 */
284 FILE *
285 fopen_boost (boost::filesystem::path p, string t)
286 {
287         wstring w (t.begin(), t.end());
288         /* c_str() on fixed here should give a UTF-16 string */
289         return _wfopen (fix_long_path(p).c_str(), w.c_str());
290 }
291
292
293 int
294 dcpomatic_fseek (FILE* stream, int64_t offset, int whence)
295 {
296         return _fseeki64 (stream, offset, whence);
297 }
298
299
300 void
301 Waker::nudge ()
302 {
303         boost::mutex::scoped_lock lm (_mutex);
304         SetThreadExecutionState (ES_SYSTEM_REQUIRED);
305 }
306
307
308 Waker::Waker ()
309 {
310
311 }
312
313
314 Waker::~Waker ()
315 {
316
317 }
318
319
320 void
321 start_tool (string executable)
322 {
323         auto batch = directory_containing_executable() / executable;
324
325         STARTUPINFO startup_info;
326         ZeroMemory (&startup_info, sizeof (startup_info));
327         startup_info.cb = sizeof (startup_info);
328
329         PROCESS_INFORMATION process_info;
330         ZeroMemory (&process_info, sizeof (process_info));
331
332         wchar_t cmd[512];
333         MultiByteToWideChar (CP_UTF8, 0, batch.string().c_str(), -1, cmd, sizeof(cmd));
334         CreateProcess (0, cmd, 0, 0, FALSE, 0, 0, 0, &startup_info, &process_info);
335 }
336
337
338 void
339 start_batch_converter ()
340 {
341         start_tool ("dcpomatic2_batch");
342 }
343
344
345 void
346 start_player ()
347 {
348         start_tool ("dcpomatic2_player");
349 }
350
351
352 uint64_t
353 thread_id ()
354 {
355         return (uint64_t) GetCurrentThreadId ();
356 }
357
358
359 static string
360 wchar_to_utf8 (wchar_t const * s)
361 {
362         int const length = (wcslen(s) + 1) * 2;
363         char* utf8 = new char[length];
364         WideCharToMultiByte (CP_UTF8, 0, s, -1, utf8, length, 0, 0);
365         string u (utf8);
366         delete[] utf8;
367         return u;
368 }
369
370
371 int
372 avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags)
373 {
374         return avio_open (s, wchar_to_utf8(file.c_str()).c_str(), flags);
375 }
376
377
378 void
379 maybe_open_console ()
380 {
381         if (Config::instance()->win32_console ()) {
382                 AllocConsole();
383
384                 auto handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
385                 int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
386                 auto hf_out = _fdopen(hCrt, "w");
387                 setvbuf(hf_out, NULL, _IONBF, 1);
388                 *stdout = *hf_out;
389
390                 auto handle_in = GetStdHandle(STD_INPUT_HANDLE);
391                 hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
392                 auto hf_in = _fdopen(hCrt, "r");
393                 setvbuf(hf_in, NULL, _IONBF, 128);
394                 *stdin = *hf_in;
395         }
396 }
397
398
399 boost::filesystem::path
400 home_directory ()
401 {
402         PWSTR wide_path;
403         auto result = SHGetKnownFolderPath(FOLDERID_Documents, 0, nullptr, &wide_path);
404
405         if (result != S_OK) {
406                 CoTaskMemFree(wide_path);
407                 return boost::filesystem::path("c:\\");
408         }
409
410         auto path = wchar_to_utf8(wide_path);
411         CoTaskMemFree(wide_path);
412         return path;
413 }
414
415
416 /** @return true if this process is a 32-bit one running on a 64-bit-capable OS */
417 bool
418 running_32_on_64 ()
419 {
420         BOOL p;
421         IsWow64Process (GetCurrentProcess(), &p);
422         return p;
423 }
424
425
426 static optional<string>
427 get_friendly_name (HDEVINFO device_info, SP_DEVINFO_DATA* device_info_data)
428 {
429         wchar_t buffer[MAX_PATH];
430         ZeroMemory (&buffer, sizeof(buffer));
431         bool r = SetupDiGetDeviceRegistryPropertyW (
432                         device_info, device_info_data, SPDRP_FRIENDLYNAME, 0, reinterpret_cast<PBYTE>(buffer), sizeof(buffer), 0
433                         );
434         if (!r) {
435                 return optional<string>();
436         }
437         return wchar_to_utf8 (buffer);
438 }
439
440
441 static const GUID GUID_DEVICE_INTERFACE_DISK = {
442         0x53F56307L, 0xB6BF, 0x11D0, { 0x94, 0xF2, 0x00, 0xA0, 0xC9, 0x1E, 0xFB, 0x8B }
443 };
444
445
446 static optional<int>
447 get_device_number (HDEVINFO device_info, SP_DEVINFO_DATA* device_info_data)
448 {
449         /* Find the Windows path to the device */
450
451         SP_DEVICE_INTERFACE_DATA device_interface_data;
452         device_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
453
454         auto r = SetupDiEnumDeviceInterfaces (device_info, device_info_data, &GUID_DEVICE_INTERFACE_DISK, 0, &device_interface_data);
455         if (!r) {
456                 LOG_DISK("SetupDiEnumDeviceInterfaces failed (%1)", GetLastError());
457                 return optional<int>();
458         }
459
460         /* Find out how much space we need for our SP_DEVICE_INTERFACE_DETAIL_DATA_W */
461         DWORD size;
462         r = SetupDiGetDeviceInterfaceDetailW(device_info, &device_interface_data, 0, 0, &size, 0);
463         PSP_DEVICE_INTERFACE_DETAIL_DATA_W device_detail_data = static_cast<PSP_DEVICE_INTERFACE_DETAIL_DATA_W> (malloc(size));
464         if (!device_detail_data) {
465                 LOG_DISK_NC("malloc failed");
466                 return optional<int>();
467         }
468
469         device_detail_data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W);
470
471         /* And get the path */
472         r = SetupDiGetDeviceInterfaceDetailW (device_info, &device_interface_data, device_detail_data, size, &size, 0);
473         if (!r) {
474                 LOG_DISK_NC("SetupDiGetDeviceInterfaceDetailW failed");
475                 free (device_detail_data);
476                 return optional<int>();
477         }
478
479         /* Open it.  We would not be allowed GENERIC_READ access here but specifying 0 for
480            dwDesiredAccess allows us to query some metadata.
481         */
482         auto device = CreateFileW (
483                         device_detail_data->DevicePath, 0,
484                         FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
485                         OPEN_EXISTING, 0, 0
486                         );
487
488         free (device_detail_data);
489
490         if (device == INVALID_HANDLE_VALUE) {
491                 LOG_DISK("CreateFileW failed with %1", GetLastError());
492                 return optional<int>();
493         }
494
495         /* Get the device number */
496         STORAGE_DEVICE_NUMBER device_number;
497         r = DeviceIoControl (
498                         device, IOCTL_STORAGE_GET_DEVICE_NUMBER, 0, 0,
499                         &device_number, sizeof(device_number), &size, 0
500                         );
501
502         CloseHandle (device);
503
504         if (!r) {
505                 return {};
506         }
507
508         return device_number.DeviceNumber;
509 }
510
511
512 typedef map<int, vector<boost::filesystem::path>> MountPoints;
513
514
515 /** Take a volume path (with a trailing \) and add any disk numbers related to that volume
516  *  to @ref disks.
517  */
518 static void
519 add_volume_mount_points (wchar_t* volume, MountPoints& mount_points)
520 {
521         LOG_DISK("Looking at %1", wchar_to_utf8(volume));
522
523         wchar_t volume_path_names[512];
524         vector<boost::filesystem::path> mp;
525         DWORD returned;
526         if (GetVolumePathNamesForVolumeNameW(volume, volume_path_names, sizeof(volume_path_names) / sizeof(wchar_t), &returned)) {
527                 wchar_t* p = volume_path_names;
528                 while (*p != L'\0') {
529                         mp.push_back (wchar_to_utf8(p));
530                         LOG_DISK ("Found mount point %1", wchar_to_utf8(p));
531                         p += wcslen(p) + 1;
532                 }
533         }
534
535         /* Strip trailing \ */
536         size_t const len = wcslen (volume);
537         DCPOMATIC_ASSERT (len > 0);
538         volume[len - 1] = L'\0';
539
540         auto handle = CreateFileW (
541                         volume, 0,
542                         FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
543                         OPEN_EXISTING, 0, 0
544                         );
545
546         DCPOMATIC_ASSERT (handle != INVALID_HANDLE_VALUE);
547
548         VOLUME_DISK_EXTENTS extents;
549         DWORD size;
550         BOOL r = DeviceIoControl (handle, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, 0, 0, &extents, sizeof(extents), &size, 0);
551         CloseHandle (handle);
552         if (!r) {
553                 return;
554         }
555         DCPOMATIC_ASSERT (extents.NumberOfDiskExtents == 1);
556
557         mount_points[extents.Extents[0].DiskNumber] = mp;
558 }
559
560
561 MountPoints
562 find_mount_points ()
563 {
564         MountPoints mount_points;
565
566         wchar_t volume_name[512];
567         auto volume = FindFirstVolumeW (volume_name, sizeof(volume_name) / sizeof(wchar_t));
568         if (volume == INVALID_HANDLE_VALUE) {
569                 return MountPoints();
570         }
571
572         add_volume_mount_points (volume_name, mount_points);
573         while (true) {
574                 if (!FindNextVolumeW(volume, volume_name, sizeof(volume_name) / sizeof(wchar_t))) {
575                         break;
576                 }
577                 add_volume_mount_points (volume_name, mount_points);
578         }
579         FindVolumeClose (volume);
580
581         return mount_points;
582 }
583
584
585 vector<Drive>
586 Drive::get ()
587 {
588         vector<Drive> drives;
589
590         auto mount_points = find_mount_points ();
591
592         /* Get a `device information set' containing information about all disks */
593         auto device_info = SetupDiGetClassDevsA (&GUID_DEVICE_INTERFACE_DISK, 0, 0, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
594         if (device_info == INVALID_HANDLE_VALUE) {
595                 LOG_DISK_NC ("SetupDiClassDevsA failed");
596                 return drives;
597         }
598
599         int i = 0;
600         while (true) {
601                 /* Find out about the next disk */
602                 SP_DEVINFO_DATA device_info_data;
603                 device_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
604                 if (!SetupDiEnumDeviceInfo(device_info, i, &device_info_data)) {
605                         DWORD e = GetLastError();
606                         if (e != ERROR_NO_MORE_ITEMS) {
607                                 LOG_DISK ("SetupDiEnumDeviceInfo failed (%1)", GetLastError());
608                         }
609                         break;
610                 }
611                 ++i;
612
613                 auto const friendly_name = get_friendly_name (device_info, &device_info_data);
614                 auto device_number = get_device_number (device_info, &device_info_data);
615                 if (!device_number) {
616                         continue;
617                 }
618
619                 string const physical_drive = String::compose("\\\\.\\PHYSICALDRIVE%1", *device_number);
620
621                 HANDLE device = CreateFileA (
622                                 physical_drive.c_str(), 0,
623                                 FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
624                                 OPEN_EXISTING, 0, 0
625                                 );
626
627                 if (device == INVALID_HANDLE_VALUE) {
628                         LOG_DISK_NC("Could not open PHYSICALDRIVE");
629                         continue;
630                 }
631
632                 DISK_GEOMETRY geom;
633                 DWORD returned;
634                 BOOL r = DeviceIoControl (
635                                 device, IOCTL_DISK_GET_DRIVE_GEOMETRY, 0, 0,
636                                 &geom, sizeof(geom), &returned, 0
637                                 );
638
639                 LOG_DISK("Having a look through %1 locked volumes", locked_volumes.size());
640                 bool locked = false;
641                 for (auto const& i: locked_volumes) {
642                         if (i.second == physical_drive) {
643                                 locked = true;
644                         }
645                 }
646
647                 if (r) {
648                         uint64_t const disk_size = geom.Cylinders.QuadPart * geom.TracksPerCylinder * geom.SectorsPerTrack * geom.BytesPerSector;
649                         drives.push_back (Drive(physical_drive, locked ? vector<boost::filesystem::path>() : mount_points[*device_number], disk_size, friendly_name, optional<string>()));
650                         LOG_DISK("Added drive %1%2", drives.back().log_summary(), locked ? "(locked by us)" : "");
651                 }
652
653                 CloseHandle (device);
654         }
655
656         return drives;
657 }
658
659
660 bool
661 Drive::unmount ()
662 {
663         LOG_DISK("Unmounting %1 with %2 mount points", _device, _mount_points.size());
664         DCPOMATIC_ASSERT (_mount_points.size() == 1);
665         string const device_name = String::compose ("\\\\.\\%1", _mount_points.front());
666         string const truncated = device_name.substr (0, device_name.length() - 1);
667         //LOG_DISK("Actually opening %1", _device);
668         //HANDLE device = CreateFileA (_device.c_str(), (GENERIC_READ | GENERIC_WRITE), FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
669         LOG_DISK("Actually opening %1", truncated);
670         HANDLE device = CreateFileA (truncated.c_str(), (GENERIC_READ | GENERIC_WRITE), FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
671         if (device == INVALID_HANDLE_VALUE) {
672                 LOG_DISK("Could not open %1 for unmount (%2)", truncated, GetLastError());
673                 return false;
674         }
675         DWORD returned;
676         BOOL r = DeviceIoControl (device, FSCTL_LOCK_VOLUME, 0, 0, 0, 0, &returned, 0);
677         if (!r) {
678                 LOG_DISK("Unmount of %1 failed (%2)", truncated, GetLastError());
679                 return false;
680         }
681
682         LOG_DISK("Unmount of %1 succeeded", _device);
683         locked_volumes.push_back (make_pair(device, _device));
684
685         return true;
686 }
687
688
689 boost::filesystem::path
690 config_path (optional<string> version)
691 {
692         boost::filesystem::path p;
693         p /= g_get_user_config_dir ();
694         p /= "dcpomatic2";
695         if (version) {
696                 p /= *version;
697         }
698         return p;
699 }
700
701
702 void
703 disk_write_finished ()
704 {
705         for (auto const& i: locked_volumes) {
706                 CloseHandle (i.first);
707         }
708 }
709
710
711 string
712 dcpomatic::get_process_id ()
713 {
714         return dcp::raw_convert<string>(GetCurrentProcessId());
715 }
716
717
718 bool
719 show_in_file_manager (boost::filesystem::path, boost::filesystem::path select)
720 {
721         std::wstringstream args;
722         args << "/select," << select;
723         auto const r = ShellExecute (0, L"open", L"explorer.exe", args.str().c_str(), 0, SW_SHOWDEFAULT);
724         return (reinterpret_cast<int64_t>(r) <= 32);
725 }
726