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