45a5e8c60a44345ab7eb74e631edca1a5701cad3
[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 /* 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;
95
96 #define SHORT_TIMEOUT 100
97 #define LONG_TIMEOUT 2000
98
99 static
100 void
101 count (boost::filesystem::path dir, uint64_t& total_bytes)
102 {
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);
107                 } else {
108                         total_bytes += file_size (*i);
109                 }
110         }
111 }
112
113 static
114 string
115 write (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total)
116 {
117         ext4_file out;
118         int r = ext4_fopen(&out, to.generic_string().c_str(), "wb");
119         if (r != EOK) {
120                 throw CopyError (String::compose("Failed to open file %1", to.generic_string()), r);
121         }
122
123         FILE* in = fopen_boost (from, "rb");
124         if (!in) {
125                 ext4_fclose (&out);
126                 throw CopyError (String::compose("Failed to open file %1", from.string()), 0);
127         }
128
129         uint8_t* buffer = new uint8_t[block_size];
130         Digester digester;
131
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) {
139                         fclose (in);
140                         ext4_fclose (&out);
141                         delete[] buffer;
142                         throw CopyError (String::compose("Short read; expected %1 but read %2", this_time, read), 0);
143                 }
144
145                 digester.add (buffer, this_time);
146
147                 size_t written;
148                 r = ext4_fwrite (&out, buffer, this_time, &written);
149                 if (r != EOK) {
150                         fclose (in);
151                         ext4_fclose (&out);
152                         delete[] buffer;
153                         throw CopyError ("Write failed", r);
154                 }
155                 if (written != this_time) {
156                         fclose (in);
157                         ext4_fclose (&out);
158                         delete[] buffer;
159                         throw CopyError (String::compose("Short write; expected %1 but wrote %2", this_time, written), 0);
160                 }
161                 remaining -= this_time;
162                 total_remaining -= this_time;
163
164                 ++progress_count;
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);
167                 }
168         }
169
170         fclose (in);
171         ext4_fclose (&out);
172         delete[] buffer;
173
174         return digester.get ();
175 }
176
177 static
178 string
179 read (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total)
180 {
181         ext4_file in;
182         LOG_DISK("Opening %1 for read", to.generic_string());
183         int r = ext4_fopen(&in, to.generic_string().c_str(), "rb");
184         if (r != EOK) {
185                 throw VerifyError (String::compose("Failed to open file %1", to.generic_string()), r);
186         }
187         LOG_DISK("Opened %1 for read", to.generic_string());
188
189         uint8_t* buffer = new uint8_t[block_size];
190         Digester digester;
191
192         uint64_t remaining = file_size (from);
193         while (remaining > 0) {
194                 uint64_t const this_time = min(remaining, block_size);
195                 size_t read;
196                 r = ext4_fread (&in, buffer, this_time, &read);
197                 if (read != this_time) {
198                         ext4_fclose (&in);
199                         delete[] buffer;
200                         throw VerifyError (String::compose("Short read; expected %1 but read %2", this_time, read), 0);
201                 }
202
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);
207         }
208
209         ext4_fclose (&in);
210         delete[] buffer;
211
212         return digester.get ();
213 }
214
215
216 class CopiedFile
217 {
218 public:
219         CopiedFile (boost::filesystem::path from_, boost::filesystem::path to_, string write_digest_)
220                 : from (from_)
221                 , to (to_)
222                 , write_digest (write_digest_)
223         {}
224
225         boost::filesystem::path from;
226         boost::filesystem::path to;
227         /** digest calculated from data as it was read from the source during write */
228         string write_digest;
229 };
230
231
232 /** @param from File to copy from.
233  *  @param to Directory to copy to.
234  */
235 static
236 void
237 copy (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total, vector<CopiedFile>& copied_files)
238 {
239         LOG_DISK ("Copy %1 -> %2", from.string(), to.generic_string());
240
241         using namespace boost::filesystem;
242
243         path const cr = to / from.filename();
244
245         if (is_directory(from)) {
246                 int r = ext4_dir_mk (cr.generic_string().c_str());
247                 if (r != EOK) {
248                         throw CopyError (String::compose("Failed to create directory %1", cr.generic_string()), r);
249                 }
250
251                 for (directory_iterator i = directory_iterator(from); i != directory_iterator(); ++i) {
252                         copy (i->path(), cr, total_remaining, total, copied_files);
253                 }
254         } else {
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));
258         }
259 }
260
261
262 static
263 void
264 verify (vector<CopiedFile> const& copied_files, uint64_t total)
265 {
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);
272                 }
273         }
274 }
275
276
277 static
278 void
279 write (boost::filesystem::path dcp_path, string device)
280 try
281 {
282         ext4_dmask_set (DEBUG_ALL);
283
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;
290
291 #ifdef WIN32
292         file_windows_name_set(device.c_str());
293         struct ext4_blockdev* bd = file_windows_dev_get();
294 #else
295         file_dev_name_set (device.c_str());
296         struct ext4_blockdev* bd = file_dev_get ();
297 #endif
298
299         if (!bd) {
300                 throw CopyError ("Failed to open drive", 0);
301         }
302         LOG_DISK_NC ("Opened drive");
303
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;
309
310 #ifdef DCPOMATIC_LINUX
311         PrivilegeEscalator e;
312 #endif
313
314         /* XXX: not sure if disk_id matters */
315         int r = ext4_mbr_write (bd, &parts, 0);
316         if (r) {
317                 throw CopyError ("Failed to write MBR", r);
318         }
319         LOG_DISK_NC ("Wrote MBR");
320
321         struct ext4_mbr_bdevs bdevs;
322         r = ext4_mbr_scan (bd, &bdevs);
323         if (r != EOK) {
324                 throw CopyError ("Failed to read MBR", r);
325         }
326
327 #ifdef DCPOMATIC_WINDOWS
328         file_windows_partition_set (bdevs.partitions[0].part_offset, bdevs.partitions[0].part_size);
329 #endif
330
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);
332
333 #ifdef DCPOMATIC_LINUX
334         /* Re-read the partition table */
335         int fd = open(device.c_str(), O_RDONLY);
336         ioctl(fd, BLKRRPART, NULL);
337         close(fd);
338 #endif
339
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])) {
344                 partition += "p1";
345         } else {
346                 partition += "1";
347         }
348         file_dev_name_set (partition.c_str());
349         bd = file_dev_get ();
350 #endif
351
352 #ifdef DCPOMATIC_OSX
353         string partition = device + "s1";
354         file_dev_name_set (partition.c_str());
355         bd = file_dev_get ();
356 #endif
357
358         if (!bd) {
359                 throw CopyError ("Failed to open partition", 0);
360         }
361         LOG_DISK_NC ("Opened partition");
362
363         nanomsg->send(DISK_WRITER_FORMATTING "\n", SHORT_TIMEOUT);
364
365         r = ext4_mkfs(&fs, bd, &info, F_SET_EXT2);
366         if (r != EOK) {
367                 throw CopyError ("Failed to make filesystem", r);
368         }
369         LOG_DISK_NC ("Made filesystem");
370
371         r = ext4_device_register(bd, "ext4_fs");
372         if (r != EOK) {
373                 throw CopyError ("Failed to register device", r);
374         }
375         LOG_DISK_NC ("Registered device");
376
377         r = ext4_mount("ext4_fs", "/mp/", false);
378         if (r != EOK) {
379                 throw CopyError ("Failed to mount device", r);
380         }
381         LOG_DISK_NC ("Mounted device");
382
383         uint64_t total_bytes = 0;
384         count (dcp_path, total_bytes);
385
386         uint64_t total_remaining = total_bytes;
387         vector<CopiedFile> copied_files;
388         copy (dcp_path, "/mp", total_remaining, total_bytes, copied_files);
389
390         /* Unmount and re-mount to make sure the write has finished */
391         r = ext4_umount("/mp/");
392         if (r != EOK) {
393                 throw CopyError ("Failed to unmount device", r);
394         }
395         r = ext4_mount("ext4_fs", "/mp/", false);
396         if (r != EOK) {
397                 throw CopyError ("Failed to mount device", r);
398         }
399         LOG_DISK_NC ("Re-mounted device");
400
401         verify (copied_files, total_bytes);
402
403         r = ext4_umount("/mp/");
404         if (r != EOK) {
405                 throw CopyError ("Failed to unmount device", r);
406         }
407
408         ext4_device_unregister("ext4_fs");
409         if (!nanomsg->send(DISK_WRITER_OK "\n", LONG_TIMEOUT)) {
410                 throw CommunicationFailedError ();
411         }
412
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);
423 }
424
425 struct Parameters
426 {
427         boost::filesystem::path dcp_path;
428         std::string device;
429 };
430
431 #ifdef DCPOMATIC_LINUX
432 static
433 void
434 polkit_callback (GObject *, GAsyncResult* res, gpointer data)
435 {
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);
440         }
441         delete parameters;
442         if (result) {
443                 g_object_unref (result);
444         }
445 }
446 #endif
447
448
449 bool
450 idle ()
451 try
452 {
453         using namespace boost::algorithm;
454
455         optional<string> s = nanomsg->receive (0);
456         if (!s) {
457                 return true;
458         }
459
460         LOG_DISK("Writer receives command: %1", *s);
461
462         if (*s == DISK_WRITER_QUIT) {
463                 exit (EXIT_SUCCESS);
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 ();
473                 }
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 ();
478                 }
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();
485                 }
486
487                 /* Do some basic sanity checks; this is a bit belt-and-braces but it can't hurt... */
488
489 #ifdef DCPOMATIC_OSX
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);
493                         return true;
494                 }
495 #endif
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);
500                         return true;
501                 }
502 #endif
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);
507                         return true;
508                 }
509 #endif
510
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();
517                         }
518                 }
519
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);
523                         return true;
524                 }
525                 if (mounted) {
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);
528                         return true;
529                 }
530
531                 LOG_DISK ("Here we go writing %1 to %2", *dcp_path, *device);
532
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
541                                 );
542 #else
543                 write (*dcp_path, *device);
544 #endif
545         }
546
547         return true;
548 } catch (exception& e) {
549         LOG_DISK("Exception (from idle): %1", e.what());
550         return true;
551 }
552
553 int
554 main ()
555 {
556 #ifdef DCPOMATIC_OSX
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
560          */
561         dcpomatic_log.reset(new StdoutLog(LogEntry::TYPE_DISK));
562         LOG_DISK("dcpomatic_disk_writer %1 started", dcpomatic_git_commit);
563 #else
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.
566          */
567         dcpomatic_log.reset(new FileLog(config_path() / "disk_writer.log", LogEntry::TYPE_DISK));
568         LOG_DISK_NC("dcpomatic_disk_writer started");
569 #endif
570
571 #ifdef DCPOMATIC_OSX
572         /* I *think* this confumes the notifyd event that we used to start the process, so we only
573          * get started once per notification.
574          */
575         xpc_set_event_stream_handler("com.apple.notifyd.matching", DISPATCH_TARGET_QUEUE_DEFAULT, ^(xpc_object_t) {});
576 #endif
577
578         try {
579                 nanomsg = new Nanomsg (false);
580         } catch (runtime_error& e) {
581                 LOG_DISK_NC("Could not set up nanomsg socket");
582                 exit (EXIT_FAILURE);
583         }
584
585         Glib::RefPtr<Glib::MainLoop> ml = Glib::MainLoop::create ();
586         Glib::signal_timeout().connect(sigc::ptr_fun(&idle), 500);
587         ml->run ();
588 }