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