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