Merge master
[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 <openssl/sha.h>
30 #include <libxml++/nodes/element.h>
31 #include <libxml++/document.h>
32 #include <xmlsec/xmldsig.h>
33 #include <xmlsec/dl.h>
34 #include <xmlsec/app.h>
35 #include "KM_util.h"
36 #include "KM_fileio.h"
37 #include "AS_DCP.h"
38 #include "util.h"
39 #include "exceptions.h"
40 #include "types.h"
41 #include "argb_frame.h"
42 #include "lut.h"
43 #include "certificates.h"
44
45 using std::string;
46 using std::cout;
47 using std::stringstream;
48 using std::min;
49 using std::max;
50 using std::list;
51 using boost::shared_ptr;
52 using namespace libdcp;
53
54 /** Create a UUID.
55  *  @return UUID.
56  */
57 string
58 libdcp::make_uuid ()
59 {
60         char buffer[64];
61         Kumu::UUID id;
62         Kumu::GenRandomValue (id);
63         id.EncodeHex (buffer, 64);
64         return string (buffer);
65 }
66
67
68 /** Create a digest for a file.
69  *  @param filename File name.
70  *  @return Digest.
71  */
72 string
73 libdcp::make_digest (string filename)
74 {
75         Kumu::FileReader reader;
76         if (ASDCP_FAILURE (reader.OpenRead (filename.c_str ()))) {
77                 throw FileError ("could not open file to compute digest", filename);
78         }
79         
80         SHA_CTX sha;
81         SHA1_Init (&sha);
82         
83         Kumu::ByteString read_buffer (65536);
84         int done = 0;
85         while (1) {
86                 ui32_t read = 0;
87                 Kumu::Result_t r = reader.Read (read_buffer.Data(), read_buffer.Capacity(), &read);
88                 
89                 if (r == Kumu::RESULT_ENDOFFILE) {
90                         break;
91                 } else if (ASDCP_FAILURE (r)) {
92                         throw FileError ("could not read file to compute digest", filename);
93                 }
94                 
95                 SHA1_Update (&sha, read_buffer.Data(), read);
96                 done += read;
97         }
98
99         byte_t byte_buffer[20];
100         SHA1_Final (byte_buffer, &sha);
101
102         char digest[64];
103         return Kumu::base64encode (byte_buffer, 20, digest, 64);
104 }
105
106 /** Convert a content kind to a string which can be used in a
107  *  <ContentKind> node.
108  *  @param kind ContentKind.
109  *  @return string.
110  */
111 string
112 libdcp::content_kind_to_string (ContentKind kind)
113 {
114         switch (kind) {
115         case FEATURE:
116                 return "feature";
117         case SHORT:
118                 return "short";
119         case TRAILER:
120                 return "trailer";
121         case TEST:
122                 return "test";
123         case TRANSITIONAL:
124                 return "transitional";
125         case RATING:
126                 return "rating";
127         case TEASER:
128                 return "teaser";
129         case POLICY:
130                 return "policy";
131         case PUBLIC_SERVICE_ANNOUNCEMENT:
132                 return "psa";
133         case ADVERTISEMENT:
134                 return "advertisement";
135         }
136
137         assert (false);
138 }
139
140 /** Convert a string from a <ContentKind> node to a libdcp ContentKind.
141  *  Reasonably tolerant about varying case.
142  *  @param type Content kind string.
143  *  @return libdcp ContentKind.
144  */
145 libdcp::ContentKind
146 libdcp::content_kind_from_string (string type)
147 {
148         /* XXX: should probably just convert type to lower-case and have done with it */
149         
150         if (type == "feature") {
151                 return FEATURE;
152         } else if (type == "short") {
153                 return SHORT;
154         } else if (type == "trailer" || type == "Trailer") {
155                 return TRAILER;
156         } else if (type == "test") {
157                 return TEST;
158         } else if (type == "transitional") {
159                 return TRANSITIONAL;
160         } else if (type == "rating") {
161                 return RATING;
162         } else if (type == "teaser" || type == "Teaser") {
163                 return TEASER;
164         } else if (type == "policy") {
165                 return POLICY;
166         } else if (type == "psa") {
167                 return PUBLIC_SERVICE_ANNOUNCEMENT;
168         } else if (type == "advertisement") {
169                 return ADVERTISEMENT;
170         }
171
172         assert (false);
173 }
174
175 /** Decompress a JPEG2000 image to a bitmap.
176  *  @param data JPEG2000 data.
177  *  @param size Size of data in bytes.
178  *  @param reduce A power of 2 by which to reduce the size of the decoded image;
179  *  e.g. 0 reduces by (2^0 == 1), ie keeping the same size.
180  *       1 reduces by (2^1 == 2), ie halving the size of the image.
181  *  This is useful for scaling 4K DCP images down to 2K.
182  *  @return openjpeg image, which the caller must call opj_image_destroy() on.
183  */
184 opj_image_t *
185 libdcp::decompress_j2k (uint8_t* data, int64_t size, int reduce)
186 {
187         opj_dinfo_t* decoder = opj_create_decompress (CODEC_J2K);
188         opj_dparameters_t parameters;
189         opj_set_default_decoder_parameters (&parameters);
190         parameters.cp_reduce = reduce;
191         opj_setup_decoder (decoder, &parameters);
192         opj_cio_t* cio = opj_cio_open ((opj_common_ptr) decoder, data, size);
193         opj_image_t* image = opj_decode (decoder, cio);
194         if (!image) {
195                 opj_destroy_decompress (decoder);
196                 opj_cio_close (cio);
197                 throw DCPReadError ("could not decode JPEG2000 codestream");
198         }
199
200         opj_cio_close (cio);
201
202         image->x1 = rint (float(image->x1) / pow (2, reduce));
203         image->y1 = rint (float(image->y1) / pow (2, reduce));
204         return image;
205 }
206
207 /** Convert an openjpeg XYZ image to RGB.
208  *  @param xyz_frame Frame in XYZ.
209  *  @return RGB image.
210  */
211 shared_ptr<ARGBFrame>
212 libdcp::xyz_to_rgb (opj_image_t* xyz_frame)
213 {
214         struct {
215                 double x, y, z;
216         } s;
217         
218         struct {
219                 double r, g, b;
220         } d;
221         
222         int* xyz_x = xyz_frame->comps[0].data;
223         int* xyz_y = xyz_frame->comps[1].data;
224         int* xyz_z = xyz_frame->comps[2].data;
225
226         shared_ptr<ARGBFrame> argb_frame (new ARGBFrame (xyz_frame->x1, xyz_frame->y1));
227
228         uint8_t* argb = argb_frame->data ();
229         
230         for (int y = 0; y < xyz_frame->y1; ++y) {
231                 uint8_t* argb_line = argb;
232                 for (int x = 0; x < xyz_frame->x1; ++x) {
233
234                         assert (*xyz_x >= 0 && *xyz_y >= 0 && *xyz_z >= 0 && *xyz_x < 4096 && *xyz_x < 4096 && *xyz_z < 4096);
235                         
236                         /* In gamma LUT */
237                         s.x = lut_in[*xyz_x++];
238                         s.y = lut_in[*xyz_y++];
239                         s.z = lut_in[*xyz_z++];
240                         
241                         /* DCI companding */
242                         s.x /= DCI_COEFFICIENT;
243                         s.y /= DCI_COEFFICIENT;
244                         s.z /= DCI_COEFFICIENT;
245                         
246                         /* XYZ to RGB */
247                         d.r = ((s.x * color_matrix[0][0]) + (s.y * color_matrix[0][1]) + (s.z * color_matrix[0][2]));
248                         d.g = ((s.x * color_matrix[1][0]) + (s.y * color_matrix[1][1]) + (s.z * color_matrix[1][2]));
249                         d.b = ((s.x * color_matrix[2][0]) + (s.y * color_matrix[2][1]) + (s.z * color_matrix[2][2]));
250                         
251                         d.r = min (d.r, 1.0);
252                         d.r = max (d.r, 0.0);
253                         
254                         d.g = min (d.g, 1.0);
255                         d.g = max (d.g, 0.0);
256                         
257                         d.b = min (d.b, 1.0);
258                         d.b = max (d.b, 0.0);
259                         
260                         /* Out gamma LUT */
261                         *argb_line++ = lut_out[(int) (d.b * COLOR_DEPTH)];
262                         *argb_line++ = lut_out[(int) (d.g * COLOR_DEPTH)];
263                         *argb_line++ = lut_out[(int) (d.r * COLOR_DEPTH)];
264                         *argb_line++ = 0xff;
265                 }
266                 
267                 argb += argb_frame->stride ();
268         }
269
270         return argb_frame;
271 }
272
273 /** @param s A string.
274  *  @return true if the string contains only space, newline or tab characters, or is empty.
275  */
276 bool
277 libdcp::empty_or_white_space (string s)
278 {
279         for (size_t i = 0; i < s.length(); ++i) {
280                 if (s[i] != ' ' && s[i] != '\n' && s[i] != '\t') {
281                         return false;
282                 }
283         }
284
285         return true;
286 }
287
288 void
289 libdcp::init ()
290 {
291         if (xmlSecInit() < 0) {
292                 throw MiscError ("could not initialise xmlsec");
293         }
294
295 #ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
296         if (xmlSecCryptoDLLoadLibrary (BAD_CAST XMLSEC_CRYPTO) < 0) {
297                 throw MiscError ("unable to load default xmlsec-crypto library");
298         }
299 #endif
300         
301         if (xmlSecCryptoAppInit (0) < 0) {
302                 throw MiscError ("could not initialise crypto library");
303         }
304         
305         if (xmlSecCryptoInit() < 0) {
306                 throw MiscError ("could not initialise xmlsec-crypto");
307         }
308 }
309
310 void
311 libdcp::add_signature_value (xmlpp::Element* parent, CertificateChain const & certificates, string const & signer_key, string const & ns)
312 {
313         parent->add_child("SignatureValue", ns);
314         
315         xmlpp::Element* key_info = parent->add_child("KeyInfo", ns);
316         list<shared_ptr<Certificate> > c = certificates.leaf_to_root ();
317         for (list<shared_ptr<Certificate> >::iterator i = c.begin(); i != c.end(); ++i) {
318                 xmlpp::Element* data = key_info->add_child("X509Data", ns);
319                 
320                 {
321                         xmlpp::Element* serial = data->add_child("X509IssuerSerial", ns);
322                         serial->add_child("X509IssuerName", ns)->add_child_text(
323                                 Certificate::name_for_xml ((*i)->issuer())
324                                 );
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         if (xmlSecCryptoAppDefaultKeysMngrInit (keys_manager) < 0) {
336                 throw MiscError ("could not initialise keys manager");
337         }
338         
339         xmlSecKeyPtr const key = xmlSecCryptoAppKeyLoad (signer_key.c_str(), xmlSecKeyDataFormatPem, 0, 0, 0);
340         if (key == 0) {
341                 throw MiscError ("could not load signer key");
342                 }
343         
344         if (xmlSecCryptoAppDefaultKeysMngrAdoptKey (keys_manager, key) < 0) {
345                 xmlSecKeyDestroy (key);
346                 throw MiscError ("could not use signer key");
347         }
348         
349         xmlSecDSigCtx signature_context;
350         
351         if (xmlSecDSigCtxInitialize (&signature_context, keys_manager) < 0) {
352                 throw MiscError ("could not initialise XMLSEC context");
353         }
354         
355         if (xmlSecDSigCtxSign (&signature_context, parent->cobj()) < 0) {
356                 throw MiscError ("could not sign");
357         }
358         
359         xmlSecDSigCtxFinalize (&signature_context);
360         xmlSecKeysMngrDestroy (keys_manager);
361 }
362
363
364 void
365 libdcp::add_signer (xmlpp::Element* parent, CertificateChain const & certificates, string const & ns)
366 {
367         xmlpp::Element* signer = parent->add_child("Signer");
368
369         {
370                 xmlpp::Element* data = signer->add_child("X509Data", ns);
371                 
372                 {
373                         xmlpp::Element* serial_element = data->add_child("X509IssuerSerial", ns);
374                         serial_element->add_child("X509IssuerName", ns)->add_child_text (
375                                 Certificate::name_for_xml (certificates.leaf()->issuer())
376                                 );
377                         serial_element->add_child("X509SerialNumber", ns)->add_child_text (
378                                 certificates.leaf()->serial()
379                                 );
380                 }
381                 
382                 data->add_child("X509SubjectName", ns)->add_child_text (Certificate::name_for_xml (certificates.leaf()->subject()));
383         }
384 }
385
386 void
387 libdcp::sign (xmlpp::Element* parent, CertificateChain const & certificates, string const & signer_key)
388 {
389         add_signer (parent, certificates, "dsig");
390
391         xmlpp::Element* signature = parent->add_child("Signature", "dsig");
392         
393         {
394                 xmlpp::Element* signed_info = signature->add_child ("SignedInfo", "dsig");
395                 signed_info->add_child("CanonicalizationMethod", "dsig")->set_attribute ("Algorithm", "http://www.w3.org/TR/2001/REC-xml-c14n-20010315");
396                 signed_info->add_child("SignatureMethod", "dsig")->set_attribute("Algorithm", "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
397                 {
398                         xmlpp::Element* reference = signed_info->add_child("Reference", "dsig");
399                         reference->set_attribute ("URI", "");
400                         {
401                                 xmlpp::Element* transforms = reference->add_child("Transforms", "dsig");
402                                 transforms->add_child("Transform", "dsig")->set_attribute (
403                                         "Algorithm", "http://www.w3.org/2000/09/xmldsig#enveloped-signature"
404                                         );
405                         }
406                         reference->add_child("DigestMethod", "dsig")->set_attribute("Algorithm", "http://www.w3.org/2000/09/xmldsig#sha1");
407                         /* This will be filled in by the signing later */
408                         reference->add_child("DigestValue", "dsig");
409                 }
410         }
411         
412         add_signature_value (signature, certificates, signer_key, "dsig");
413 }
414