c7d090eaa016764411e8e44e935bc1a63d0a9c99
[libdcp.git] / src / util.cc
1 /*
2     Copyright (C) 2012-2014 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 /** @file  src/util.cc
35  *  @brief Utility methods.
36  */
37
38 #include "util.h"
39 #include "exceptions.h"
40 #include "types.h"
41 #include "certificate.h"
42 #include "openjpeg_image.h"
43 #include "dcp_assert.h"
44 #include "compose.hpp"
45 #include <openjpeg.h>
46 #include <asdcp/KM_util.h>
47 #include <asdcp/KM_fileio.h>
48 #include <asdcp/AS_DCP.h>
49 #include <xmlsec/xmldsig.h>
50 #include <xmlsec/dl.h>
51 #include <xmlsec/app.h>
52 #include <xmlsec/crypto.h>
53 #include <libxml++/nodes/element.h>
54 #include <libxml++/document.h>
55 #include <openssl/sha.h>
56 #include <boost/filesystem.hpp>
57 #include <boost/algorithm/string.hpp>
58 #include <boost/foreach.hpp>
59 #include <stdexcept>
60 #include <iostream>
61 #include <iomanip>
62
63 using std::string;
64 using std::wstring;
65 using std::cout;
66 using std::min;
67 using std::max;
68 using std::list;
69 using std::setw;
70 using std::setfill;
71 using std::ostream;
72 using boost::shared_ptr;
73 using boost::shared_array;
74 using boost::optional;
75 using boost::function;
76 using boost::algorithm::trim;
77 using namespace dcp;
78
79 /** Create a UUID.
80  *  @return UUID.
81  */
82 string
83 dcp::make_uuid ()
84 {
85         char buffer[64];
86         Kumu::UUID id;
87         Kumu::GenRandomValue (id);
88         id.EncodeHex (buffer, 64);
89         return string (buffer);
90 }
91
92 string
93 dcp::make_digest (Data data)
94 {
95         SHA_CTX sha;
96         SHA1_Init (&sha);
97         SHA1_Update (&sha, data.data().get(), data.size());
98         byte_t byte_buffer[SHA_DIGEST_LENGTH];
99         SHA1_Final (byte_buffer, &sha);
100         char digest[64];
101         return Kumu::base64encode (byte_buffer, SHA_DIGEST_LENGTH, digest, 64);
102 }
103
104 /** Create a digest for a file.
105  *  @param filename File name.
106  *  @param progress Optional progress reporting function.  The function will be called
107  *  with a progress value between 0 and 1.
108  *  @return Digest.
109  */
110 string
111 dcp::make_digest (boost::filesystem::path filename, function<void (float)> progress)
112 {
113         Kumu::FileReader reader;
114         Kumu::Result_t r = reader.OpenRead (filename.string().c_str ());
115         if (ASDCP_FAILURE (r)) {
116                 boost::throw_exception (FileError ("could not open file to compute digest", filename, r));
117         }
118
119         SHA_CTX sha;
120         SHA1_Init (&sha);
121
122         int const buffer_size = 65536;
123         Kumu::ByteString read_buffer (buffer_size);
124
125         Kumu::fsize_t done = 0;
126         Kumu::fsize_t const size = reader.Size ();
127         while (1) {
128                 ui32_t read = 0;
129                 Kumu::Result_t r = reader.Read (read_buffer.Data(), read_buffer.Capacity(), &read);
130
131                 if (r == Kumu::RESULT_ENDOFFILE) {
132                         break;
133                 } else if (ASDCP_FAILURE (r)) {
134                         boost::throw_exception (FileError ("could not read file to compute digest", filename, r));
135                 }
136
137                 SHA1_Update (&sha, read_buffer.Data(), read);
138
139                 if (progress) {
140                         progress (float (done) / size);
141                         done += read;
142                 }
143         }
144
145         byte_t byte_buffer[SHA_DIGEST_LENGTH];
146         SHA1_Final (byte_buffer, &sha);
147
148         char digest[64];
149         return Kumu::base64encode (byte_buffer, SHA_DIGEST_LENGTH, digest, 64);
150 }
151
152 /** @param s A string.
153  *  @return true if the string contains only space, newline or tab characters, or is empty.
154  */
155 bool
156 dcp::empty_or_white_space (string s)
157 {
158         for (size_t i = 0; i < s.length(); ++i) {
159                 if (s[i] != ' ' && s[i] != '\n' && s[i] != '\t') {
160                         return false;
161                 }
162         }
163
164         return true;
165 }
166
167 /** Set up various bits that the library needs.  Should be called one
168  *  by client applications.
169  */
170 void
171 dcp::init ()
172 {
173         if (xmlSecInit() < 0) {
174                 throw MiscError ("could not initialise xmlsec");
175         }
176
177 #ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
178         if (xmlSecCryptoDLLoadLibrary(BAD_CAST "openssl") < 0) {
179                 throw MiscError ("unable to load openssl xmlsec-crypto library");
180         }
181 #endif
182
183         if (xmlSecCryptoAppInit(0) < 0) {
184                 throw MiscError ("could not initialise crypto");
185         }
186
187         if (xmlSecCryptoInit() < 0) {
188                 throw MiscError ("could not initialise xmlsec-crypto");
189         }
190
191         OpenSSL_add_all_algorithms();
192 }
193
194 /** Decode a base64 string.  The base64 decode routine in KM_util.cpp
195  *  gives different values to both this and the command-line base64
196  *  for some inputs.  Not sure why.
197  *
198  *  @param in base64-encoded string.
199  *  @param out Output buffer.
200  *  @param out_length Length of output buffer.
201  *  @return Number of characters written to the output buffer.
202  */
203 int
204 dcp::base64_decode (string const & in, unsigned char* out, int out_length)
205 {
206         BIO* b64 = BIO_new (BIO_f_base64 ());
207
208         /* This means the input should have no newlines */
209         BIO_set_flags (b64, BIO_FLAGS_BASE64_NO_NL);
210
211         /* Copy our input string, removing newlines */
212         char in_buffer[in.size() + 1];
213         char* p = in_buffer;
214         for (size_t i = 0; i < in.size(); ++i) {
215                 if (in[i] != '\n' && in[i] != '\r') {
216                         *p++ = in[i];
217                 }
218         }
219
220         BIO* bmem = BIO_new_mem_buf (in_buffer, p - in_buffer);
221         bmem = BIO_push (b64, bmem);
222         int const N = BIO_read (bmem, out, out_length);
223         BIO_free_all (bmem);
224
225         return N;
226 }
227
228 /** @param p Path to open.
229  *  @param t mode flags, as for fopen(3).
230  *  @return FILE pointer or 0 on error.
231  *
232  *  Apparently there is no way to create an ofstream using a UTF-8
233  *  filename under Windows.  We are hence reduced to using fopen
234  *  with this wrapper.
235  */
236 FILE *
237 dcp::fopen_boost (boost::filesystem::path p, string t)
238 {
239 #ifdef LIBDCP_WINDOWS
240         wstring w (t.begin(), t.end());
241         /* c_str() here should give a UTF-16 string */
242         return _wfopen (p.c_str(), w.c_str ());
243 #else
244         return fopen (p.c_str(), t.c_str ());
245 #endif
246 }
247
248 optional<boost::filesystem::path>
249 dcp::relative_to_root (boost::filesystem::path root, boost::filesystem::path file)
250 {
251         boost::filesystem::path::const_iterator i = root.begin ();
252         boost::filesystem::path::const_iterator j = file.begin ();
253
254         while (i != root.end() && j != file.end() && *i == *j) {
255                 ++i;
256                 ++j;
257         }
258
259         if (i != root.end ()) {
260                 return optional<boost::filesystem::path> ();
261         }
262
263         boost::filesystem::path rel;
264         while (j != file.end ()) {
265                 rel /= *j++;
266         }
267
268         return rel;
269 }
270
271 bool
272 dcp::ids_equal (string a, string b)
273 {
274         transform (a.begin(), a.end(), a.begin(), ::tolower);
275         transform (b.begin(), b.end(), b.begin(), ::tolower);
276         trim (a);
277         trim (b);
278         return a == b;
279 }
280
281 string
282 dcp::file_to_string (boost::filesystem::path p, uintmax_t max_length)
283 {
284         uintmax_t len = boost::filesystem::file_size (p);
285         if (len > max_length) {
286                 throw MiscError (String::compose ("Unexpectedly long file (%1)", p.string()));
287         }
288
289         FILE* f = fopen_boost (p, "r");
290         if (!f) {
291                 throw FileError ("could not open file", p, errno);
292         }
293
294         char* c = new char[len];
295         /* This may read less than `len' if we are on Windows and we have CRLF in the file */
296         int const N = fread (c, 1, len, f);
297         fclose (f);
298
299         string s (c, N);
300         delete[] c;
301
302         return s;
303 }
304
305 /** @param key RSA private key in PEM format (optionally with -----BEGIN... / -----END...)
306  *  @return SHA1 fingerprint of key
307  */
308 string
309 dcp::private_key_fingerprint (string key)
310 {
311         boost::replace_all (key, "-----BEGIN RSA PRIVATE KEY-----\n", "");
312         boost::replace_all (key, "\n-----END RSA PRIVATE KEY-----\n", "");
313
314         unsigned char buffer[4096];
315         int const N = base64_decode (key, buffer, sizeof (buffer));
316
317         SHA_CTX sha;
318         SHA1_Init (&sha);
319         SHA1_Update (&sha, buffer, N);
320         uint8_t digest[20];
321         SHA1_Final (digest, &sha);
322
323         char digest_base64[64];
324         return Kumu::base64encode (digest, 20, digest_base64, 64);
325 }
326
327 xmlpp::Node *
328 dcp::find_child (xmlpp::Node const * node, string name)
329 {
330         xmlpp::Node::NodeList c = node->get_children ();
331         xmlpp::Node::NodeList::iterator i = c.begin();
332         while (i != c.end() && (*i)->get_name() != name) {
333                 ++i;
334         }
335
336         DCP_ASSERT (i != c.end ());
337         return *i;
338 }
339
340 string
341 dcp::remove_urn_uuid (string raw)
342 {
343         DCP_ASSERT (raw.substr(0, 9) == "urn:uuid:");
344         return raw.substr (9);
345 }
346
347 string
348 dcp::openjpeg_version ()
349 {
350         return opj_version ();
351 }
352
353 string
354 dcp::spaces (int n)
355 {
356         string s = "";
357         for (int i = 0; i < n; ++i) {
358                 s += " ";
359         }
360         return s;
361 }
362
363 void
364 dcp::indent (xmlpp::Element* element, int initial)
365 {
366         xmlpp::Node* last = 0;
367         BOOST_FOREACH (xmlpp::Node * n, element->get_children()) {
368                 xmlpp::Element* e = dynamic_cast<xmlpp::Element*>(n);
369                 if (e) {
370                         element->add_child_text_before (e, "\n" + spaces(initial + 2));
371                         indent (e, initial + 2);
372                         last = n;
373                 }
374         }
375         if (last) {
376                 element->add_child_text (last, "\n" + spaces(initial));
377         }
378 }
379
380 /** @return true if the day represented by \ref a is less than or
381  *  equal to the one represented by \ref b, ignoring the time parts.
382  */
383 bool
384 dcp::day_less_than_or_equal (LocalTime a, LocalTime b)
385 {
386         if (a.year() != b.year()) {
387                 return a.year() < b.year();
388         }
389
390         if (a.month() != b.month()) {
391                 return a.month() < b.month();
392         }
393
394         return a.day() <= b.day();
395 }
396
397 /** @return true if the day represented by \ref a is greater than or
398  *  equal to the one represented by \ref b, ignoring the time parts.
399  */
400 bool
401 dcp::day_greater_than_or_equal (LocalTime a, LocalTime b)
402 {
403         if (a.year() != b.year()) {
404                 return a.year() > b.year();
405         }
406
407         if (a.month() != b.month()) {
408                 return a.month() > b.month();
409         }
410
411         return a.day() >= b.day();
412 }
413
414 /** Try quite hard to find a string which starts with \ref base and is
415  *  not in \ref existing.
416  */
417 string
418 dcp::unique_string (list<string> existing, string base)
419 {
420         int const max_tries = existing.size() + 1;
421         for (int i = 0; i < max_tries; ++i) {
422                 string trial = String::compose("%1%2", base, i);
423                 if (find(existing.begin(), existing.end(), trial) == existing.end()) {
424                         return trial;
425                 }
426         }
427
428         DCP_ASSERT (false);
429 }
430
431
432 ASDCPErrorSuspender::ASDCPErrorSuspender ()
433         : _old (Kumu::DefaultLogSink())
434 {
435         _sink = new Kumu::EntryListLogSink(_log);
436         Kumu::SetDefaultLogSink (_sink);
437 }
438
439
440 ASDCPErrorSuspender::~ASDCPErrorSuspender ()
441 {
442         Kumu::SetDefaultLogSink (&_old);
443         delete _sink;
444 }
445
446