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 static uint64_t const block_size = 4096;
93 static Nanomsg* nanomsg = 0;
95 #define SHORT_TIMEOUT 100
96 #define LONG_TIMEOUT 2000
100 count (boost::filesystem::path dir, uint64_t& total_bytes)
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);
107 total_bytes += file_size (*i);
114 write (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total)
117 int r = ext4_fopen(&out, to.generic_string().c_str(), "wb");
119 throw CopyError (String::compose("Failed to open file %1", to.generic_string()), r);
122 FILE* in = fopen_boost (from, "rb");
125 throw CopyError (String::compose("Failed to open file %1", from.string()), 0);
128 uint8_t* buffer = new uint8_t[block_size];
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) {
141 throw CopyError (String::compose("Short read; expected %1 but read %2", this_time, read), 0);
144 digester.add (buffer, this_time);
147 r = ext4_fwrite (&out, buffer, this_time, &written);
152 throw CopyError ("Write failed", r);
154 if (written != this_time) {
158 throw CopyError (String::compose("Short write; expected %1 but wrote %2", this_time, written), 0);
160 remaining -= this_time;
161 total_remaining -= this_time;
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);
173 return digester.get ();
178 read (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total)
181 LOG_DISK("Opening %1 for read", to.generic_string());
182 int r = ext4_fopen(&in, to.generic_string().c_str(), "rb");
184 throw VerifyError (String::compose("Failed to open file %1", to.generic_string()), r);
186 LOG_DISK("Opened %1 for read", to.generic_string());
188 uint8_t* buffer = new uint8_t[block_size];
191 uint64_t remaining = file_size (from);
192 while (remaining > 0) {
193 uint64_t const this_time = min(remaining, block_size);
195 r = ext4_fread (&in, buffer, this_time, &read);
196 if (read != this_time) {
199 throw VerifyError (String::compose("Short read; expected %1 but read %2", this_time, read), 0);
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);
211 return digester.get ();
218 CopiedFile (boost::filesystem::path from_, boost::filesystem::path to_, string write_digest_)
221 , write_digest (write_digest_)
224 boost::filesystem::path from;
225 boost::filesystem::path to;
226 /** digest calculated from data as it was read from the source during write */
231 /** @param from File to copy from.
232 * @param to Directory to copy to.
236 copy (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total, vector<CopiedFile>& copied_files)
238 LOG_DISK ("Copy %1 -> %2", from.string(), to.generic_string());
240 using namespace boost::filesystem;
242 path const cr = to / from.filename();
244 if (is_directory(from)) {
245 int r = ext4_dir_mk (cr.generic_string().c_str());
247 throw CopyError (String::compose("Failed to create directory %1", cr.generic_string()), r);
250 for (directory_iterator i = directory_iterator(from); i != directory_iterator(); ++i) {
251 copy (i->path(), cr, total_remaining, total, copied_files);
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));
263 verify (vector<CopiedFile> const& copied_files, uint64_t total)
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);
278 write (boost::filesystem::path dcp_path, string device)
281 ext4_dmask_set (DEBUG_ALL);
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;
291 file_windows_name_set(device.c_str());
292 struct ext4_blockdev* bd = file_windows_dev_get();
294 file_dev_name_set (device.c_str());
295 struct ext4_blockdev* bd = file_dev_get ();
299 throw CopyError ("Failed to open drive", 0);
301 LOG_DISK_NC ("Opened drive");
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;
309 #ifdef DCPOMATIC_LINUX
310 PrivilegeEscalator e;
313 /* XXX: not sure if disk_id matters */
314 int r = ext4_mbr_write (bd, &parts, 0);
316 throw CopyError ("Failed to write MBR", r);
318 LOG_DISK_NC ("Wrote MBR");
320 struct ext4_mbr_bdevs bdevs;
321 r = ext4_mbr_scan (bd, &bdevs);
323 throw CopyError ("Failed to read MBR", r);
326 #ifdef DCPOMATIC_WINDOWS
327 file_windows_partition_set (bdevs.partitions[0].part_offset, bdevs.partitions[0].part_size);
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);
332 #ifdef DCPOMATIC_LINUX
333 /* Re-read the partition table */
334 int fd = open(device.c_str(), O_RDONLY);
335 ioctl(fd, BLKRRPART, NULL);
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])) {
347 file_dev_name_set (partition.c_str());
348 bd = file_dev_get ();
352 string partition = device + "s1";
353 file_dev_name_set (partition.c_str());
354 bd = file_dev_get ();
358 throw CopyError ("Failed to open partition", 0);
360 LOG_DISK_NC ("Opened partition");
362 nanomsg->send(DISK_WRITER_FORMATTING "\n", SHORT_TIMEOUT);
364 r = ext4_mkfs(&fs, bd, &info, F_SET_EXT2);
366 throw CopyError ("Failed to make filesystem", r);
368 LOG_DISK_NC ("Made filesystem");
370 r = ext4_device_register(bd, "ext4_fs");
372 throw CopyError ("Failed to register device", r);
374 LOG_DISK_NC ("Registered device");
376 r = ext4_mount("ext4_fs", "/mp/", false);
378 throw CopyError ("Failed to mount device", r);
380 LOG_DISK_NC ("Mounted device");
382 uint64_t total_bytes = 0;
383 count (dcp_path, total_bytes);
385 uint64_t total_remaining = total_bytes;
386 vector<CopiedFile> copied_files;
387 copy (dcp_path, "/mp", total_remaining, total_bytes, copied_files);
389 /* Unmount and re-mount to make sure the write has finished */
390 r = ext4_umount("/mp/");
392 throw CopyError ("Failed to unmount device", r);
394 r = ext4_mount("ext4_fs", "/mp/", false);
396 throw CopyError ("Failed to mount device", r);
398 LOG_DISK_NC ("Re-mounted device");
400 verify (copied_files, total_bytes);
402 r = ext4_umount("/mp/");
404 throw CopyError ("Failed to unmount device", r);
407 ext4_device_unregister("ext4_fs");
408 if (!nanomsg->send(DISK_WRITER_OK "\n", LONG_TIMEOUT)) {
409 throw CommunicationFailedError ();
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);
426 boost::filesystem::path dcp_path;
430 #ifdef DCPOMATIC_LINUX
433 polkit_callback (GObject *, GAsyncResult* res, gpointer data)
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);
442 g_object_unref (result);
452 using namespace boost::algorithm;
454 optional<string> s = nanomsg->receive (0);
459 LOG_DISK("Writer receives command: %1", *s);
461 if (*s == DISK_WRITER_QUIT) {
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 ();
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 ();
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();
484 /* Do some basic sanity checks; this is a bit belt-and-braces but it can't hurt... */
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);
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);
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);
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();
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);
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);
528 LOG_DISK ("Here we go writing %1 to %2", *dcp_path, *device);
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
540 write (*dcp_path, *device);
545 } catch (exception& e) {
546 LOG_DISK("Exception (from idle): %1", e.what());
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
558 dcpomatic_log.reset(new StdoutLog(LogEntry::TYPE_DISK));
559 LOG_DISK("dcpomatic_disk_writer %1 started", dcpomatic_git_commit);
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.
564 dcpomatic_log.reset(new FileLog(config_path() / "disk_writer.log", LogEntry::TYPE_DISK));
565 LOG_DISK_NC("dcpomatic_disk_writer started");
569 /* I *think* this confumes the notifyd event that we used to start the process, so we only
570 * get started once per notification.
572 xpc_set_event_stream_handler("com.apple.notifyd.matching", DISPATCH_TARGET_QUEUE_DEFAULT, ^(xpc_object_t) {});
576 nanomsg = new Nanomsg (false);
577 } catch (runtime_error& e) {
578 LOG_DISK_NC("Could not set up nanomsg socket");
582 Glib::RefPtr<Glib::MainLoop> ml = Glib::MainLoop::create ();
583 Glib::signal_timeout().connect(sigc::ptr_fun(&idle), 500);