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