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