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