2 Copyright (C) 2012-2014 Carl Hetherington <cth@carlh.net>
4 This file is part of libdcp.
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.
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.
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/>.
22 * @brief Utility methods.
26 #include "exceptions.h"
28 #include "certificate.h"
29 #include "openjpeg_image.h"
30 #include "dcp_assert.h"
31 #include "compose.hpp"
33 #include "KM_fileio.h"
35 #include <xmlsec/xmldsig.h>
36 #include <xmlsec/dl.h>
37 #include <xmlsec/app.h>
38 #include <xmlsec/crypto.h>
39 #include <libxml++/nodes/element.h>
40 #include <libxml++/document.h>
41 #include <openssl/sha.h>
42 #include <boost/filesystem.hpp>
43 #include <boost/algorithm/string.hpp>
52 using std::stringstream;
59 using boost::shared_ptr;
60 using boost::shared_array;
61 using boost::optional;
62 using boost::function;
63 using boost::algorithm::trim;
74 Kumu::GenRandomValue (id);
75 id.EncodeHex (buffer, 64);
76 return string (buffer);
80 /** Create a digest for a file.
81 * @param filename File name.
82 * @param progress Optional progress reporting function. The function will be called
83 * with a progress value between 0 and 1.
87 dcp::make_digest (boost::filesystem::path filename, function<void (float)> progress)
89 Kumu::FileReader reader;
90 Kumu::Result_t r = reader.OpenRead (filename.string().c_str ());
91 if (ASDCP_FAILURE (r)) {
92 boost::throw_exception (FileError ("could not open file to compute digest", filename, r));
98 int const buffer_size = 65536;
99 Kumu::ByteString read_buffer (buffer_size);
101 Kumu::fsize_t done = 0;
102 Kumu::fsize_t const size = reader.Size ();
105 Kumu::Result_t r = reader.Read (read_buffer.Data(), read_buffer.Capacity(), &read);
107 if (r == Kumu::RESULT_ENDOFFILE) {
109 } else if (ASDCP_FAILURE (r)) {
110 boost::throw_exception (FileError ("could not read file to compute digest", filename, r));
113 SHA1_Update (&sha, read_buffer.Data(), read);
116 progress (float (done) / size);
121 byte_t byte_buffer[SHA_DIGEST_LENGTH];
122 SHA1_Final (byte_buffer, &sha);
125 return Kumu::base64encode (byte_buffer, SHA_DIGEST_LENGTH, digest, 64);
128 /** Convert a content kind to a string which can be used in a
129 * <ContentKind> node.
130 * @param kind ContentKind.
134 dcp::content_kind_to_string (ContentKind kind)
146 return "transitional";
153 case PUBLIC_SERVICE_ANNOUNCEMENT:
156 return "advertisement";
162 /** Convert a string from a <ContentKind> node to a libdcp ContentKind.
163 * Reasonably tolerant about varying case.
164 * @param kind Content kind string.
165 * @return libdcp ContentKind.
168 dcp::content_kind_from_string (string kind)
170 transform (kind.begin(), kind.end(), kind.begin(), ::tolower);
172 if (kind == "feature") {
174 } else if (kind == "short") {
176 } else if (kind == "trailer") {
178 } else if (kind == "test") {
180 } else if (kind == "transitional") {
182 } else if (kind == "rating") {
184 } else if (kind == "teaser") {
186 } else if (kind == "policy") {
188 } else if (kind == "psa") {
189 return PUBLIC_SERVICE_ANNOUNCEMENT;
190 } else if (kind == "advertisement") {
191 return ADVERTISEMENT;
197 /** @param s A string.
198 * @return true if the string contains only space, newline or tab characters, or is empty.
201 dcp::empty_or_white_space (string s)
203 for (size_t i = 0; i < s.length(); ++i) {
204 if (s[i] != ' ' && s[i] != '\n' && s[i] != '\t') {
212 /** Set up various bits that the library needs. Should be called one
213 * by client applications.
218 if (xmlSecInit() < 0) {
219 throw MiscError ("could not initialise xmlsec");
222 #ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
223 if (xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 0) {
224 throw MiscError ("unable to load default xmlsec-crypto library");
228 if (xmlSecCryptoAppInit(0) < 0) {
229 throw MiscError ("could not initialise crypto");
232 if (xmlSecCryptoInit() < 0) {
233 throw MiscError ("could not initialise xmlsec-crypto");
237 bool dcp::operator== (dcp::Size const & a, dcp::Size const & b)
239 return (a.width == b.width && a.height == b.height);
242 bool dcp::operator!= (dcp::Size const & a, dcp::Size const & b)
247 ostream& dcp::operator<< (ostream& s, dcp::Size const & a)
249 s << a.width << "x" << a.height;
253 /** Decode a base64 string. The base64 decode routine in KM_util.cpp
254 * gives different values to both this and the command-line base64
255 * for some inputs. Not sure why.
257 * @param in base64-encoded string.
258 * @param out Output buffer.
259 * @param out_length Length of output buffer.
260 * @return Number of characters written to the output buffer.
263 dcp::base64_decode (string const & in, unsigned char* out, int out_length)
265 BIO* b64 = BIO_new (BIO_f_base64 ());
267 /* This means the input should have no newlines */
268 BIO_set_flags (b64, BIO_FLAGS_BASE64_NO_NL);
270 /* Copy our input string, removing newlines */
271 char in_buffer[in.size() + 1];
273 for (size_t i = 0; i < in.size(); ++i) {
274 if (in[i] != '\n' && in[i] != '\r') {
279 BIO* bmem = BIO_new_mem_buf (in_buffer, p - in_buffer);
280 bmem = BIO_push (b64, bmem);
281 int const N = BIO_read (bmem, out, out_length);
287 /** @param p Path to open.
288 * @param t mode flags, as for fopen(3).
289 * @return FILE pointer or 0 on error.
291 * Apparently there is no way to create an ofstream using a UTF-8
292 * filename under Windows. We are hence reduced to using fopen
296 dcp::fopen_boost (boost::filesystem::path p, string t)
298 #ifdef LIBDCP_WINDOWS
299 wstring w (t.begin(), t.end());
300 /* c_str() here should give a UTF-16 string */
301 return _wfopen (p.c_str(), w.c_str ());
303 return fopen (p.c_str(), t.c_str ());
307 optional<boost::filesystem::path>
308 dcp::relative_to_root (boost::filesystem::path root, boost::filesystem::path file)
310 boost::filesystem::path::const_iterator i = root.begin ();
311 boost::filesystem::path::const_iterator j = file.begin ();
313 while (i != root.end() && j != file.end() && *i == *j) {
318 if (i != root.end ()) {
319 return optional<boost::filesystem::path> ();
322 boost::filesystem::path rel;
323 while (j != file.end ()) {
331 dcp::ids_equal (string a, string b)
333 transform (a.begin(), a.end(), a.begin(), ::tolower);
334 transform (b.begin(), b.end(), b.begin(), ::tolower);
341 dcp::file_to_string (boost::filesystem::path p, uintmax_t max_length)
343 uintmax_t len = boost::filesystem::file_size (p);
344 if (len > max_length) {
345 throw MiscError ("Unexpectedly long file");
348 FILE* f = fopen_boost (p, "r");
350 throw FileError ("could not open file", p, errno);
353 char* c = new char[len];
354 /* This may read less than `len' if we are on Windows and we have CRLF in the file */
355 int const N = fread (c, 1, len, f);
364 /** @param key RSA private key in PEM format (optionally with -----BEGIN... / -----END...)
365 * @return SHA1 fingerprint of key
368 dcp::private_key_fingerprint (string key)
370 boost::replace_all (key, "-----BEGIN RSA PRIVATE KEY-----\n", "");
371 boost::replace_all (key, "\n-----END RSA PRIVATE KEY-----\n", "");
373 unsigned char buffer[4096];
374 int const N = base64_decode (key, buffer, sizeof (buffer));
378 SHA1_Update (&sha, buffer, N);
380 SHA1_Final (digest, &sha);
382 char digest_base64[64];
383 return Kumu::base64encode (digest, 20, digest_base64, 64);
387 dcp::find_child (xmlpp::Node const * node, string name)
389 xmlpp::Node::NodeList c = node->get_children ();
390 xmlpp::Node::NodeList::iterator i = c.begin();
391 while (i != c.end() && (*i)->get_name() != name) {
395 DCP_ASSERT (i != c.end ());
400 dcp::remove_urn_uuid (string raw)
402 DCP_ASSERT (raw.substr(0, 9) == "urn:uuid:");
403 return raw.substr (9);