86d1bc87d2810e0bfe7f3632e4509b586015447e
[libdcp.git] / src / util.cc
1 /*
2     Copyright (C) 2012-2014 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
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 "certificates.h"
28 #include "xyz_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::optional;
60 using boost::function;
61 using boost::algorithm::trim;
62 using namespace dcp;
63
64 /** Create a UUID.
65  *  @return UUID.
66  */
67 string
68 dcp::make_uuid ()
69 {
70         char buffer[64];
71         Kumu::UUID id;
72         Kumu::GenRandomValue (id);
73         id.EncodeHex (buffer, 64);
74         return string (buffer);
75 }
76
77
78 /** Create a digest for a file.
79  *  @param filename File name.
80  *  @param progress Optional progress reporting function.  The function will be called
81  *  with a progress value between 0 and 1.
82  *  @return Digest.
83  */
84 string
85 dcp::make_digest (boost::filesystem::path filename, function<void (float)> progress)
86 {
87         Kumu::FileReader reader;
88         Kumu::Result_t r = reader.OpenRead (filename.string().c_str ());
89         if (ASDCP_FAILURE (r)) {
90                 boost::throw_exception (FileError ("could not open file to compute digest", filename, r));
91         }
92         
93         SHA_CTX sha;
94         SHA1_Init (&sha);
95
96         int const buffer_size = 65536;
97         Kumu::ByteString read_buffer (buffer_size);
98
99         Kumu::fsize_t done = 0;
100         Kumu::fsize_t const size = reader.Size ();
101         while (1) {
102                 ui32_t read = 0;
103                 Kumu::Result_t r = reader.Read (read_buffer.Data(), read_buffer.Capacity(), &read);
104                 
105                 if (r == Kumu::RESULT_ENDOFFILE) {
106                         break;
107                 } else if (ASDCP_FAILURE (r)) {
108                         boost::throw_exception (FileError ("could not read file to compute digest", filename, r));
109                 }
110                 
111                 SHA1_Update (&sha, read_buffer.Data(), read);
112
113                 if (progress) {
114                         progress (float (done) / size);
115                         done += read;
116                 }
117         }
118
119         byte_t byte_buffer[SHA_DIGEST_LENGTH];
120         SHA1_Final (byte_buffer, &sha);
121
122         char digest[64];
123         return Kumu::base64encode (byte_buffer, SHA_DIGEST_LENGTH, digest, 64);
124 }
125
126 /** Convert a content kind to a string which can be used in a
127  *  &lt;ContentKind&gt; node.
128  *  @param kind ContentKind.
129  *  @return string.
130  */
131 string
132 dcp::content_kind_to_string (ContentKind kind)
133 {
134         switch (kind) {
135         case FEATURE:
136                 return "feature";
137         case SHORT:
138                 return "short";
139         case TRAILER:
140                 return "trailer";
141         case TEST:
142                 return "test";
143         case TRANSITIONAL:
144                 return "transitional";
145         case RATING:
146                 return "rating";
147         case TEASER:
148                 return "teaser";
149         case POLICY:
150                 return "policy";
151         case PUBLIC_SERVICE_ANNOUNCEMENT:
152                 return "psa";
153         case ADVERTISEMENT:
154                 return "advertisement";
155         }
156
157         DCP_ASSERT (false);
158 }
159
160 /** Convert a string from a &lt;ContentKind&gt; node to a libdcp ContentKind.
161  *  Reasonably tolerant about varying case.
162  *  @param kind Content kind string.
163  *  @return libdcp ContentKind.
164  */
165 dcp::ContentKind
166 dcp::content_kind_from_string (string kind)
167 {
168         transform (kind.begin(), kind.end(), kind.begin(), ::tolower);
169         
170         if (kind == "feature") {
171                 return FEATURE;
172         } else if (kind == "short") {
173                 return SHORT;
174         } else if (kind == "trailer") {
175                 return TRAILER;
176         } else if (kind == "test") {
177                 return TEST;
178         } else if (kind == "transitional") {
179                 return TRANSITIONAL;
180         } else if (kind == "rating") {
181                 return RATING;
182         } else if (kind == "teaser") {
183                 return TEASER;
184         } else if (kind == "policy") {
185                 return POLICY;
186         } else if (kind == "psa") {
187                 return PUBLIC_SERVICE_ANNOUNCEMENT;
188         } else if (kind == "advertisement") {
189                 return ADVERTISEMENT;
190         }
191
192         DCP_ASSERT (false);
193 }
194
195 /** Decompress a JPEG2000 image to a bitmap.
196  *  @param data JPEG2000 data.
197  *  @param size Size of data in bytes.
198  *  @param reduce A power of 2 by which to reduce the size of the decoded image;
199  *  e.g. 0 reduces by (2^0 == 1), ie keeping the same size.
200  *       1 reduces by (2^1 == 2), ie halving the size of the image.
201  *  This is useful for scaling 4K DCP images down to 2K.
202  *  @return XYZ image.
203  */
204 shared_ptr<dcp::XYZImage>
205 dcp::decompress_j2k (uint8_t* data, int64_t size, int reduce)
206 {
207         opj_dinfo_t* decoder = opj_create_decompress (CODEC_J2K);
208         opj_dparameters_t parameters;
209         opj_set_default_decoder_parameters (&parameters);
210         parameters.cp_reduce = reduce;
211         opj_setup_decoder (decoder, &parameters);
212         opj_cio_t* cio = opj_cio_open ((opj_common_ptr) decoder, data, size);
213         opj_image_t* image = opj_decode (decoder, cio);
214         if (!image) {
215                 opj_destroy_decompress (decoder);
216                 opj_cio_close (cio);
217                 boost::throw_exception (DCPReadError (String::compose ("could not decode JPEG2000 codestream of %1 bytes.", size)));
218         }
219
220         opj_destroy_decompress (decoder);
221         opj_cio_close (cio);
222
223         image->x1 = rint (float(image->x1) / pow (2, reduce));
224         image->y1 = rint (float(image->y1) / pow (2, reduce));
225         return shared_ptr<XYZImage> (new XYZImage (image));
226 }
227
228 /** @param s A string.
229  *  @return true if the string contains only space, newline or tab characters, or is empty.
230  */
231 bool
232 dcp::empty_or_white_space (string s)
233 {
234         for (size_t i = 0; i < s.length(); ++i) {
235                 if (s[i] != ' ' && s[i] != '\n' && s[i] != '\t') {
236                         return false;
237                 }
238         }
239
240         return true;
241 }
242
243 /** Set up various bits that the library needs.  Should be called one
244  *  by client applications.
245  */
246 void
247 dcp::init ()
248 {
249         if (xmlSecInit() < 0) {
250                 throw MiscError ("could not initialise xmlsec");
251         }
252
253 #ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
254         if (xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 0) {
255                 throw MiscError ("unable to load default xmlsec-crypto library");
256         }
257 #endif  
258
259         if (xmlSecCryptoAppInit(0) < 0) {
260                 throw MiscError ("could not initialise crypto");
261         }
262
263         if (xmlSecCryptoInit() < 0) {
264                 throw MiscError ("could not initialise xmlsec-crypto");
265         }
266 }
267
268 bool dcp::operator== (dcp::Size const & a, dcp::Size const & b)
269 {
270         return (a.width == b.width && a.height == b.height);
271 }
272
273 bool dcp::operator!= (dcp::Size const & a, dcp::Size const & b)
274 {
275         return !(a == b);
276 }
277
278 ostream& dcp::operator<< (ostream& s, dcp::Size const & a)
279 {
280         s << a.width << "x" << a.height;
281         return s;
282 }
283
284 /** Decode a base64 string.  The base64 decode routine in KM_util.cpp
285  *  gives different values to both this and the command-line base64
286  *  for some inputs.  Not sure why.
287  *
288  *  @param in base64-encoded string.
289  *  @param out Output buffer.
290  *  @param out_length Length of output buffer.
291  *  @return Number of characters written to the output buffer.
292  */
293 int
294 dcp::base64_decode (string const & in, unsigned char* out, int out_length)
295 {
296         BIO* b64 = BIO_new (BIO_f_base64 ());
297
298         /* This means the input should have no newlines */
299         BIO_set_flags (b64, BIO_FLAGS_BASE64_NO_NL);
300
301         /* Copy our input string, removing newlines */
302         char in_buffer[in.size() + 1];
303         char* p = in_buffer;
304         for (size_t i = 0; i < in.size(); ++i) {
305                 if (in[i] != '\n' && in[i] != '\r') {
306                         *p++ = in[i];
307                 }
308         }
309                 
310         BIO* bmem = BIO_new_mem_buf (in_buffer, p - in_buffer);
311         bmem = BIO_push (b64, bmem);
312         int const N = BIO_read (bmem, out, out_length);
313         BIO_free_all (bmem);
314
315         return N;
316 }
317
318 /** @param p Path to open.
319  *  @param t mode flags, as for fopen(3).
320  *  @return FILE pointer or 0 on error.
321  *
322  *  Apparently there is no way to create an ofstream using a UTF-8
323  *  filename under Windows.  We are hence reduced to using fopen
324  *  with this wrapper.
325  */
326 FILE *
327 dcp::fopen_boost (boost::filesystem::path p, string t)
328 {
329 #ifdef LIBDCP_WINDOWS
330         wstring w (t.begin(), t.end());
331         /* c_str() here should give a UTF-16 string */
332         return _wfopen (p.c_str(), w.c_str ());
333 #else
334         return fopen (p.c_str(), t.c_str ());
335 #endif
336 }
337
338 optional<boost::filesystem::path>
339 dcp::relative_to_root (boost::filesystem::path root, boost::filesystem::path file)
340 {
341         boost::filesystem::path::const_iterator i = root.begin ();
342         boost::filesystem::path::const_iterator j = file.begin ();
343
344         while (i != root.end() && j != file.end() && *i == *j) {
345                 ++i;
346                 ++j;
347         }
348
349         if (i != root.end ()) {
350                 return optional<boost::filesystem::path> ();
351         }
352
353         boost::filesystem::path rel;
354         while (j != file.end ()) {
355                 rel /= *j++;
356         }
357
358         return rel;
359 }
360
361 bool
362 dcp::ids_equal (string a, string b)
363 {
364         transform (a.begin(), a.end(), a.begin(), ::tolower);
365         transform (b.begin(), b.end(), b.begin(), ::tolower);
366         trim (a);
367         trim (b);
368         return a == b;
369 }
370
371 string
372 dcp::file_to_string (boost::filesystem::path p, uintmax_t max_length)
373 {
374         uintmax_t len = boost::filesystem::file_size (p);
375         if (len > max_length) {
376                 throw MiscError ("Unexpectedly long file");
377         }
378         
379         char* c = new char[len + 1];
380                            
381         FILE* f = fopen_boost (p, "r");
382         if (!f) {
383                 return "";
384         }
385
386         fread (c, 1, len, f);
387         fclose (f);
388         c[len] = '\0';
389
390         string s (c);
391         delete[] c;
392
393         return s;
394 }
395
396 /** @param key RSA private key in PEM format (optionally with -----BEGIN... / -----END...)
397  *  @return SHA1 fingerprint of key
398  */
399 string
400 dcp::private_key_fingerprint (string key)
401 {
402         boost::replace_all (key, "-----BEGIN RSA PRIVATE KEY-----\n", "");
403         boost::replace_all (key, "\n-----END RSA PRIVATE KEY-----\n", "");
404
405         unsigned char buffer[4096];
406         int const N = base64_decode (key, buffer, sizeof (buffer));
407
408         SHA_CTX sha;
409         SHA1_Init (&sha);
410         SHA1_Update (&sha, buffer, N);
411         uint8_t digest[20];
412         SHA1_Final (digest, &sha);
413
414         char digest_base64[64];
415         return Kumu::base64encode (digest, 20, digest_base64, 64);
416 }
417
418 xmlpp::Node *
419 dcp::find_child (xmlpp::Node const * node, string name)
420 {
421         xmlpp::Node::NodeList c = node->get_children ();
422         xmlpp::Node::NodeList::iterator i = c.begin();
423         while (i != c.end() && (*i)->get_name() != name) {
424                 ++i;
425         }
426
427         DCP_ASSERT (i != c.end ());
428         return *i;
429 }