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