Create a dcp::Signer in Config even when there is no existing file.
[dcpomatic.git] / src / lib / config.cc
1 /*
2     Copyright (C) 2012-2014 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 <cstdlib>
21 #include <fstream>
22 #include <glib.h>
23 #include <boost/filesystem.hpp>
24 #include <boost/algorithm/string.hpp>
25 #include <dcp/colour_matrix.h>
26 #include <dcp/raw_convert.h>
27 #include <dcp/signer.h>
28 #include <dcp/certificate_chain.h>
29 #include <libcxml/cxml.h>
30 #include "config.h"
31 #include "server.h"
32 #include "scaler.h"
33 #include "filter.h"
34 #include "ratio.h"
35 #include "dcp_content_type.h"
36 #include "cinema_sound_processor.h"
37 #include "colour_conversion.h"
38 #include "cinema.h"
39 #include "util.h"
40 #include "cross.h"
41
42 #include "i18n.h"
43
44 using std::vector;
45 using std::ifstream;
46 using std::string;
47 using std::list;
48 using std::max;
49 using std::exception;
50 using std::cerr;
51 using boost::shared_ptr;
52 using boost::optional;
53 using boost::algorithm::is_any_of;
54 using boost::algorithm::split;
55 using dcp::raw_convert;
56
57 Config* Config::_instance = 0;
58
59 /** Construct default configuration */
60 Config::Config ()
61         : _num_local_encoding_threads (max (2U, boost::thread::hardware_concurrency()))
62         , _server_port_base (6192)
63         , _use_any_servers (true)
64         , _tms_path (".")
65         , _cinema_sound_processor (CinemaSoundProcessor::from_id (N_("dolby_cp750")))
66         , _allow_any_dcp_frame_rate (false)
67         , _default_still_length (10)
68         , _default_scale (Ratio::from_id ("185"))
69         , _default_container (Ratio::from_id ("185"))
70         , _default_dcp_content_type (DCPContentType::from_isdcf_name ("TST"))
71         , _default_j2k_bandwidth (100000000)
72         , _default_audio_delay (0)
73         , _check_for_updates (false)
74         , _check_for_test_updates (false)
75         , _maximum_j2k_bandwidth (250000000)
76         , _log_types (Log::TYPE_GENERAL | Log::TYPE_WARNING | Log::TYPE_ERROR)
77 {
78         _allowed_dcp_frame_rates.push_back (24);
79         _allowed_dcp_frame_rates.push_back (25);
80         _allowed_dcp_frame_rates.push_back (30);
81         _allowed_dcp_frame_rates.push_back (48);
82         _allowed_dcp_frame_rates.push_back (50);
83         _allowed_dcp_frame_rates.push_back (60);
84
85         _colour_conversions.push_back (PresetColourConversion (_("sRGB"), 2.4, true, dcp::colour_matrix::srgb_to_xyz, 2.6));
86         _colour_conversions.push_back (PresetColourConversion (_("sRGB non-linearised"), 2.4, false, dcp::colour_matrix::srgb_to_xyz, 2.6));
87         _colour_conversions.push_back (PresetColourConversion (_("Rec. 709"), 2.2, false, dcp::colour_matrix::rec709_to_xyz, 2.6));
88
89         reset_kdm_email ();
90 }
91
92 void
93 Config::read ()
94 {
95         if (!boost::filesystem::exists (file (false))) {
96                 /* Make a new set of signing certificates and key */
97                 _signer.reset (new dcp::Signer (openssl_path ()));
98                 return;
99         }
100
101         cxml::Document f ("Config");
102         f.read_file (file (false));
103         optional<string> c;
104
105         optional<int> version = f.optional_number_child<int> ("Version");
106
107         _num_local_encoding_threads = f.number_child<int> ("NumLocalEncodingThreads");
108         _default_directory = f.string_child ("DefaultDirectory");
109
110         boost::optional<int> b = f.optional_number_child<int> ("ServerPort");
111         if (!b) {
112                 b = f.optional_number_child<int> ("ServerPortBase");
113         }
114         _server_port_base = b.get ();
115
116         boost::optional<bool> u = f.optional_bool_child ("UseAnyServers");
117         _use_any_servers = u.get_value_or (true);
118
119         list<cxml::NodePtr> servers = f.node_children ("Server");
120         for (list<cxml::NodePtr>::iterator i = servers.begin(); i != servers.end(); ++i) {
121                 if ((*i)->node_children("HostName").size() == 1) {
122                         _servers.push_back ((*i)->string_child ("HostName"));
123                 } else {
124                         _servers.push_back ((*i)->content ());
125                 }
126         }
127         
128         _tms_ip = f.string_child ("TMSIP");
129         _tms_path = f.string_child ("TMSPath");
130         _tms_user = f.string_child ("TMSUser");
131         _tms_password = f.string_child ("TMSPassword");
132
133         c = f.optional_string_child ("SoundProcessor");
134         if (c) {
135                 _cinema_sound_processor = CinemaSoundProcessor::from_id (c.get ());
136         }
137         c = f.optional_string_child ("CinemaSoundProcessor");
138         if (c) {
139                 _cinema_sound_processor = CinemaSoundProcessor::from_id (c.get ());
140         }
141
142         _language = f.optional_string_child ("Language");
143
144         c = f.optional_string_child ("DefaultScale");
145         if (c) {
146                 _default_scale = Ratio::from_id (c.get ());
147         }
148
149         c = f.optional_string_child ("DefaultContainer");
150         if (c) {
151                 _default_container = Ratio::from_id (c.get ());
152         }
153
154         c = f.optional_string_child ("DefaultDCPContentType");
155         if (c) {
156                 _default_dcp_content_type = DCPContentType::from_isdcf_name (c.get ());
157         }
158
159         _dcp_metadata.issuer = f.optional_string_child ("DCPMetadataIssuer").get_value_or ("");
160         _dcp_metadata.creator = f.optional_string_child ("DCPMetadataCreator").get_value_or ("");
161
162         if (version && version.get() >= 2) {
163                 _default_isdcf_metadata = ISDCFMetadata (f.node_child ("ISDCFMetadata"));
164         } else {
165                 _default_isdcf_metadata = ISDCFMetadata (f.node_child ("DCIMetadata"));
166         }
167         
168         _default_still_length = f.optional_number_child<int>("DefaultStillLength").get_value_or (10);
169         _default_j2k_bandwidth = f.optional_number_child<int>("DefaultJ2KBandwidth").get_value_or (200000000);
170         _default_audio_delay = f.optional_number_child<int>("DefaultAudioDelay").get_value_or (0);
171
172         list<cxml::NodePtr> cc = f.node_children ("ColourConversion");
173
174         if (!cc.empty ()) {
175                 _colour_conversions.clear ();
176         }
177         
178         for (list<cxml::NodePtr>::iterator i = cc.begin(); i != cc.end(); ++i) {
179                 _colour_conversions.push_back (PresetColourConversion (*i));
180         }
181
182         if (!version) {
183                 /* Loading version 0 (before Rec. 709 was added as a preset).
184                    Add it in.
185                 */
186                 _colour_conversions.push_back (PresetColourConversion (_("Rec. 709"), 2.2, false, dcp::colour_matrix::rec709_to_xyz, 2.6));
187         }
188
189         list<cxml::NodePtr> cin = f.node_children ("Cinema");
190         for (list<cxml::NodePtr>::iterator i = cin.begin(); i != cin.end(); ++i) {
191                 /* Slightly grotty two-part construction of Cinema here so that we can use
192                    shared_from_this.
193                 */
194                 shared_ptr<Cinema> cinema (new Cinema (*i));
195                 cinema->read_screens (*i);
196                 _cinemas.push_back (cinema);
197         }
198
199         _mail_server = f.string_child ("MailServer");
200         _mail_user = f.optional_string_child("MailUser").get_value_or ("");
201         _mail_password = f.optional_string_child("MailPassword").get_value_or ("");
202         _kdm_subject = f.optional_string_child ("KDMSubject").get_value_or (_("KDM delivery: $CPL_NAME"));
203         _kdm_from = f.string_child ("KDMFrom");
204         _kdm_cc = f.optional_string_child ("KDMCC").get_value_or ("");
205         _kdm_bcc = f.optional_string_child ("KDMBCC").get_value_or ("");
206         _kdm_email = f.string_child ("KDMEmail");
207
208         _check_for_updates = f.optional_bool_child("CheckForUpdates").get_value_or (false);
209         _check_for_test_updates = f.optional_bool_child("CheckForTestUpdates").get_value_or (false);
210
211         _maximum_j2k_bandwidth = f.optional_number_child<int> ("MaximumJ2KBandwidth").get_value_or (250000000);
212         _allow_any_dcp_frame_rate = f.optional_bool_child ("AllowAnyDCPFrameRate");
213
214         _log_types = f.optional_number_child<int> ("LogTypes").get_value_or (Log::TYPE_GENERAL | Log::TYPE_WARNING | Log::TYPE_ERROR);
215
216         cxml::NodePtr signer = f.optional_node_child ("Signer");
217         dcp::CertificateChain signer_chain;
218         if (signer) {
219                 /* Read the signing certificates and private key in from the config file */
220                 list<cxml::NodePtr> certificates = signer->node_children ("Certificate");
221                 for (list<cxml::NodePtr>::const_iterator i = certificates.begin(); i != certificates.end(); ++i) {
222                         signer_chain.add (dcp::Certificate ((*i)->content ()));
223                 }
224
225                 _signer.reset (new dcp::Signer (signer_chain, signer->string_child ("PrivateKey")));
226         } else {
227                 /* Make a new set of signing certificates and key */
228                 _signer.reset (new dcp::Signer (openssl_path ()));
229         }
230
231         if (f.optional_string_child ("DecryptionCertificate")) {
232                 _decryption_certificate = dcp::Certificate (f.string_child ("DecryptionCertificate"));
233         }
234
235         if (f.optional_string_child ("DecryptionPrivateKey")) {
236                 _decryption_private_key = f.string_child ("DecryptionPrivateKey");
237         }
238
239         if (!f.optional_string_child ("DecryptionCertificate") || !f.optional_string_child ("DecryptionPrivateKey")) {
240                 /* Generate our own decryption certificate and key if either is not present in config */
241                 boost::filesystem::path p = dcp::make_certificate_chain (openssl_path ());
242                 _decryption_certificate = dcp::Certificate (dcp::file_to_string (p / "leaf.signed.pem"));
243                 _decryption_private_key = dcp::file_to_string (p / "leaf.key");
244                 boost::filesystem::remove_all (p);
245         }
246 }
247
248 /** @return Filename to write configuration to */
249 boost::filesystem::path
250 Config::file (bool old) const
251 {
252         boost::filesystem::path p;
253         p /= g_get_user_config_dir ();
254         boost::system::error_code ec;
255         boost::filesystem::create_directory (p, ec);
256         if (old) {
257                 p /= ".dvdomatic";
258         } else {
259                 p /= "dcpomatic";
260                 boost::filesystem::create_directory (p, ec);
261                 p /= "config.xml";
262         }
263         return p;
264 }
265
266 /** @return Singleton instance */
267 Config *
268 Config::instance ()
269 {
270         if (_instance == 0) {
271                 _instance = new Config;
272                 try {
273                         _instance->read ();
274                 } catch (exception& e) {
275                         /* configuration load failed; never mind, just
276                            stick with the default.
277                         */
278                         cerr << "dcpomatic: failed to load configuration (" << e.what() << ")\n";
279                 } catch (...) {
280                         cerr << "dcpomatic: failed to load configuration\n";
281                 }
282         }
283
284         return _instance;
285 }
286
287 /** Write our configuration to disk */
288 void
289 Config::write () const
290 {
291         xmlpp::Document doc;
292         xmlpp::Element* root = doc.create_root_node ("Config");
293
294         root->add_child("Version")->add_child_text ("2");
295         root->add_child("NumLocalEncodingThreads")->add_child_text (raw_convert<string> (_num_local_encoding_threads));
296         root->add_child("DefaultDirectory")->add_child_text (_default_directory.string ());
297         root->add_child("ServerPortBase")->add_child_text (raw_convert<string> (_server_port_base));
298         root->add_child("UseAnyServers")->add_child_text (_use_any_servers ? "1" : "0");
299         
300         for (vector<string>::const_iterator i = _servers.begin(); i != _servers.end(); ++i) {
301                 root->add_child("Server")->add_child_text (*i);
302         }
303
304         root->add_child("TMSIP")->add_child_text (_tms_ip);
305         root->add_child("TMSPath")->add_child_text (_tms_path);
306         root->add_child("TMSUser")->add_child_text (_tms_user);
307         root->add_child("TMSPassword")->add_child_text (_tms_password);
308         if (_cinema_sound_processor) {
309                 root->add_child("CinemaSoundProcessor")->add_child_text (_cinema_sound_processor->id ());
310         }
311         if (_language) {
312                 root->add_child("Language")->add_child_text (_language.get());
313         }
314         if (_default_scale) {
315                 root->add_child("DefaultScale")->add_child_text (_default_scale->id ());
316         }
317         if (_default_container) {
318                 root->add_child("DefaultContainer")->add_child_text (_default_container->id ());
319         }
320         if (_default_dcp_content_type) {
321                 root->add_child("DefaultDCPContentType")->add_child_text (_default_dcp_content_type->isdcf_name ());
322         }
323         root->add_child("DCPMetadataIssuer")->add_child_text (_dcp_metadata.issuer);
324         root->add_child("DCPMetadataCreator")->add_child_text (_dcp_metadata.creator);
325
326         _default_isdcf_metadata.as_xml (root->add_child ("ISDCFMetadata"));
327
328         root->add_child("DefaultStillLength")->add_child_text (raw_convert<string> (_default_still_length));
329         root->add_child("DefaultJ2KBandwidth")->add_child_text (raw_convert<string> (_default_j2k_bandwidth));
330         root->add_child("DefaultAudioDelay")->add_child_text (raw_convert<string> (_default_audio_delay));
331
332         for (vector<PresetColourConversion>::const_iterator i = _colour_conversions.begin(); i != _colour_conversions.end(); ++i) {
333                 i->as_xml (root->add_child ("ColourConversion"));
334         }
335
336         for (list<shared_ptr<Cinema> >::const_iterator i = _cinemas.begin(); i != _cinemas.end(); ++i) {
337                 (*i)->as_xml (root->add_child ("Cinema"));
338         }
339
340         root->add_child("MailServer")->add_child_text (_mail_server);
341         root->add_child("MailUser")->add_child_text (_mail_user);
342         root->add_child("MailPassword")->add_child_text (_mail_password);
343         root->add_child("KDMSubject")->add_child_text (_kdm_subject);
344         root->add_child("KDMFrom")->add_child_text (_kdm_from);
345         root->add_child("KDMCC")->add_child_text (_kdm_cc);
346         root->add_child("KDMBCC")->add_child_text (_kdm_bcc);
347         root->add_child("KDMEmail")->add_child_text (_kdm_email);
348
349         root->add_child("CheckForUpdates")->add_child_text (_check_for_updates ? "1" : "0");
350         root->add_child("CheckForTestUpdates")->add_child_text (_check_for_test_updates ? "1" : "0");
351
352         root->add_child("MaximumJ2KBandwidth")->add_child_text (raw_convert<string> (_maximum_j2k_bandwidth));
353         root->add_child("AllowAnyDCPFrameRate")->add_child_text (_allow_any_dcp_frame_rate ? "1" : "0");
354         root->add_child("LogTypes")->add_child_text (raw_convert<string> (_log_types));
355
356         xmlpp::Element* signer = root->add_child ("Signer");
357         dcp::CertificateChain::List certs = _signer->certificates().root_to_leaf ();
358         for (dcp::CertificateChain::List::const_iterator i = certs.begin(); i != certs.end(); ++i) {
359                 signer->add_child("Certificate")->add_child_text (i->certificate (true));
360         }
361         signer->add_child("PrivateKey")->add_child_text (_signer->key ());
362
363         root->add_child("DecryptionCertificate")->add_child_text (_decryption_certificate.certificate (true));
364         root->add_child("DecryptionPrivateKey")->add_child_text (_decryption_private_key);
365
366         doc.write_to_file_formatted (file(false).string ());
367 }
368
369 boost::filesystem::path
370 Config::default_directory_or (boost::filesystem::path a) const
371 {
372         if (_default_directory.empty()) {
373                 return a;
374         }
375
376         boost::system::error_code ec;
377         bool const e = boost::filesystem::exists (_default_directory, ec);
378         if (ec || !e) {
379                 return a;
380         }
381
382         return _default_directory;
383 }
384
385 void
386 Config::drop ()
387 {
388         delete _instance;
389         _instance = 0;
390 }
391
392 void
393 Config::changed ()
394 {
395         write ();
396         Changed ();
397 }
398
399 void
400 Config::reset_kdm_email ()
401 {
402         _kdm_email = _(
403                 "Dear Projectionist\n\n"
404                 "Please find attached KDMs for $CPL_NAME.\n\n"
405                 "Cinema: $CINEMA_NAME\n"
406                 "Screen(s): $SCREENS\n\n"
407                 "The KDMs are valid from $START_TIME until $END_TIME.\n\n"
408                 "Best regards,\nDCP-o-matic"
409                 );
410 }