2 Copyright (C) 2012-2014 Carl Hetherington <cth@carlh.net>
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.
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.
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.
21 * @brief Utility methods.
25 #include "exceptions.h"
27 #include "certificates.h"
28 #include "xyz_image.h"
29 #include "dcp_assert.h"
30 #include "compose.hpp"
32 #include "KM_fileio.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>
51 using std::stringstream;
58 using boost::shared_ptr;
59 using boost::optional;
60 using boost::function;
61 using boost::algorithm::trim;
72 Kumu::GenRandomValue (id);
73 id.EncodeHex (buffer, 64);
74 return string (buffer);
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.
85 dcp::make_digest (boost::filesystem::path filename, function<void (float)> progress)
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));
96 int const buffer_size = 65536;
97 Kumu::ByteString read_buffer (buffer_size);
99 Kumu::fsize_t done = 0;
100 Kumu::fsize_t const size = reader.Size ();
103 Kumu::Result_t r = reader.Read (read_buffer.Data(), read_buffer.Capacity(), &read);
105 if (r == Kumu::RESULT_ENDOFFILE) {
107 } else if (ASDCP_FAILURE (r)) {
108 boost::throw_exception (FileError ("could not read file to compute digest", filename, r));
111 SHA1_Update (&sha, read_buffer.Data(), read);
114 progress (float (done) / size);
119 byte_t byte_buffer[SHA_DIGEST_LENGTH];
120 SHA1_Final (byte_buffer, &sha);
123 return Kumu::base64encode (byte_buffer, SHA_DIGEST_LENGTH, digest, 64);
126 /** Convert a content kind to a string which can be used in a
127 * <ContentKind> node.
128 * @param kind ContentKind.
132 dcp::content_kind_to_string (ContentKind kind)
144 return "transitional";
151 case PUBLIC_SERVICE_ANNOUNCEMENT:
154 return "advertisement";
160 /** Convert a string from a <ContentKind> node to a libdcp ContentKind.
161 * Reasonably tolerant about varying case.
162 * @param kind Content kind string.
163 * @return libdcp ContentKind.
166 dcp::content_kind_from_string (string kind)
168 transform (kind.begin(), kind.end(), kind.begin(), ::tolower);
170 if (kind == "feature") {
172 } else if (kind == "short") {
174 } else if (kind == "trailer") {
176 } else if (kind == "test") {
178 } else if (kind == "transitional") {
180 } else if (kind == "rating") {
182 } else if (kind == "teaser") {
184 } else if (kind == "policy") {
186 } else if (kind == "psa") {
187 return PUBLIC_SERVICE_ANNOUNCEMENT;
188 } else if (kind == "advertisement") {
189 return ADVERTISEMENT;
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.
204 shared_ptr<dcp::XYZImage>
205 dcp::decompress_j2k (uint8_t* data, int64_t size, int reduce)
207 opj_dinfo_t* decoder = opj_create_decompress (CODEC_J2K);
208 opj_dparameters_t parameters;
209 opj_set_default_decoder_parameters (¶meters);
210 parameters.cp_reduce = reduce;
211 opj_setup_decoder (decoder, ¶meters);
212 opj_cio_t* cio = opj_cio_open ((opj_common_ptr) decoder, data, size);
213 opj_image_t* image = opj_decode (decoder, cio);
215 opj_destroy_decompress (decoder);
217 boost::throw_exception (DCPReadError (String::compose ("could not decode JPEG2000 codestream of %1 bytes.", size)));
220 opj_destroy_decompress (decoder);
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));
228 /** @param s A string.
229 * @return true if the string contains only space, newline or tab characters, or is empty.
232 dcp::empty_or_white_space (string s)
234 for (size_t i = 0; i < s.length(); ++i) {
235 if (s[i] != ' ' && s[i] != '\n' && s[i] != '\t') {
243 /** Set up various bits that the library needs. Should be called one
244 * by client applications.
249 if (xmlSecInit() < 0) {
250 throw MiscError ("could not initialise xmlsec");
253 #ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
254 if (xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 0) {
255 throw MiscError ("unable to load default xmlsec-crypto library");
259 if (xmlSecCryptoAppInit(0) < 0) {
260 throw MiscError ("could not initialise crypto");
263 if (xmlSecCryptoInit() < 0) {
264 throw MiscError ("could not initialise xmlsec-crypto");
268 bool dcp::operator== (dcp::Size const & a, dcp::Size const & b)
270 return (a.width == b.width && a.height == b.height);
273 bool dcp::operator!= (dcp::Size const & a, dcp::Size const & b)
278 ostream& dcp::operator<< (ostream& s, dcp::Size const & a)
280 s << a.width << "x" << a.height;
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.
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.
294 dcp::base64_decode (string const & in, unsigned char* out, int out_length)
296 BIO* b64 = BIO_new (BIO_f_base64 ());
298 /* This means the input should have no newlines */
299 BIO_set_flags (b64, BIO_FLAGS_BASE64_NO_NL);
301 /* Copy our input string, removing newlines */
302 char in_buffer[in.size() + 1];
304 for (size_t i = 0; i < in.size(); ++i) {
305 if (in[i] != '\n' && in[i] != '\r') {
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);
318 /** @param p Path to open.
319 * @param t mode flags, as for fopen(3).
320 * @return FILE pointer or 0 on error.
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
327 dcp::fopen_boost (boost::filesystem::path p, string t)
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 ());
334 return fopen (p.c_str(), t.c_str ());
338 optional<boost::filesystem::path>
339 dcp::relative_to_root (boost::filesystem::path root, boost::filesystem::path file)
341 boost::filesystem::path::const_iterator i = root.begin ();
342 boost::filesystem::path::const_iterator j = file.begin ();
344 while (i != root.end() && j != file.end() && *i == *j) {
349 if (i != root.end ()) {
350 return optional<boost::filesystem::path> ();
353 boost::filesystem::path rel;
354 while (j != file.end ()) {
362 dcp::ids_equal (string a, string b)
364 transform (a.begin(), a.end(), a.begin(), ::tolower);
365 transform (b.begin(), b.end(), b.begin(), ::tolower);
372 dcp::file_to_string (boost::filesystem::path p, uintmax_t max_length)
374 uintmax_t len = boost::filesystem::file_size (p);
375 if (len > max_length) {
376 throw MiscError ("Unexpectedly long file");
379 char* c = new char[len + 1];
381 FILE* f = fopen_boost (p, "r");
386 fread (c, 1, len, f);
396 /** @param key RSA private key in PEM format (optionally with -----BEGIN... / -----END...)
397 * @return SHA1 fingerprint of key
400 dcp::private_key_fingerprint (string key)
402 boost::replace_all (key, "-----BEGIN RSA PRIVATE KEY-----\n", "");
403 boost::replace_all (key, "\n-----END RSA PRIVATE KEY-----\n", "");
405 unsigned char buffer[4096];
406 int const N = base64_decode (key, buffer, sizeof (buffer));
410 SHA1_Update (&sha, buffer, N);
412 SHA1_Final (digest, &sha);
414 char digest_base64[64];
415 return Kumu::base64encode (digest, 20, digest_base64, 64);
419 dcp::find_child (xmlpp::Node const * node, string name)
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) {
427 DCP_ASSERT (i != c.end ());