Change internal name dist -> disk.
[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 <iostream>
71
72 using std::cin;
73 using std::min;
74 using std::string;
75 using std::runtime_error;
76 using std::exception;
77 using boost::optional;
78
79 #ifdef DCPOMATIC_LINUX
80 static PolkitAuthority* polkit_authority = 0;
81 #endif
82 static boost::filesystem::path dcp_path;
83 static std::string device;
84 static uint64_t const block_size = 4096;
85 static Nanomsg* nanomsg = 0;
86
87 static
88 void
89 count (boost::filesystem::path dir, uint64_t& total_bytes)
90 {
91         using namespace boost::filesystem;
92         for (directory_iterator i = directory_iterator(dir); i != directory_iterator(); ++i) {
93                 if (is_directory(*i)) {
94                         count (*i, total_bytes);
95                 } else {
96                         total_bytes += file_size (*i);
97                 }
98         }
99 }
100
101 static
102 string
103 write (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total)
104 {
105         ext4_file out;
106         int r = ext4_fopen(&out, to.generic_string().c_str(), "wb");
107         if (r != EOK) {
108                 throw CopyError (String::compose("Failed to open file %1", to.generic_string()), r);
109         }
110
111         FILE* in = fopen_boost (from, "rb");
112         if (!in) {
113                 ext4_fclose (&out);
114                 throw CopyError (String::compose("Failed to open file %1", from.string()), 0);
115         }
116
117         uint8_t* buffer = new uint8_t[block_size];
118         Digester digester;
119
120         uint64_t remaining = file_size (from);
121         while (remaining > 0) {
122                 uint64_t const this_time = min(remaining, block_size);
123                 size_t read = fread (buffer, 1, this_time, in);
124                 if (read != this_time) {
125                         fclose (in);
126                         ext4_fclose (&out);
127                         delete[] buffer;
128                         throw CopyError (String::compose("Short read; expected %1 but read %2", this_time, read), 0);
129                 }
130
131                 digester.add (buffer, this_time);
132
133                 size_t written;
134                 r = ext4_fwrite (&out, buffer, this_time, &written);
135                 if (r != EOK) {
136                         fclose (in);
137                         ext4_fclose (&out);
138                         delete[] buffer;
139                         throw CopyError ("Write failed", r);
140                 }
141                 if (written != this_time) {
142                         fclose (in);
143                         ext4_fclose (&out);
144                         delete[] buffer;
145                         throw CopyError (String::compose("Short write; expected %1 but wrote %2", this_time, written), 0);
146                 }
147                 remaining -= this_time;
148                 total_remaining -= this_time;
149                 nanomsg->blocking_send(String::compose(DISK_WRITER_PROGRESS "\n%1\n", (1 - float(total_remaining) / total)));
150         }
151
152         fclose (in);
153         ext4_fclose (&out);
154         delete[] buffer;
155
156         return digester.get ();
157 }
158
159 static
160 string
161 read (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total)
162 {
163         ext4_file in;
164         LOG_DISK("Opening %1 for read", to.generic_string());
165         int r = ext4_fopen(&in, to.generic_string().c_str(), "rb");
166         if (r != EOK) {
167                 throw VerifyError (String::compose("Failed to open file %1", to.generic_string()), r);
168         }
169         LOG_DISK("Opened %1 for read", to.generic_string());
170
171         uint8_t* buffer = new uint8_t[block_size];
172         Digester digester;
173
174         uint64_t remaining = file_size (from);
175         while (remaining > 0) {
176                 uint64_t const this_time = min(remaining, block_size);
177                 size_t read;
178                 r = ext4_fread (&in, buffer, this_time, &read);
179                 if (read != this_time) {
180                         ext4_fclose (&in);
181                         delete[] buffer;
182                         throw VerifyError (String::compose("Short read; expected %1 but read %2", this_time, read), 0);
183                 }
184
185                 digester.add (buffer, this_time);
186                 remaining -= this_time;
187                 total_remaining -= this_time;
188                 nanomsg->blocking_send(String::compose(DISK_WRITER_PROGRESS "\n%1\n", (1 - float(total_remaining) / total)));
189         }
190
191         ext4_fclose (&in);
192         delete[] buffer;
193
194         return digester.get ();
195 }
196
197
198 /** @param from File to copy from.
199  *  @param to Directory to copy to.
200  */
201 static
202 void
203 copy (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total)
204 {
205         LOG_DISK ("Copy %1 -> %2", from.string(), to.generic_string());
206
207         using namespace boost::filesystem;
208
209         path const cr = to / from.filename();
210
211         if (is_directory(from)) {
212                 int r = ext4_dir_mk (cr.generic_string().c_str());
213                 if (r != EOK) {
214                         throw CopyError (String::compose("Failed to create directory %1", cr.generic_string()), r);
215                 }
216
217                 for (directory_iterator i = directory_iterator(from); i != directory_iterator(); ++i) {
218                         copy (i->path(), cr, total_remaining, total);
219                 }
220         } else {
221                 string const write_digest = write (from, cr, total_remaining, total);
222                 LOG_DISK ("Wrote %1 %2 with %3", from.string(), cr.generic_string(), write_digest);
223                 string const read_digest = read (from, cr, total_remaining, total);
224                 LOG_DISK ("Read %1 %2 with %3", from.string(), cr.generic_string(), write_digest);
225                 if (write_digest != read_digest) {
226                         throw VerifyError ("Hash of written data is incorrect", 0);
227                 }
228         }
229 }
230
231 static
232 void
233 write ()
234 try
235 {
236 //      ext4_dmask_set (DEBUG_ALL);
237
238         /* We rely on static initialization for these */
239         static struct ext4_fs fs;
240         static struct ext4_mkfs_info info;
241         info.block_size = 1024;
242         info.inode_size = 128;
243         info.journal = false;
244
245 #ifdef WIN32
246         file_windows_name_set(device.c_str());
247         struct ext4_blockdev* bd = file_windows_dev_get();
248 #else
249         file_dev_name_set (device.c_str());
250         struct ext4_blockdev* bd = file_dev_get ();
251 #endif
252
253         if (!bd) {
254                 throw CopyError ("Failed to open drive", 0);
255         }
256         LOG_DISK_NC ("Opened drive");
257
258         struct ext4_mbr_parts parts;
259         parts.division[0] = 100;
260         parts.division[1] = 0;
261         parts.division[2] = 0;
262         parts.division[3] = 0;
263
264 #ifdef DCPOMATIC_LINUX
265         PrivilegeEscalator e;
266 #endif
267
268         /* XXX: not sure if disk_id matters */
269         int r = ext4_mbr_write (bd, &parts, 0);
270
271         if (r) {
272                 throw CopyError ("Failed to write MBR", r);
273         }
274         LOG_DISK_NC ("Wrote MBR");
275
276 #ifdef DCPOMATIC_WINDOWS
277         struct ext4_mbr_bdevs bdevs;
278         r = ext4_mbr_scan (bd, &bdevs);
279         if (r != EOK) {
280                 throw CopyError ("Failed to read MBR", r);
281         }
282
283         file_windows_partition_set (bdevs.partitions[0].part_offset, bdevs.partitions[0].part_size);
284 #endif
285
286 #ifdef DCPOMATIC_LINUX
287         /* Re-read the partition table */
288         int fd = open(device.c_str(), O_RDONLY);
289         ioctl(fd, BLKRRPART, NULL);
290         close(fd);
291 #endif
292
293 #ifdef DCPOMATIC_POSIX
294         string partition = device;
295         /* XXX: don't know if this logic is sensible */
296         if (partition.size() > 0 && isdigit(partition[partition.length() - 1])) {
297                 partition += "p1";
298         } else {
299                 partition += "1";
300         }
301         file_dev_name_set (partition.c_str());
302         bd = file_dev_get ();
303 #endif
304
305         if (!bd) {
306                 throw CopyError ("Failed to open partition", 0);
307         }
308         LOG_DISK_NC ("Opened partition");
309
310         nanomsg->blocking_send(DISK_WRITER_FORMATTING "\n");
311
312         r = ext4_mkfs(&fs, bd, &info, F_SET_EXT4);
313         if (r != EOK) {
314                 throw CopyError ("Failed to make filesystem", r);
315         }
316         LOG_DISK_NC ("Made filesystem");
317
318         r = ext4_device_register(bd, "ext4_fs");
319         if (r != EOK) {
320                 throw CopyError ("Failed to register device", r);
321         }
322         LOG_DISK_NC ("Registered device");
323
324         r = ext4_mount("ext4_fs", "/mp/", false);
325         if (r != EOK) {
326                 throw CopyError ("Failed to mount device", r);
327         }
328         LOG_DISK_NC ("Mounted device");
329
330         uint64_t total_bytes = 0;
331         count (dcp_path, total_bytes);
332
333         /* XXX: this is a hack.  We are going to "treat" every byte twice; write it, and then verify it.  Double the
334          * bytes totals so that progress works itself out (assuming write is the same speed as read).
335          */
336         total_bytes *= 2;
337         copy (dcp_path, "/mp", total_bytes, total_bytes);
338
339         r = ext4_umount("/mp/");
340         if (r != EOK) {
341                 throw CopyError ("Failed to unmount device", r);
342         }
343
344         nanomsg->blocking_send(DISK_WRITER_OK "\n");
345 } catch (CopyError& e) {
346         LOG_DISK("CopyError: %1 %2", e.message(), e.number());
347         nanomsg->blocking_send(String::compose(DISK_WRITER_ERROR "\n%1\n%2\n", e.message(), e.number()));
348 } catch (VerifyError& e) {
349         LOG_DISK("VerifyError: %1 %2", e.message(), e.number());
350         nanomsg->blocking_send(String::compose(DISK_WRITER_ERROR "\n%1\n%2\n", e.message(), e.number()));
351 } catch (exception& e) {
352         LOG_DISK("Exception: %1", e.what());
353         nanomsg->blocking_send(String::compose(DISK_WRITER_ERROR "\n%1\n0\n", e.what()));
354 }
355
356 #ifdef DCPOMATIC_LINUX
357 static
358 void
359 polkit_callback (GObject *, GAsyncResult* res, gpointer)
360 {
361         PolkitAuthorizationResult* result = polkit_authority_check_authorization_finish (polkit_authority, res, 0);
362         if (result && polkit_authorization_result_get_is_authorized(result)) {
363                 write ();
364         }
365         if (result) {
366                 g_object_unref (result);
367         }
368 }
369 #endif
370
371 bool
372 idle ()
373 {
374         optional<string> s = nanomsg->nonblocking_get ();
375         if (!s) {
376                 return true;
377         }
378
379         if (*s == "Q") {
380                 exit (EXIT_SUCCESS);
381         } else if (*s == "W") {
382                 dcp_path = nanomsg->blocking_get();
383                 device = nanomsg->blocking_get();
384
385                 LOG_DISK ("Here we go writing %1 to %2", dcp_path, device);
386
387 #ifdef DCPOMATIC_LINUX
388                 polkit_authority = polkit_authority_get_sync (0, 0);
389                 PolkitSubject* subject = polkit_unix_process_new (getppid());
390                 polkit_authority_check_authorization (
391                                 polkit_authority, subject, "com.dcpomatic.write-drive", 0, POLKIT_CHECK_AUTHORIZATION_FLAGS_ALLOW_USER_INTERACTION, 0, polkit_callback, 0
392                                 );
393 #else
394                 write ();
395 #endif
396         }
397
398         return true;
399 }
400
401 int
402 main ()
403 {
404         /* XXX: this is a hack, but I expect we'll need logs and I'm not sure if there's
405          * a better place to put them.
406          */
407         dcpomatic_log.reset(new FileLog(config_path() / "disk_writer.log"));
408         dcpomatic_log->set_types (dcpomatic_log->types() | LogEntry::TYPE_DISK);
409         LOG_DISK_NC("dcpomatic_disk_writer started");
410
411         try {
412                 nanomsg = new Nanomsg (false);
413         } catch (runtime_error& e) {
414                 LOG_DISK_NC("Could not set up nanomsg socket");
415                 exit (EXIT_FAILURE);
416         }
417
418         Glib::RefPtr<Glib::MainLoop> ml = Glib::MainLoop::create ();
419         Glib::signal_timeout().connect(sigc::ptr_fun(&idle), 500);
420         ml->run ();
421 }