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