Fix some unused variable warnings on macOS.
[dcpomatic.git] / src / tools / dcpomatic_disk_writer.cc
1 /*
2     Copyright (C) 2019-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 "lib/version.h"
22 #include "lib/disk_writer_messages.h"
23 #include "lib/compose.hpp"
24 #include "lib/exceptions.h"
25 #include "lib/cross.h"
26 #include "lib/digester.h"
27 #include "lib/file_log.h"
28 #include "lib/dcpomatic_log.h"
29 #include "lib/nanomsg.h"
30 #include "lib/warnings.h"
31 extern "C" {
32 #include <lwext4/ext4_mbr.h>
33 #include <lwext4/ext4_fs.h>
34 #include <lwext4/ext4_mkfs.h>
35 #include <lwext4/ext4_errno.h>
36 #include <lwext4/ext4_debug.h>
37 #include <lwext4/ext4.h>
38 }
39
40 #ifdef DCPOMATIC_POSIX
41 #include <sys/ioctl.h>
42 #include <sys/types.h>
43 #include <sys/stat.h>
44 #endif
45
46 #ifdef DCPOMATIC_OSX
47 #include "lib/stdout_log.h"
48 #undef nil
49 extern "C" {
50 #include <lwext4/file_dev.h>
51 }
52 #include <xpc/xpc.h>
53 #endif
54
55 #ifdef DCPOMATIC_LINUX
56 #include <linux/fs.h>
57 #include <polkit/polkit.h>
58 extern "C" {
59 #include <lwext4/file_dev.h>
60 }
61 #include <poll.h>
62 #endif
63
64 #ifdef DCPOMATIC_WINDOWS
65 extern "C" {
66 #include <lwext4/file_windows.h>
67 }
68 #endif
69
70 DCPOMATIC_DISABLE_WARNINGS
71 #include <glibmm.h>
72 DCPOMATIC_ENABLE_WARNINGS
73
74 #include <unistd.h>
75 #include <sys/types.h>
76 #include <boost/filesystem.hpp>
77 #include <boost/algorithm/string.hpp>
78 #include <boost/foreach.hpp>
79 #include <iostream>
80
81 using std::cin;
82 using std::min;
83 using std::string;
84 using std::runtime_error;
85 using std::exception;
86 using std::vector;
87 using boost::optional;
88
89 #ifdef DCPOMATIC_LINUX
90 static PolkitAuthority* polkit_authority = 0;
91 #endif
92 static uint64_t const block_size = 4096;
93 static Nanomsg* nanomsg = 0;
94
95 #define SHORT_TIMEOUT 100
96 #define LONG_TIMEOUT 2000
97
98 static
99 void
100 count (boost::filesystem::path dir, uint64_t& total_bytes)
101 {
102         using namespace boost::filesystem;
103         for (directory_iterator i = directory_iterator(dir); i != directory_iterator(); ++i) {
104                 if (is_directory(*i)) {
105                         count (*i, total_bytes);
106                 } else {
107                         total_bytes += file_size (*i);
108                 }
109         }
110 }
111
112 static
113 string
114 write (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total)
115 {
116         ext4_file out;
117         int r = ext4_fopen(&out, to.generic_string().c_str(), "wb");
118         if (r != EOK) {
119                 throw CopyError (String::compose("Failed to open file %1", to.generic_string()), r);
120         }
121
122         FILE* in = fopen_boost (from, "rb");
123         if (!in) {
124                 ext4_fclose (&out);
125                 throw CopyError (String::compose("Failed to open file %1", from.string()), 0);
126         }
127
128         uint8_t* buffer = new uint8_t[block_size];
129         Digester digester;
130
131         int progress_frequency = 5000;
132         int progress_count = 0;
133         uint64_t remaining = file_size (from);
134         while (remaining > 0) {
135                 uint64_t const this_time = min(remaining, block_size);
136                 size_t read = fread (buffer, 1, this_time, in);
137                 if (read != this_time) {
138                         fclose (in);
139                         ext4_fclose (&out);
140                         delete[] buffer;
141                         throw CopyError (String::compose("Short read; expected %1 but read %2", this_time, read), 0);
142                 }
143
144                 digester.add (buffer, this_time);
145
146                 size_t written;
147                 r = ext4_fwrite (&out, buffer, this_time, &written);
148                 if (r != EOK) {
149                         fclose (in);
150                         ext4_fclose (&out);
151                         delete[] buffer;
152                         throw CopyError ("Write failed", r);
153                 }
154                 if (written != this_time) {
155                         fclose (in);
156                         ext4_fclose (&out);
157                         delete[] buffer;
158                         throw CopyError (String::compose("Short write; expected %1 but wrote %2", this_time, written), 0);
159                 }
160                 remaining -= this_time;
161                 total_remaining -= this_time;
162
163                 ++progress_count;
164                 if ((progress_count % progress_frequency) == 0) {
165                         nanomsg->send(String::compose(DISK_WRITER_COPY_PROGRESS "\n%1\n", (1 - float(total_remaining) / total)), SHORT_TIMEOUT);
166                 }
167         }
168
169         fclose (in);
170         ext4_fclose (&out);
171         delete[] buffer;
172
173         return digester.get ();
174 }
175
176 static
177 string
178 read (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total)
179 {
180         ext4_file in;
181         LOG_DISK("Opening %1 for read", to.generic_string());
182         int r = ext4_fopen(&in, to.generic_string().c_str(), "rb");
183         if (r != EOK) {
184                 throw VerifyError (String::compose("Failed to open file %1", to.generic_string()), r);
185         }
186         LOG_DISK("Opened %1 for read", to.generic_string());
187
188         uint8_t* buffer = new uint8_t[block_size];
189         Digester digester;
190
191         uint64_t remaining = file_size (from);
192         while (remaining > 0) {
193                 uint64_t const this_time = min(remaining, block_size);
194                 size_t read;
195                 r = ext4_fread (&in, buffer, this_time, &read);
196                 if (read != this_time) {
197                         ext4_fclose (&in);
198                         delete[] buffer;
199                         throw VerifyError (String::compose("Short read; expected %1 but read %2", this_time, read), 0);
200                 }
201
202                 digester.add (buffer, this_time);
203                 remaining -= this_time;
204                 total_remaining -= this_time;
205                 nanomsg->send(String::compose(DISK_WRITER_VERIFY_PROGRESS "\n%1\n", (1 - float(total_remaining) / total)), SHORT_TIMEOUT);
206         }
207
208         ext4_fclose (&in);
209         delete[] buffer;
210
211         return digester.get ();
212 }
213
214
215 class CopiedFile
216 {
217 public:
218         CopiedFile (boost::filesystem::path from_, boost::filesystem::path to_, string write_digest_)
219                 : from (from_)
220                 , to (to_)
221                 , write_digest (write_digest_)
222         {}
223
224         boost::filesystem::path from;
225         boost::filesystem::path to;
226         /** digest calculated from data as it was read from the source during write */
227         string write_digest;
228 };
229
230
231 /** @param from File to copy from.
232  *  @param to Directory to copy to.
233  */
234 static
235 void
236 copy (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total, vector<CopiedFile>& copied_files)
237 {
238         LOG_DISK ("Copy %1 -> %2", from.string(), to.generic_string());
239
240         using namespace boost::filesystem;
241
242         path const cr = to / from.filename();
243
244         if (is_directory(from)) {
245                 int r = ext4_dir_mk (cr.generic_string().c_str());
246                 if (r != EOK) {
247                         throw CopyError (String::compose("Failed to create directory %1", cr.generic_string()), r);
248                 }
249
250                 for (directory_iterator i = directory_iterator(from); i != directory_iterator(); ++i) {
251                         copy (i->path(), cr, total_remaining, total, copied_files);
252                 }
253         } else {
254                 string const write_digest = write (from, cr, total_remaining, total);
255                 LOG_DISK ("Wrote %1 %2 with %3", from.string(), cr.generic_string(), write_digest);
256                 copied_files.push_back (CopiedFile(from, cr, write_digest));
257         }
258 }
259
260
261 static
262 void
263 verify (vector<CopiedFile> const& copied_files, uint64_t total)
264 {
265         uint64_t total_remaining = total;
266         BOOST_FOREACH (CopiedFile const& i, copied_files) {
267                 string const read_digest = read (i.from, i.to, total_remaining, total);
268                 LOG_DISK ("Read %1 %2 was %3 on write, now %4", i.from.string(), i.to.generic_string(), i.write_digest, read_digest);
269                 if (read_digest != i.write_digest) {
270                         throw VerifyError ("Hash of written data is incorrect", 0);
271                 }
272         }
273 }
274
275
276 static
277 void
278 write (boost::filesystem::path dcp_path, string device)
279 try
280 {
281         ext4_dmask_set (DEBUG_ALL);
282
283         /* We rely on static initialization for these */
284         static struct ext4_fs fs;
285         static struct ext4_mkfs_info info;
286         info.block_size = 4096;
287         info.inode_size = 128;
288         info.journal = false;
289
290 #ifdef WIN32
291         file_windows_name_set(device.c_str());
292         struct ext4_blockdev* bd = file_windows_dev_get();
293 #else
294         file_dev_name_set (device.c_str());
295         struct ext4_blockdev* bd = file_dev_get ();
296 #endif
297
298         if (!bd) {
299                 throw CopyError ("Failed to open drive", 0);
300         }
301         LOG_DISK_NC ("Opened drive");
302
303         struct ext4_mbr_parts parts;
304         parts.division[0] = 100;
305         parts.division[1] = 0;
306         parts.division[2] = 0;
307         parts.division[3] = 0;
308
309 #ifdef DCPOMATIC_LINUX
310         PrivilegeEscalator e;
311 #endif
312
313         /* XXX: not sure if disk_id matters */
314         int r = ext4_mbr_write (bd, &parts, 0);
315         if (r) {
316                 throw CopyError ("Failed to write MBR", r);
317         }
318         LOG_DISK_NC ("Wrote MBR");
319
320         struct ext4_mbr_bdevs bdevs;
321         r = ext4_mbr_scan (bd, &bdevs);
322         if (r != EOK) {
323                 throw CopyError ("Failed to read MBR", r);
324         }
325
326 #ifdef DCPOMATIC_WINDOWS
327         file_windows_partition_set (bdevs.partitions[0].part_offset, bdevs.partitions[0].part_size);
328 #endif
329
330         LOG_DISK ("Writing to partition at %1 size %2; bd part size is %3", bdevs.partitions[0].part_offset, bdevs.partitions[0].part_size, bd->part_size);
331
332 #ifdef DCPOMATIC_LINUX
333         /* Re-read the partition table */
334         int fd = open(device.c_str(), O_RDONLY);
335         ioctl(fd, BLKRRPART, NULL);
336         close(fd);
337 #endif
338
339 #ifdef DCPOMATIC_LINUX
340         string partition = device;
341         /* XXX: don't know if this logic is sensible */
342         if (partition.size() > 0 && isdigit(partition[partition.length() - 1])) {
343                 partition += "p1";
344         } else {
345                 partition += "1";
346         }
347         file_dev_name_set (partition.c_str());
348         bd = file_dev_get ();
349 #endif
350
351 #ifdef DCPOMATIC_OSX
352         string partition = device + "s1";
353         file_dev_name_set (partition.c_str());
354         bd = file_dev_get ();
355 #endif
356
357         if (!bd) {
358                 throw CopyError ("Failed to open partition", 0);
359         }
360         LOG_DISK_NC ("Opened partition");
361
362         nanomsg->send(DISK_WRITER_FORMATTING "\n", SHORT_TIMEOUT);
363
364         r = ext4_mkfs(&fs, bd, &info, F_SET_EXT2);
365         if (r != EOK) {
366                 throw CopyError ("Failed to make filesystem", r);
367         }
368         LOG_DISK_NC ("Made filesystem");
369
370         r = ext4_device_register(bd, "ext4_fs");
371         if (r != EOK) {
372                 throw CopyError ("Failed to register device", r);
373         }
374         LOG_DISK_NC ("Registered device");
375
376         r = ext4_mount("ext4_fs", "/mp/", false);
377         if (r != EOK) {
378                 throw CopyError ("Failed to mount device", r);
379         }
380         LOG_DISK_NC ("Mounted device");
381
382         uint64_t total_bytes = 0;
383         count (dcp_path, total_bytes);
384
385         uint64_t total_remaining = total_bytes;
386         vector<CopiedFile> copied_files;
387         copy (dcp_path, "/mp", total_remaining, total_bytes, copied_files);
388
389         /* Unmount and re-mount to make sure the write has finished */
390         r = ext4_umount("/mp/");
391         if (r != EOK) {
392                 throw CopyError ("Failed to unmount device", r);
393         }
394         r = ext4_mount("ext4_fs", "/mp/", false);
395         if (r != EOK) {
396                 throw CopyError ("Failed to mount device", r);
397         }
398         LOG_DISK_NC ("Re-mounted device");
399
400         verify (copied_files, total_bytes);
401
402         r = ext4_umount("/mp/");
403         if (r != EOK) {
404                 throw CopyError ("Failed to unmount device", r);
405         }
406
407         ext4_device_unregister("ext4_fs");
408         if (!nanomsg->send(DISK_WRITER_OK "\n", LONG_TIMEOUT)) {
409                 throw CommunicationFailedError ();
410         }
411
412         disk_write_finished ();
413 } catch (CopyError& e) {
414         LOG_DISK("CopyError (from write): %1 %2", e.message(), e.number().get_value_or(0));
415         nanomsg->send(String::compose(DISK_WRITER_ERROR "\n%1\n%2\n", e.message(), e.number().get_value_or(0)), LONG_TIMEOUT);
416 } catch (VerifyError& e) {
417         LOG_DISK("VerifyError (from write): %1 %2", e.message(), e.number());
418         nanomsg->send(String::compose(DISK_WRITER_ERROR "\n%1\n%2\n", e.message(), e.number()), LONG_TIMEOUT);
419 } catch (exception& e) {
420         LOG_DISK("Exception (from write): %1", e.what());
421         nanomsg->send(String::compose(DISK_WRITER_ERROR "\n%1\n0\n", e.what()), LONG_TIMEOUT);
422 }
423
424 struct Parameters
425 {
426         boost::filesystem::path dcp_path;
427         std::string device;
428 };
429
430 #ifdef DCPOMATIC_LINUX
431 static
432 void
433 polkit_callback (GObject *, GAsyncResult* res, gpointer data)
434 {
435         Parameters* parameters = reinterpret_cast<Parameters*> (data);
436         PolkitAuthorizationResult* result = polkit_authority_check_authorization_finish (polkit_authority, res, 0);
437         if (result && polkit_authorization_result_get_is_authorized(result)) {
438                 write (parameters->dcp_path, parameters->device);
439         }
440         delete parameters;
441         if (result) {
442                 g_object_unref (result);
443         }
444 }
445 #endif
446
447
448 bool
449 idle ()
450 try
451 {
452         using namespace boost::algorithm;
453
454         optional<string> s = nanomsg->receive (0);
455         if (!s) {
456                 return true;
457         }
458
459         LOG_DISK("Writer receives command: %1", *s);
460
461         if (*s == DISK_WRITER_QUIT) {
462                 exit (EXIT_SUCCESS);
463         } else if (*s == DISK_WRITER_UNMOUNT) {
464                 /* XXX: should do Linux polkit stuff here */
465                 optional<string> xml_head = nanomsg->receive (LONG_TIMEOUT);
466                 optional<string> xml_body = nanomsg->receive (LONG_TIMEOUT);
467                 if (!xml_head || !xml_body) {
468                         LOG_DISK_NC("Failed to receive unmount request");
469                         throw CommunicationFailedError ();
470                 }
471                 bool const success = Drive(*xml_head + *xml_body).unmount();
472                 if (!nanomsg->send (success ? (DISK_WRITER_OK "\n") : (DISK_WRITER_ERROR "\n"), LONG_TIMEOUT)) {
473                         LOG_DISK_NC("CommunicationFailedError in unmount_finished");
474                         throw CommunicationFailedError ();
475                 }
476         } else if (*s == DISK_WRITER_WRITE) {
477                 optional<string> dcp_path = nanomsg->receive (LONG_TIMEOUT);
478                 optional<string> device = nanomsg->receive (LONG_TIMEOUT);
479                 if (!dcp_path || !device) {
480                         LOG_DISK_NC("Failed to receive write request");
481                         throw CommunicationFailedError();
482                 }
483
484                 /* Do some basic sanity checks; this is a bit belt-and-braces but it can't hurt... */
485
486 #ifdef DCPOMATIC_OSX
487                 if (!starts_with(*device, "/dev/disk")) {
488                         LOG_DISK ("Will not write to %1", *device);
489                         nanomsg->send(DISK_WRITER_ERROR "\nRefusing to write to this drive\n1\n", LONG_TIMEOUT);
490                         return true;
491                 }
492 #endif
493 #ifdef DCPOMATIC_LINUX
494                 if (!starts_with(*device, "/dev/sd") && !starts_with(*device, "/dev/hd")) {
495                         LOG_DISK ("Will not write to %1", *device);
496                         nanomsg->send(DISK_WRITER_ERROR "\nRefusing to write to this drive\n1\n", LONG_TIMEOUT);
497                         return true;
498                 }
499 #endif
500 #ifdef DCPOMATIC_WINDOWS
501                 if (!starts_with(*device, "\\\\.\\PHYSICALDRIVE")) {
502                         LOG_DISK ("Will not write to %1", *device);
503                         nanomsg->send(DISK_WRITER_ERROR "\nRefusing to write to this drive\n1\n", LONG_TIMEOUT);
504                         return true;
505                 }
506 #endif
507
508                 bool on_drive_list = false;
509                 bool mounted = false;
510                 for (auto const& i: Drive::get()) {
511                         if (i.device() == *device) {
512                                 on_drive_list = true;
513                                 mounted = i.mounted();
514                         }
515                 }
516
517                 if (!on_drive_list) {
518                         LOG_DISK ("Will not write to %1 as it's not recognised as a drive", *device);
519                         nanomsg->send(DISK_WRITER_ERROR "\nRefusing to write to this drive\n1\n", LONG_TIMEOUT);
520                         return true;
521                 }
522                 if (mounted) {
523                         LOG_DISK ("Will not write to %1 as it's mounted", *device);
524                         nanomsg->send(DISK_WRITER_ERROR "\nRefusing to write to this drive\n1\n", LONG_TIMEOUT);
525                         return true;
526                 }
527
528                 LOG_DISK ("Here we go writing %1 to %2", *dcp_path, *device);
529
530 #ifdef DCPOMATIC_LINUX
531                 polkit_authority = polkit_authority_get_sync (0, 0);
532                 PolkitSubject* subject = polkit_unix_process_new_for_owner (getppid(), 0, -1);
533                 Parameters* parameters = new Parameters;
534                 parameters->dcp_path = *dcp_path;
535                 parameters->device = *device;
536                 polkit_authority_check_authorization (
537                                 polkit_authority, subject, "com.dcpomatic.write-drive", 0, POLKIT_CHECK_AUTHORIZATION_FLAGS_ALLOW_USER_INTERACTION, 0, polkit_callback, parameters
538                                 );
539 #else
540                 write (*dcp_path, *device);
541 #endif
542         }
543
544         return true;
545 } catch (exception& e) {
546         LOG_DISK("Exception (from idle): %1", e.what());
547         return true;
548 }
549
550 int
551 main ()
552 {
553 #ifdef DCPOMATIC_OSX
554         /* On macOS this is running as root, so config_path() will be somewhere in root's
555          * home.  Instead, just write to stdout as the macOS process control stuff will
556          * redirect this to a file in /var/log
557          */
558         dcpomatic_log.reset(new StdoutLog(LogEntry::TYPE_DISK));
559         LOG_DISK("dcpomatic_disk_writer %1 started", dcpomatic_git_commit);
560 #else
561         /* XXX: this is a hack, but I expect we'll need logs and I'm not sure if there's
562          * a better place to put them.
563          */
564         dcpomatic_log.reset(new FileLog(config_path() / "disk_writer.log", LogEntry::TYPE_DISK));
565         LOG_DISK_NC("dcpomatic_disk_writer started");
566 #endif
567
568 #ifdef DCPOMATIC_OSX
569         /* I *think* this confumes the notifyd event that we used to start the process, so we only
570          * get started once per notification.
571          */
572         xpc_set_event_stream_handler("com.apple.notifyd.matching", DISPATCH_TARGET_QUEUE_DEFAULT, ^(xpc_object_t) {});
573 #endif
574
575         try {
576                 nanomsg = new Nanomsg (false);
577         } catch (runtime_error& e) {
578                 LOG_DISK_NC("Could not set up nanomsg socket");
579                 exit (EXIT_FAILURE);
580         }
581
582         Glib::RefPtr<Glib::MainLoop> ml = Glib::MainLoop::create ();
583         Glib::signal_timeout().connect(sigc::ptr_fun(&idle), 500);
584         ml->run ();
585 }