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