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