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