Optional progress reporting when making MXF hashes.
[libdcp.git] / src / util.cc
1 /*
2     Copyright (C) 2012 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 <stdexcept>
25 #include <sstream>
26 #include <iostream>
27 #include <iomanip>
28 #include <boost/filesystem.hpp>
29 #include <boost/lexical_cast.hpp>
30 #include <openssl/sha.h>
31 #include <libxml++/nodes/element.h>
32 #include <libxml++/document.h>
33 #include <xmlsec/xmldsig.h>
34 #include <xmlsec/dl.h>
35 #include <xmlsec/app.h>
36 #include "KM_util.h"
37 #include "KM_fileio.h"
38 #include "AS_DCP.h"
39 #include "util.h"
40 #include "exceptions.h"
41 #include "types.h"
42 #include "argb_frame.h"
43 #include "certificates.h"
44 #include "gamma_lut.h"
45 #include "xyz_frame.h"
46
47 using std::string;
48 using std::cout;
49 using std::stringstream;
50 using std::min;
51 using std::max;
52 using std::list;
53 using boost::shared_ptr;
54 using boost::lexical_cast;
55 using namespace libdcp;
56
57 /** Create a UUID.
58  *  @return UUID.
59  */
60 string
61 libdcp::make_uuid ()
62 {
63         char buffer[64];
64         Kumu::UUID id;
65         Kumu::GenRandomValue (id);
66         id.EncodeHex (buffer, 64);
67         return string (buffer);
68 }
69
70
71 /** Create a digest for a file.
72  *  @param filename File name.
73  *  @param progress Pointer to a progress reporting function, or 0.  The function will be called
74  *  with a progress value between 0 and 1.
75  *  @return Digest.
76  */
77 string
78 libdcp::make_digest (string filename, boost::function<void (float)>* progress)
79 {
80         Kumu::FileReader reader;
81         if (ASDCP_FAILURE (reader.OpenRead (filename.c_str ()))) {
82                 boost::throw_exception (FileError ("could not open file to compute digest", filename));
83         }
84         
85         SHA_CTX sha;
86         SHA1_Init (&sha);
87
88         int const buffer_size = 65536;
89         Kumu::ByteString read_buffer (buffer_size);
90
91         Kumu::fsize_t done = 0;
92         Kumu::fsize_t const size = reader.Size ();
93         while (1) {
94                 ui32_t read = 0;
95                 Kumu::Result_t r = reader.Read (read_buffer.Data(), read_buffer.Capacity(), &read);
96                 
97                 if (r == Kumu::RESULT_ENDOFFILE) {
98                         break;
99                 } else if (ASDCP_FAILURE (r)) {
100                         boost::throw_exception (FileError ("could not read file to compute digest", filename));
101                 }
102                 
103                 SHA1_Update (&sha, read_buffer.Data(), read);
104
105                 if (progress) {
106                         (*progress) (float (done) / size);
107                         done += read;
108                 }
109         }
110
111         byte_t byte_buffer[20];
112         SHA1_Final (byte_buffer, &sha);
113
114         char digest[64];
115         return Kumu::base64encode (byte_buffer, 20, digest, 64);
116 }
117
118 /** Convert a content kind to a string which can be used in a
119  *  <ContentKind> node.
120  *  @param kind ContentKind.
121  *  @return string.
122  */
123 string
124 libdcp::content_kind_to_string (ContentKind kind)
125 {
126         switch (kind) {
127         case FEATURE:
128                 return "feature";
129         case SHORT:
130                 return "short";
131         case TRAILER:
132                 return "trailer";
133         case TEST:
134                 return "test";
135         case TRANSITIONAL:
136                 return "transitional";
137         case RATING:
138                 return "rating";
139         case TEASER:
140                 return "teaser";
141         case POLICY:
142                 return "policy";
143         case PUBLIC_SERVICE_ANNOUNCEMENT:
144                 return "psa";
145         case ADVERTISEMENT:
146                 return "advertisement";
147         }
148
149         assert (false);
150 }
151
152 /** Convert a string from a <ContentKind> node to a libdcp ContentKind.
153  *  Reasonably tolerant about varying case.
154  *  @param type Content kind string.
155  *  @return libdcp ContentKind.
156  */
157 libdcp::ContentKind
158 libdcp::content_kind_from_string (string type)
159 {
160         /* XXX: should probably just convert type to lower-case and have done with it */
161         
162         if (type == "feature") {
163                 return FEATURE;
164         } else if (type == "short") {
165                 return SHORT;
166         } else if (type == "trailer" || type == "Trailer") {
167                 return TRAILER;
168         } else if (type == "test") {
169                 return TEST;
170         } else if (type == "transitional") {
171                 return TRANSITIONAL;
172         } else if (type == "rating") {
173                 return RATING;
174         } else if (type == "teaser" || type == "Teaser") {
175                 return TEASER;
176         } else if (type == "policy") {
177                 return POLICY;
178         } else if (type == "psa") {
179                 return PUBLIC_SERVICE_ANNOUNCEMENT;
180         } else if (type == "advertisement") {
181                 return ADVERTISEMENT;
182         }
183
184         assert (false);
185 }
186
187 /** Decompress a JPEG2000 image to a bitmap.
188  *  @param data JPEG2000 data.
189  *  @param size Size of data in bytes.
190  *  @param reduce A power of 2 by which to reduce the size of the decoded image;
191  *  e.g. 0 reduces by (2^0 == 1), ie keeping the same size.
192  *       1 reduces by (2^1 == 2), ie halving the size of the image.
193  *  This is useful for scaling 4K DCP images down to 2K.
194  *  @return XYZ image.
195  */
196 shared_ptr<libdcp::XYZFrame>
197 libdcp::decompress_j2k (uint8_t* data, int64_t size, int reduce)
198 {
199         opj_dinfo_t* decoder = opj_create_decompress (CODEC_J2K);
200         opj_dparameters_t parameters;
201         opj_set_default_decoder_parameters (&parameters);
202         parameters.cp_reduce = reduce;
203         opj_setup_decoder (decoder, &parameters);
204         opj_cio_t* cio = opj_cio_open ((opj_common_ptr) decoder, data, size);
205         opj_image_t* image = opj_decode (decoder, cio);
206         if (!image) {
207                 opj_destroy_decompress (decoder);
208                 opj_cio_close (cio);
209                 boost::throw_exception (DCPReadError ("could not decode JPEG2000 codestream of " + lexical_cast<string> (size) + " bytes."));
210         }
211
212         opj_cio_close (cio);
213
214         image->x1 = rint (float(image->x1) / pow (2, reduce));
215         image->y1 = rint (float(image->y1) / pow (2, reduce));
216         return shared_ptr<XYZFrame> (new XYZFrame (image));
217 }
218
219 /** @param s A string.
220  *  @return true if the string contains only space, newline or tab characters, or is empty.
221  */
222 bool
223 libdcp::empty_or_white_space (string s)
224 {
225         for (size_t i = 0; i < s.length(); ++i) {
226                 if (s[i] != ' ' && s[i] != '\n' && s[i] != '\t') {
227                         return false;
228                 }
229         }
230
231         return true;
232 }
233
234 void
235 libdcp::init ()
236 {
237         if (xmlSecInit() < 0) {
238                 throw MiscError ("could not initialise xmlsec");
239         }
240 }
241
242 void
243 libdcp::add_signature_value (xmlpp::Element* parent, CertificateChain const & certificates, string const & signer_key, string const & ns)
244 {
245         parent->add_child("SignatureValue", ns);
246         
247         xmlpp::Element* key_info = parent->add_child("KeyInfo", ns);
248         list<shared_ptr<Certificate> > c = certificates.leaf_to_root ();
249         for (list<shared_ptr<Certificate> >::iterator i = c.begin(); i != c.end(); ++i) {
250                 xmlpp::Element* data = key_info->add_child("X509Data", ns);
251                 
252                 {
253                         xmlpp::Element* serial = data->add_child("X509IssuerSerial", ns);
254                         serial->add_child("X509IssuerName", ns)->add_child_text((*i)->issuer ());
255                         serial->add_child("X509SerialNumber", ns)->add_child_text((*i)->serial ());
256                 }
257                 
258                 data->add_child("X509Certificate", ns)->add_child_text((*i)->certificate());
259         }
260
261         xmlSecKeysMngrPtr keys_manager = xmlSecKeysMngrCreate();
262         if (!keys_manager) {
263                 throw MiscError ("could not create keys manager");
264         }
265         
266         xmlSecDSigCtx signature_context;
267         
268         if (xmlSecDSigCtxInitialize (&signature_context, keys_manager) < 0) {
269                 throw MiscError ("could not initialise XMLSEC context");
270         }
271         
272         if (xmlSecDSigCtxSign (&signature_context, parent->cobj()) < 0) {
273                 throw MiscError ("could not sign");
274         }
275         
276         xmlSecDSigCtxFinalize (&signature_context);
277         xmlSecKeysMngrDestroy (keys_manager);
278 }
279
280
281 void
282 libdcp::add_signer (xmlpp::Element* parent, CertificateChain const & certificates, string const & ns)
283 {
284         xmlpp::Element* signer = parent->add_child("Signer");
285
286         {
287                 xmlpp::Element* data = signer->add_child("X509Data", ns);
288                 
289                 {
290                         xmlpp::Element* serial_element = data->add_child("X509IssuerSerial", ns);
291                         serial_element->add_child("X509IssuerName", ns)->add_child_text (certificates.leaf()->issuer());
292                         serial_element->add_child("X509SerialNumber", ns)->add_child_text (certificates.leaf()->serial());
293                 }
294                 
295                 data->add_child("X509SubjectName", ns)->add_child_text (certificates.leaf()->subject());
296         }
297 }
298
299 void
300 libdcp::sign (xmlpp::Element* parent, CertificateChain const & certificates, string const & signer_key, bool interop)
301 {
302         add_signer (parent, certificates, "dsig");
303
304         xmlpp::Element* signature = parent->add_child("Signature", "dsig");
305         
306         {
307                 xmlpp::Element* signed_info = signature->add_child ("SignedInfo", "dsig");
308                 signed_info->add_child("CanonicalizationMethod", "dsig")->set_attribute ("Algorithm", "http://www.w3.org/TR/2001/REC-xml-c14n-20010315");
309
310                 if (interop) {
311                         signed_info->add_child("SignatureMethod", "dsig")->set_attribute("Algorithm", "http://www.w3.org/2000/09/xmldsig#rsa-sha1");
312                 } else {
313                         signed_info->add_child("SignatureMethod", "dsig")->set_attribute("Algorithm", "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
314                 }
315                 
316                 {
317                         xmlpp::Element* reference = signed_info->add_child("Reference", "dsig");
318                         reference->set_attribute ("URI", "");
319                         {
320                                 xmlpp::Element* transforms = reference->add_child("Transforms", "dsig");
321                                 transforms->add_child("Transform", "dsig")->set_attribute (
322                                         "Algorithm", "http://www.w3.org/2000/09/xmldsig#enveloped-signature"
323                                         );
324                         }
325                         reference->add_child("DigestMethod", "dsig")->set_attribute("Algorithm", "http://www.w3.org/2000/09/xmldsig#sha1");
326                         /* This will be filled in by the signing later */
327                         reference->add_child("DigestValue", "dsig");
328                 }
329         }
330         
331         add_signature_value (signature, certificates, signer_key, "dsig");
332 }
333
334 bool libdcp::operator== (libdcp::Size const & a, libdcp::Size const & b)
335 {
336         return (a.width == b.width && a.height == b.height);
337 }
338
339 bool libdcp::operator!= (libdcp::Size const & a, libdcp::Size const & b)
340 {
341         return !(a == b);
342 }
343
344 /** The base64 decode routine in KM_util.cpp gives different values to both
345  *  this and the command-line base64 for some inputs.  Not sure why.
346  */
347 int
348 libdcp::base64_decode (string const & in, unsigned char* out, int out_length)
349 {
350         BIO* b64 = BIO_new (BIO_f_base64 ());
351
352         /* This means the input should have no newlines */
353         BIO_set_flags (b64, BIO_FLAGS_BASE64_NO_NL);
354
355         /* Copy our input string, removing newlines */
356         char in_buffer[in.size() + 1];
357         char* p = in_buffer;
358         for (size_t i = 0; i < in.size(); ++i) {
359                 if (in[i] != '\n' && in[i] != '\r') {
360                         *p++ = in[i];
361                 }
362         }
363                 
364         BIO* bmem = BIO_new_mem_buf (in_buffer, p - in_buffer);
365         bmem = BIO_push (b64, bmem);
366         int const N = BIO_read (bmem, out, out_length);
367         BIO_free_all (bmem);
368
369         return N;
370 }