Make dcp::init() take a general resources directory rather than specifically tags.
[libdcp.git] / src / util.cc
1 /*
2     Copyright (C) 2012-2021 Carl Hetherington <cth@carlh.net>
3
4     This file is part of libdcp.
5
6     libdcp 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     libdcp 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 libdcp.  If not, see <http://www.gnu.org/licenses/>.
18
19     In addition, as a special exception, the copyright holders give
20     permission to link the code of portions of this program with the
21     OpenSSL library under certain conditions as described in each
22     individual source file, and distribute linked combinations
23     including the two.
24
25     You must obey the GNU General Public License in all respects
26     for all of the code used other than OpenSSL.  If you modify
27     file(s) with this exception, you may extend this exception to your
28     version of the file(s), but you are not obligated to do so.  If you
29     do not wish to do so, delete this exception statement from your
30     version.  If you delete this exception statement from all source
31     files in the program, then also delete it here.
32 */
33
34
35 /** @file  src/util.cc
36  *  @brief Utility methods and classes
37  */
38
39
40 #include "util.h"
41 #include "language_tag.h"
42 #include "exceptions.h"
43 #include "types.h"
44 #include "certificate.h"
45 #include "openjpeg_image.h"
46 #include "dcp_assert.h"
47 #include "compose.hpp"
48 #include <openjpeg.h>
49 #include <asdcp/KM_util.h>
50 #include <asdcp/KM_fileio.h>
51 #include <asdcp/AS_DCP.h>
52 #include <xmlsec/xmldsig.h>
53 #include <xmlsec/dl.h>
54 #include <xmlsec/app.h>
55 #include <xmlsec/crypto.h>
56 #include <libxml++/nodes/element.h>
57 #include <libxml++/document.h>
58 #include <openssl/sha.h>
59 #include <boost/algorithm/string.hpp>
60 #if BOOST_VERSION >= 106100
61 #include <boost/dll/runtime_symbol_info.hpp>
62 #endif
63 #include <boost/filesystem.hpp>
64 #include <stdexcept>
65 #include <iostream>
66 #include <iomanip>
67
68
69 using std::string;
70 using std::wstring;
71 using std::cout;
72 using std::min;
73 using std::max;
74 using std::setw;
75 using std::setfill;
76 using std::ostream;
77 using std::shared_ptr;
78 using std::vector;
79 using boost::shared_array;
80 using boost::optional;
81 using boost::function;
82 using boost::algorithm::trim;
83 using namespace dcp;
84
85
86 /* Some ASDCP objects store this as a *&, for reasons which are not
87  * at all clear, so we have to keep this around forever.
88  */
89 ASDCP::Dictionary const* dcp::asdcp_smpte_dict = nullptr;
90
91
92 string
93 dcp::make_uuid ()
94 {
95         char buffer[64];
96         Kumu::UUID id;
97         Kumu::GenRandomValue (id);
98         id.EncodeHex (buffer, 64);
99         return string (buffer);
100 }
101
102
103 string
104 dcp::make_digest (ArrayData data)
105 {
106         SHA_CTX sha;
107         SHA1_Init (&sha);
108         SHA1_Update (&sha, data.data(), data.size());
109         byte_t byte_buffer[SHA_DIGEST_LENGTH];
110         SHA1_Final (byte_buffer, &sha);
111         char digest[64];
112         return Kumu::base64encode (byte_buffer, SHA_DIGEST_LENGTH, digest, 64);
113 }
114
115
116 string
117 dcp::make_digest (boost::filesystem::path filename, function<void (float)> progress)
118 {
119         Kumu::FileReader reader;
120         auto r = reader.OpenRead (filename.string().c_str ());
121         if (ASDCP_FAILURE(r)) {
122                 boost::throw_exception (FileError("could not open file to compute digest", filename, r));
123         }
124
125         SHA_CTX sha;
126         SHA1_Init (&sha);
127
128         int const buffer_size = 65536;
129         Kumu::ByteString read_buffer (buffer_size);
130
131         Kumu::fsize_t done = 0;
132         Kumu::fsize_t const size = reader.Size ();
133         while (true) {
134                 ui32_t read = 0;
135                 auto r = reader.Read (read_buffer.Data(), read_buffer.Capacity(), &read);
136
137                 if (r == Kumu::RESULT_ENDOFFILE) {
138                         break;
139                 } else if (ASDCP_FAILURE (r)) {
140                         boost::throw_exception (FileError("could not read file to compute digest", filename, r));
141                 }
142
143                 SHA1_Update (&sha, read_buffer.Data(), read);
144
145                 if (progress) {
146                         progress (float (done) / size);
147                         done += read;
148                 }
149         }
150
151         byte_t byte_buffer[SHA_DIGEST_LENGTH];
152         SHA1_Final (byte_buffer, &sha);
153
154         char digest[64];
155         return Kumu::base64encode (byte_buffer, SHA_DIGEST_LENGTH, digest, 64);
156 }
157
158
159 bool
160 dcp::empty_or_white_space (string s)
161 {
162         for (size_t i = 0; i < s.length(); ++i) {
163                 if (s[i] != ' ' && s[i] != '\n' && s[i] != '\t') {
164                         return false;
165                 }
166         }
167
168         return true;
169 }
170
171
172 void
173 dcp::init (optional<boost::filesystem::path> given_resources_directory)
174 {
175         if (xmlSecInit() < 0) {
176                 throw MiscError ("could not initialise xmlsec");
177         }
178
179 #ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
180         if (xmlSecCryptoDLLoadLibrary(BAD_CAST "openssl") < 0) {
181                 throw MiscError ("unable to load openssl xmlsec-crypto library");
182         }
183 #endif
184
185         if (xmlSecCryptoAppInit(0) < 0) {
186                 throw MiscError ("could not initialise crypto");
187         }
188
189         if (xmlSecCryptoInit() < 0) {
190                 throw MiscError ("could not initialise xmlsec-crypto");
191         }
192
193         OpenSSL_add_all_algorithms();
194
195         asdcp_smpte_dict = &ASDCP::DefaultSMPTEDict();
196
197         load_language_tag_lists (given_resources_directory.get_value_or(resources_directory()) / "tags");
198 }
199
200
201 int
202 dcp::base64_decode (string const & in, unsigned char* out, int out_length)
203 {
204         auto b64 = BIO_new (BIO_f_base64());
205
206         /* This means the input should have no newlines */
207         BIO_set_flags (b64, BIO_FLAGS_BASE64_NO_NL);
208
209         /* Copy our input string, removing newlines */
210         char in_buffer[in.size() + 1];
211         char* p = in_buffer;
212         for (size_t i = 0; i < in.size(); ++i) {
213                 if (in[i] != '\n' && in[i] != '\r') {
214                         *p++ = in[i];
215                 }
216         }
217
218         auto bmem = BIO_new_mem_buf (in_buffer, p - in_buffer);
219         bmem = BIO_push (b64, bmem);
220         int const N = BIO_read (bmem, out, out_length);
221         BIO_free_all (bmem);
222
223         return N;
224 }
225
226
227 FILE *
228 dcp::fopen_boost (boost::filesystem::path p, string t)
229 {
230 #ifdef LIBDCP_WINDOWS
231         wstring w (t.begin(), t.end());
232         /* c_str() here should give a UTF-16 string */
233         return _wfopen (p.c_str(), w.c_str ());
234 #else
235         return fopen (p.c_str(), t.c_str ());
236 #endif
237 }
238
239
240 optional<boost::filesystem::path>
241 dcp::relative_to_root (boost::filesystem::path root, boost::filesystem::path file)
242 {
243         auto i = root.begin ();
244         auto j = file.begin ();
245
246         while (i != root.end() && j != file.end() && *i == *j) {
247                 ++i;
248                 ++j;
249         }
250
251         if (i != root.end()) {
252                 return {};
253         }
254
255         boost::filesystem::path rel;
256         while (j != file.end()) {
257                 rel /= *j++;
258         }
259
260         return rel;
261 }
262
263
264 bool
265 dcp::ids_equal (string a, string b)
266 {
267         transform (a.begin(), a.end(), a.begin(), ::tolower);
268         transform (b.begin(), b.end(), b.begin(), ::tolower);
269         trim (a);
270         trim (b);
271         return a == b;
272 }
273
274
275 string
276 dcp::file_to_string (boost::filesystem::path p, uintmax_t max_length)
277 {
278         auto len = boost::filesystem::file_size (p);
279         if (len > max_length) {
280                 throw MiscError (String::compose("Unexpectedly long file (%1)", p.string()));
281         }
282
283         auto f = fopen_boost (p, "r");
284         if (!f) {
285                 throw FileError ("could not open file", p, errno);
286         }
287
288         char* c = new char[len];
289         /* This may read less than `len' if we are on Windows and we have CRLF in the file */
290         int const N = fread (c, 1, len, f);
291         fclose (f);
292
293         string s (c, N);
294         delete[] c;
295
296         return s;
297 }
298
299
300 string
301 dcp::private_key_fingerprint (string key)
302 {
303         boost::replace_all (key, "-----BEGIN RSA PRIVATE KEY-----\n", "");
304         boost::replace_all (key, "\n-----END RSA PRIVATE KEY-----\n", "");
305
306         unsigned char buffer[4096];
307         int const N = base64_decode (key, buffer, sizeof (buffer));
308
309         SHA_CTX sha;
310         SHA1_Init (&sha);
311         SHA1_Update (&sha, buffer, N);
312         uint8_t digest[20];
313         SHA1_Final (digest, &sha);
314
315         char digest_base64[64];
316         return Kumu::base64encode (digest, 20, digest_base64, 64);
317 }
318
319
320 xmlpp::Node *
321 dcp::find_child (xmlpp::Node const * node, string name)
322 {
323         auto c = node->get_children ();
324         auto i = c.begin();
325         while (i != c.end() && (*i)->get_name() != name) {
326                 ++i;
327         }
328
329         DCP_ASSERT (i != c.end ());
330         return *i;
331 }
332
333
334 string
335 dcp::remove_urn_uuid (string raw)
336 {
337         DCP_ASSERT (raw.substr(0, 9) == "urn:uuid:");
338         return raw.substr (9);
339 }
340
341
342 string
343 dcp::openjpeg_version ()
344 {
345         return opj_version ();
346 }
347
348
349 string
350 dcp::spaces (int n)
351 {
352         string s = "";
353         for (int i = 0; i < n; ++i) {
354                 s += " ";
355         }
356         return s;
357 }
358
359
360 void
361 dcp::indent (xmlpp::Element* element, int initial)
362 {
363         xmlpp::Node* last = nullptr;
364         for (auto n: element->get_children()) {
365                 auto e = dynamic_cast<xmlpp::Element*>(n);
366                 if (e) {
367                         element->add_child_text_before (e, "\n" + spaces(initial + 2));
368                         indent (e, initial + 2);
369                         last = n;
370                 }
371         }
372         if (last) {
373                 element->add_child_text (last, "\n" + spaces(initial));
374         }
375 }
376
377
378 bool
379 dcp::day_less_than_or_equal (LocalTime a, LocalTime b)
380 {
381         if (a.year() != b.year()) {
382                 return a.year() < b.year();
383         }
384
385         if (a.month() != b.month()) {
386                 return a.month() < b.month();
387         }
388
389         return a.day() <= b.day();
390 }
391
392
393 bool
394 dcp::day_greater_than_or_equal (LocalTime a, LocalTime b)
395 {
396         if (a.year() != b.year()) {
397                 return a.year() > b.year();
398         }
399
400         if (a.month() != b.month()) {
401                 return a.month() > b.month();
402         }
403
404         return a.day() >= b.day();
405 }
406
407
408 string
409 dcp::unique_string (vector<string> existing, string base)
410 {
411         int const max_tries = existing.size() + 1;
412         for (int i = 0; i < max_tries; ++i) {
413                 string trial = String::compose("%1%2", base, i);
414                 if (find(existing.begin(), existing.end(), trial) == existing.end()) {
415                         return trial;
416                 }
417         }
418
419         DCP_ASSERT (false);
420 }
421
422
423 ASDCPErrorSuspender::ASDCPErrorSuspender ()
424         : _old (Kumu::DefaultLogSink())
425 {
426         _sink = new Kumu::EntryListLogSink(_log);
427         Kumu::SetDefaultLogSink (_sink);
428 }
429
430
431 ASDCPErrorSuspender::~ASDCPErrorSuspender ()
432 {
433         Kumu::SetDefaultLogSink (&_old);
434         delete _sink;
435 }
436
437
438 boost::filesystem::path dcp::directory_containing_executable ()
439 {
440 #if BOOST_VERSION >= 106100
441         return boost::filesystem::canonical(boost::dll::program_location().parent_path());
442 #else
443         char buffer[PATH_MAX];
444         ssize_t N = readlink ("/proc/self/exe", buffer, PATH_MAX);
445         return boost::filesystem::path(string(buffer, N)).parent_path();
446 #endif
447 }
448
449
450 boost::filesystem::path dcp::resources_directory ()
451 {
452         /* We need a way to specify the tags directory for running un-installed binaries */
453         char* prefix = getenv("LIBDCP_RESOURCES");
454         if (prefix) {
455                 return prefix;
456         }
457
458 #if defined(LIBDCP_OSX)
459         return directory_containing_executable().parent_path() / "Resources";
460 #elif defined(LIBDCP_WINDOWS)
461         return directory_containing_executable().parent_path();
462 #else
463         return directory_containing_executable().parent_path() / "share" / "libdcp";
464 #endif
465 }
466
467