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