Fix path separators on Windows.
[dcpomatic.git] / src / tools / dcpomatic_dist_writer.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 #include "lib/dist_writer_messages.h"
22 #include "lib/compose.hpp"
23 #include "lib/exceptions.h"
24 #include "lib/cross.h"
25 #include "lib/digester.h"
26 #include "lib/file_log.h"
27 #include "lib/dcpomatic_log.h"
28 #include "lib/nanomsg.h"
29 extern "C" {
30 #include <lwext4/ext4_mbr.h>
31 #include <lwext4/ext4_fs.h>
32 #include <lwext4/ext4_mkfs.h>
33 #include <lwext4/ext4_errno.h>
34 #include <lwext4/ext4_debug.h>
35 #include <lwext4/ext4.h>
36 }
37
38 #ifdef DCPOMATIC_POSIX
39 #include <sys/ioctl.h>
40 #include <sys/types.h>
41 #include <sys/stat.h>
42 #endif
43
44 #ifdef DCPOMATIC_OSX
45 #undef nil
46 #endif
47
48 #ifdef DCPOMATIC_LINUX
49 #include <linux/fs.h>
50 #include <polkit/polkit.h>
51 extern "C" {
52 #include <lwext4/file_dev.h>
53 }
54 #include <poll.h>
55 #endif
56
57 #ifdef DCPOMATIC_WINDOWS
58 extern "C" {
59 #include <lwext4/file_windows.h>
60 }
61 #endif
62
63 #include <glibmm.h>
64 #include <unistd.h>
65 #include <sys/types.h>
66 #include <boost/filesystem.hpp>
67 #include <iostream>
68
69 using std::cin;
70 using std::min;
71 using std::string;
72 using std::runtime_error;
73 using boost::optional;
74
75 #ifdef DCPOMATIC_LINUX
76 static PolkitAuthority* polkit_authority = 0;
77 #endif
78 static boost::filesystem::path dcp_path;
79 static std::string device;
80 static uint64_t const block_size = 4096;
81 static Nanomsg* nanomsg = 0;
82
83 static
84 void
85 count (boost::filesystem::path dir, uint64_t& total_bytes)
86 {
87         using namespace boost::filesystem;
88         for (directory_iterator i = directory_iterator(dir); i != directory_iterator(); ++i) {
89                 if (is_directory(*i)) {
90                         count (*i, total_bytes);
91                 } else {
92                         total_bytes += file_size (*i);
93                 }
94         }
95 }
96
97 static
98 string
99 write (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total)
100 {
101         ext4_file out;
102         int r = ext4_fopen(&out, to.generic_string().c_str(), "wb");
103         if (r != EOK) {
104                 throw CopyError (String::compose("Failed to open file %1", to.generic_string()), r);
105         }
106
107         FILE* in = fopen_boost (from, "rb");
108         if (!in) {
109                 ext4_fclose (&out);
110                 throw CopyError (String::compose("Failed to open file %1", from.string()), 0);
111         }
112
113         uint8_t* buffer = new uint8_t[block_size];
114         Digester digester;
115
116         uint64_t remaining = file_size (from);
117         while (remaining > 0) {
118                 uint64_t const this_time = min(remaining, block_size);
119                 size_t read = fread (buffer, 1, this_time, in);
120                 if (read != this_time) {
121                         fclose (in);
122                         ext4_fclose (&out);
123                         delete[] buffer;
124                         throw CopyError (String::compose("Short read; expected %1 but read %2", this_time, read), 0);
125                 }
126
127                 digester.add (buffer, this_time);
128
129                 size_t written;
130                 r = ext4_fwrite (&out, buffer, this_time, &written);
131                 if (r != EOK) {
132                         fclose (in);
133                         ext4_fclose (&out);
134                         delete[] buffer;
135                         throw CopyError ("Write failed", r);
136                 }
137                 if (written != this_time) {
138                         fclose (in);
139                         ext4_fclose (&out);
140                         delete[] buffer;
141                         throw CopyError (String::compose("Short write; expected %1 but wrote %2", this_time, written), 0);
142                 }
143                 remaining -= this_time;
144                 total_remaining -= this_time;
145                 nanomsg->send(String::compose(DIST_WRITER_PROGRESS "\n%1\n", (1 - float(total_remaining) / total)));
146         }
147
148         fclose (in);
149         ext4_fclose (&out);
150         delete[] buffer;
151
152         return digester.get ();
153 }
154
155 static
156 string
157 read (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total)
158 {
159         ext4_file in;
160         int r = ext4_fopen(&in, to.generic_string().c_str(), "rb");
161         if (r != EOK) {
162                 throw VerifyError (String::compose("Failed to open file %1", to.generic_string()), r);
163         }
164
165         uint8_t* buffer = new uint8_t[block_size];
166         Digester digester;
167
168         uint64_t remaining = file_size (from);
169         while (remaining > 0) {
170                 uint64_t const this_time = min(remaining, block_size);
171                 size_t read;
172                 r = ext4_fread (&in, buffer, this_time, &read);
173                 if (read != this_time) {
174                         ext4_fclose (&in);
175                         delete[] buffer;
176                         throw VerifyError (String::compose("Short read; expected %1 but read %2", this_time, read), 0);
177                 }
178
179                 digester.add (buffer, this_time);
180                 remaining -= this_time;
181                 total_remaining -= this_time;
182                 nanomsg->send(String::compose(DIST_WRITER_PROGRESS "\n%1\n", (1 - float(total_remaining) / total)));
183         }
184
185         ext4_fclose (&in);
186         delete[] buffer;
187
188         return digester.get ();
189 }
190
191
192 /** @param from File to copy from.
193  *  @param to Directory to copy to.
194  */
195 static
196 void
197 copy (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total)
198 {
199         LOG_DIST ("Copy %1 -> %2", from.string(), to.generic_string());
200
201         using namespace boost::filesystem;
202
203         path const cr = to / from.filename();
204
205         if (is_directory(from)) {
206                 int r = ext4_dir_mk (cr.generic_string().c_str());
207                 if (r != EOK) {
208                         throw CopyError (String::compose("Failed to create directory %1", cr.generic_string()), r);
209                 }
210
211                 for (directory_iterator i = directory_iterator(from); i != directory_iterator(); ++i) {
212                         copy (i->path(), cr, total_remaining, total);
213                 }
214         } else {
215                 string const write_digest = write (from, cr, total_remaining, total);
216                 LOG_DIST ("Wrote %1 %2 with %3", from.string(), cr.generic_string(), write_digest);
217                 string const read_digest = read (from, cr, total_remaining, total);
218                 LOG_DIST ("Read %1 %2 with %3", from.string(), cr.generic_string(), write_digest);
219                 if (write_digest != read_digest) {
220                         throw VerifyError ("Hash of written data is incorrect", 0);
221                 }
222         }
223 }
224
225 static
226 void
227 write ()
228 try
229 {
230 //      ext4_dmask_set (DEBUG_ALL);
231
232         nanomsg->send("U\n");
233
234         /* We rely on static initialization for these */
235         static struct ext4_fs fs;
236         static struct ext4_mkfs_info info;
237         info.block_size = 1024;
238         info.inode_size = 128;
239         info.journal = false;
240
241 #ifdef WIN32
242         file_windows_name_set(device.c_str());
243         struct ext4_blockdev* bd = file_windows_dev_get();
244 #else
245         file_dev_name_set (device.c_str());
246         struct ext4_blockdev* bd = file_dev_get ();
247 #endif
248
249         if (!bd) {
250                 throw CopyError ("Failed to open drive", 0);
251         }
252         LOG_DIST_NC ("Opened drive");
253
254         struct ext4_mbr_parts parts;
255         parts.division[0] = 100;
256         parts.division[1] = 0;
257         parts.division[2] = 0;
258         parts.division[3] = 0;
259
260 #ifdef DCPOMATIC_LINUX
261         PrivilegeEscalator e;
262 #endif
263
264         /* XXX: not sure if disk_id matters */
265         int r = ext4_mbr_write (bd, &parts, 0);
266
267         if (r) {
268                 throw CopyError ("Failed to write MBR", r);
269         }
270         LOG_DIST_NC ("Wrote MBR");
271
272 #ifdef DCPOMATIC_WINDOWS
273         struct ext4_mbr_bdevs bdevs;
274         r = ext4_mbr_scan (bd, &bdevs);
275         if (r != EOK) {
276                 throw CopyError ("Failed to read MBR", r);
277         }
278
279         file_windows_partition_set (bdevs.partitions[0].part_offset, bdevs.partitions[0].part_size);
280 #endif
281
282 #ifdef DCPOMATIC_LINUX
283         /* Re-read the partition table */
284         int fd = open(device.c_str(), O_RDONLY);
285         ioctl(fd, BLKRRPART, NULL);
286         close(fd);
287 #endif
288
289 #ifdef DCPOMATIC_POSIX
290         string partition = device;
291         /* XXX: don't know if this logic is sensible */
292         if (partition.size() > 0 && isdigit(partition[partition.length() - 1])) {
293                 partition += "p1";
294         } else {
295                 partition += "1";
296         }
297         file_dev_name_set (partition.c_str());
298         bd = file_dev_get ();
299 #endif
300
301         if (!bd) {
302                 throw CopyError ("Failed to open partition", 0);
303         }
304         LOG_DIST_NC ("Opened partition");
305
306         r = ext4_mkfs(&fs, bd, &info, F_SET_EXT4);
307         if (r != EOK) {
308                 throw CopyError ("Failed to make filesystem", r);
309         }
310         LOG_DIST_NC ("Made filesystem");
311
312         r = ext4_device_register(bd, "ext4_fs");
313         if (r != EOK) {
314                 throw CopyError ("Failed to register device", r);
315         }
316         LOG_DIST_NC ("Registered device");
317
318         r = ext4_mount("ext4_fs", "/mp/", false);
319         if (r != EOK) {
320                 throw CopyError ("Failed to mount device", r);
321         }
322         LOG_DIST_NC ("Mounted device");
323
324         uint64_t total_bytes = 0;
325         count (dcp_path, total_bytes);
326
327         /* XXX: this is a hack.  We are going to "treat" every byte twice; write it, and then verify it.  Double the
328          * bytes totals so that progress works itself out (assuming write is the same speed as read).
329          */
330         total_bytes *= 2;
331         copy (dcp_path, "/mp", total_bytes, total_bytes);
332
333         r = ext4_umount("/mp/");
334         if (r != EOK) {
335                 throw CopyError ("Failed to unmount device", r);
336         }
337
338         nanomsg->send(DIST_WRITER_OK "\n");
339 } catch (CopyError& e) {
340         nanomsg->send(String::compose(DIST_WRITER_ERROR "\n%1\n%2\n", e.message(), e.number()));
341 } catch (VerifyError& e) {
342         nanomsg->send(String::compose(DIST_WRITER_ERROR "\n%1\n%2\n", e.message(), e.number()));
343 }
344
345 #ifdef DCPOMATIC_LINUX
346 static
347 void
348 polkit_callback (GObject *, GAsyncResult* res, gpointer)
349 {
350         PolkitAuthorizationResult* result = polkit_authority_check_authorization_finish (polkit_authority, res, 0);
351         if (result && polkit_authorization_result_get_is_authorized(result)) {
352                 write ();
353         }
354         if (result) {
355                 g_object_unref (result);
356         }
357 }
358 #endif
359
360 bool
361 idle ()
362 {
363         optional<string> s = nanomsg->nonblocking_get ();
364         if (!s) {
365                 return true;
366         }
367
368         dcp_path = *s;
369         device = nanomsg->blocking_get();
370
371         LOG_DIST ("Here we go writing %1 to %2", dcp_path, device);
372
373 #ifdef DCPOMATIC_LINUX
374         polkit_authority = polkit_authority_get_sync (0, 0);
375         PolkitSubject* subject = polkit_unix_process_new (getppid());
376         polkit_authority_check_authorization (
377                         polkit_authority, subject, "com.dcpomatic.write-drive", 0, POLKIT_CHECK_AUTHORIZATION_FLAGS_ALLOW_USER_INTERACTION, 0, polkit_callback, 0
378                         );
379 #else
380         write ();
381 #endif
382         return true;
383 }
384
385 int
386 main ()
387 {
388         /* XXX: this is a hack, but I expect we'll need logs and I'm not sure if there's
389          * a better place to put them.
390          */
391         dcpomatic_log.reset(new FileLog(config_path() / "dist_writer.log"));
392         dcpomatic_log->set_types (dcpomatic_log->types() | LogEntry::TYPE_DIST);
393         LOG_DIST_NC("dcpomatic_dist_writer started");
394
395         try {
396                 nanomsg = new Nanomsg (false);
397         } catch (runtime_error& e) {
398                 LOG_DIST_NC("Could not set up nanomsg socket");
399                 exit (EXIT_FAILURE);
400         }
401
402         Glib::RefPtr<Glib::MainLoop> ml = Glib::MainLoop::create ();
403         Glib::signal_timeout().connect(sigc::ptr_fun(&idle), 500);
404         ml->run ();
405 }