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