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