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