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