Supporters update.
[dcpomatic.git] / src / lib / cross_osx.cc
1 /*
2     Copyright (C) 2012-2021 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
22 #include "cross.h"
23 #include "compose.hpp"
24 #include "log.h"
25 #include "dcpomatic_log.h"
26 #include "config.h"
27 #include "exceptions.h"
28 #include <dcp/filesystem.h>
29 #include <dcp/raw_convert.h>
30 #include <glib.h>
31 #include <boost/algorithm/string.hpp>
32 #include <boost/regex.hpp>
33 #if BOOST_VERSION >= 106100
34 #include <boost/dll/runtime_symbol_info.hpp>
35 #endif
36 #include <ApplicationServices/ApplicationServices.h>
37 #include <sys/sysctl.h>
38 #include <mach-o/dyld.h>
39 #include <IOKit/pwr_mgt/IOPMLib.h>
40 #include <IOKit/storage/IOMedia.h>
41 #include <DiskArbitration/DADisk.h>
42 #include <DiskArbitration/DiskArbitration.h>
43 #include <CoreFoundation/CFURL.h>
44 #include <sys/types.h>
45 #include <ifaddrs.h>
46 #include <netinet/in.h>
47 #include <arpa/inet.h>
48 #include <fstream>
49 #include <cstring>
50
51 #include "i18n.h"
52
53
54 using std::pair;
55 using std::list;
56 using std::ifstream;
57 using std::string;
58 using std::make_pair;
59 using std::vector;
60 using std::cerr;
61 using std::cout;
62 using std::runtime_error;
63 using std::map;
64 using std::shared_ptr;
65 using boost::optional;
66 using std::function;
67
68
69 /** @return A string of CPU information (model name etc.) */
70 string
71 cpu_info ()
72 {
73         string info;
74
75         char buffer[64];
76         size_t N = sizeof (buffer);
77         if (sysctlbyname("machdep.cpu.brand_string", buffer, &N, 0, 0) == 0) {
78                 info = buffer;
79         }
80
81         return info;
82 }
83
84
85 boost::filesystem::path
86 directory_containing_executable ()
87 {
88         return dcp::filesystem::canonical(boost::dll::program_location()).parent_path();
89 }
90
91
92 boost::filesystem::path
93 resources_path ()
94 {
95         return directory_containing_executable().parent_path() / "Resources";
96 }
97
98
99 boost::filesystem::path
100 libdcp_resources_path ()
101 {
102         return resources_path();
103 }
104
105
106 void
107 run_ffprobe(boost::filesystem::path content, boost::filesystem::path out, bool err, string args)
108 {
109         auto path = directory_containing_executable () / "ffprobe";
110         if (!dcp::filesystem::exists(path)) {
111                 /* This is a hack but we need ffprobe during tests */
112                 path = "/Users/ci/workspace/bin/ffprobe";
113         }
114         string const redirect = err ? "2>" : ">";
115
116         auto const ffprobe = String::compose("\"%1\" %2 \"%3\" %4 \"%5\"", path, args.empty() ? " " : args, content.string(), redirect, out.string());
117         LOG_GENERAL (N_("Probing with %1"), ffprobe);
118         system (ffprobe.c_str());
119 }
120
121
122
123 list<pair<string, string>>
124 mount_info ()
125 {
126         return {};
127 }
128
129
130 boost::filesystem::path
131 openssl_path ()
132 {
133         return directory_containing_executable() / "openssl";
134 }
135
136
137 #ifdef DCPOMATIC_DISK
138 /* Note: this isn't actually used at the moment as the disk writer is started as a service */
139 boost::filesystem::path
140 disk_writer_path ()
141 {
142         return directory_containing_executable() / "dcpomatic2_disk_writer";
143 }
144 #endif
145
146
147 void
148 Waker::nudge ()
149 {
150
151 }
152
153
154 Waker::Waker ()
155 {
156         boost::mutex::scoped_lock lm (_mutex);
157         IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, CFSTR ("Encoding DCP"), &_assertion_id);
158 }
159
160
161 Waker::~Waker ()
162 {
163         boost::mutex::scoped_lock lm (_mutex);
164         IOPMAssertionRelease (_assertion_id);
165 }
166
167
168 void
169 start_tool (string executable, string app)
170 {
171         auto exe_path = directory_containing_executable();
172         exe_path = exe_path.parent_path(); // Contents
173         exe_path = exe_path.parent_path(); // DCP-o-matic 2.app
174         exe_path = exe_path.parent_path(); // Applications
175         exe_path /= app;
176         exe_path /= "Contents";
177         exe_path /= "MacOS";
178         exe_path /= executable;
179
180         pid_t pid = fork ();
181         if (pid == 0) {
182                 LOG_GENERAL ("start_tool %1 %2 with path %3", executable, app, exe_path.string());
183                 int const r = system (exe_path.string().c_str());
184                 exit (WEXITSTATUS (r));
185         } else if (pid == -1) {
186                 LOG_ERROR_NC("Fork failed in start_tool");
187         }
188 }
189
190
191 void
192 start_batch_converter ()
193 {
194         start_tool ("dcpomatic2_batch", "DCP-o-matic\\ 2\\ Batch\\ Converter.app");
195 }
196
197
198 void
199 start_player ()
200 {
201         start_tool ("dcpomatic2_player", "DCP-o-matic\\ 2\\ Player.app");
202 }
203
204
205 static optional<string>
206 get_vendor (CFDictionaryRef& description)
207 {
208         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceVendorKey);
209         if (!str) {
210                 return {};
211         }
212
213         auto c_str = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
214         if (!c_str) {
215                 return {};
216         }
217
218         string s (c_str);
219         boost::algorithm::trim (s);
220         return s;
221 }
222
223
224 static optional<string>
225 get_model (CFDictionaryRef& description)
226 {
227         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceModelKey);
228         if (!str) {
229                 return {};
230         }
231
232         auto c_str = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
233         if (!c_str) {
234                 return {};
235         }
236
237         string s (c_str);
238         boost::algorithm::trim (s);
239         return s;
240 }
241
242
243 static optional<OSXMediaPath>
244 analyse_media_path (CFDictionaryRef& description)
245 {
246         using namespace boost::algorithm;
247
248         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionMediaPathKey);
249         if (!str) {
250                 LOG_DISK_NC("There is no MediaPathKey (no dictionary value)");
251                 return {};
252         }
253
254         auto path_key_cstr = CFStringGetCStringPtr((CFStringRef) str, kCFStringEncodingUTF8);
255         if (!path_key_cstr) {
256                 LOG_DISK_NC("There is no MediaPathKey (no cstring)");
257                 return {};
258         }
259
260         string path(path_key_cstr);
261         LOG_DISK("MediaPathKey is %1", path);
262         return analyse_osx_media_path (path);
263 }
264
265
266 static bool
267 is_whole_drive (DADiskRef& disk)
268 {
269         io_service_t service = DADiskCopyIOMedia (disk);
270         CFTypeRef whole_media_ref = IORegistryEntryCreateCFProperty (service, CFSTR(kIOMediaWholeKey), kCFAllocatorDefault, 0);
271         bool whole_media = false;
272         if (whole_media_ref) {
273                 whole_media = CFBooleanGetValue((CFBooleanRef) whole_media_ref);
274                 CFRelease (whole_media_ref);
275         }
276         IOObjectRelease (service);
277         return whole_media;
278 }
279
280
281 static optional<boost::filesystem::path>
282 mount_point (CFDictionaryRef& description)
283 {
284         auto volume_path_key = (CFURLRef) CFDictionaryGetValue (description, kDADiskDescriptionVolumePathKey);
285         if (!volume_path_key) {
286                 return {};
287         }
288
289         char mount_path_buffer[1024];
290         if (!CFURLGetFileSystemRepresentation(volume_path_key, false, (UInt8 *) mount_path_buffer, sizeof(mount_path_buffer))) {
291                 return {};
292         }
293         return boost::filesystem::path(mount_path_buffer);
294 }
295
296
297 /* Here follows some rather intricate and (probably) fragile code to find the list of available
298  * "real" drives on macOS that we might want to write a DCP to.
299  *
300  * We use the Disk Arbitration framework to give us a series of mount_points (/dev/disk0, /dev/disk1,
301  * /dev/disk1s1 and so on) and we use the API to gather useful information about these mount_points into
302  * a vector of Disk structs.
303  *
304  * Then we read the Disks that we found and try to derive a list of drives that we should offer to the
305  * user, with details of whether those drives are currently mounted or not.
306  *
307  * At the basic level we find the "disk"-level mount_points, looking at whether any of their partitions are mounted.
308  *
309  * This is complicated enormously by recent-ish macOS versions' habit of making `synthesized' volumes which
310  * reflect data in `real' partitions.  So, for example, we might have a real (physical) drive /dev/disk2 with
311  * a partition /dev/disk2s2 whose content is made into a synthesized /dev/disk3, itself containing some partitions
312  * which are mounted.  /dev/disk2s2 is not considered to be mounted, in this case.  So we need to know that
313  * disk2s2 is related to disk3 so we can consider disk2s2 as mounted if any parts of disk3 are.  In order to do
314  * this I am taking the first two parts of the IODeviceTree and seeing if they exist anywhere in a
315  * IOService identifier.  If they do, I am assuming the IOService device is on the matching IODeviceTree device.
316  *
317  * Lots of this is guesswork and may be broken.  In my defence the documentation that I have been able to
318  * unearth is, to put it impolitely, crap.
319  */
320
321 static void
322 disk_appeared (DADiskRef disk, void* context)
323 {
324         auto bsd_name = DADiskGetBSDName (disk);
325         if (!bsd_name) {
326                 LOG_DISK_NC("Disk with no BSDName appeared");
327                 return;
328         }
329         LOG_DISK("%1 appeared", bsd_name);
330
331         OSXDisk this_disk;
332
333         this_disk.device = string("/dev/") + bsd_name;
334         LOG_DISK("Device is %1", this_disk.device);
335
336         CFDictionaryRef description = DADiskCopyDescription (disk);
337
338         this_disk.vendor = get_vendor (description);
339         this_disk.model = get_model (description);
340         LOG_DISK("Vendor/model: %1 %2", this_disk.vendor.get_value_or("[none]"), this_disk.model.get_value_or("[none]"));
341
342         auto media_path = analyse_media_path (description);
343         if (!media_path) {
344                 LOG_DISK("Finding media path for %1 failed", bsd_name);
345                 return;
346         }
347
348         this_disk.media_path = *media_path;
349         this_disk.whole = is_whole_drive (disk);
350         auto mp = mount_point (description);
351         if (mp) {
352                 this_disk.mount_points.push_back (*mp);
353         }
354
355         LOG_DISK(
356                 "%1 %2 mounted at %3",
357                  this_disk.media_path.real ? "Real" : "Synth",
358                  this_disk.whole ? "whole" : "part",
359                  mp ? mp->string() : "[nowhere]"
360                 );
361
362         auto media_size_cstr = CFDictionaryGetValue (description, kDADiskDescriptionMediaSizeKey);
363         if (!media_size_cstr) {
364                 LOG_DISK_NC("Could not read media size");
365                 return;
366         }
367
368         CFNumberGetValue ((CFNumberRef) media_size_cstr, kCFNumberLongType, &this_disk.size);
369         CFRelease (description);
370
371         reinterpret_cast<vector<OSXDisk>*>(context)->push_back(this_disk);
372 }
373
374
375 vector<Drive>
376 Drive::get ()
377 {
378         using namespace boost::algorithm;
379         vector<OSXDisk> disks;
380
381         LOG_DISK_NC("Drive::get() starts");
382
383         auto session = DASessionCreate(kCFAllocatorDefault);
384         if (!session) {
385                 return {};
386         }
387
388         LOG_DISK_NC("Drive::get() has session");
389
390         DARegisterDiskAppearedCallback (session, NULL, disk_appeared, &disks);
391         auto run_loop = CFRunLoopGetCurrent ();
392         DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
393         CFRunLoopStop (run_loop);
394         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.05, 0);
395         DAUnregisterCallback(session, (void *) disk_appeared, &disks);
396         CFRelease(session);
397
398         auto drives = osx_disks_to_drives(disks);
399
400         LOG_DISK("Drive::get() found %1 drives:", drives.size());
401         for (auto const& drive: drives) {
402                 LOG_DISK("%1 %2 mounted=%3", drive.description(), drive.device(), drive.mounted() ? "yes" : "no");
403         }
404
405         return drives;
406 }
407
408
409 boost::filesystem::path
410 config_path (optional<string> version)
411 {
412         boost::filesystem::path p;
413         p /= g_get_home_dir ();
414         p /= "Library";
415         p /= "Preferences";
416         p /= "com.dcpomatic";
417         p /= "2";
418         if (version) {
419                 p /= *version;
420         }
421         return p;
422 }
423
424
425 struct UnmountState
426 {
427         bool success = false;
428         bool callback = false;
429 };
430
431
432 void done_callback(DADiskRef, DADissenterRef dissenter, void* context)
433 {
434         LOG_DISK_NC("Unmount finished");
435         auto state = reinterpret_cast<UnmountState*>(context);
436         state->callback = true;
437         if (dissenter) {
438                 LOG_DISK("Error: %1", DADissenterGetStatus(dissenter));
439         } else {
440                 LOG_DISK_NC("Successful");
441                 state->success = true;
442         }
443 }
444
445
446 bool
447 Drive::unmount ()
448 {
449         LOG_DISK_NC("Unmount operation started");
450
451         auto session = DASessionCreate(kCFAllocatorDefault);
452         if (!session) {
453                 return false;
454         }
455
456         auto disk = DADiskCreateFromBSDName(kCFAllocatorDefault, session, _device.c_str());
457         if (!disk) {
458                 return false;
459         }
460         LOG_DISK("Requesting unmount of %1 from %2", _device, thread_id());
461         UnmountState state;
462         DADiskUnmount(disk, kDADiskUnmountOptionWhole, &done_callback, &state);
463         CFRelease (disk);
464
465         CFRunLoopRef run_loop = CFRunLoopGetCurrent ();
466         DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
467         CFRunLoopStop (run_loop);
468         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 5, 0);
469         CFRelease(session);
470
471         if (!state.callback) {
472                 LOG_DISK_NC("End of unmount: timeout");
473         } else {
474                 LOG_DISK("End of unmount: %1", state.success ? "success" : "failure");
475         }
476         return state.success;
477 }
478
479
480 void
481 disk_write_finished ()
482 {
483
484 }
485
486
487 void
488 make_foreground_application ()
489 {
490         ProcessSerialNumber serial;
491 LIBDCP_DISABLE_WARNINGS
492         GetCurrentProcess (&serial);
493 LIBDCP_ENABLE_WARNINGS
494         TransformProcessType (&serial, kProcessTransformToForegroundApplication);
495 }
496
497
498 bool
499 show_in_file_manager (boost::filesystem::path, boost::filesystem::path select)
500 {
501         int r = system (String::compose("open -R \"%1\"", select.string()).c_str());
502         return static_cast<bool>(WEXITSTATUS(r));
503 }
504