BOOST_FOREACH.
[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 optional<string>();
276         }
277
278         string s = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
279         boost::algorithm::trim (s);
280         return s;
281 }
282
283 static optional<string>
284 get_model (CFDictionaryRef& description)
285 {
286         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceModelKey);
287         if (!str) {
288                 return optional<string>();
289         }
290
291         string s = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
292         boost::algorithm::trim (s);
293         return s;
294 }
295
296 struct MediaPath
297 {
298         bool real;       ///< true for a "real" disk, false for a synthesized APFS one
299         std::string prt; ///< "PRT" entry from the media path
300 };
301
302 static optional<MediaPath>
303 analyse_media_path (CFDictionaryRef& description)
304 {
305         using namespace boost::algorithm;
306
307         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionMediaPathKey);
308         if (!str) {
309                 LOG_DISK_NC("There is no MediaPathKey");
310                 return optional<MediaPath>();
311         }
312
313         string path(CFStringGetCStringPtr((CFStringRef) str, kCFStringEncodingUTF8));
314         LOG_DISK("MediaPathKey is %1", path);
315
316         if (path.find("/IOHDIXController") != string::npos) {
317                 /* This is a disk image, so we completely ignore it */
318                 LOG_DISK_NC("Ignoring this as it seems to be a disk image");
319                 return optional<MediaPath>();
320         }
321
322         MediaPath mp;
323         if (starts_with(path, "IODeviceTree:")) {
324                 mp.real = true;
325         } else if (starts_with(path, "IOService:")) {
326                 mp.real = false;
327         } else {
328                 return optional<MediaPath>();
329         }
330
331         vector<string> bits;
332         split(bits, path, boost::is_any_of("/"));
333         for (auto i: bits) {
334                 if (starts_with(i, "PRT")) {
335                         mp.prt = i;
336                 }
337         }
338
339         return mp;
340 }
341
342 static bool
343 is_whole_drive (DADiskRef& disk)
344 {
345         io_service_t service = DADiskCopyIOMedia (disk);
346         CFTypeRef whole_media_ref = IORegistryEntryCreateCFProperty (service, CFSTR(kIOMediaWholeKey), kCFAllocatorDefault, 0);
347         bool whole_media = false;
348         if (whole_media_ref) {
349                 whole_media = CFBooleanGetValue((CFBooleanRef) whole_media_ref);
350                 CFRelease (whole_media_ref);
351         }
352         IOObjectRelease (service);
353         return whole_media;
354 }
355
356 static optional<boost::filesystem::path>
357 mount_point (CFDictionaryRef& description)
358 {
359         CFURLRef volume_path_key = (CFURLRef) CFDictionaryGetValue (description, kDADiskDescriptionVolumePathKey);
360         char mount_path_buffer[1024];
361         if (!CFURLGetFileSystemRepresentation(volume_path_key, false, (UInt8 *) mount_path_buffer, sizeof(mount_path_buffer))) {
362                 return boost::optional<boost::filesystem::path>();
363         }
364         return boost::filesystem::path(mount_path_buffer);
365 }
366
367 /* Here follows some rather intricate and (probably) fragile code to find the list of available
368  * "real" drives on macOS that we might want to write a DCP to.
369  *
370  * We use the Disk Arbitration framework to give us a series of mount_points (/dev/disk0, /dev/disk1,
371  * /dev/disk1s1 and so on) and we use the API to gather useful information about these mount_points into
372  * a vector of Disk structs.
373  *
374  * Then we read the Disks that we found and try to derive a list of drives that we should offer to the
375  * user, with details of whether those drives are currently mounted or not.
376  *
377  * At the basic level we find the "disk"-level mount_points, looking at whether any of their partitions are mounted.
378  *
379  * This is complicated enormously by recent-ish macOS versions' habit of making `synthesized' volumes which
380  * reflect data in `real' partitions.  So, for example, we might have a real (physical) drive /dev/disk2 with
381  * a partition /dev/disk2s2 whose content is made into a synthesized /dev/disk3, itself containing some partitions
382  * which are mounted.  /dev/disk2s2 is not considered to be mounted, in this case.  So we need to know that
383  * disk2s2 is related to disk3 so we can consider disk2s2 as mounted if any parts of disk3 are.  In order to do
384  * this I am picking out what looks like a suitable identifier prefixed with PRT from the MediaContentKey.
385  * If disk2s2 and disk3 have the same PRT code I am assuming they are linked.
386  *
387  * Lots of this is guesswork and may be broken.  In my defence the documentation that I have been able to
388  * unearth is, to put it impolitely, crap.
389  */
390
391 struct Disk
392 {
393         string mount_point;
394         optional<string> vendor;
395         optional<string> model;
396         bool real;
397         string prt;
398         bool whole;
399         vector<boost::filesystem::path> mount_points;
400         unsigned long size;
401 };
402
403 static void
404 disk_appeared (DADiskRef disk, void* context)
405 {
406         const char* bsd_name = DADiskGetBSDName (disk);
407         if (!bsd_name) {
408                 return;
409         }
410         LOG_DISK("%1 appeared", bsd_name);
411
412         Disk this_disk;
413
414         this_disk.mount_point = string("/dev/") + bsd_name;
415
416         CFDictionaryRef description = DADiskCopyDescription (disk);
417
418         this_disk.vendor = get_vendor (description);
419         this_disk.model = get_model (description);
420         LOG_DISK("Vendor/model: %1 %2", this_disk.vendor.get_value_or("[none]"), this_disk.model.get_value_or("[none]"));
421
422         optional<MediaPath> media_path = analyse_media_path (description);
423         if (!media_path) {
424                 LOG_DISK("Finding media path for %1 failed", bsd_name);
425                 return;
426         }
427
428         this_disk.real = media_path->real;
429         this_disk.prt = media_path->prt;
430         this_disk.whole = is_whole_drive (disk);
431         optional<boost::filesystem::path> mp = mount_point (description);
432         if (mp) {
433                 this_disk.mount_points.push_back (*mp);
434         }
435
436         LOG_DISK(
437                 "%1 prt %2 whole %3 mounted %4",
438                  this_disk.real ? "Real" : "Synth",
439                  this_disk.prt,
440                  this_disk.whole ? "whole" : "part",
441                  mp ? ("mounted at " + mp->string()) : "unmounted"
442                 );
443
444         CFNumberGetValue ((CFNumberRef) CFDictionaryGetValue (description, kDADiskDescriptionMediaSizeKey), kCFNumberLongType, &this_disk.size);
445         CFRelease (description);
446
447         reinterpret_cast<vector<Disk>*>(context)->push_back(this_disk);
448 }
449
450 vector<Drive>
451 Drive::get ()
452 {
453         using namespace boost::algorithm;
454         vector<Disk> disks;
455
456         DASessionRef session = DASessionCreate(kCFAllocatorDefault);
457         if (!session) {
458                 return vector<Drive>();
459         }
460
461         DARegisterDiskAppearedCallback (session, NULL, disk_appeared, &disks);
462         CFRunLoopRef run_loop = CFRunLoopGetCurrent ();
463         DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
464         CFRunLoopStop (run_loop);
465         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.05, 0);
466         DAUnregisterCallback(session, (void *) disk_appeared, &disks);
467         CFRelease(session);
468
469         /* Mark disks containing mounted partitions as themselves mounted */
470         for (auto& i: disks) {
471                 if (!i.whole) {
472                         continue;
473                 }
474                 for (auto& j: disks) {
475                         if (!j.mount_points.empty() && starts_with(j.mount_point, i.mount_point)) {
476                                 LOG_DISK("Marking %1 as mounted because %2 is", i.mount_point, j.mount_point);
477                                 std::copy(j.mount_points.begin(), j.mount_points.end(), back_inserter(i.mount_points));
478                         }
479                 }
480         }
481
482         /* Make a map of the PRT codes and mount points of mounted, synthesized disks */
483         map<string, vector<boost::filesystem::path> > mounted_synths;
484         for (auto& i: disks) {
485                 if (!i.real && !i.mount_points.empty()) {
486                         LOG_DISK("Found a mounted synth %1 with %2", i.mount_point, i.prt);
487                         mounted_synths[i.prt] = i.mount_points;
488                 }
489         }
490
491         /* Mark containers of those mounted synths as themselves mounted */
492         for (auto& i: disks) {
493                 if (i.real) {
494                         map<string, vector<boost::filesystem::path> >::const_iterator j = mounted_synths.find(i.prt);
495                         if (j != mounted_synths.end()) {
496                                 LOG_DISK("Marking %1 (%2) as mounted because it contains a mounted synth", i.mount_point, i.prt);
497                                 std::copy(j->second.begin(), j->second.end(), back_inserter(i.mount_points));
498                         }
499                 }
500         }
501
502         vector<Drive> drives;
503         for (auto& i: disks) {
504                 if (i.whole) {
505                         /* A whole disk that is not a container for a mounted synth */
506                         drives.push_back(Drive(i.mount_point, i.mount_points, i.size, i.vendor, i.model));
507                         LOG_DISK_NC(drives.back().log_summary());
508                 }
509         }
510         return drives;
511 }
512
513
514 boost::filesystem::path
515 config_path ()
516 {
517         boost::filesystem::path p;
518         p /= g_get_home_dir ();
519         p /= "Library";
520         p /= "Preferences";
521         p /= "com.dcpomatic";
522         p /= "2";
523         return p;
524 }
525
526
527 void done_callback(DADiskRef, DADissenterRef dissenter, void* context)
528 {
529         LOG_DISK_NC("Unmount finished");
530         bool* success = reinterpret_cast<bool*> (context);
531         if (dissenter) {
532                 LOG_DISK("Error: %1", DADissenterGetStatus(dissenter));
533                 *success = false;
534         } else {
535                 LOG_DISK_NC("Successful");
536                 *success = true;
537         }
538 }
539
540
541 bool
542 Drive::unmount ()
543 {
544         LOG_DISK_NC("Unmount operation started");
545
546         DASessionRef session = DASessionCreate(kCFAllocatorDefault);
547         if (!session) {
548                 return false;
549         }
550
551         DADiskRef disk = DADiskCreateFromBSDName(kCFAllocatorDefault, session, _device.c_str());
552         if (!disk) {
553                 return false;
554         }
555         LOG_DISK("Requesting unmount of %1 from %2", _device, thread_id());
556         bool success = false;
557         DADiskUnmount(disk, kDADiskUnmountOptionWhole, &done_callback, &success);
558         CFRelease (disk);
559
560         CFRunLoopRef run_loop = CFRunLoopGetCurrent ();
561         DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
562         CFRunLoopStop (run_loop);
563         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.5, 0);
564         CFRelease(session);
565
566         LOG_DISK_NC("End of unmount");
567         return success;
568 }
569
570
571 void
572 disk_write_finished ()
573 {
574
575 }
576
577
578 void
579 make_foreground_application ()
580 {
581         ProcessSerialNumber serial;
582 DCPOMATIC_DISABLE_WARNINGS
583         GetCurrentProcess (&serial);
584 DCPOMATIC_ENABLE_WARNINGS
585         TransformProcessType (&serial, kProcessTransformToForegroundApplication);
586 }
587
588
589 string
590 dcpomatic::get_process_id ()
591 {
592         return dcp::raw_convert<string>(getpid());
593 }