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