Import.
[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 #include <stdexcept>
21 #include <sstream>
22 #include <iomanip>
23 #include <openssl/sha.h>
24 #include "KM_util.h"
25 #include "KM_fileio.h"
26 #include "AS_DCP.h"
27 #include "util.h"
28
29 using namespace std;
30
31 bool libdcp::libdcp_test = false;
32
33 /** Create a UUID.
34  *  @return UUID.
35  */
36 string
37 libdcp::make_uuid ()
38 {
39         char buffer[64];
40         Kumu::UUID id;
41
42         if (libdcp_test) {
43                 static int N = 0;
44                 byte_t t[16];
45                 for (int i = 0; i < 16; ++i) {
46                         t[i] = N;
47                 }
48                 ++N;
49                 
50                 id = Kumu::UUID (t);
51         } else {
52                 Kumu::GenRandomValue (id);
53         }
54         
55         id.EncodeHex (buffer, 64);
56         return string (buffer);
57 }
58
59 /** Create a digest for a file.
60  *  @param filename File name.
61  *  @return Digest.
62  */
63 string
64 libdcp::make_digest (string filename)
65 {
66         Kumu::FileReader reader;
67         if (ASDCP_FAILURE (reader.OpenRead (filename.c_str ()))) {
68                 throw runtime_error ("could not open file to compute digest");
69         }
70         
71         SHA_CTX sha;
72         SHA1_Init (&sha);
73         
74         Kumu::ByteString read_buffer (65536);
75         while (1) {
76                 ui32_t read = 0;
77                 Kumu::Result_t r = reader.Read (read_buffer.Data(), read_buffer.Capacity(), &read);
78                 
79                 if (r == Kumu::RESULT_ENDOFFILE) {
80                         break;
81                 } else if (ASDCP_FAILURE (r)) {
82                         throw runtime_error ("could not read file to compute digest");
83                 }
84                 
85                 SHA1_Update (&sha, read_buffer.Data(), read);
86         }
87
88         byte_t byte_buffer[20];
89         SHA1_Final (byte_buffer, &sha);
90
91         stringstream s;
92         char digest[64];
93         s << setfill('0') << setw(36) << Kumu::base64encode (byte_buffer, 20, digest, 64);
94         return s.str ();
95 }