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