b06f45a77e82c14b86ec3c1c88bc3535e84f4c67
[dcpomatic.git] / src / lib / cross_osx.cc
1 /*
2     Copyright (C) 2012-2021 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
22 #include "cross.h"
23 #include "compose.hpp"
24 #include "log.h"
25 #include "dcpomatic_log.h"
26 #include "config.h"
27 #include "exceptions.h"
28 #include "warnings.h"
29 #include <dcp/raw_convert.h>
30 #include <glib.h>
31 extern "C" {
32 #include <libavformat/avio.h>
33 }
34 #include <boost/algorithm/string.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
57 using std::pair;
58 using std::list;
59 using std::ifstream;
60 using std::string;
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 std::shared_ptr;
68 using boost::optional;
69 using std::function;
70
71
72 /** @param s Number of seconds to sleep for */
73 void
74 dcpomatic_sleep_seconds (int s)
75 {
76         sleep (s);
77 }
78
79
80 void
81 dcpomatic_sleep_milliseconds (int ms)
82 {
83         usleep (ms * 1000);
84 }
85
86
87 /** @return A string of CPU information (model name etc.) */
88 string
89 cpu_info ()
90 {
91         string info;
92
93         char buffer[64];
94         size_t N = sizeof (buffer);
95         if (sysctlbyname("machdep.cpu.brand_string", buffer, &N, 0, 0) == 0) {
96                 info = buffer;
97         }
98
99         return info;
100 }
101
102
103 boost::filesystem::path
104 directory_containing_executable ()
105 {
106         return boost::filesystem::canonical(boost::dll::program_location()).parent_path();
107 }
108
109
110 boost::filesystem::path
111 resources_path ()
112 {
113         return directory_containing_executable().parent_path() / "Resources";
114 }
115
116
117 boost::filesystem::path
118 xsd_path ()
119 {
120         return resources_path() / "xsd";
121 }
122
123
124 boost::filesystem::path
125 tags_path ()
126 {
127         return resources_path() / "tags";
128 }
129
130
131 void
132 run_ffprobe (boost::filesystem::path content, boost::filesystem::path out)
133 {
134         auto path = directory_containing_executable () / "ffprobe";
135
136         string ffprobe = "\"" + path.string() + "\" \"" + content.string() + "\" 2> \"" + out.string() + "\"";
137         LOG_GENERAL (N_("Probing with %1"), ffprobe);
138         system (ffprobe.c_str ());
139 }
140
141
142
143 list<pair<string, string>>
144 mount_info ()
145 {
146         return {};
147 }
148
149
150 boost::filesystem::path
151 openssl_path ()
152 {
153         return directory_containing_executable() / "openssl";
154 }
155
156
157 #ifdef DCPOMATIC_DISK
158 /* Note: this isn't actually used at the moment as the disk writer is started as a service */
159 boost::filesystem::path
160 disk_writer_path ()
161 {
162         return directory_containing_executable() / "dcpomatic2_disk_writer";
163 }
164 #endif
165
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
178 int
179 dcpomatic_fseek (FILE* stream, int64_t offset, int whence)
180 {
181         return fseek (stream, offset, whence);
182 }
183
184
185 void
186 Waker::nudge ()
187 {
188
189 }
190
191
192 Waker::Waker ()
193 {
194         boost::mutex::scoped_lock lm (_mutex);
195         IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, CFSTR ("Encoding DCP"), &_assertion_id);
196 }
197
198
199 Waker::~Waker ()
200 {
201         boost::mutex::scoped_lock lm (_mutex);
202         IOPMAssertionRelease (_assertion_id);
203 }
204
205
206 void
207 start_tool (string executable, string app)
208 {
209         auto exe_path = directory_containing_executable();
210         exe_path = exe_path.parent_path(); // Contents
211         exe_path = exe_path.parent_path(); // DCP-o-matic 2.app
212         exe_path = exe_path.parent_path(); // Applications
213         exe_path /= app;
214         exe_path /= "Contents";
215         exe_path /= "MacOS";
216         exe_path /= executable;
217
218         pid_t pid = fork ();
219         if (pid == 0) {
220                 LOG_GENERAL ("start_tool %1 %2 with path %3", executable, app, exe_path.string());
221                 int const r = system (exe_path.string().c_str());
222                 exit (WEXITSTATUS (r));
223         } else if (pid == -1) {
224                 LOG_ERROR_NC("Fork failed in start_tool");
225         }
226 }
227
228
229 void
230 start_batch_converter ()
231 {
232         start_tool ("dcpomatic2_batch", "DCP-o-matic\\ 2\\ Batch\\ Converter.app");
233 }
234
235
236 void
237 start_player ()
238 {
239         start_tool ("dcpomatic2_player", "DCP-o-matic\\ 2\\ Player.app");
240 }
241
242
243 uint64_t
244 thread_id ()
245 {
246         return (uint64_t) pthread_self ();
247 }
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
257 boost::filesystem::path
258 home_directory ()
259 {
260         return getenv("HOME");
261 }
262
263
264 /** @return true if this process is a 32-bit one running on a 64-bit-capable OS */
265 bool
266 running_32_on_64 ()
267 {
268         /* I'm assuming nobody does this on OS X */
269         return false;
270 }
271
272
273 static optional<string>
274 get_vendor (CFDictionaryRef& description)
275 {
276         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceVendorKey);
277         if (!str) {
278                 return {};
279         }
280
281         auto c_str = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
282         if (!c_str) {
283                 return {};
284         }
285
286         string s (c_str);
287         boost::algorithm::trim (s);
288         return s;
289 }
290
291
292 static optional<string>
293 get_model (CFDictionaryRef& description)
294 {
295         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceModelKey);
296         if (!str) {
297                 return {};
298         }
299
300         auto c_str = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
301         if (!c_str) {
302                 return {};
303         }
304
305         string s (c_str);
306         boost::algorithm::trim (s);
307         return s;
308 }
309
310
311 static optional<OSXMediaPath>
312 analyse_media_path (CFDictionaryRef& description)
313 {
314         using namespace boost::algorithm;
315
316         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionMediaPathKey);
317         if (!str) {
318                 LOG_DISK_NC("There is no MediaPathKey (no dictionary value)");
319                 return {};
320         }
321
322         auto path_key_cstr = CFStringGetCStringPtr((CFStringRef) str, kCFStringEncodingUTF8);
323         if (!path_key_cstr) {
324                 LOG_DISK_NC("There is no MediaPathKey (no cstring)");
325                 return {};
326         }
327
328         string path(path_key_cstr);
329         LOG_DISK("MediaPathKey is %1", path);
330         return analyse_osx_media_path (path);
331 }
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
349 static optional<boost::filesystem::path>
350 mount_point (CFDictionaryRef& description)
351 {
352         auto volume_path_key = (CFURLRef) CFDictionaryGetValue (description, kDADiskDescriptionVolumePathKey);
353         if (!volume_path_key) {
354                 return {};
355         }
356
357         char mount_path_buffer[1024];
358         if (!CFURLGetFileSystemRepresentation(volume_path_key, false, (UInt8 *) mount_path_buffer, sizeof(mount_path_buffer))) {
359                 return {};
360         }
361         return boost::filesystem::path(mount_path_buffer);
362 }
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 taking the first two parts of the IODeviceTree and seeing if they exist anywhere in a
383  * IOService identifier.  If they do, I am assuming the IOService device is on the matching IODeviceTree device.
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 static void
390 disk_appeared (DADiskRef disk, void* context)
391 {
392         auto bsd_name = DADiskGetBSDName (disk);
393         if (!bsd_name) {
394                 LOG_DISK_NC("Disk with no BSDName appeared");
395                 return;
396         }
397         LOG_DISK("%1 appeared", bsd_name);
398
399         OSXDisk this_disk;
400
401         this_disk.device = string("/dev/") + bsd_name;
402         LOG_DISK("Device is %1", this_disk.device);
403
404         CFDictionaryRef description = DADiskCopyDescription (disk);
405
406         this_disk.vendor = get_vendor (description);
407         this_disk.model = get_model (description);
408         LOG_DISK("Vendor/model: %1 %2", this_disk.vendor.get_value_or("[none]"), this_disk.model.get_value_or("[none]"));
409
410         auto media_path = analyse_media_path (description);
411         if (!media_path) {
412                 LOG_DISK("Finding media path for %1 failed", bsd_name);
413                 return;
414         }
415
416         this_disk.media_path = *media_path;
417         this_disk.whole = is_whole_drive (disk);
418         auto mp = mount_point (description);
419         if (mp) {
420                 this_disk.mount_points.push_back (*mp);
421         }
422
423         LOG_DISK(
424                 "%1 %2 mounted at %3",
425                  this_disk.media_path.real ? "Real" : "Synth",
426                  this_disk.whole ? "whole" : "part",
427                  mp ? mp->string() : "[nowhere]"
428                 );
429
430         auto media_size_cstr = CFDictionaryGetValue (description, kDADiskDescriptionMediaSizeKey);
431         if (!media_size_cstr) {
432                 LOG_DISK_NC("Could not read media size");
433                 return;
434         }
435
436         CFNumberGetValue ((CFNumberRef) media_size_cstr, kCFNumberLongType, &this_disk.size);
437         CFRelease (description);
438
439         reinterpret_cast<vector<OSXDisk>*>(context)->push_back(this_disk);
440 }
441
442
443 vector<Drive>
444 Drive::get ()
445 {
446         using namespace boost::algorithm;
447         vector<OSXDisk> disks;
448
449         auto session = DASessionCreate(kCFAllocatorDefault);
450         if (!session) {
451                 return {};
452         }
453
454         DARegisterDiskAppearedCallback (session, NULL, disk_appeared, &disks);
455         auto run_loop = CFRunLoopGetCurrent ();
456         DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
457         CFRunLoopStop (run_loop);
458         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.05, 0);
459         DAUnregisterCallback(session, (void *) disk_appeared, &disks);
460         CFRelease(session);
461
462         return osx_disks_to_drives (disks);
463 }
464
465
466 boost::filesystem::path
467 config_path (optional<string> version)
468 {
469         boost::filesystem::path p;
470         p /= g_get_home_dir ();
471         p /= "Library";
472         p /= "Preferences";
473         p /= "com.dcpomatic";
474         p /= "2";
475         if (version) {
476                 p /= *version;
477         }
478         return p;
479 }
480
481
482 void done_callback(DADiskRef, DADissenterRef dissenter, void* context)
483 {
484         LOG_DISK_NC("Unmount finished");
485         bool* success = reinterpret_cast<bool*> (context);
486         if (dissenter) {
487                 LOG_DISK("Error: %1", DADissenterGetStatus(dissenter));
488                 *success = false;
489         } else {
490                 LOG_DISK_NC("Successful");
491                 *success = true;
492         }
493 }
494
495
496 bool
497 Drive::unmount ()
498 {
499         LOG_DISK_NC("Unmount operation started");
500
501         auto session = DASessionCreate(kCFAllocatorDefault);
502         if (!session) {
503                 return false;
504         }
505
506         auto disk = DADiskCreateFromBSDName(kCFAllocatorDefault, session, _device.c_str());
507         if (!disk) {
508                 return false;
509         }
510         LOG_DISK("Requesting unmount of %1 from %2", _device, thread_id());
511         bool success = false;
512         DADiskUnmount(disk, kDADiskUnmountOptionWhole, &done_callback, &success);
513         CFRelease (disk);
514
515         CFRunLoopRef run_loop = CFRunLoopGetCurrent ();
516         DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
517         CFRunLoopStop (run_loop);
518         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.5, 0);
519         CFRelease(session);
520
521         LOG_DISK_NC("End of unmount");
522         return success;
523 }
524
525
526 void
527 disk_write_finished ()
528 {
529
530 }
531
532
533 void
534 make_foreground_application ()
535 {
536         ProcessSerialNumber serial;
537 DCPOMATIC_DISABLE_WARNINGS
538         GetCurrentProcess (&serial);
539 DCPOMATIC_ENABLE_WARNINGS
540         TransformProcessType (&serial, kProcessTransformToForegroundApplication);
541 }
542
543
544 string
545 dcpomatic::get_process_id ()
546 {
547         return dcp::raw_convert<string>(getpid());
548 }
549
550
551 boost::filesystem::path
552 fix_long_path (boost::filesystem::path path)
553 {
554         return path;
555 }
556
557
558 bool
559 show_in_file_manager (boost::filesystem::path, boost::filesystem::path select)
560 {
561         int r = system (String::compose("open -R \"%1\"", select.string()).c_str());
562         return static_cast<bool>(WEXITSTATUS(r));
563 }
564