Better error handling with Linux privilege escalator.
[dcpomatic.git] / src / lib / cross_linux.cc
1 /*
2     Copyright (C) 2012-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 "cross.h"
22 #include "compose.hpp"
23 #include "log.h"
24 #include "dcpomatic_log.h"
25 #include "config.h"
26 #include "exceptions.h"
27 #include "dcpomatic_log.h"
28 #include <dcp/raw_convert.h>
29 #include <glib.h>
30 extern "C" {
31 #include <libavformat/avio.h>
32 }
33 #include <boost/algorithm/string.hpp>
34 #include <boost/foreach.hpp>
35 #include <boost/function.hpp>
36 #if BOOST_VERSION >= 106100
37 #include <boost/dll/runtime_symbol_info.hpp>
38 #endif
39 #include <unistd.h>
40 #include <mntent.h>
41 #include <sys/types.h>
42 #include <sys/mount.h>
43 #include <ifaddrs.h>
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
46 #include <fstream>
47
48 #include "i18n.h"
49
50 using std::pair;
51 using std::list;
52 using std::ifstream;
53 using std::string;
54 using std::wstring;
55 using std::make_pair;
56 using std::vector;
57 using std::cerr;
58 using std::cout;
59 using std::runtime_error;
60 using boost::shared_ptr;
61 using boost::optional;
62 using boost::function;
63
64 /** @param s Number of seconds to sleep for */
65 void
66 dcpomatic_sleep_seconds (int s)
67 {
68         sleep (s);
69 }
70
71 void
72 dcpomatic_sleep_milliseconds (int ms)
73 {
74         usleep (ms * 1000);
75 }
76
77 /** @return A string of CPU information (model name etc.) */
78 string
79 cpu_info ()
80 {
81         string info;
82
83         /* This use of ifstream is ok; the filename can never
84            be non-Latin
85         */
86         ifstream f ("/proc/cpuinfo");
87         while (f.good ()) {
88                 string l;
89                 getline (f, l);
90                 if (boost::algorithm::starts_with (l, "model name")) {
91                         string::size_type const c = l.find (':');
92                         if (c != string::npos) {
93                                 info = l.substr (c + 2);
94                         }
95                 }
96         }
97
98         return info;
99 }
100
101 boost::filesystem::path
102 shared_path ()
103 {
104         char const * p = getenv ("DCPOMATIC_LINUX_SHARE_PREFIX");
105         if (p) {
106                 return p;
107         }
108         return boost::filesystem::canonical (LINUX_SHARE_PREFIX);
109 }
110
111 void
112 run_ffprobe (boost::filesystem::path content, boost::filesystem::path out)
113 {
114         string ffprobe = "ffprobe \"" + content.string() + "\" 2> \"" + out.string() + "\"";
115         LOG_GENERAL (N_("Probing with %1"), ffprobe);
116         int const r = system (ffprobe.c_str());
117         if (r == -1 || (WIFEXITED(r) && WEXITSTATUS(r) != 0)) {
118                 LOG_GENERAL (N_("Could not run ffprobe (system returned %1"), r);
119         }
120 }
121
122 list<pair<string, string> >
123 mount_info ()
124 {
125         list<pair<string, string> > m;
126
127         FILE* f = setmntent ("/etc/mtab", "r");
128         if (!f) {
129                 return m;
130         }
131
132         while (true) {
133                 struct mntent* mnt = getmntent (f);
134                 if (!mnt) {
135                         break;
136                 }
137
138                 m.push_back (make_pair (mnt->mnt_dir, mnt->mnt_type));
139         }
140
141         endmntent (f);
142
143         return m;
144 }
145
146
147 boost::filesystem::path
148 directory_containing_executable ()
149 {
150 #if BOOST_VERSION >= 106100
151         return boost::dll::program_location().parent_path();
152 #else
153         char buffer[PATH_MAX];
154         ssize_t N = readlink ("/proc/self/exe", buffer, PATH_MAX);
155         return boost::filesystem::path(string(buffer, N)).parent_path();
156 #endif
157 }
158
159
160 boost::filesystem::path
161 openssl_path ()
162 {
163         boost::filesystem::path p = directory_containing_executable() / "dcpomatic2_openssl";
164         if (boost::filesystem::is_regular_file(p)) {
165                 return p;
166         }
167
168         return "dcpomatic2_openssl";
169 }
170
171
172 #ifdef DCPOMATIC_DISK
173 boost::filesystem::path
174 disk_writer_path ()
175 {
176         return directory_containing_executable() / "dcpomatic2_disk_writer";
177 }
178 #endif
179
180
181 /* Apparently there is no way to create an ofstream using a UTF-8
182    filename under Windows.  We are hence reduced to using fopen
183    with this wrapper.
184 */
185 FILE *
186 fopen_boost (boost::filesystem::path p, string t)
187 {
188         return fopen (p.c_str(), t.c_str ());
189 }
190
191 int
192 dcpomatic_fseek (FILE* stream, int64_t offset, int whence)
193 {
194         return fseek (stream, offset, whence);
195 }
196
197 void
198 Waker::nudge ()
199 {
200
201 }
202
203 Waker::Waker ()
204 {
205
206 }
207
208 Waker::~Waker ()
209 {
210
211 }
212
213
214 void
215 start_tool (string executable)
216 {
217         boost::filesystem::path batch = directory_containing_executable() / executable;
218
219         pid_t pid = fork ();
220         if (pid == 0) {
221                 int const r = system (batch.string().c_str());
222                 exit (WEXITSTATUS (r));
223         }
224 }
225
226
227 void
228 start_batch_converter ()
229 {
230         start_tool ("dcpomatic2_batch");
231 }
232
233
234 void
235 start_player ()
236 {
237         start_tool ("dcpomatic2_player");
238 }
239
240
241 uint64_t
242 thread_id ()
243 {
244         return (uint64_t) pthread_self ();
245 }
246
247 int
248 avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags)
249 {
250         return avio_open (s, file.c_str(), flags);
251 }
252
253
254 boost::filesystem::path
255 home_directory ()
256 {
257         return getenv("HOME");
258 }
259
260 string
261 command_and_read (string cmd)
262 {
263         FILE* pipe = popen (cmd.c_str(), "r");
264         if (!pipe) {
265                 throw runtime_error ("popen failed");
266         }
267
268         string result;
269         char buffer[128];
270         try {
271                 while (fgets(buffer, sizeof(buffer), pipe)) {
272                         result += buffer;
273                 }
274         } catch (...) {
275                 pclose (pipe);
276                 throw;
277         }
278
279         pclose (pipe);
280         return result;
281 }
282
283 /** @return true if this process is a 32-bit one running on a 64-bit-capable OS */
284 bool
285 running_32_on_64 ()
286 {
287         /* I'm assuming nobody does this on Linux */
288         return false;
289 }
290
291
292 static
293 vector<pair<string, string> >
294 get_mounts (string prefix)
295 {
296         vector<pair<string, string> > mounts;
297
298         std::ifstream f("/proc/mounts");
299         string line;
300         while (f.good()) {
301                 getline(f, line);
302                 vector<string> bits;
303                 boost::algorithm::split (bits, line, boost::is_any_of(" "));
304                 if (bits.size() > 1 && boost::algorithm::starts_with(bits[0], prefix)) {
305                         boost::algorithm::replace_all (bits[1], "\\040", " ");
306                         mounts.push_back(make_pair(bits[0], bits[1]));
307                         LOG_DISK("Found mounted device %1 from prefix %2", bits[0], prefix);
308                 }
309         }
310
311         return mounts;
312 }
313
314
315 vector<Drive>
316 Drive::get ()
317 {
318         vector<Drive> drives;
319
320         using namespace boost::filesystem;
321         vector<pair<string, string> > mounted_devices = get_mounts("/dev/");
322
323         for (directory_iterator i = directory_iterator("/sys/block"); i != directory_iterator(); ++i) {
324                 string const name = i->path().filename().string();
325                 path device_type_file("/sys/block/" + name + "/device/type");
326                 optional<string> device_type;
327                 if (exists(device_type_file)) {
328                         device_type = dcp::file_to_string (device_type_file);
329                         boost::trim(*device_type);
330                 }
331                 /* Device type 5 is "SCSI_TYPE_ROM" in blkdev.h; seems usually to be a CD/DVD drive */
332                 if (!boost::algorithm::starts_with(name, "loop") && (!device_type || *device_type != "5")) {
333                         uint64_t const size = dcp::raw_convert<uint64_t>(dcp::file_to_string(*i / "size")) * 512;
334                         if (size == 0) {
335                                 continue;
336                         }
337                         optional<string> vendor;
338                         try {
339                                 vendor = dcp::file_to_string("/sys/block/" + name + "/device/vendor");
340                                 boost::trim(*vendor);
341                         } catch (...) {}
342                         optional<string> model;
343                         try {
344                                 model = dcp::file_to_string("/sys/block/" + name + "/device/model");
345                                 boost::trim(*model);
346                         } catch (...) {}
347                         vector<boost::filesystem::path> mount_points;
348                         for (vector<pair<string, string> >::const_iterator j = mounted_devices.begin(); j != mounted_devices.end(); ++j) {
349                                 if (boost::algorithm::starts_with(j->first, "/dev/" + name)) {
350                                         mount_points.push_back (j->second);
351                                 }
352                         }
353                         drives.push_back(Drive("/dev/" + name, mount_points, size, vendor, model));
354                         LOG_DISK_NC(drives.back().log_summary());
355                 }
356         }
357
358         return drives;
359 }
360
361
362 bool
363 Drive::unmount ()
364 {
365         BOOST_FOREACH (boost::filesystem::path i, _mount_points) {
366                 int const r = umount(i.string().c_str());
367                 LOG_DISK("Tried to unmount %1 and got %2 and %3", i.string(), r, errno);
368                 if (r == -1) {
369                         return false;
370                 }
371         }
372         return true;
373 }
374
375
376 void
377 unprivileged ()
378 {
379         uid_t ruid, euid, suid;
380         if (getresuid(&ruid, &euid, &suid) == -1) {
381                 cerr << "getresuid() failed.\n";
382         }
383         if (seteuid(ruid) == -1) {
384                 cerr << "seteuid() failed.\n";
385         }
386 }
387
388 PrivilegeEscalator::~PrivilegeEscalator ()
389 {
390         unprivileged ();
391 }
392
393 PrivilegeEscalator::PrivilegeEscalator ()
394 {
395         int const r = seteuid(0);
396         if (r < 0) {
397                 throw PrivilegeError (String::compose("seteuid() call failed with %1", errno));
398         }
399 }
400
401 boost::filesystem::path
402 config_path ()
403 {
404         boost::filesystem::path p;
405         p /= g_get_user_config_dir ();
406         p /= "dcpomatic2";
407         return p;
408 }
409
410
411 void
412 disk_write_finished ()
413 {
414
415 }
416