Tidy up nanomsg class API; add unmounting for Linux.
[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 boost::shared_ptr;
62 using boost::optional;
63
64 /** @param s Number of seconds to sleep for */
65 void
66 dcpomatic_sleep_seconds (int s)
67 {
68         sleep (s);
69 }
70
71 void
72 dcpomatic_sleep_milliseconds (int ms)
73 {
74         usleep (ms * 1000);
75 }
76
77 /** @return A string of CPU information (model name etc.) */
78 string
79 cpu_info ()
80 {
81         string info;
82
83         char buffer[64];
84         size_t N = sizeof (buffer);
85         if (sysctlbyname ("machdep.cpu.brand_string", buffer, &N, 0, 0) == 0) {
86                 info = buffer;
87         }
88
89         return info;
90 }
91
92 /** @return Path of the Contents directory in the .app */
93 boost::filesystem::path
94 app_contents ()
95 {
96         /* Could use boost::dll::program_location().parent_path().parent_path() but that
97          * boost library isn't in the 10.6 environment we're currently using and I don't
98          * really want to change it right now.
99          */
100         uint32_t size = 1024;
101         char buffer[size];
102         if (_NSGetExecutablePath (buffer, &size)) {
103                 throw runtime_error ("_NSGetExecutablePath failed");
104         }
105
106         boost::filesystem::path path (buffer);
107         path = boost::filesystem::canonical (path);
108         path = path.parent_path ();
109         path = path.parent_path ();
110         return path;
111 }
112
113 boost::filesystem::path
114 shared_path ()
115 {
116         return app_contents() / "Resources";
117 }
118
119 void
120 run_ffprobe (boost::filesystem::path content, boost::filesystem::path out)
121 {
122         boost::filesystem::path path = app_contents();
123         path /= "MacOS";
124         path /= "ffprobe";
125
126         string ffprobe = "\"" + path.string() + "\" \"" + content.string() + "\" 2> \"" + out.string() + "\"";
127         LOG_GENERAL (N_("Probing with %1"), ffprobe);
128         system (ffprobe.c_str ());
129 }
130
131 list<pair<string, string> >
132 mount_info ()
133 {
134         list<pair<string, string> > m;
135         return m;
136 }
137
138 boost::filesystem::path
139 openssl_path ()
140 {
141         boost::filesystem::path path = app_contents();
142         path /= "MacOS";
143         path /= "openssl";
144         return path;
145 }
146
147 #ifdef DCPOMATIC_DISK
148 boost::filesystem::path
149 disk_writer_path ()
150 {
151         boost::filesystem::path path = app_contents();
152         path /= "MacOS";
153         path /= "dcpomatic2_disk_writer";
154         return path;
155 }
156 #endif
157
158 /* Apparently there is no way to create an ofstream using a UTF-8
159    filename under Windows.  We are hence reduced to using fopen
160    with this wrapper.
161 */
162 FILE *
163 fopen_boost (boost::filesystem::path p, string t)
164 {
165         return fopen (p.c_str(), t.c_str ());
166 }
167
168 int
169 dcpomatic_fseek (FILE* stream, int64_t offset, int whence)
170 {
171         return fseek (stream, offset, whence);
172 }
173
174 void
175 Waker::nudge ()
176 {
177
178 }
179
180 Waker::Waker ()
181 {
182         boost::mutex::scoped_lock lm (_mutex);
183         /* We should use this */
184         // IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, CFSTR ("Encoding DCP"), &_assertion_id);
185         /* but it's not available on 10.5, so we use this */
186         IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &_assertion_id);
187 }
188
189 Waker::~Waker ()
190 {
191         boost::mutex::scoped_lock lm (_mutex);
192         IOPMAssertionRelease (_assertion_id);
193 }
194
195 void
196 start_tool (boost::filesystem::path dcpomatic, string executable, string app)
197 {
198         boost::filesystem::path batch = dcpomatic.parent_path ();
199         batch = batch.parent_path (); // MacOS
200         batch = batch.parent_path (); // Contents
201         batch = batch.parent_path (); // DCP-o-matic.app
202         batch = batch.parent_path (); // Applications
203         batch /= app;
204         batch /= "Contents";
205         batch /= "MacOS";
206         batch /= executable;
207
208         pid_t pid = fork ();
209         if (pid == 0) {
210                 int const r = system (batch.string().c_str());
211                 exit (WEXITSTATUS (r));
212         }
213 }
214
215 void
216 start_batch_converter (boost::filesystem::path dcpomatic)
217 {
218         start_tool (dcpomatic, "dcpomatic2_batch", "DCP-o-matic\\ 2\\ Batch\\ Converter.app");
219 }
220
221 void
222 start_player (boost::filesystem::path dcpomatic)
223 {
224         start_tool (dcpomatic, "dcpomatic2_player", "DCP-o-matic\\ 2\\ Player.app");
225 }
226
227 uint64_t
228 thread_id ()
229 {
230         return (uint64_t) pthread_self ();
231 }
232
233 int
234 avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags)
235 {
236         return avio_open (s, file.c_str(), flags);
237 }
238
239 boost::filesystem::path
240 home_directory ()
241 {
242                 return getenv("HOME");
243 }
244
245 string
246 command_and_read (string cmd)
247 {
248         return "";
249 }
250
251 /** @return true if this process is a 32-bit one running on a 64-bit-capable OS */
252 bool
253 running_32_on_64 ()
254 {
255         /* I'm assuming nobody does this on OS X */
256         return false;
257 }
258
259 static optional<string>
260 get_vendor (CFDictionaryRef& description)
261 {
262         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceVendorKey);
263         if (!str) {
264                 return optional<string>();
265         }
266
267         string s = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
268         boost::algorithm::trim (s);
269         return s;
270 }
271
272 static optional<string>
273 get_model (CFDictionaryRef& description)
274 {
275         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceModelKey);
276         if (!str) {
277                 return optional<string>();
278         }
279
280         string s = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
281         boost::algorithm::trim (s);
282         return s;
283 }
284
285 struct MediaPath
286 {
287         bool real;       ///< true for a "real" disk, false for a synthesized APFS one
288         std::string prt; ///< "PRT" entry from the media path
289 };
290
291 static optional<MediaPath>
292 analyse_media_path (CFDictionaryRef& description)
293 {
294         using namespace boost::algorithm;
295
296         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionMediaPathKey);
297         if (!str) {
298                 return optional<MediaPath>();
299         }
300
301         string path(CFStringGetCStringPtr((CFStringRef) str, kCFStringEncodingUTF8));
302         MediaPath mp;
303         if (starts_with(path, "IODeviceTree:")) {
304                 mp.real = true;
305         } else if (starts_with(path, "IOService:")) {
306                 mp.real = false;
307         } else {
308                 return optional<MediaPath>();
309         }
310
311         vector<string> bits;
312         split(bits, path, boost::is_any_of("/"));
313         BOOST_FOREACH (string i, bits) {
314                 if (starts_with(i, "PRT")) {
315                         mp.prt = i;
316                 }
317         }
318
319         return mp;
320 }
321
322 static bool
323 is_whole_drive (DADiskRef& disk)
324 {
325         io_service_t service = DADiskCopyIOMedia (disk);
326         CFTypeRef whole_media_ref = IORegistryEntryCreateCFProperty (service, CFSTR(kIOMediaWholeKey), kCFAllocatorDefault, 0);
327         bool whole_media = false;
328         if (whole_media_ref) {
329                 whole_media = CFBooleanGetValue((CFBooleanRef) whole_media_ref);
330                 CFRelease (whole_media_ref);
331         }
332         IOObjectRelease (service);
333         return whole_media;
334 }
335
336 static bool
337 is_mounted (CFDictionaryRef& description)
338 {
339         CFURLRef volume_path_key = (CFURLRef) CFDictionaryGetValue (description, kDADiskDescriptionVolumePathKey);
340         char mount_path_buffer[1024];
341         return CFURLGetFileSystemRepresentation(volume_path_key, false, (UInt8 *) mount_path_buffer, sizeof(mount_path_buffer));
342 }
343
344 /* Here follows some rather intricate and (probably) fragile code to find the list of available
345  * "real" drives on macOS that we might want to write a DCP to.
346  *
347  * We use the Disk Arbitration framework to give us a series of devices (/dev/disk0, /dev/disk1,
348  * /dev/disk1s1 and so on) and we use the API to gather useful information about these devices into
349  * a vector of Disk structs.
350  *
351  * Then we read the Disks that we found and try to derive a list of drives that we should offer to the
352  * user, with details of whether those drives are currently mounted or not.
353  *
354  * At the basic level we find the "disk"-level devices, looking at whether any of their partitions are mounted.
355  *
356  * This is complicated enormously by recent-ish macOS versions' habit of making `synthesized' volumes which
357  * reflect data in `real' partitions.  So, for example, we might have a real (physical) drive /dev/disk2 with
358  * a partition /dev/disk2s2 whose content is made into a synthesized /dev/disk3, itself containing some partitions
359  * which are mounted.  /dev/disk2s2 is not considered to be mounted, in this case.  So we need to know that
360  * disk2s2 is related to disk3 so we can consider disk2s2 as mounted if any parts of disk3 are.  In order to do
361  * this I am picking out what looks like a suitable identifier prefixed with PRT from the MediaContentKey.
362  * If disk2s2 and disk3 have the same PRT code I am assuming they are linked.
363  *
364  * Lots of this is guesswork and may be broken.  In my defence the documentation that I have been able to
365  * unearth is, to put it impolitely, crap.
366  */
367
368 struct Disk
369 {
370         string device;
371         optional<string> vendor;
372         optional<string> model;
373         bool real;
374         string prt;
375         bool whole;
376         bool mounted;
377         unsigned long size;
378 };
379
380 static void
381 disk_appeared (DADiskRef disk, void* context)
382 {
383         const char* bsd_name = DADiskGetBSDName (disk);
384         if (!bsd_name) {
385                 return;
386         }
387         LOG_DISK("%1 appeared", bsd_name);
388
389         Disk this_disk;
390
391         this_disk.device = string("/dev/") + bsd_name;
392
393         CFDictionaryRef description = DADiskCopyDescription (disk);
394
395         this_disk.vendor = get_vendor (description);
396         this_disk.model = get_model (description);
397         LOG_DISK("Vendor/model: %1 %2", this_disk.vendor.get_value_or("[none]"), this_disk.model.get_value_or("[none]"));
398
399         optional<MediaPath> media_path = analyse_media_path (description);
400         if (!media_path) {
401                 LOG_DISK("Finding media path for %1 failed", bsd_name);
402                 return;
403         }
404
405         this_disk.real = media_path->real;
406         this_disk.prt = media_path->prt;
407         this_disk.whole = is_whole_drive (disk);
408         this_disk.mounted = is_mounted (description);
409         LOG_DISK("%1 prt %2 whole %3 mounted %4", this_disk.real ? "Real" : "Synth", this_disk.prt, this_disk.whole ? "whole" : "part", this_disk.mounted ? "mounted" : "unmounted");
410
411         CFNumberGetValue ((CFNumberRef) CFDictionaryGetValue (description, kDADiskDescriptionMediaSizeKey), kCFNumberLongType, &this_disk.size);
412         CFRelease (description);
413
414         reinterpret_cast<vector<Disk>*>(context)->push_back(this_disk);
415 }
416
417 vector<Drive>
418 get_drives ()
419 {
420         using namespace boost::algorithm;
421         vector<Disk> disks;
422
423         DASessionRef session = DASessionCreate(kCFAllocatorDefault);
424         if (!session) {
425                 return vector<Drive>();
426         }
427
428         DARegisterDiskAppearedCallback (session, NULL, disk_appeared, &disks);
429         CFRunLoopRef run_loop = CFRunLoopGetCurrent ();
430         DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
431         CFRunLoopStop (run_loop);
432         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.05, 0);
433         DAUnregisterCallback(session, (void *) disk_appeared, &disks);
434         CFRelease(session);
435
436         /* Mark disks containing mounted partitions as themselves mounted */
437         BOOST_FOREACH (Disk& i, disks) {
438                 if (!i.whole) {
439                         continue;
440                 }
441                 BOOST_FOREACH (Disk& j, disks) {
442                         if (j.mounted && starts_with(j.device, i.device)) {
443                                 LOG_DISK("Marking %1 as mounted because %2 is", i.device, j.device);
444                                 i.mounted = true;
445                         }
446                 }
447         }
448
449         /* Make a list of the PRT codes of mounted, synthesized disks */
450         vector<string> mounted_synths;
451         BOOST_FOREACH (Disk& i, disks) {
452                 if (!i.real && i.mounted) {
453                         LOG_DISK("Found a mounted synth %1 with %2", i.device, i.prt);
454                         mounted_synths.push_back (i.prt);
455                 }
456         }
457
458         /* Mark containers of those mounted synths as themselves mounted */
459         BOOST_FOREACH (Disk& i, disks) {
460                 if (i.real && find(mounted_synths.begin(), mounted_synths.end(), i.prt) != mounted_synths.end()) {
461                         LOG_DISK("Marking %1 (%2) as mounted because it contains a mounted synth", i.device, i.prt);
462                         i.mounted = true;
463                 }
464         }
465
466         vector<Drive> drives;
467         BOOST_FOREACH (Disk& i, disks) {
468                 if (i.whole) {
469                         /* A whole disk that is not a container for a mounted synth */
470                         LOG_DISK("Adding drive: %1 %2 %3 %4 %5", i.device, i.size, i.mounted ? "mounted" : "unmounted", i.vendor.get_value_or("[none]"), i.model.get_value_or("[none]"));
471                         drives.push_back(Drive(i.device, i.size, i.mounted, i.vendor, i.model));
472                 }
473         }
474         return drives;
475 }
476
477 boost::filesystem::path
478 config_path ()
479 {
480         boost::filesystem::path p;
481         p /= g_get_home_dir ();
482         p /= "Library";
483         p /= "Preferences";
484         p /= "com.dcpomatic";
485         p /= "2";
486         return p;
487 }
488
489 bool
490 unmount_device (string device)
491 {
492         int const r = umount(device.c_str());
493         LOG_DISK("Tried to unmount %1 and got %2 and %3", device, r, errno);
494         return r == 0;
495
496 }