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