Get Signer to take a PEM string rather than a filename.
[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 "argb_frame.h"
28 #include "certificates.h"
29 #include "gamma_lut.h"
30 #include "xyz_frame.h"
31 #include "compose.hpp"
32 #include "KM_util.h"
33 #include "KM_fileio.h"
34 #include "AS_DCP.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>
44 #include <stdexcept>
45 #include <sstream>
46 #include <iostream>
47 #include <iomanip>
48
49 using std::string;
50 using std::wstring;
51 using std::cout;
52 using std::stringstream;
53 using std::min;
54 using std::max;
55 using std::list;
56 using std::setw;
57 using std::setfill;
58 using std::ostream;
59 using boost::shared_ptr;
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         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         assert (false);
194 }
195
196 /** Decompress a JPEG2000 image to a bitmap.
197  *  @param data JPEG2000 data.
198  *  @param size Size of data in bytes.
199  *  @param reduce A power of 2 by which to reduce the size of the decoded image;
200  *  e.g. 0 reduces by (2^0 == 1), ie keeping the same size.
201  *       1 reduces by (2^1 == 2), ie halving the size of the image.
202  *  This is useful for scaling 4K DCP images down to 2K.
203  *  @return XYZ image.
204  */
205 shared_ptr<dcp::XYZFrame>
206 dcp::decompress_j2k (uint8_t* data, int64_t size, int reduce)
207 {
208         opj_dinfo_t* decoder = opj_create_decompress (CODEC_J2K);
209         opj_dparameters_t parameters;
210         opj_set_default_decoder_parameters (&parameters);
211         parameters.cp_reduce = reduce;
212         opj_setup_decoder (decoder, &parameters);
213         opj_cio_t* cio = opj_cio_open ((opj_common_ptr) decoder, data, size);
214         opj_image_t* image = opj_decode (decoder, cio);
215         if (!image) {
216                 opj_destroy_decompress (decoder);
217                 opj_cio_close (cio);
218                 boost::throw_exception (DCPReadError (String::compose ("could not decode JPEG2000 codestream of %1 bytes.", size)));
219         }
220
221         opj_destroy_decompress (decoder);
222         opj_cio_close (cio);
223
224         image->x1 = rint (float(image->x1) / pow (2, reduce));
225         image->y1 = rint (float(image->y1) / pow (2, reduce));
226         return shared_ptr<XYZFrame> (new XYZFrame (image));
227 }
228
229 /** @param s A string.
230  *  @return true if the string contains only space, newline or tab characters, or is empty.
231  */
232 bool
233 dcp::empty_or_white_space (string s)
234 {
235         for (size_t i = 0; i < s.length(); ++i) {
236                 if (s[i] != ' ' && s[i] != '\n' && s[i] != '\t') {
237                         return false;
238                 }
239         }
240
241         return true;
242 }
243
244 /** Set up various bits that the library needs.  Should be called one
245  *  by client applications.
246  */
247 void
248 dcp::init ()
249 {
250         if (xmlSecInit() < 0) {
251                 throw MiscError ("could not initialise xmlsec");
252         }
253
254 #ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
255         if (xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 0) {
256                 throw MiscError ("unable to load default xmlsec-crypto library");
257         }
258 #endif  
259
260         if (xmlSecCryptoAppInit(0) < 0) {
261                 throw MiscError ("could not initialise crypto");
262         }
263
264         if (xmlSecCryptoInit() < 0) {
265                 throw MiscError ("could not initialise xmlsec-crypto");
266         }
267 }
268
269 bool dcp::operator== (dcp::Size const & a, dcp::Size const & b)
270 {
271         return (a.width == b.width && a.height == b.height);
272 }
273
274 bool dcp::operator!= (dcp::Size const & a, dcp::Size const & b)
275 {
276         return !(a == b);
277 }
278
279 ostream& dcp::operator<< (ostream& s, dcp::Size const & a)
280 {
281         s << a.width << "x" << a.height;
282         return s;
283 }
284
285 /** Decode a base64 string.  The base64 decode routine in KM_util.cpp
286  *  gives different values to both this and the command-line base64
287  *  for some inputs.  Not sure why.
288  *
289  *  @param in base64-encoded string.
290  *  @param out Output buffer.
291  *  @param out_length Length of output buffer.
292  *  @return Number of characters written to the output buffer.
293  */
294 int
295 dcp::base64_decode (string const & in, unsigned char* out, int out_length)
296 {
297         BIO* b64 = BIO_new (BIO_f_base64 ());
298
299         /* This means the input should have no newlines */
300         BIO_set_flags (b64, BIO_FLAGS_BASE64_NO_NL);
301
302         /* Copy our input string, removing newlines */
303         char in_buffer[in.size() + 1];
304         char* p = in_buffer;
305         for (size_t i = 0; i < in.size(); ++i) {
306                 if (in[i] != '\n' && in[i] != '\r') {
307                         *p++ = in[i];
308                 }
309         }
310                 
311         BIO* bmem = BIO_new_mem_buf (in_buffer, p - in_buffer);
312         bmem = BIO_push (b64, bmem);
313         int const N = BIO_read (bmem, out, out_length);
314         BIO_free_all (bmem);
315
316         return N;
317 }
318
319 /** @param p Path to open.
320  *  @param t mode flags, as for fopen(3).
321  *  @return FILE pointer or 0 on error.
322  *
323  *  Apparently there is no way to create an ofstream using a UTF-8
324  *  filename under Windows.  We are hence reduced to using fopen
325  *  with this wrapper.
326  */
327 FILE *
328 dcp::fopen_boost (boost::filesystem::path p, string t)
329 {
330 #ifdef LIBDCP_WINDOWS
331         wstring w (t.begin(), t.end());
332         /* c_str() here should give a UTF-16 string */
333         return _wfopen (p.c_str(), w.c_str ());
334 #else
335         return fopen (p.c_str(), t.c_str ());
336 #endif
337 }
338
339 optional<boost::filesystem::path>
340 dcp::relative_to_root (boost::filesystem::path root, boost::filesystem::path file)
341 {
342         boost::filesystem::path::const_iterator i = root.begin ();
343         boost::filesystem::path::const_iterator j = file.begin ();
344
345         while (i != root.end() && j != file.end() && *i == *j) {
346                 ++i;
347                 ++j;
348         }
349
350         if (i != root.end ()) {
351                 return optional<boost::filesystem::path> ();
352         }
353
354         boost::filesystem::path rel;
355         while (j != file.end ()) {
356                 rel /= *j++;
357         }
358
359         return rel;
360 }
361
362 bool
363 dcp::ids_equal (string a, string b)
364 {
365         transform (a.begin(), a.end(), a.begin(), ::tolower);
366         transform (b.begin(), b.end(), b.begin(), ::tolower);
367         trim (a);
368         trim (b);
369         return a == b;
370 }
371
372 string
373 dcp::file_to_string (boost::filesystem::path p)
374 {
375         uintmax_t len = boost::filesystem::file_size (p);
376         char* c = new char[len];
377                            
378         FILE* f = fopen_boost (p, "r");
379         if (!f) {
380                 return "";
381         }
382
383         fread (c, 1, len, f);
384         fclose (f);
385
386         string s (c);
387         delete[] c;
388
389         return s;
390 }