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