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