Supporters update.
[dcpomatic.git] / src / lib / ext.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
22 #include "compose.hpp"
23 #include "cross.h"
24 #include "dcpomatic_log.h"
25 #include "digester.h"
26 #include "disk_writer_messages.h"
27 #include "exceptions.h"
28 #include "ext.h"
29 #include "nanomsg.h"
30 #include <dcp/file.h>
31 #include <dcp/filesystem.h>
32
33 #ifdef DCPOMATIC_LINUX
34 #include <linux/fs.h>
35 #include <sys/ioctl.h>
36 extern "C" {
37 #include <lwext4/file_dev.h>
38 }
39 #endif
40
41 #ifdef DCPOMATIC_OSX
42 extern "C" {
43 #include <lwext4/file_dev.h>
44 }
45 #endif
46
47 #ifdef DCPOMATIC_WINDOWS
48 extern "C" {
49 #include <lwext4/file_windows.h>
50 }
51 #endif
52
53 extern "C" {
54 #include <lwext4/ext4.h>
55 #include <lwext4/ext4_debug.h>
56 #include <lwext4/ext4_errno.h>
57 #include <lwext4/ext4_fs.h>
58 #include <lwext4/ext4_mbr.h>
59 #include <lwext4/ext4_mkfs.h>
60 }
61 #include <boost/filesystem.hpp>
62 #include <chrono>
63 #include <string>
64
65
66 using std::exception;
67 using std::min;
68 using std::string;
69 using std::vector;
70
71
72 #define SHORT_TIMEOUT 100
73 #define LONG_TIMEOUT 2000
74
75
76 /* Use quite a big block size here, as ext4's fwrite() has quite a bit of overhead */
77 uint64_t constexpr block_size = 4096 * 4096;
78
79
80 static
81 void
82 count (std::vector<boost::filesystem::path> dirs, uint64_t& total_bytes)
83 {
84         using namespace boost::filesystem;
85
86         for (auto dir: dirs) {
87                 dir = dcp::filesystem::fix_long_path(dir);
88                 for (auto path: directory_iterator(dir)) {
89                         if (is_directory(path)) {
90                                 count({path}, total_bytes);
91                         } else {
92                                 total_bytes += file_size(path);
93                         }
94                 }
95         }
96 }
97
98
99 static
100 void
101 set_timestamps_to_now (boost::filesystem::path path)
102 {
103         auto const now = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
104         ext4_mtime_set (path.generic_string().c_str(), now);
105         ext4_ctime_set (path.generic_string().c_str(), now);
106         ext4_atime_set (path.generic_string().c_str(), now);
107 }
108
109
110 static
111 string
112 write (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total, Nanomsg* nanomsg)
113 {
114         ext4_file out;
115         int r = ext4_fopen(&out, to.generic_string().c_str(), "wb");
116         if (r != EOK) {
117                 throw CopyError(String::compose("Failed to open file %1", to.generic_string()), r, ext4_blockdev_errno);
118         }
119
120         dcp::File in(from, "rb");
121         if (!in) {
122                 ext4_fclose (&out);
123                 throw CopyError(String::compose("Failed to open file %1", from.string()), 0);
124         }
125
126         std::vector<uint8_t> buffer(block_size);
127         Digester digester;
128
129         int progress_frequency = 1;
130         int progress_count = 0;
131         uint64_t remaining = file_size (from);
132         while (remaining > 0) {
133                 uint64_t const this_time = min(remaining, block_size);
134                 size_t read = in.read(buffer.data(), 1, this_time);
135                 if (read != this_time) {
136                         ext4_fclose (&out);
137                         throw CopyError(String::compose("Short read; expected %1 but read %2", this_time, read), 0, ext4_blockdev_errno);
138                 }
139
140                 digester.add (buffer.data(), this_time);
141
142                 size_t written;
143                 r = ext4_fwrite (&out, buffer.data(), this_time, &written);
144                 if (r != EOK) {
145                         ext4_fclose (&out);
146                         throw CopyError("Write failed", r, ext4_blockdev_errno);
147                 }
148                 if (written != this_time) {
149                         ext4_fclose (&out);
150                         throw CopyError(String::compose("Short write; expected %1 but wrote %2", this_time, written), 0, ext4_blockdev_errno);
151                 }
152                 remaining -= this_time;
153                 total_remaining -= this_time;
154
155                 ++progress_count;
156                 if ((progress_count % progress_frequency) == 0 && nanomsg) {
157                         DiskWriterBackEndResponse::copy_progress(1 - float(total_remaining) / total).write_to_nanomsg(*nanomsg, SHORT_TIMEOUT);
158                 }
159         }
160
161         ext4_fclose (&out);
162
163         set_timestamps_to_now (to);
164
165         return digester.get ();
166 }
167
168
169 static
170 string
171 read (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total, Nanomsg* nanomsg)
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         std::vector<uint8_t> buffer(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.data(), this_time, &read);
189                 if (read != this_time) {
190                         ext4_fclose (&in);
191                         throw VerifyError (String::compose("Short read; expected %1 but read %2", this_time, read), 0);
192                 }
193
194                 digester.add (buffer.data(), this_time);
195                 remaining -= this_time;
196                 total_remaining -= this_time;
197                 if (nanomsg) {
198                         DiskWriterBackEndResponse::verify_progress(1 - float(total_remaining) / total).write_to_nanomsg(*nanomsg, SHORT_TIMEOUT);
199                 }
200         }
201
202         ext4_fclose (&in);
203
204         return digester.get ();
205 }
206
207
208 class CopiedFile
209 {
210 public:
211         CopiedFile (boost::filesystem::path from_, boost::filesystem::path to_, string write_digest_)
212                 : from (from_)
213                 , to (to_)
214                 , write_digest (write_digest_)
215         {}
216
217         boost::filesystem::path from;
218         boost::filesystem::path to;
219         /** digest calculated from data as it was read from the source during write */
220         string write_digest;
221 };
222
223
224 /** @param from File to copy from.
225  *  @param to Directory to copy to.
226  */
227 static
228 void
229 copy (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total, vector<CopiedFile>& copied_files, Nanomsg* nanomsg)
230 {
231         LOG_DISK ("Copy %1 -> %2", from.string(), to.generic_string());
232         from = dcp::filesystem::fix_long_path(from);
233
234         using namespace boost::filesystem;
235
236         path const cr = to / from.filename();
237
238         if (is_directory(from)) {
239                 int r = ext4_dir_mk (cr.generic_string().c_str());
240                 if (r != EOK) {
241                         throw CopyError(String::compose("Failed to create directory %1", cr.generic_string()), r, ext4_blockdev_errno);
242                 }
243                 set_timestamps_to_now (cr);
244
245                 for (auto i: directory_iterator(from)) {
246                         copy (i.path(), cr, total_remaining, total, copied_files, nanomsg);
247                 }
248         } else {
249                 string const write_digest = write (from, cr, total_remaining, total, nanomsg);
250                 LOG_DISK ("Wrote %1 %2 with %3", from.string(), cr.generic_string(), write_digest);
251                 copied_files.push_back (CopiedFile(from, cr, write_digest));
252         }
253 }
254
255
256 static
257 void
258 verify (vector<CopiedFile> const& copied_files, uint64_t total, Nanomsg* nanomsg)
259 {
260         uint64_t total_remaining = total;
261         for (auto const& i: copied_files) {
262                 string const read_digest = read (i.from, i.to, total_remaining, total, nanomsg);
263                 LOG_DISK ("Read %1 %2 was %3 on write, now %4", i.from.string(), i.to.generic_string(), i.write_digest, read_digest);
264                 if (read_digest != i.write_digest) {
265                         throw VerifyError ("Hash of written data is incorrect", 0);
266                 }
267         }
268 }
269
270
271 static
272 void
273 format_progress (void* context, float progress)
274 {
275         if (context) {
276                 DiskWriterBackEndResponse::format_progress(progress).write_to_nanomsg(*reinterpret_cast<Nanomsg*>(context), SHORT_TIMEOUT);
277         }
278 }
279
280
281 void
282 #ifdef DCPOMATIC_WINDOWS
283 dcpomatic::write (vector<boost::filesystem::path> dcp_paths, string device, string, Nanomsg* nanomsg)
284 #else
285 dcpomatic::write (vector<boost::filesystem::path> dcp_paths, string device, string posix_partition, Nanomsg* nanomsg)
286 #endif
287 try
288 {
289         ext4_dmask_set (DEBUG_ALL);
290
291         struct ext4_fs fs;
292         fs.read_only = false;
293         fs.bdev = nullptr;
294         fs.last_inode_bg_id = 0;
295         fs.jbd_fs = nullptr;
296         fs.jbd_journal = nullptr;
297         fs.curr_trans = nullptr;
298         struct ext4_mkfs_info info;
299         info.len = 0;
300         info.block_size = 4096;
301         info.blocks_per_group = 0;
302         info.inode_size = 128;
303         info.inodes = 0;
304         info.journal_blocks = 0;
305         info.dsc_size = 0;
306         for (int i = 0; i < UUID_SIZE; ++i) {
307                 info.uuid[i] = rand() & 0xff;
308         }
309         info.journal = false;
310         info.label = nullptr;
311
312 #ifdef WIN32
313         file_windows_name_set(device.c_str());
314         struct ext4_blockdev* bd = file_windows_dev_get();
315 #else
316         file_dev_name_set (device.c_str());
317         struct ext4_blockdev* bd = file_dev_get ();
318 #endif
319
320         if (!bd) {
321                 throw CopyError("Failed to open drive", 0, ext4_blockdev_errno);
322         }
323         LOG_DISK_NC ("Opened drive");
324
325         struct ext4_mbr_parts parts;
326         parts.division[0] = 100;
327         parts.division[1] = 0;
328         parts.division[2] = 0;
329         parts.division[3] = 0;
330
331         /* XXX: not sure if disk_id matters */
332         int r = ext4_mbr_write (bd, &parts, 0);
333         if (r) {
334                 throw CopyError("Failed to write MBR", r, ext4_blockdev_errno);
335         }
336         LOG_DISK_NC ("Wrote MBR");
337
338         struct ext4_mbr_bdevs bdevs;
339         r = ext4_mbr_scan (bd, &bdevs);
340         if (r != EOK) {
341                 throw CopyError("Failed to read MBR", r, ext4_blockdev_errno);
342         }
343
344 #ifdef DCPOMATIC_LINUX
345         /* Re-read the partition table */
346         int fd = open(device.c_str(), O_RDONLY);
347         ioctl(fd, BLKRRPART, NULL);
348         close(fd);
349 #endif
350
351         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);
352
353 #ifdef DCPOMATIC_WINDOWS
354         file_windows_partition_set (bdevs.partitions[0].part_offset, bdevs.partitions[0].part_size);
355 #else
356         file_dev_name_set (posix_partition.c_str());
357
358         /* On macOS (at least) if you try to write to a drive that is sleeping the ext4_mkfs call
359          * below is liable to return EIO because it can't open the device.  Try to work around that
360          * here by opening and closing the device, waiting 5 seconds if it fails.
361          */
362         int wake = open(posix_partition.c_str(), O_RDWR);
363         if (wake == -1) {
364                 dcpomatic_sleep_seconds (5);
365         } else {
366                 close(wake);
367         }
368
369         bd = file_dev_get ();
370 #endif
371
372         if (!bd) {
373                 throw CopyError("Failed to open partition", 0, ext4_blockdev_errno);
374         }
375         LOG_DISK_NC ("Opened partition");
376
377         r = ext4_mkfs(&fs, bd, &info, F_SET_EXT2, format_progress, nanomsg);
378         if (r != EOK) {
379                 throw CopyError("Failed to make filesystem", r, ext4_blockdev_errno);
380         }
381         LOG_DISK_NC ("Made filesystem");
382
383         r = ext4_device_register(bd, "ext4_fs");
384         if (r != EOK) {
385                 throw CopyError("Failed to register device", r, ext4_blockdev_errno);
386         }
387         LOG_DISK_NC ("Registered device");
388
389         r = ext4_mount("ext4_fs", "/mp/", false);
390         if (r != EOK) {
391                 throw CopyError("Failed to mount device", r, ext4_blockdev_errno);
392         }
393         LOG_DISK_NC ("Mounted device");
394
395         uint64_t total_bytes = 0;
396         count (dcp_paths, total_bytes);
397
398         uint64_t total_remaining = total_bytes;
399         vector<CopiedFile> copied_files;
400         for (auto dcp_path: dcp_paths) {
401                 copy (dcp_path, "/mp", total_remaining, total_bytes, copied_files, nanomsg);
402         }
403
404         /* Unmount and re-mount to make sure the write has finished */
405         r = ext4_umount("/mp/");
406         if (r != EOK) {
407                 throw CopyError("Failed to unmount device", r, ext4_blockdev_errno);
408         }
409         r = ext4_mount("ext4_fs", "/mp/", false);
410         if (r != EOK) {
411                 throw CopyError("Failed to mount device", r, ext4_blockdev_errno);
412         }
413         LOG_DISK_NC ("Re-mounted device");
414
415         verify (copied_files, total_bytes, nanomsg);
416
417         r = ext4_umount("/mp/");
418         if (r != EOK) {
419                 throw CopyError("Failed to unmount device", r, ext4_blockdev_errno);
420         }
421
422         ext4_device_unregister("ext4_fs");
423         if (nanomsg && !DiskWriterBackEndResponse::ok().write_to_nanomsg(*nanomsg, LONG_TIMEOUT)) {
424                 throw CommunicationFailedError ();
425         }
426
427         disk_write_finished ();
428 } catch (CopyError& e) {
429         LOG_DISK("CopyError (from write): %1 %2 %3", e.message(), e.ext4_number().get_value_or(0), e.platform_number().get_value_or(0));
430         if (nanomsg) {
431                 DiskWriterBackEndResponse::error(e.message(), e.ext4_number().get_value_or(0), e.platform_number().get_value_or(0)).write_to_nanomsg(*nanomsg, LONG_TIMEOUT);
432         }
433 } catch (VerifyError& e) {
434         LOG_DISK("VerifyError (from write): %1 %2", e.message(), e.number());
435         if (nanomsg) {
436                 DiskWriterBackEndResponse::error(e.message(), e.number(), 0).write_to_nanomsg(*nanomsg, LONG_TIMEOUT);
437         }
438 } catch (exception& e) {
439         LOG_DISK("Exception (from write): %1", e.what());
440         if (nanomsg) {
441                 DiskWriterBackEndResponse::error(e.what(), 0, 0).write_to_nanomsg(*nanomsg, LONG_TIMEOUT);
442         }
443 }
444
445