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