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