2 Copyright (C) 2019-2020 Carl Hetherington <cth@carlh.net>
4 This file is part of DCP-o-matic.
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.
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.
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/>.
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"
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>
40 #ifdef DCPOMATIC_POSIX
41 #include <sys/ioctl.h>
42 #include <sys/types.h>
47 #include "lib/stdout_log.h"
50 #include <lwext4/file_dev.h>
55 #ifdef DCPOMATIC_LINUX
57 #include <polkit/polkit.h>
59 #include <lwext4/file_dev.h>
64 #ifdef DCPOMATIC_WINDOWS
66 #include <lwext4/file_windows.h>
70 DCPOMATIC_DISABLE_WARNINGS
72 DCPOMATIC_ENABLE_WARNINGS
75 #include <sys/types.h>
76 #include <boost/filesystem.hpp>
77 #include <boost/algorithm/string.hpp>
78 #include <boost/foreach.hpp>
84 using std::runtime_error;
87 using boost::optional;
89 #ifdef DCPOMATIC_LINUX
90 static PolkitAuthority* polkit_authority = 0;
92 /* Use quite a big block size here, as ext4's fwrite() has quite a bit of overhead */
93 static uint64_t const block_size = 4096 * 4096;
94 static Nanomsg* nanomsg = 0;
96 #define SHORT_TIMEOUT 100
97 #define LONG_TIMEOUT 2000
101 count (boost::filesystem::path dir, uint64_t& total_bytes)
103 using namespace boost::filesystem;
104 for (directory_iterator i = directory_iterator(dir); i != directory_iterator(); ++i) {
105 if (is_directory(*i)) {
106 count (*i, total_bytes);
108 total_bytes += file_size (*i);
115 write (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total)
118 int r = ext4_fopen(&out, to.generic_string().c_str(), "wb");
120 throw CopyError (String::compose("Failed to open file %1", to.generic_string()), r);
123 FILE* in = fopen_boost (from, "rb");
126 throw CopyError (String::compose("Failed to open file %1", from.string()), 0);
129 uint8_t* buffer = new uint8_t[block_size];
132 int progress_frequency = 1;
133 int progress_count = 0;
134 uint64_t remaining = file_size (from);
135 while (remaining > 0) {
136 uint64_t const this_time = min(remaining, block_size);
137 size_t read = fread (buffer, 1, this_time, in);
138 if (read != this_time) {
142 throw CopyError (String::compose("Short read; expected %1 but read %2", this_time, read), 0);
145 digester.add (buffer, this_time);
148 r = ext4_fwrite (&out, buffer, this_time, &written);
153 throw CopyError ("Write failed", r);
155 if (written != this_time) {
159 throw CopyError (String::compose("Short write; expected %1 but wrote %2", this_time, written), 0);
161 remaining -= this_time;
162 total_remaining -= this_time;
165 if ((progress_count % progress_frequency) == 0) {
166 nanomsg->send(String::compose(DISK_WRITER_COPY_PROGRESS "\n%1\n", (1 - float(total_remaining) / total)), SHORT_TIMEOUT);
174 return digester.get ();
179 read (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total)
182 LOG_DISK("Opening %1 for read", to.generic_string());
183 int r = ext4_fopen(&in, to.generic_string().c_str(), "rb");
185 throw VerifyError (String::compose("Failed to open file %1", to.generic_string()), r);
187 LOG_DISK("Opened %1 for read", to.generic_string());
189 uint8_t* buffer = new uint8_t[block_size];
192 uint64_t remaining = file_size (from);
193 while (remaining > 0) {
194 uint64_t const this_time = min(remaining, block_size);
196 r = ext4_fread (&in, buffer, this_time, &read);
197 if (read != this_time) {
200 throw VerifyError (String::compose("Short read; expected %1 but read %2", this_time, read), 0);
203 digester.add (buffer, this_time);
204 remaining -= this_time;
205 total_remaining -= this_time;
206 nanomsg->send(String::compose(DISK_WRITER_VERIFY_PROGRESS "\n%1\n", (1 - float(total_remaining) / total)), SHORT_TIMEOUT);
212 return digester.get ();
219 CopiedFile (boost::filesystem::path from_, boost::filesystem::path to_, string write_digest_)
222 , write_digest (write_digest_)
225 boost::filesystem::path from;
226 boost::filesystem::path to;
227 /** digest calculated from data as it was read from the source during write */
232 /** @param from File to copy from.
233 * @param to Directory to copy to.
237 copy (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total, vector<CopiedFile>& copied_files)
239 LOG_DISK ("Copy %1 -> %2", from.string(), to.generic_string());
241 using namespace boost::filesystem;
243 path const cr = to / from.filename();
245 if (is_directory(from)) {
246 int r = ext4_dir_mk (cr.generic_string().c_str());
248 throw CopyError (String::compose("Failed to create directory %1", cr.generic_string()), r);
251 for (directory_iterator i = directory_iterator(from); i != directory_iterator(); ++i) {
252 copy (i->path(), cr, total_remaining, total, copied_files);
255 string const write_digest = write (from, cr, total_remaining, total);
256 LOG_DISK ("Wrote %1 %2 with %3", from.string(), cr.generic_string(), write_digest);
257 copied_files.push_back (CopiedFile(from, cr, write_digest));
264 verify (vector<CopiedFile> const& copied_files, uint64_t total)
266 uint64_t total_remaining = total;
267 BOOST_FOREACH (CopiedFile const& i, copied_files) {
268 string const read_digest = read (i.from, i.to, total_remaining, total);
269 LOG_DISK ("Read %1 %2 was %3 on write, now %4", i.from.string(), i.to.generic_string(), i.write_digest, read_digest);
270 if (read_digest != i.write_digest) {
271 throw VerifyError ("Hash of written data is incorrect", 0);
279 write (boost::filesystem::path dcp_path, string device)
282 ext4_dmask_set (DEBUG_ALL);
284 /* We rely on static initialization for these */
285 static struct ext4_fs fs;
286 static struct ext4_mkfs_info info;
287 info.block_size = 4096;
288 info.inode_size = 128;
289 info.journal = false;
292 file_windows_name_set(device.c_str());
293 struct ext4_blockdev* bd = file_windows_dev_get();
295 file_dev_name_set (device.c_str());
296 struct ext4_blockdev* bd = file_dev_get ();
300 throw CopyError ("Failed to open drive", 0);
302 LOG_DISK_NC ("Opened drive");
304 struct ext4_mbr_parts parts;
305 parts.division[0] = 100;
306 parts.division[1] = 0;
307 parts.division[2] = 0;
308 parts.division[3] = 0;
310 #ifdef DCPOMATIC_LINUX
311 PrivilegeEscalator e;
314 /* XXX: not sure if disk_id matters */
315 int r = ext4_mbr_write (bd, &parts, 0);
317 throw CopyError ("Failed to write MBR", r);
319 LOG_DISK_NC ("Wrote MBR");
321 struct ext4_mbr_bdevs bdevs;
322 r = ext4_mbr_scan (bd, &bdevs);
324 throw CopyError ("Failed to read MBR", r);
327 #ifdef DCPOMATIC_WINDOWS
328 file_windows_partition_set (bdevs.partitions[0].part_offset, bdevs.partitions[0].part_size);
331 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);
333 #ifdef DCPOMATIC_LINUX
334 /* Re-read the partition table */
335 int fd = open(device.c_str(), O_RDONLY);
336 ioctl(fd, BLKRRPART, NULL);
340 #ifdef DCPOMATIC_LINUX
341 string partition = device;
342 /* XXX: don't know if this logic is sensible */
343 if (partition.size() > 0 && isdigit(partition[partition.length() - 1])) {
348 file_dev_name_set (partition.c_str());
349 bd = file_dev_get ();
353 string partition = device + "s1";
354 file_dev_name_set (partition.c_str());
355 bd = file_dev_get ();
359 throw CopyError ("Failed to open partition", 0);
361 LOG_DISK_NC ("Opened partition");
363 nanomsg->send(DISK_WRITER_FORMATTING "\n", SHORT_TIMEOUT);
365 r = ext4_mkfs(&fs, bd, &info, F_SET_EXT2);
367 throw CopyError ("Failed to make filesystem", r);
369 LOG_DISK_NC ("Made filesystem");
371 r = ext4_device_register(bd, "ext4_fs");
373 throw CopyError ("Failed to register device", r);
375 LOG_DISK_NC ("Registered device");
377 r = ext4_mount("ext4_fs", "/mp/", false);
379 throw CopyError ("Failed to mount device", r);
381 LOG_DISK_NC ("Mounted device");
383 uint64_t total_bytes = 0;
384 count (dcp_path, total_bytes);
386 uint64_t total_remaining = total_bytes;
387 vector<CopiedFile> copied_files;
388 copy (dcp_path, "/mp", total_remaining, total_bytes, copied_files);
390 /* Unmount and re-mount to make sure the write has finished */
391 r = ext4_umount("/mp/");
393 throw CopyError ("Failed to unmount device", r);
395 r = ext4_mount("ext4_fs", "/mp/", false);
397 throw CopyError ("Failed to mount device", r);
399 LOG_DISK_NC ("Re-mounted device");
401 verify (copied_files, total_bytes);
403 r = ext4_umount("/mp/");
405 throw CopyError ("Failed to unmount device", r);
408 ext4_device_unregister("ext4_fs");
409 if (!nanomsg->send(DISK_WRITER_OK "\n", LONG_TIMEOUT)) {
410 throw CommunicationFailedError ();
413 disk_write_finished ();
414 } catch (CopyError& e) {
415 LOG_DISK("CopyError (from write): %1 %2", e.message(), e.number().get_value_or(0));
416 nanomsg->send(String::compose(DISK_WRITER_ERROR "\n%1\n%2\n", e.message(), e.number().get_value_or(0)), LONG_TIMEOUT);
417 } catch (VerifyError& e) {
418 LOG_DISK("VerifyError (from write): %1 %2", e.message(), e.number());
419 nanomsg->send(String::compose(DISK_WRITER_ERROR "\n%1\n%2\n", e.message(), e.number()), LONG_TIMEOUT);
420 } catch (exception& e) {
421 LOG_DISK("Exception (from write): %1", e.what());
422 nanomsg->send(String::compose(DISK_WRITER_ERROR "\n%1\n0\n", e.what()), LONG_TIMEOUT);
427 boost::filesystem::path dcp_path;
431 #ifdef DCPOMATIC_LINUX
434 polkit_callback (GObject *, GAsyncResult* res, gpointer data)
436 Parameters* parameters = reinterpret_cast<Parameters*> (data);
437 PolkitAuthorizationResult* result = polkit_authority_check_authorization_finish (polkit_authority, res, 0);
438 if (result && polkit_authorization_result_get_is_authorized(result)) {
439 write (parameters->dcp_path, parameters->device);
443 g_object_unref (result);
453 using namespace boost::algorithm;
455 optional<string> s = nanomsg->receive (0);
460 LOG_DISK("Writer receives command: %1", *s);
462 if (*s == DISK_WRITER_QUIT) {
464 } else if (*s == DISK_WRITER_PING) {
465 nanomsg->send(DISK_WRITER_PONG "\n", LONG_TIMEOUT);
466 } else if (*s == DISK_WRITER_UNMOUNT) {
467 /* XXX: should do Linux polkit stuff here */
468 optional<string> xml_head = nanomsg->receive (LONG_TIMEOUT);
469 optional<string> xml_body = nanomsg->receive (LONG_TIMEOUT);
470 if (!xml_head || !xml_body) {
471 LOG_DISK_NC("Failed to receive unmount request");
472 throw CommunicationFailedError ();
474 bool const success = Drive(*xml_head + *xml_body).unmount();
475 if (!nanomsg->send (success ? (DISK_WRITER_OK "\n") : (DISK_WRITER_ERROR "\n"), LONG_TIMEOUT)) {
476 LOG_DISK_NC("CommunicationFailedError in unmount_finished");
477 throw CommunicationFailedError ();
479 } else if (*s == DISK_WRITER_WRITE) {
480 optional<string> dcp_path = nanomsg->receive (LONG_TIMEOUT);
481 optional<string> device = nanomsg->receive (LONG_TIMEOUT);
482 if (!dcp_path || !device) {
483 LOG_DISK_NC("Failed to receive write request");
484 throw CommunicationFailedError();
487 /* Do some basic sanity checks; this is a bit belt-and-braces but it can't hurt... */
490 if (!starts_with(*device, "/dev/disk")) {
491 LOG_DISK ("Will not write to %1", *device);
492 nanomsg->send(DISK_WRITER_ERROR "\nRefusing to write to this drive\n1\n", LONG_TIMEOUT);
496 #ifdef DCPOMATIC_LINUX
497 if (!starts_with(*device, "/dev/sd") && !starts_with(*device, "/dev/hd")) {
498 LOG_DISK ("Will not write to %1", *device);
499 nanomsg->send(DISK_WRITER_ERROR "\nRefusing to write to this drive\n1\n", LONG_TIMEOUT);
503 #ifdef DCPOMATIC_WINDOWS
504 if (!starts_with(*device, "\\\\.\\PHYSICALDRIVE")) {
505 LOG_DISK ("Will not write to %1", *device);
506 nanomsg->send(DISK_WRITER_ERROR "\nRefusing to write to this drive\n1\n", LONG_TIMEOUT);
511 bool on_drive_list = false;
512 bool mounted = false;
513 for (auto const& i: Drive::get()) {
514 if (i.device() == *device) {
515 on_drive_list = true;
516 mounted = i.mounted();
520 if (!on_drive_list) {
521 LOG_DISK ("Will not write to %1 as it's not recognised as a drive", *device);
522 nanomsg->send(DISK_WRITER_ERROR "\nRefusing to write to this drive\n1\n", LONG_TIMEOUT);
526 LOG_DISK ("Will not write to %1 as it's mounted", *device);
527 nanomsg->send(DISK_WRITER_ERROR "\nRefusing to write to this drive\n1\n", LONG_TIMEOUT);
531 LOG_DISK ("Here we go writing %1 to %2", *dcp_path, *device);
533 #ifdef DCPOMATIC_LINUX
534 polkit_authority = polkit_authority_get_sync (0, 0);
535 PolkitSubject* subject = polkit_unix_process_new_for_owner (getppid(), 0, -1);
536 Parameters* parameters = new Parameters;
537 parameters->dcp_path = *dcp_path;
538 parameters->device = *device;
539 polkit_authority_check_authorization (
540 polkit_authority, subject, "com.dcpomatic.write-drive", 0, POLKIT_CHECK_AUTHORIZATION_FLAGS_ALLOW_USER_INTERACTION, 0, polkit_callback, parameters
543 write (*dcp_path, *device);
548 } catch (exception& e) {
549 LOG_DISK("Exception (from idle): %1", e.what());
557 /* On macOS this is running as root, so config_path() will be somewhere in root's
558 * home. Instead, just write to stdout as the macOS process control stuff will
559 * redirect this to a file in /var/log
561 dcpomatic_log.reset(new StdoutLog(LogEntry::TYPE_DISK));
562 LOG_DISK("dcpomatic_disk_writer %1 started", dcpomatic_git_commit);
564 /* XXX: this is a hack, but I expect we'll need logs and I'm not sure if there's
565 * a better place to put them.
567 dcpomatic_log.reset(new FileLog(config_path() / "disk_writer.log", LogEntry::TYPE_DISK));
568 LOG_DISK_NC("dcpomatic_disk_writer started");
572 /* I *think* this confumes the notifyd event that we used to start the process, so we only
573 * get started once per notification.
575 xpc_set_event_stream_handler("com.apple.notifyd.matching", DISPATCH_TARGET_QUEUE_DEFAULT, ^(xpc_object_t) {});
579 nanomsg = new Nanomsg (false);
580 } catch (runtime_error& e) {
581 LOG_DISK_NC("Could not set up nanomsg socket");
585 Glib::RefPtr<Glib::MainLoop> ml = Glib::MainLoop::create ();
586 Glib::signal_timeout().connect(sigc::ptr_fun(&idle), 500);