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