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