C++11 tidying.
[dcpomatic.git] / src / tools / dcpomatic_disk_writer.cc
1 /*
2     Copyright (C) 2019-2021 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 "lib/compose.hpp"
23 #include "lib/cross.h"
24 #include "lib/dcpomatic_log.h"
25 #include "lib/digester.h"
26 #include "lib/disk_writer_messages.h"
27 #include "lib/exceptions.h"
28 #include "lib/ext.h"
29 #include "lib/file_log.h"
30 #include "lib/nanomsg.h"
31 #include "lib/version.h"
32 #include "lib/warnings.h"
33
34 #ifdef DCPOMATIC_POSIX
35 #include <sys/ioctl.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #endif
39
40 #ifdef DCPOMATIC_OSX
41 #include "lib/stdout_log.h"
42 #undef nil
43 extern "C" {
44 #include <lwext4/file_dev.h>
45 }
46 #include <xpc/xpc.h>
47 #endif
48
49 #ifdef DCPOMATIC_LINUX
50 #include <polkit/polkit.h>
51 #include <poll.h>
52 #endif
53
54 #ifdef DCPOMATIC_WINDOWS
55 extern "C" {
56 #include <lwext4/file_windows.h>
57 }
58 #endif
59
60 DCPOMATIC_DISABLE_WARNINGS
61 #include <glibmm.h>
62 DCPOMATIC_ENABLE_WARNINGS
63
64 #include <unistd.h>
65 #include <sys/types.h>
66 #include <boost/filesystem.hpp>
67 #include <boost/algorithm/string.hpp>
68 #include <iostream>
69
70
71 using std::cin;
72 using std::min;
73 using std::string;
74 using std::runtime_error;
75 using std::exception;
76 using std::vector;
77 using boost::optional;
78
79
80 #define SHORT_TIMEOUT 100
81 #define LONG_TIMEOUT 2000
82
83
84 #ifdef DCPOMATIC_LINUX
85 static PolkitAuthority* polkit_authority = nullptr;
86 #endif
87 static Nanomsg* nanomsg = nullptr;
88
89
90 struct Parameters
91 {
92         boost::filesystem::path dcp_path;
93         std::string device;
94         std::string posix_partition;
95 };
96
97
98 #ifdef DCPOMATIC_LINUX
99 static
100 void
101 polkit_callback (GObject *, GAsyncResult* res, gpointer data)
102 {
103         auto parameters = reinterpret_cast<Parameters*> (data);
104         GError* error = nullptr;
105         auto result = polkit_authority_check_authorization_finish (polkit_authority, res, &error);
106         bool failed = false;
107
108         if (error) {
109                 LOG_DISK("polkit authority check failed (check_authorization_finish failed with %1)", error->message);
110                 failed = true;
111         } else {
112                 if (polkit_authorization_result_get_is_authorized(result)) {
113                         dcpomatic::write (parameters->dcp_path, parameters->device, parameters->posix_partition, nanomsg);
114                 } else {
115                         failed = true;
116                         if (polkit_authorization_result_get_is_challenge(result)) {
117                                 LOG_DISK_NC("polkit authority check failed (challenge)");
118                         } else {
119                                 LOG_DISK_NC("polkit authority check failed (not authorized)");
120                         }
121                 }
122         }
123
124         if (failed && nanomsg) {
125                 nanomsg->send(DISK_WRITER_ERROR "\nCould not obtain authorization to write to the drive\n", LONG_TIMEOUT);
126         }
127
128         delete parameters;
129
130         if (result) {
131                 g_object_unref (result);
132         }
133 }
134 #endif
135
136
137 bool
138 idle ()
139 try
140 {
141         using namespace boost::algorithm;
142
143         auto s = nanomsg->receive (0);
144         if (!s) {
145                 return true;
146         }
147
148         LOG_DISK("Writer receives command: %1", *s);
149
150         if (*s == DISK_WRITER_QUIT) {
151                 exit (EXIT_SUCCESS);
152         } else if (*s == DISK_WRITER_PING) {
153                 nanomsg->send(DISK_WRITER_PONG "\n", LONG_TIMEOUT);
154         } else if (*s == DISK_WRITER_UNMOUNT) {
155                 /* XXX: should do Linux polkit stuff here */
156                 auto xml_head = nanomsg->receive (LONG_TIMEOUT);
157                 auto xml_body = nanomsg->receive (LONG_TIMEOUT);
158                 if (!xml_head || !xml_body) {
159                         LOG_DISK_NC("Failed to receive unmount request");
160                         throw CommunicationFailedError ();
161                 }
162                 bool const success = Drive(*xml_head + *xml_body).unmount();
163                 if (!nanomsg->send (success ? (DISK_WRITER_OK "\n") : (DISK_WRITER_ERROR "\n"), LONG_TIMEOUT)) {
164                         LOG_DISK_NC("CommunicationFailedError in unmount_finished");
165                         throw CommunicationFailedError ();
166                 }
167         } else if (*s == DISK_WRITER_WRITE) {
168                 auto dcp_path = nanomsg->receive (LONG_TIMEOUT);
169                 auto device = nanomsg->receive (LONG_TIMEOUT);
170                 if (!dcp_path || !device) {
171                         LOG_DISK_NC("Failed to receive write request");
172                         throw CommunicationFailedError();
173                 }
174
175                 /* Do some basic sanity checks; this is a bit belt-and-braces but it can't hurt... */
176
177 #ifdef DCPOMATIC_OSX
178                 if (!starts_with(*device, "/dev/disk")) {
179                         LOG_DISK ("Will not write to %1", *device);
180                         nanomsg->send(DISK_WRITER_ERROR "\nRefusing to write to this drive\n1\n", LONG_TIMEOUT);
181                         return true;
182                 }
183 #endif
184 #ifdef DCPOMATIC_LINUX
185                 if (!starts_with(*device, "/dev/sd") && !starts_with(*device, "/dev/hd")) {
186                         LOG_DISK ("Will not write to %1", *device);
187                         nanomsg->send(DISK_WRITER_ERROR "\nRefusing to write to this drive\n1\n", LONG_TIMEOUT);
188                         return true;
189                 }
190 #endif
191 #ifdef DCPOMATIC_WINDOWS
192                 if (!starts_with(*device, "\\\\.\\PHYSICALDRIVE")) {
193                         LOG_DISK ("Will not write to %1", *device);
194                         nanomsg->send(DISK_WRITER_ERROR "\nRefusing to write to this drive\n1\n", LONG_TIMEOUT);
195                         return true;
196                 }
197 #endif
198
199                 bool on_drive_list = false;
200                 bool mounted = false;
201                 for (auto const& i: Drive::get()) {
202                         if (i.device() == *device) {
203                                 on_drive_list = true;
204                                 mounted = i.mounted();
205                         }
206                 }
207
208                 if (!on_drive_list) {
209                         LOG_DISK ("Will not write to %1 as it's not recognised as a drive", *device);
210                         nanomsg->send(DISK_WRITER_ERROR "\nRefusing to write to this drive\n1\n", LONG_TIMEOUT);
211                         return true;
212                 }
213                 if (mounted) {
214                         LOG_DISK ("Will not write to %1 as it's mounted", *device);
215                         nanomsg->send(DISK_WRITER_ERROR "\nRefusing to write to this drive\n1\n", LONG_TIMEOUT);
216                         return true;
217                 }
218
219                 LOG_DISK ("Here we go writing %1 to %2", *dcp_path, *device);
220
221 #if defined(DCPOMATIC_LINUX)
222                 polkit_authority = polkit_authority_get_sync (0, 0);
223                 auto subject = polkit_unix_process_new_for_owner (getppid(), 0, -1);
224                 auto parameters = new Parameters;
225                 parameters->dcp_path = *dcp_path;
226                 parameters->device = *device;
227                 parameters->posix_partition = *device;
228                 /* XXX: don't know if this logic is sensible */
229                 if (parameters->posix_partition.size() > 0 && isdigit(parameters->posix_partition[parameters->posix_partition.length() - 1])) {
230                         parameters->posix_partition += "p1";
231                 } else {
232                         parameters->posix_partition += "1";
233                 }
234                 polkit_authority_check_authorization (
235                         polkit_authority, subject, "com.dcpomatic.write-drive", 0, POLKIT_CHECK_AUTHORIZATION_FLAGS_ALLOW_USER_INTERACTION, 0, polkit_callback, parameters
236                         );
237 #elif defined(DCPOMATIC_OSX)
238                 auto fast_device = boost::algorithm::replace_first_copy (*device, "/dev/disk", "/dev/rdisk");
239                 dcpomatic::write (*dcp_path, fast_device, fast_device + "s1", nanomsg);
240 #elif defined(DCPOMATIC_WINDOWS)
241                 dcpomatic::write (*dcp_path, *device, "", nanomsg);
242 #endif
243         }
244
245         return true;
246 } catch (exception& e) {
247         LOG_DISK("Exception (from idle): %1", e.what());
248         return true;
249 }
250
251 int
252 main ()
253 {
254 #ifdef DCPOMATIC_OSX
255         /* On macOS this is running as root, so config_path() will be somewhere in root's
256          * home.  Instead, just write to stdout as the macOS process control stuff will
257          * redirect this to a file in /var/log
258          */
259         dcpomatic_log.reset(new StdoutLog(LogEntry::TYPE_DISK));
260         LOG_DISK("dcpomatic_disk_writer %1 started", dcpomatic_git_commit);
261 #else
262         /* XXX: this is a hack, but I expect we'll need logs and I'm not sure if there's
263          * a better place to put them.
264          */
265         dcpomatic_log.reset(new FileLog(config_path() / "disk_writer.log", LogEntry::TYPE_DISK));
266         LOG_DISK_NC("dcpomatic_disk_writer started");
267 #endif
268
269 #ifdef DCPOMATIC_OSX
270         /* I *think* this consumes the notifyd event that we used to start the process, so we only
271          * get started once per notification.
272          */
273         xpc_set_event_stream_handler("com.apple.notifyd.matching", DISPATCH_TARGET_QUEUE_DEFAULT, ^(xpc_object_t) {});
274 #endif
275
276         try {
277                 nanomsg = new Nanomsg (false);
278         } catch (runtime_error& e) {
279                 LOG_DISK_NC("Could not set up nanomsg socket");
280                 exit (EXIT_FAILURE);
281         }
282
283         auto ml = Glib::MainLoop::create ();
284         Glib::signal_timeout().connect(sigc::ptr_fun(&idle), 500);
285         ml->run ();
286 }