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