hackz.
[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 #include <stdlib.h>
81
82 using std::bad_alloc;
83 using std::cin;
84 using std::min;
85 using std::string;
86 using std::runtime_error;
87 using std::exception;
88 using std::vector;
89 using boost::optional;
90
91 #ifdef DCPOMATIC_LINUX
92 static PolkitAuthority* polkit_authority = 0;
93 #endif
94 static uint64_t const block_size = 4096 * 4096;
95 static Nanomsg* nanomsg = 0;
96
97 #define SHORT_TIMEOUT 100
98 #define LONG_TIMEOUT 2000
99
100 static
101 void
102 count (boost::filesystem::path dir, uint64_t& total_bytes)
103 {
104         using namespace boost::filesystem;
105         for (directory_iterator i = directory_iterator(dir); i != directory_iterator(); ++i) {
106                 if (is_directory(*i)) {
107                         count (*i, total_bytes);
108                 } else {
109                         total_bytes += file_size (*i);
110                 }
111         }
112 }
113
114 static
115 string
116 write (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total)
117 {
118         ext4_file out;
119         int r = ext4_fopen(&out, to.generic_string().c_str(), "wb");
120         if (r != EOK) {
121                 throw CopyError (String::compose("Failed to open file %1", to.generic_string()), r);
122         }
123
124         FILE* in = fopen_boost (from, "rb");
125         if (!in) {
126                 ext4_fclose (&out);
127                 throw CopyError (String::compose("Failed to open file %1", from.string()), 0);
128         }
129
130         uint8_t* buffer = new uint8_t[block_size];
131         Digester digester;
132
133         int progress_frequency = 1;
134         int progress_count = 0;
135         uint64_t remaining = file_size (from);
136         while (remaining > 0) {
137                 std::cout << "write " << from << " " << remaining << " / " << total << "\n";
138                 uint64_t const this_time = min(remaining, block_size);
139                 size_t read = fread (buffer, 1, this_time, in);
140                 if (read != this_time) {
141                         fclose (in);
142                         ext4_fclose (&out);
143                         delete[] buffer;
144                         throw CopyError (String::compose("Short read; expected %1 but read %2", this_time, read), 0);
145                 }
146
147                 digester.add (buffer, this_time);
148
149                 size_t written;
150                 r = ext4_fwrite (&out, buffer, this_time, &written);
151                 if (r != EOK) {
152                         fclose (in);
153                         ext4_fclose (&out);
154                         delete[] buffer;
155                         throw CopyError ("Write failed", r);
156                 }
157                 if (written != this_time) {
158                         fclose (in);
159                         ext4_fclose (&out);
160                         delete[] buffer;
161                         throw CopyError (String::compose("Short write; expected %1 but wrote %2", this_time, written), 0);
162                 }
163                 remaining -= this_time;
164                 total_remaining -= this_time;
165
166                 ++progress_count;
167                 if ((progress_count % progress_frequency) == 0) {
168                         nanomsg->send(String::compose(DISK_WRITER_COPY_PROGRESS "\n%1\n", (1 - float(total_remaining) / total)), SHORT_TIMEOUT);
169                 }
170         }
171
172         fclose (in);
173         ext4_fclose (&out);
174         delete[] buffer;
175
176         return digester.get ();
177 }
178
179 static
180 string
181 read (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total)
182 {
183         ext4_file in;
184         LOG_DISK("Opening %1 for read", to.generic_string());
185         int r = ext4_fopen(&in, to.generic_string().c_str(), "rb");
186         if (r != EOK) {
187                 throw VerifyError (String::compose("Failed to open file %1", to.generic_string()), r);
188         }
189         LOG_DISK("Opened %1 for read", to.generic_string());
190
191         uint8_t* buffer = new uint8_t[block_size];
192         Digester digester;
193
194         uint64_t remaining = file_size (from);
195         while (remaining > 0) {
196                 uint64_t const this_time = min(remaining, block_size);
197                 size_t read;
198                 r = ext4_fread (&in, buffer, this_time, &read);
199                 if (read != this_time) {
200                         ext4_fclose (&in);
201                         delete[] buffer;
202                         throw VerifyError (String::compose("Short read; expected %1 but read %2", this_time, read), 0);
203                 }
204
205                 digester.add (buffer, this_time);
206                 remaining -= this_time;
207                 total_remaining -= this_time;
208                 nanomsg->send(String::compose(DISK_WRITER_VERIFY_PROGRESS "\n%1\n", (1 - float(total_remaining) / total)), SHORT_TIMEOUT);
209         }
210
211         ext4_fclose (&in);
212         delete[] buffer;
213
214         return digester.get ();
215 }
216
217
218 class CopiedFile
219 {
220 public:
221         CopiedFile (boost::filesystem::path from_, boost::filesystem::path to_, string write_digest_)
222                 : from (from_)
223                 , to (to_)
224                 , write_digest (write_digest_)
225         {}
226
227         boost::filesystem::path from;
228         boost::filesystem::path to;
229         /** digest calculated from data as it was read from the source during write */
230         string write_digest;
231 };
232
233
234 /** @param from File to copy from.
235  *  @param to Directory to copy to.
236  */
237 static
238 void
239 copy (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total, vector<CopiedFile>& copied_files)
240 {
241         LOG_DISK ("Copy %1 -> %2", from.string(), to.generic_string());
242
243         using namespace boost::filesystem;
244
245         path const cr = to / from.filename();
246
247         if (is_directory(from)) {
248                 int r = ext4_dir_mk (cr.generic_string().c_str());
249                 if (r != EOK) {
250                         throw CopyError (String::compose("Failed to create directory %1", cr.generic_string()), r);
251                 }
252
253                 for (directory_iterator i = directory_iterator(from); i != directory_iterator(); ++i) {
254                         copy (i->path(), cr, total_remaining, total, copied_files);
255                 }
256         } else {
257                 string const write_digest = write (from, cr, total_remaining, total);
258                 LOG_DISK ("Wrote %1 %2 with %3", from.string(), cr.generic_string(), write_digest);
259                 copied_files.push_back (CopiedFile(from, cr, write_digest));
260         }
261 }
262
263
264 static
265 void
266 verify (vector<CopiedFile> const& copied_files, uint64_t total)
267 {
268         uint64_t total_remaining = total;
269         BOOST_FOREACH (CopiedFile const& i, copied_files) {
270                 string const read_digest = read (i.from, i.to, total_remaining, total);
271                 LOG_DISK ("Read %1 %2 was %3 on write, now %4", i.from.string(), i.to.generic_string(), i.write_digest, read_digest);
272                 if (read_digest != i.write_digest) {
273                         throw VerifyError ("Hash of written data is incorrect", 0);
274                 }
275         }
276 }
277
278
279 static
280 void
281 write (boost::filesystem::path dcp_path, string device)
282 try
283 {
284         ext4_dmask_set (DEBUG_ALL);
285
286         /* We rely on static initialization for these */
287         static struct ext4_fs fs;
288         static struct ext4_mkfs_info info;
289         info.block_size = 4096;
290         info.inode_size = 128;
291         info.journal = false;
292
293 #ifdef WIN32
294         file_windows_name_set(device.c_str());
295         struct ext4_blockdev* bd = file_windows_dev_get();
296 #else
297         file_dev_name_set (device.c_str());
298         struct ext4_blockdev* bd = file_dev_get ();
299 #endif
300
301         if (!bd) {
302                 throw CopyError ("Failed to open drive", 0);
303         }
304         LOG_DISK_NC ("Opened drive");
305
306         struct ext4_mbr_parts parts;
307         parts.division[0] = 100;
308         parts.division[1] = 0;
309         parts.division[2] = 0;
310         parts.division[3] = 0;
311
312 #ifdef DCPOMATIC_LINUX
313         PrivilegeEscalator e;
314 #endif
315
316         /* XXX: not sure if disk_id matters */
317         int r = ext4_mbr_write (bd, &parts, 0);
318         if (r) {
319                 throw CopyError ("Failed to write MBR", r);
320         }
321         LOG_DISK_NC ("Wrote MBR");
322
323         struct ext4_mbr_bdevs bdevs;
324         r = ext4_mbr_scan (bd, &bdevs);
325         if (r != EOK) {
326                 throw CopyError ("Failed to read MBR", r);
327         }
328
329 #ifdef DCPOMATIC_WINDOWS
330         file_windows_partition_set (bdevs.partitions[0].part_offset, bdevs.partitions[0].part_size);
331 #endif
332
333         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);
334
335 #ifdef DCPOMATIC_LINUX
336         /* Re-read the partition table */
337         int fd = open(device.c_str(), O_RDONLY);
338         ioctl(fd, BLKRRPART, NULL);
339         close(fd);
340 #endif
341
342 #ifdef DCPOMATIC_LINUX
343         string partition = device;
344         /* XXX: don't know if this logic is sensible */
345         if (partition.size() > 0 && isdigit(partition[partition.length() - 1])) {
346                 partition += "p1";
347         } else {
348                 partition += "1";
349         }
350         file_dev_name_set (partition.c_str());
351         bd = file_dev_get ();
352 #endif
353
354 #ifdef DCPOMATIC_OSX
355         string partition = device + "s1";
356         file_dev_name_set (partition.c_str());
357         bd = file_dev_get ();
358 #endif
359
360         if (!bd) {
361                 throw CopyError ("Failed to open partition", 0);
362         }
363         LOG_DISK_NC ("Opened partition");
364
365         nanomsg->send(DISK_WRITER_FORMATTING "\n", SHORT_TIMEOUT);
366
367         r = ext4_mkfs(&fs, bd, &info, F_SET_EXT2);
368         if (r != EOK) {
369                 throw CopyError ("Failed to make filesystem", r);
370         }
371         LOG_DISK_NC ("Made filesystem");
372
373         r = ext4_device_register(bd, "ext4_fs");
374         if (r != EOK) {
375                 throw CopyError ("Failed to register device", r);
376         }
377         LOG_DISK_NC ("Registered device");
378
379         r = ext4_mount("ext4_fs", "/mp/", false);
380         if (r != EOK) {
381                 throw CopyError ("Failed to mount device", r);
382         }
383         LOG_DISK_NC ("Mounted device");
384
385         uint64_t total_bytes = 0;
386         count (dcp_path, total_bytes);
387
388         uint64_t total_remaining = total_bytes;
389         vector<CopiedFile> copied_files;
390         copy (dcp_path, "/mp", total_remaining, total_bytes, copied_files);
391
392         /* Unmount and re-mount to make sure the write has finished */
393         r = ext4_umount("/mp/");
394         if (r != EOK) {
395                 throw CopyError ("Failed to unmount device", r);
396         }
397         r = ext4_mount("ext4_fs", "/mp/", false);
398         if (r != EOK) {
399                 throw CopyError ("Failed to mount device", r);
400         }
401         LOG_DISK_NC ("Re-mounted device");
402
403         verify (copied_files, total_bytes);
404
405         r = ext4_umount("/mp/");
406         if (r != EOK) {
407                 throw CopyError ("Failed to unmount device", r);
408         }
409
410         ext4_device_unregister("ext4_fs");
411         if (!nanomsg->send(DISK_WRITER_OK "\n", LONG_TIMEOUT)) {
412                 throw CommunicationFailedError ();
413         }
414
415         disk_write_finished ();
416 } catch (CopyError& e) {
417         LOG_DISK("CopyError (from write): %1 %2", e.message(), e.number().get_value_or(0));
418         nanomsg->send(String::compose(DISK_WRITER_ERROR "\n%1\n%2\n", e.message(), e.number().get_value_or(0)), LONG_TIMEOUT);
419 } catch (VerifyError& e) {
420         LOG_DISK("VerifyError (from write): %1 %2", e.message(), e.number());
421         nanomsg->send(String::compose(DISK_WRITER_ERROR "\n%1\n%2\n", e.message(), e.number()), LONG_TIMEOUT);
422 } catch (exception& e) {
423         LOG_DISK("Exception (from write): %1", e.what());
424         nanomsg->send(String::compose(DISK_WRITER_ERROR "\n%1\n0\n", e.what()), LONG_TIMEOUT);
425 }
426
427 struct Parameters
428 {
429         boost::filesystem::path dcp_path;
430         std::string device;
431 };
432
433 #ifdef DCPOMATIC_LINUX
434 static
435 void
436 polkit_callback (GObject *, GAsyncResult* res, gpointer data)
437 {
438         Parameters* parameters = reinterpret_cast<Parameters*> (data);
439         PolkitAuthorizationResult* result = polkit_authority_check_authorization_finish (polkit_authority, res, 0);
440         if (result && polkit_authorization_result_get_is_authorized(result)) {
441                 write (parameters->dcp_path, parameters->device);
442         }
443         delete parameters;
444         if (result) {
445                 g_object_unref (result);
446         }
447 }
448 #endif
449
450
451 bool
452 idle ()
453 try
454 {
455         using namespace boost::algorithm;
456
457         optional<string> s = nanomsg->receive (0);
458         if (!s) {
459                 return true;
460         }
461
462         LOG_DISK("Writer receives command: %1", *s);
463
464         if (*s == DISK_WRITER_QUIT) {
465                 exit (EXIT_SUCCESS);
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 }