Use openssl's base-64 decoding for KDMs.
[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
46 using std::string;
47 using std::cout;
48 using std::stringstream;
49 using std::min;
50 using std::max;
51 using std::list;
52 using boost::shared_ptr;
53 using boost::lexical_cast;
54 using namespace libdcp;
55
56 /** Create a UUID.
57  *  @return UUID.
58  */
59 string
60 libdcp::make_uuid ()
61 {
62         char buffer[64];
63         Kumu::UUID id;
64         Kumu::GenRandomValue (id);
65         id.EncodeHex (buffer, 64);
66         return string (buffer);
67 }
68
69
70 /** Create a digest for a file.
71  *  @param filename File name.
72  *  @return Digest.
73  */
74 string
75 libdcp::make_digest (string filename)
76 {
77         Kumu::FileReader reader;
78         if (ASDCP_FAILURE (reader.OpenRead (filename.c_str ()))) {
79                 boost::throw_exception (FileError ("could not open file to compute digest", filename));
80         }
81         
82         SHA_CTX sha;
83         SHA1_Init (&sha);
84         
85         Kumu::ByteString read_buffer (65536);
86         int done = 0;
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                 done += read;
99         }
100
101         byte_t byte_buffer[20];
102         SHA1_Final (byte_buffer, &sha);
103
104         char digest[64];
105         return Kumu::base64encode (byte_buffer, 20, digest, 64);
106 }
107
108 /** Convert a content kind to a string which can be used in a
109  *  <ContentKind> node.
110  *  @param kind ContentKind.
111  *  @return string.
112  */
113 string
114 libdcp::content_kind_to_string (ContentKind kind)
115 {
116         switch (kind) {
117         case FEATURE:
118                 return "feature";
119         case SHORT:
120                 return "short";
121         case TRAILER:
122                 return "trailer";
123         case TEST:
124                 return "test";
125         case TRANSITIONAL:
126                 return "transitional";
127         case RATING:
128                 return "rating";
129         case TEASER:
130                 return "teaser";
131         case POLICY:
132                 return "policy";
133         case PUBLIC_SERVICE_ANNOUNCEMENT:
134                 return "psa";
135         case ADVERTISEMENT:
136                 return "advertisement";
137         }
138
139         assert (false);
140 }
141
142 /** Convert a string from a <ContentKind> node to a libdcp ContentKind.
143  *  Reasonably tolerant about varying case.
144  *  @param type Content kind string.
145  *  @return libdcp ContentKind.
146  */
147 libdcp::ContentKind
148 libdcp::content_kind_from_string (string type)
149 {
150         /* XXX: should probably just convert type to lower-case and have done with it */
151         
152         if (type == "feature") {
153                 return FEATURE;
154         } else if (type == "short") {
155                 return SHORT;
156         } else if (type == "trailer" || type == "Trailer") {
157                 return TRAILER;
158         } else if (type == "test") {
159                 return TEST;
160         } else if (type == "transitional") {
161                 return TRANSITIONAL;
162         } else if (type == "rating") {
163                 return RATING;
164         } else if (type == "teaser" || type == "Teaser") {
165                 return TEASER;
166         } else if (type == "policy") {
167                 return POLICY;
168         } else if (type == "psa") {
169                 return PUBLIC_SERVICE_ANNOUNCEMENT;
170         } else if (type == "advertisement") {
171                 return ADVERTISEMENT;
172         }
173
174         assert (false);
175 }
176
177 /** Decompress a JPEG2000 image to a bitmap.
178  *  @param data JPEG2000 data.
179  *  @param size Size of data in bytes.
180  *  @param reduce A power of 2 by which to reduce the size of the decoded image;
181  *  e.g. 0 reduces by (2^0 == 1), ie keeping the same size.
182  *       1 reduces by (2^1 == 2), ie halving the size of the image.
183  *  This is useful for scaling 4K DCP images down to 2K.
184  *  @return openjpeg image, which the caller must call opj_image_destroy() on.
185  */
186 opj_image_t *
187 libdcp::decompress_j2k (uint8_t* data, int64_t size, int reduce)
188 {
189         opj_dinfo_t* decoder = opj_create_decompress (CODEC_J2K);
190         opj_dparameters_t parameters;
191         opj_set_default_decoder_parameters (&parameters);
192         parameters.cp_reduce = reduce;
193         opj_setup_decoder (decoder, &parameters);
194         opj_cio_t* cio = opj_cio_open ((opj_common_ptr) decoder, data, size);
195         opj_image_t* image = opj_decode (decoder, cio);
196         if (!image) {
197                 opj_destroy_decompress (decoder);
198                 opj_cio_close (cio);
199                 boost::throw_exception (DCPReadError ("could not decode JPEG2000 codestream of " + lexical_cast<string> (size) + " bytes."));
200         }
201
202         opj_cio_close (cio);
203
204         image->x1 = rint (float(image->x1) / pow (2, reduce));
205         image->y1 = rint (float(image->y1) / pow (2, reduce));
206         return image;
207 }
208
209 /** Convert an openjpeg XYZ image to RGB.
210  *  @param xyz_frame Frame in XYZ.
211  *  @return RGB image.
212  */
213 shared_ptr<ARGBFrame>
214 libdcp::xyz_to_rgb (opj_image_t* xyz_frame, shared_ptr<const GammaLUT> lut_in, shared_ptr<const GammaLUT> lut_out)
215 {
216         float const dci_coefficient = 48.0 / 52.37;
217
218         /* sRGB color matrix for XYZ -> RGB.  This is the same as the one used by the Fraunhofer
219            EasyDCP player, I think.
220         */
221
222         float const colour_matrix[3][3] = {
223                 {  3.24096989631653,   -1.5373831987381,  -0.498610764741898 },
224                 { -0.96924364566803,    1.87596750259399,  0.0415550582110882 },
225                 {  0.0556300804018974, -0.203976958990097, 1.05697154998779 }
226         };
227
228         int const max_colour = pow (2, lut_out->bit_depth()) - 1;
229
230         struct {
231                 double x, y, z;
232         } s;
233         
234         struct {
235                 double r, g, b;
236         } d;
237         
238         int* xyz_x = xyz_frame->comps[0].data;
239         int* xyz_y = xyz_frame->comps[1].data;
240         int* xyz_z = xyz_frame->comps[2].data;
241
242         shared_ptr<ARGBFrame> argb_frame (new ARGBFrame (Size (xyz_frame->x1, xyz_frame->y1)));
243
244         uint8_t* argb = argb_frame->data ();
245         
246         for (int y = 0; y < xyz_frame->y1; ++y) {
247                 uint8_t* argb_line = argb;
248                 for (int x = 0; x < xyz_frame->x1; ++x) {
249
250                         assert (*xyz_x >= 0 && *xyz_y >= 0 && *xyz_z >= 0 && *xyz_x < 4096 && *xyz_x < 4096 && *xyz_z < 4096);
251                         
252                         /* In gamma LUT */
253                         s.x = lut_in->lut()[*xyz_x++];
254                         s.y = lut_in->lut()[*xyz_y++];
255                         s.z = lut_in->lut()[*xyz_z++];
256
257                         /* DCI companding */
258                         s.x /= dci_coefficient;
259                         s.y /= dci_coefficient;
260                         s.z /= dci_coefficient;
261                         
262                         /* XYZ to RGB */
263                         d.r = ((s.x * colour_matrix[0][0]) + (s.y * colour_matrix[0][1]) + (s.z * colour_matrix[0][2]));
264                         d.g = ((s.x * colour_matrix[1][0]) + (s.y * colour_matrix[1][1]) + (s.z * colour_matrix[1][2]));
265                         d.b = ((s.x * colour_matrix[2][0]) + (s.y * colour_matrix[2][1]) + (s.z * colour_matrix[2][2]));
266                         
267                         d.r = min (d.r, 1.0);
268                         d.r = max (d.r, 0.0);
269                         
270                         d.g = min (d.g, 1.0);
271                         d.g = max (d.g, 0.0);
272                         
273                         d.b = min (d.b, 1.0);
274                         d.b = max (d.b, 0.0);
275                         
276                         /* Out gamma LUT */
277                         *argb_line++ = lut_out->lut()[(int) (d.b * max_colour)] * 0xff;
278                         *argb_line++ = lut_out->lut()[(int) (d.g * max_colour)] * 0xff;
279                         *argb_line++ = lut_out->lut()[(int) (d.r * max_colour)] * 0xff;
280                         *argb_line++ = 0xff;
281                 }
282                 
283                 argb += argb_frame->stride ();
284         }
285
286         return argb_frame;
287 }
288
289 /** @param s A string.
290  *  @return true if the string contains only space, newline or tab characters, or is empty.
291  */
292 bool
293 libdcp::empty_or_white_space (string s)
294 {
295         for (size_t i = 0; i < s.length(); ++i) {
296                 if (s[i] != ' ' && s[i] != '\n' && s[i] != '\t') {
297                         return false;
298                 }
299         }
300
301         return true;
302 }
303
304 void
305 libdcp::init ()
306 {
307         if (xmlSecInit() < 0) {
308                 throw MiscError ("could not initialise xmlsec");
309         }
310 }
311
312 void
313 libdcp::add_signature_value (xmlpp::Element* parent, CertificateChain const & certificates, string const & signer_key, string const & ns)
314 {
315         parent->add_child("SignatureValue", ns);
316         
317         xmlpp::Element* key_info = parent->add_child("KeyInfo", ns);
318         list<shared_ptr<Certificate> > c = certificates.leaf_to_root ();
319         for (list<shared_ptr<Certificate> >::iterator i = c.begin(); i != c.end(); ++i) {
320                 xmlpp::Element* data = key_info->add_child("X509Data", ns);
321                 
322                 {
323                         xmlpp::Element* serial = data->add_child("X509IssuerSerial", ns);
324                         serial->add_child("X509IssuerName", ns)->add_child_text((*i)->issuer ());
325                         serial->add_child("X509SerialNumber", ns)->add_child_text((*i)->serial ());
326                 }
327                 
328                 data->add_child("X509Certificate", ns)->add_child_text((*i)->certificate());
329         }
330
331         xmlSecKeysMngrPtr keys_manager = xmlSecKeysMngrCreate();
332         if (!keys_manager) {
333                 throw MiscError ("could not create keys manager");
334         }
335         
336         xmlSecDSigCtx signature_context;
337         
338         if (xmlSecDSigCtxInitialize (&signature_context, keys_manager) < 0) {
339                 throw MiscError ("could not initialise XMLSEC context");
340         }
341         
342         if (xmlSecDSigCtxSign (&signature_context, parent->cobj()) < 0) {
343                 throw MiscError ("could not sign");
344         }
345         
346         xmlSecDSigCtxFinalize (&signature_context);
347         xmlSecKeysMngrDestroy (keys_manager);
348 }
349
350
351 void
352 libdcp::add_signer (xmlpp::Element* parent, CertificateChain const & certificates, string const & ns)
353 {
354         xmlpp::Element* signer = parent->add_child("Signer");
355
356         {
357                 xmlpp::Element* data = signer->add_child("X509Data", ns);
358                 
359                 {
360                         xmlpp::Element* serial_element = data->add_child("X509IssuerSerial", ns);
361                         serial_element->add_child("X509IssuerName", ns)->add_child_text (certificates.leaf()->issuer());
362                         serial_element->add_child("X509SerialNumber", ns)->add_child_text (certificates.leaf()->serial());
363                 }
364                 
365                 data->add_child("X509SubjectName", ns)->add_child_text (certificates.leaf()->subject());
366         }
367 }
368
369 void
370 libdcp::sign (xmlpp::Element* parent, CertificateChain const & certificates, string const & signer_key)
371 {
372         add_signer (parent, certificates, "dsig");
373
374         xmlpp::Element* signature = parent->add_child("Signature", "dsig");
375         
376         {
377                 xmlpp::Element* signed_info = signature->add_child ("SignedInfo", "dsig");
378                 signed_info->add_child("CanonicalizationMethod", "dsig")->set_attribute ("Algorithm", "http://www.w3.org/TR/2001/REC-xml-c14n-20010315");
379                 signed_info->add_child("SignatureMethod", "dsig")->set_attribute("Algorithm", "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
380                 {
381                         xmlpp::Element* reference = signed_info->add_child("Reference", "dsig");
382                         reference->set_attribute ("URI", "");
383                         {
384                                 xmlpp::Element* transforms = reference->add_child("Transforms", "dsig");
385                                 transforms->add_child("Transform", "dsig")->set_attribute (
386                                         "Algorithm", "http://www.w3.org/2000/09/xmldsig#enveloped-signature"
387                                         );
388                         }
389                         reference->add_child("DigestMethod", "dsig")->set_attribute("Algorithm", "http://www.w3.org/2000/09/xmldsig#sha1");
390                         /* This will be filled in by the signing later */
391                         reference->add_child("DigestValue", "dsig");
392                 }
393         }
394         
395         add_signature_value (signature, certificates, signer_key, "dsig");
396 }
397
398 bool libdcp::operator== (libdcp::Size const & a, libdcp::Size const & b)
399 {
400         return (a.width == b.width && a.height == b.height);
401 }
402
403 bool libdcp::operator!= (libdcp::Size const & a, libdcp::Size const & b)
404 {
405         return !(a == b);
406 }
407
408 /** The base64 decode routine in KM_util.cpp gives different values to both
409  *  this and the command-line base64 for some inputs.  Not sure why.
410  */
411 int
412 libdcp::base64_decode (string const & in, unsigned char* out, int out_length)
413 {
414         BIO* b64 = BIO_new (BIO_f_base64 ());
415
416         /* This means the input should have no newlines */
417         BIO_set_flags (b64, BIO_FLAGS_BASE64_NO_NL);
418
419         /* Copy our input string, removing newlines */
420         char in_buffer[in.size() + 1];
421         char* p = in_buffer;
422         for (size_t i = 0; i < in.size(); ++i) {
423                 if (in[i] != '\n' && in[i] != '\r') {
424                         *p++ = in[i];
425                 }
426         }
427                 
428         BIO* bmem = BIO_new_mem_buf (in_buffer, p - in_buffer);
429         bmem = BIO_push (b64, bmem);
430         int const N = BIO_read (bmem, out, out_length);
431         BIO_free_all (bmem);
432
433         return N;
434 }