e91d3df16c4a6e982bcd871aee39d3b2de77ed1e
[dcpomatic.git] / src / lib / cross_osx.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 "warnings.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/regex.hpp>
36 #if BOOST_VERSION >= 106100
37 #include <boost/dll/runtime_symbol_info.hpp>
38 #endif
39 #include <ApplicationServices/ApplicationServices.h>
40 #include <sys/sysctl.h>
41 #include <mach-o/dyld.h>
42 #include <IOKit/pwr_mgt/IOPMLib.h>
43 #include <IOKit/storage/IOMedia.h>
44 #include <DiskArbitration/DADisk.h>
45 #include <DiskArbitration/DiskArbitration.h>
46 #include <CoreFoundation/CFURL.h>
47 #include <sys/types.h>
48 #include <ifaddrs.h>
49 #include <netinet/in.h>
50 #include <arpa/inet.h>
51 #include <fstream>
52 #include <cstring>
53
54 #include "i18n.h"
55
56 using std::pair;
57 using std::list;
58 using std::ifstream;
59 using std::string;
60 using std::wstring;
61 using std::make_pair;
62 using std::vector;
63 using std::cerr;
64 using std::cout;
65 using std::runtime_error;
66 using std::map;
67 using boost::shared_ptr;
68 using boost::optional;
69 using boost::function;
70
71 /** @param s Number of seconds to sleep for */
72 void
73 dcpomatic_sleep_seconds (int s)
74 {
75         sleep (s);
76 }
77
78 void
79 dcpomatic_sleep_milliseconds (int ms)
80 {
81         usleep (ms * 1000);
82 }
83
84 /** @return A string of CPU information (model name etc.) */
85 string
86 cpu_info ()
87 {
88         string info;
89
90         char buffer[64];
91         size_t N = sizeof (buffer);
92         if (sysctlbyname ("machdep.cpu.brand_string", buffer, &N, 0, 0) == 0) {
93                 info = buffer;
94         }
95
96         return info;
97 }
98
99
100 boost::filesystem::path
101 directory_containing_executable ()
102 {
103 #if BOOST_VERSION >= 106100
104         return boost::dll::program_location().parent_path();
105 #else
106         uint32_t size = 1024;
107         char buffer[size];
108         if (_NSGetExecutablePath (buffer, &size)) {
109                 throw runtime_error ("_NSGetExecutablePath failed");
110         }
111
112         boost::filesystem::path path (buffer);
113         path = boost::filesystem::canonical (path);
114         return path.parent_path ();
115 #endif
116 }
117
118
119 boost::filesystem::path
120 shared_path ()
121 {
122         return directory_containing_executable().parent_path() / "Resources";
123 }
124
125
126 void
127 run_ffprobe (boost::filesystem::path content, boost::filesystem::path out)
128 {
129         boost::filesystem::path path = directory_containing_executable () / "ffprobe";
130
131         string ffprobe = "\"" + path.string() + "\" \"" + content.string() + "\" 2> \"" + out.string() + "\"";
132         LOG_GENERAL (N_("Probing with %1"), ffprobe);
133         system (ffprobe.c_str ());
134 }
135
136
137 list<pair<string, string> >
138 mount_info ()
139 {
140         list<pair<string, string> > m;
141         return m;
142 }
143
144 boost::filesystem::path
145 openssl_path ()
146 {
147         return directory_containing_executable() / "openssl";
148 }
149
150
151 #ifdef DCPOMATIC_DISK
152 /* Note: this isn't actually used at the moment as the disk writer is started as a service */
153 boost::filesystem::path
154 disk_writer_path ()
155 {
156         return directory_containing_executable() / "dcpomatic2_disk_writer";
157 }
158 #endif
159
160 /* Apparently there is no way to create an ofstream using a UTF-8
161    filename under Windows.  We are hence reduced to using fopen
162    with this wrapper.
163 */
164 FILE *
165 fopen_boost (boost::filesystem::path p, string t)
166 {
167         return fopen (p.c_str(), t.c_str ());
168 }
169
170 int
171 dcpomatic_fseek (FILE* stream, int64_t offset, int whence)
172 {
173         return fseek (stream, offset, whence);
174 }
175
176 void
177 Waker::nudge ()
178 {
179
180 }
181
182 Waker::Waker ()
183 {
184         boost::mutex::scoped_lock lm (_mutex);
185         IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, CFSTR ("Encoding DCP"), &_assertion_id);
186 }
187
188 Waker::~Waker ()
189 {
190         boost::mutex::scoped_lock lm (_mutex);
191         IOPMAssertionRelease (_assertion_id);
192 }
193
194 void
195 start_tool (string executable, string app)
196 {
197         boost::filesystem::path batch = directory_containing_executable();
198         batch = batch.parent_path (); // MacOS
199         batch = batch.parent_path (); // Contents
200         batch = batch.parent_path (); // DCP-o-matic.app
201         batch = batch.parent_path (); // Applications
202         batch /= app;
203         batch /= "Contents";
204         batch /= "MacOS";
205         batch /= executable;
206
207         pid_t pid = fork ();
208         if (pid == 0) {
209                 int const r = system (batch.string().c_str());
210                 exit (WEXITSTATUS (r));
211         }
212 }
213
214
215 void
216 start_batch_converter ()
217 {
218         start_tool ("dcpomatic2_batch", "DCP-o-matic\\ 2\\ Batch\\ Converter.app");
219 }
220
221
222 void
223 start_player ()
224 {
225         start_tool ("dcpomatic2_player", "DCP-o-matic\\ 2\\ Player.app");
226 }
227
228
229 uint64_t
230 thread_id ()
231 {
232         return (uint64_t) pthread_self ();
233 }
234
235 int
236 avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags)
237 {
238         return avio_open (s, file.c_str(), flags);
239 }
240
241 boost::filesystem::path
242 home_directory ()
243 {
244                 return getenv("HOME");
245 }
246
247 string
248 command_and_read (string)
249 {
250         return "";
251 }
252
253 /** @return true if this process is a 32-bit one running on a 64-bit-capable OS */
254 bool
255 running_32_on_64 ()
256 {
257         /* I'm assuming nobody does this on OS X */
258         return false;
259 }
260
261 static optional<string>
262 get_vendor (CFDictionaryRef& description)
263 {
264         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceVendorKey);
265         if (!str) {
266                 return optional<string>();
267         }
268
269         string s = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
270         boost::algorithm::trim (s);
271         return s;
272 }
273
274 static optional<string>
275 get_model (CFDictionaryRef& description)
276 {
277         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceModelKey);
278         if (!str) {
279                 return optional<string>();
280         }
281
282         string s = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
283         boost::algorithm::trim (s);
284         return s;
285 }
286
287 struct MediaPath
288 {
289         bool real;       ///< true for a "real" disk, false for a synthesized APFS one
290         std::string prt; ///< "PRT" entry from the media path
291 };
292
293 static optional<MediaPath>
294 analyse_media_path (CFDictionaryRef& description)
295 {
296         using namespace boost::algorithm;
297
298         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionMediaPathKey);
299         if (!str) {
300                 LOG_DISK_NC("There is no MediaPathKey");
301                 return optional<MediaPath>();
302         }
303
304         string path(CFStringGetCStringPtr((CFStringRef) str, kCFStringEncodingUTF8));
305         LOG_DISK("MediaPathKey is %1", path);
306
307         if (path.find("/IOHDIXController") != string::npos) {
308                 /* This is a disk image, so we completely ignore it */
309                 LOG_DISK_NC("Ignoring this as it seems to be a disk image");
310                 return optional<MediaPath>();
311         }
312
313         MediaPath mp;
314         if (starts_with(path, "IODeviceTree:")) {
315                 mp.real = true;
316         } else if (starts_with(path, "IOService:")) {
317                 mp.real = false;
318         } else {
319                 return optional<MediaPath>();
320         }
321
322         vector<string> bits;
323         split(bits, path, boost::is_any_of("/"));
324         BOOST_FOREACH (string i, bits) {
325                 if (starts_with(i, "PRT")) {
326                         mp.prt = i;
327                 }
328         }
329
330         return mp;
331 }
332
333 static bool
334 is_whole_drive (DADiskRef& disk)
335 {
336         io_service_t service = DADiskCopyIOMedia (disk);
337         CFTypeRef whole_media_ref = IORegistryEntryCreateCFProperty (service, CFSTR(kIOMediaWholeKey), kCFAllocatorDefault, 0);
338         bool whole_media = false;
339         if (whole_media_ref) {
340                 whole_media = CFBooleanGetValue((CFBooleanRef) whole_media_ref);
341                 CFRelease (whole_media_ref);
342         }
343         IOObjectRelease (service);
344         return whole_media;
345 }
346
347 static optional<boost::filesystem::path>
348 mount_point (CFDictionaryRef& description)
349 {
350         CFURLRef volume_path_key = (CFURLRef) CFDictionaryGetValue (description, kDADiskDescriptionVolumePathKey);
351         char mount_path_buffer[1024];
352         if (!CFURLGetFileSystemRepresentation(volume_path_key, false, (UInt8 *) mount_path_buffer, sizeof(mount_path_buffer))) {
353                 return boost::optional<boost::filesystem::path>();
354         }
355         return boost::filesystem::path(mount_path_buffer);
356 }
357
358 /* Here follows some rather intricate and (probably) fragile code to find the list of available
359  * "real" drives on macOS that we might want to write a DCP to.
360  *
361  * We use the Disk Arbitration framework to give us a series of mount_points (/dev/disk0, /dev/disk1,
362  * /dev/disk1s1 and so on) and we use the API to gather useful information about these mount_points into
363  * a vector of Disk structs.
364  *
365  * Then we read the Disks that we found and try to derive a list of drives that we should offer to the
366  * user, with details of whether those drives are currently mounted or not.
367  *
368  * At the basic level we find the "disk"-level mount_points, looking at whether any of their partitions are mounted.
369  *
370  * This is complicated enormously by recent-ish macOS versions' habit of making `synthesized' volumes which
371  * reflect data in `real' partitions.  So, for example, we might have a real (physical) drive /dev/disk2 with
372  * a partition /dev/disk2s2 whose content is made into a synthesized /dev/disk3, itself containing some partitions
373  * which are mounted.  /dev/disk2s2 is not considered to be mounted, in this case.  So we need to know that
374  * disk2s2 is related to disk3 so we can consider disk2s2 as mounted if any parts of disk3 are.  In order to do
375  * this I am picking out what looks like a suitable identifier prefixed with PRT from the MediaContentKey.
376  * If disk2s2 and disk3 have the same PRT code I am assuming they are linked.
377  *
378  * Lots of this is guesswork and may be broken.  In my defence the documentation that I have been able to
379  * unearth is, to put it impolitely, crap.
380  */
381
382 struct Disk
383 {
384         string mount_point;
385         optional<string> vendor;
386         optional<string> model;
387         bool real;
388         string prt;
389         bool whole;
390         vector<boost::filesystem::path> mount_points;
391         unsigned long size;
392 };
393
394 static void
395 disk_appeared (DADiskRef disk, void* context)
396 {
397         const char* bsd_name = DADiskGetBSDName (disk);
398         if (!bsd_name) {
399                 return;
400         }
401         LOG_DISK("%1 appeared", bsd_name);
402
403         Disk this_disk;
404
405         this_disk.mount_point = string("/dev/") + bsd_name;
406
407         CFDictionaryRef description = DADiskCopyDescription (disk);
408
409         this_disk.vendor = get_vendor (description);
410         this_disk.model = get_model (description);
411         LOG_DISK("Vendor/model: %1 %2", this_disk.vendor.get_value_or("[none]"), this_disk.model.get_value_or("[none]"));
412
413         optional<MediaPath> media_path = analyse_media_path (description);
414         if (!media_path) {
415                 LOG_DISK("Finding media path for %1 failed", bsd_name);
416                 return;
417         }
418
419         this_disk.real = media_path->real;
420         this_disk.prt = media_path->prt;
421         this_disk.whole = is_whole_drive (disk);
422         optional<boost::filesystem::path> mp = mount_point (description);
423         if (mp) {
424                 this_disk.mount_points.push_back (*mp);
425         }
426
427         LOG_DISK(
428                 "%1 prt %2 whole %3 mounted %4",
429                  this_disk.real ? "Real" : "Synth",
430                  this_disk.prt,
431                  this_disk.whole ? "whole" : "part",
432                  mp ? ("mounted at " + mp->string()) : "unmounted"
433                 );
434
435         CFNumberGetValue ((CFNumberRef) CFDictionaryGetValue (description, kDADiskDescriptionMediaSizeKey), kCFNumberLongType, &this_disk.size);
436         CFRelease (description);
437
438         reinterpret_cast<vector<Disk>*>(context)->push_back(this_disk);
439 }
440
441 vector<Drive>
442 Drive::get ()
443 {
444         using namespace boost::algorithm;
445         vector<Disk> disks;
446
447         DASessionRef session = DASessionCreate(kCFAllocatorDefault);
448         if (!session) {
449                 return vector<Drive>();
450         }
451
452         DARegisterDiskAppearedCallback (session, NULL, disk_appeared, &disks);
453         CFRunLoopRef run_loop = CFRunLoopGetCurrent ();
454         DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
455         CFRunLoopStop (run_loop);
456         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.05, 0);
457         DAUnregisterCallback(session, (void *) disk_appeared, &disks);
458         CFRelease(session);
459
460         /* Mark disks containing mounted partitions as themselves mounted */
461         BOOST_FOREACH (Disk& i, disks) {
462                 if (!i.whole) {
463                         continue;
464                 }
465                 BOOST_FOREACH (Disk& j, disks) {
466                         if (!j.mount_points.empty() && starts_with(j.mount_point, i.mount_point)) {
467                                 LOG_DISK("Marking %1 as mounted because %2 is", i.mount_point, j.mount_point);
468                                 std::copy(j.mount_points.begin(), j.mount_points.end(), back_inserter(i.mount_points));
469                         }
470                 }
471         }
472
473         /* Make a map of the PRT codes and mount points of mounted, synthesized disks */
474         map<string, vector<boost::filesystem::path> > mounted_synths;
475         BOOST_FOREACH (Disk& i, disks) {
476                 if (!i.real && !i.mount_points.empty()) {
477                         LOG_DISK("Found a mounted synth %1 with %2", i.mount_point, i.prt);
478                         mounted_synths[i.prt] = i.mount_points;
479                 }
480         }
481
482         /* Mark containers of those mounted synths as themselves mounted */
483         BOOST_FOREACH (Disk& i, disks) {
484                 if (i.real) {
485                         map<string, vector<boost::filesystem::path> >::const_iterator j = mounted_synths.find(i.prt);
486                         if (j != mounted_synths.end()) {
487                                 LOG_DISK("Marking %1 (%2) as mounted because it contains a mounted synth", i.mount_point, i.prt);
488                                 std::copy(j->second.begin(), j->second.end(), back_inserter(i.mount_points));
489                         }
490                 }
491         }
492
493         vector<Drive> drives;
494         BOOST_FOREACH (Disk& i, disks) {
495                 if (i.whole) {
496                         /* A whole disk that is not a container for a mounted synth */
497                         drives.push_back(Drive(i.mount_point, i.mount_points, i.size, i.vendor, i.model));
498                         LOG_DISK_NC(drives.back().log_summary());
499                 }
500         }
501         return drives;
502 }
503
504
505 boost::filesystem::path
506 config_path ()
507 {
508         boost::filesystem::path p;
509         p /= g_get_home_dir ();
510         p /= "Library";
511         p /= "Preferences";
512         p /= "com.dcpomatic";
513         p /= "2";
514         return p;
515 }
516
517
518 void done_callback(DADiskRef, DADissenterRef dissenter, void* context)
519 {
520         LOG_DISK_NC("Unmount finished");
521         bool* success = reinterpret_cast<bool*> (context);
522         if (dissenter) {
523                 LOG_DISK("Error: %1", DADissenterGetStatus(dissenter));
524                 *success = false;
525         } else {
526                 LOG_DISK_NC("Successful");
527                 *success = true;
528         }
529 }
530
531
532 bool
533 Drive::unmount ()
534 {
535         LOG_DISK_NC("Unmount operation started");
536
537         DASessionRef session = DASessionCreate(kCFAllocatorDefault);
538         if (!session) {
539                 return false;
540         }
541
542         DADiskRef disk = DADiskCreateFromBSDName(kCFAllocatorDefault, session, _device.c_str());
543         if (!disk) {
544                 return false;
545         }
546         LOG_DISK("Requesting unmount of %1 from %2", _device, thread_id());
547         bool success = false;
548         DADiskUnmount(disk, kDADiskUnmountOptionWhole, &done_callback, &success);
549         CFRelease (disk);
550
551         CFRunLoopRef run_loop = CFRunLoopGetCurrent ();
552         DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
553         CFRunLoopStop (run_loop);
554         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.5, 0);
555         CFRelease(session);
556
557         LOG_DISK_NC("End of unmount");
558         return success;
559 }
560
561
562 void
563 disk_write_finished ()
564 {
565
566 }
567
568
569 void
570 make_foreground_application ()
571 {
572         ProcessSerialNumber serial;
573 DCPOMATIC_DISABLE_WARNINGS
574         GetCurrentProcess (&serial);
575 DCPOMATIC_ENABLE_WARNINGS
576         TransformProcessType (&serial, kProcessTransformToForegroundApplication);
577 }
578