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