Add some assertion checks to config_write.
[dcpomatic.git] / src / lib / config.cc
1 /*
2     Copyright (C) 2012-2016 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 "config.h"
21 #include "filter.h"
22 #include "ratio.h"
23 #include "types.h"
24 #include "log.h"
25 #include "dcp_content_type.h"
26 #include "cinema_sound_processor.h"
27 #include "colour_conversion.h"
28 #include "cinema.h"
29 #include "util.h"
30 #include "cross.h"
31 #include "raw_convert.h"
32 #include <dcp/colour_matrix.h>
33 #include <dcp/certificate_chain.h>
34 #include <libcxml/cxml.h>
35 #include <glib.h>
36 #include <libxml++/libxml++.h>
37 #include <boost/filesystem.hpp>
38 #include <boost/algorithm/string.hpp>
39 #include <boost/foreach.hpp>
40 #include <boost/thread.hpp>
41 #include <cstdlib>
42 #include <fstream>
43 #include <iostream>
44
45 #include "i18n.h"
46
47 using std::vector;
48 using std::cout;
49 using std::ifstream;
50 using std::string;
51 using std::list;
52 using std::max;
53 using std::remove;
54 using std::exception;
55 using std::cerr;
56 using boost::shared_ptr;
57 using boost::optional;
58 using boost::algorithm::trim;
59
60 Config* Config::_instance = 0;
61
62 /** Construct default configuration */
63 Config::Config ()
64 {
65         set_defaults ();
66 }
67
68 void
69 Config::set_defaults ()
70 {
71         _num_local_encoding_threads = max (2U, boost::thread::hardware_concurrency ());
72         _server_port_base = 6192;
73         _use_any_servers = true;
74         _servers.clear ();
75         _only_servers_encode = false;
76         _tms_protocol = PROTOCOL_SCP;
77         _tms_ip = "";
78         _tms_path = ".";
79         _tms_user = "";
80         _tms_password = "";
81         _cinema_sound_processor = CinemaSoundProcessor::from_id (N_("dolby_cp750"));
82         _allow_any_dcp_frame_rate = false;
83         _language = optional<string> ();
84         _default_still_length = 10;
85         _default_container = Ratio::from_id ("185");
86         _default_dcp_content_type = DCPContentType::from_isdcf_name ("FTR");
87         _default_j2k_bandwidth = 100000000;
88         _default_audio_delay = 0;
89         _default_interop = false;
90         _mail_server = "";
91         _mail_port = 25;
92         _mail_user = "";
93         _mail_password = "";
94         _kdm_from = "";
95         _kdm_cc.clear ();
96         _kdm_bcc = "";
97         _check_for_updates = false;
98         _check_for_test_updates = false;
99         _maximum_j2k_bandwidth = 250000000;
100         _log_types = LogEntry::TYPE_GENERAL | LogEntry::TYPE_WARNING | LogEntry::TYPE_ERROR;
101         _automatic_audio_analysis = false;
102 #ifdef DCPOMATIC_WINDOWS
103         _win32_console = false;
104 #endif
105         _cinemas_file = path ("cinemas.xml");
106
107         _allowed_dcp_frame_rates.clear ();
108         _allowed_dcp_frame_rates.push_back (24);
109         _allowed_dcp_frame_rates.push_back (25);
110         _allowed_dcp_frame_rates.push_back (30);
111         _allowed_dcp_frame_rates.push_back (48);
112         _allowed_dcp_frame_rates.push_back (50);
113         _allowed_dcp_frame_rates.push_back (60);
114
115         set_kdm_email_to_default ();
116 }
117
118 void
119 Config::restore_defaults ()
120 {
121         Config::instance()->set_defaults ();
122         Config::instance()->changed ();
123 }
124
125 shared_ptr<dcp::CertificateChain>
126 Config::create_certificate_chain ()
127 {
128         return shared_ptr<dcp::CertificateChain> (
129                 new dcp::CertificateChain (
130                         openssl_path(),
131                         "dcpomatic.com",
132                         "dcpomatic.com",
133                         ".dcpomatic.smpte-430-2.ROOT",
134                         ".dcpomatic.smpte-430-2.INTERMEDIATE",
135                         "CS.dcpomatic.smpte-430-2.LEAF"
136                         )
137                 );
138 }
139
140 void
141 Config::read ()
142 {
143         if (!have_existing ("config.xml")) {
144                 /* Make a new set of signing certificates and key */
145                 _signer_chain = create_certificate_chain ();
146                 /* And similar for decryption of KDMs */
147                 _decryption_chain = create_certificate_chain ();
148                 write ();
149                 return;
150         }
151
152         cxml::Document f ("Config");
153         f.read_file (path ("config.xml"));
154         optional<string> c;
155
156         optional<int> version = f.optional_number_child<int> ("Version");
157
158         _num_local_encoding_threads = f.number_child<int> ("NumLocalEncodingThreads");
159         _default_directory = f.string_child ("DefaultDirectory");
160
161         boost::optional<int> b = f.optional_number_child<int> ("ServerPort");
162         if (!b) {
163                 b = f.optional_number_child<int> ("ServerPortBase");
164         }
165         _server_port_base = b.get ();
166
167         boost::optional<bool> u = f.optional_bool_child ("UseAnyServers");
168         _use_any_servers = u.get_value_or (true);
169
170         list<cxml::NodePtr> servers = f.node_children ("Server");
171         for (list<cxml::NodePtr>::iterator i = servers.begin(); i != servers.end(); ++i) {
172                 if ((*i)->node_children("HostName").size() == 1) {
173                         _servers.push_back ((*i)->string_child ("HostName"));
174                 } else {
175                         _servers.push_back ((*i)->content ());
176                 }
177         }
178
179         _only_servers_encode = f.optional_bool_child ("OnlyServersEncode").get_value_or (false);
180         _tms_protocol = static_cast<Protocol> (f.optional_number_child<int> ("TMSProtocol").get_value_or (static_cast<int> (PROTOCOL_SCP)));
181         _tms_ip = f.string_child ("TMSIP");
182         _tms_path = f.string_child ("TMSPath");
183         _tms_user = f.string_child ("TMSUser");
184         _tms_password = f.string_child ("TMSPassword");
185
186         c = f.optional_string_child ("SoundProcessor");
187         if (c) {
188                 _cinema_sound_processor = CinemaSoundProcessor::from_id (c.get ());
189         }
190         c = f.optional_string_child ("CinemaSoundProcessor");
191         if (c) {
192                 _cinema_sound_processor = CinemaSoundProcessor::from_id (c.get ());
193         }
194
195         _language = f.optional_string_child ("Language");
196
197         c = f.optional_string_child ("DefaultContainer");
198         if (c) {
199                 _default_container = Ratio::from_id (c.get ());
200         }
201
202         c = f.optional_string_child ("DefaultDCPContentType");
203         if (c) {
204                 _default_dcp_content_type = DCPContentType::from_isdcf_name (c.get ());
205         }
206
207         if (f.optional_string_child ("DCPMetadataIssuer")) {
208                 _dcp_issuer = f.string_child ("DCPMetadataIssuer");
209         } else if (f.optional_string_child ("DCPIssuer")) {
210                 _dcp_issuer = f.string_child ("DCPIssuer");
211         }
212
213         _dcp_creator = f.optional_string_child ("DCPCreator").get_value_or ("");
214
215         if (version && version.get() >= 2) {
216                 _default_isdcf_metadata = ISDCFMetadata (f.node_child ("ISDCFMetadata"));
217         } else {
218                 _default_isdcf_metadata = ISDCFMetadata (f.node_child ("DCIMetadata"));
219         }
220
221         _default_still_length = f.optional_number_child<int>("DefaultStillLength").get_value_or (10);
222         _default_j2k_bandwidth = f.optional_number_child<int>("DefaultJ2KBandwidth").get_value_or (200000000);
223         _default_audio_delay = f.optional_number_child<int>("DefaultAudioDelay").get_value_or (0);
224         _default_interop = f.optional_bool_child("DefaultInterop").get_value_or (false);
225
226         /* Load any cinemas from config.xml */
227         read_cinemas (f);
228
229         _mail_server = f.string_child ("MailServer");
230         _mail_port = f.optional_number_child<int> ("MailPort").get_value_or (25);
231         _mail_user = f.optional_string_child("MailUser").get_value_or ("");
232         _mail_password = f.optional_string_child("MailPassword").get_value_or ("");
233         _kdm_subject = f.optional_string_child ("KDMSubject").get_value_or (_("KDM delivery: $CPL_NAME"));
234         _kdm_from = f.string_child ("KDMFrom");
235         BOOST_FOREACH (cxml::ConstNodePtr i, f.node_children("KDMCC")) {
236                 if (!i->content().empty()) {
237                         _kdm_cc.push_back (i->content ());
238                 }
239         }
240         _kdm_bcc = f.optional_string_child ("KDMBCC").get_value_or ("");
241         _kdm_email = f.string_child ("KDMEmail");
242
243         _check_for_updates = f.optional_bool_child("CheckForUpdates").get_value_or (false);
244         _check_for_test_updates = f.optional_bool_child("CheckForTestUpdates").get_value_or (false);
245
246         _maximum_j2k_bandwidth = f.optional_number_child<int> ("MaximumJ2KBandwidth").get_value_or (250000000);
247         _allow_any_dcp_frame_rate = f.optional_bool_child ("AllowAnyDCPFrameRate").get_value_or (false);
248
249         _log_types = f.optional_number_child<int> ("LogTypes").get_value_or (LogEntry::TYPE_GENERAL | LogEntry::TYPE_WARNING | LogEntry::TYPE_ERROR);
250         _automatic_audio_analysis = f.optional_bool_child ("AutomaticAudioAnalysis").get_value_or (false);
251 #ifdef DCPOMATIC_WINDOWS
252         _win32_console = f.optional_bool_child ("Win32Console").get_value_or (false);
253 #endif
254
255         list<cxml::NodePtr> his = f.node_children ("History");
256         for (list<cxml::NodePtr>::const_iterator i = his.begin(); i != his.end(); ++i) {
257                 _history.push_back ((*i)->content ());
258         }
259
260         cxml::NodePtr signer = f.optional_node_child ("Signer");
261         if (signer) {
262                 shared_ptr<dcp::CertificateChain> c (new dcp::CertificateChain ());
263                 /* Read the signing certificates and private key in from the config file */
264                 BOOST_FOREACH (cxml::NodePtr i, signer->node_children ("Certificate")) {
265                         c->add (dcp::Certificate (i->content ()));
266                 }
267                 c->set_key (signer->string_child ("PrivateKey"));
268                 _signer_chain = c;
269         } else {
270                 /* Make a new set of signing certificates and key */
271                 _signer_chain = create_certificate_chain ();
272         }
273
274         cxml::NodePtr decryption = f.optional_node_child ("Decryption");
275         if (decryption) {
276                 shared_ptr<dcp::CertificateChain> c (new dcp::CertificateChain ());
277                 BOOST_FOREACH (cxml::NodePtr i, decryption->node_children ("Certificate")) {
278                         c->add (dcp::Certificate (i->content ()));
279                 }
280                 c->set_key (decryption->string_child ("PrivateKey"));
281                 _decryption_chain = c;
282         } else {
283                 _decryption_chain = create_certificate_chain ();
284         }
285
286         list<cxml::NodePtr> dkdm = f.node_children ("DKDM");
287         BOOST_FOREACH (cxml::NodePtr i, f.node_children ("DKDM")) {
288                 _dkdms.push_back (dcp::EncryptedKDM (i->content ()));
289         }
290
291         _cinemas_file = f.optional_string_child("CinemasFile").get_value_or (path ("cinemas.xml").string ());
292
293         /* Replace any cinemas from config.xml with those from the configured file */
294         if (boost::filesystem::exists (_cinemas_file)) {
295                 cxml::Document f ("Cinemas");
296                 f.read_file (_cinemas_file);
297                 read_cinemas (f);
298         }
299 }
300
301 /** @return Filename to write configuration to */
302 boost::filesystem::path
303 Config::path (string file, bool create_directories)
304 {
305         boost::filesystem::path p;
306 #ifdef DCPOMATIC_OSX
307         p /= g_get_home_dir ();
308         p /= "Library";
309         p /= "Preferences";
310         p /= "com.dcpomatic";
311         p /= "2";
312 #else
313         p /= g_get_user_config_dir ();
314         p /= "dcpomatic2";
315 #endif
316         boost::system::error_code ec;
317         if (create_directories) {
318                 boost::filesystem::create_directories (p, ec);
319         }
320         p /= file;
321         return p;
322 }
323
324 /** @return Singleton instance */
325 Config *
326 Config::instance ()
327 {
328         if (_instance == 0) {
329                 _instance = new Config;
330                 try {
331                         _instance->read ();
332                 } catch (exception& e) {
333                         /* configuration load failed; never mind, just
334                            stick with the default.
335                         */
336                         cerr << "dcpomatic: warning: configuration did not load (" << e.what() << "); using defaults\n";
337                 } catch (...) {
338                         cerr << "dcpomatic: warning: configuration did not load; using defaults\n";
339                 }
340         }
341
342         return _instance;
343 }
344
345 /** Write our configuration to disk */
346 void
347 Config::write () const
348 {
349         write_config_xml ();
350         write_cinemas_xml ();
351 }
352
353 void
354 Config::write_config_xml () const
355 {
356         xmlpp::Document doc;
357         xmlpp::Element* root = doc.create_root_node ("Config");
358
359         root->add_child("Version")->add_child_text ("2");
360         root->add_child("NumLocalEncodingThreads")->add_child_text (raw_convert<string> (_num_local_encoding_threads));
361         root->add_child("DefaultDirectory")->add_child_text (_default_directory.string ());
362         root->add_child("ServerPortBase")->add_child_text (raw_convert<string> (_server_port_base));
363         root->add_child("UseAnyServers")->add_child_text (_use_any_servers ? "1" : "0");
364
365         for (vector<string>::const_iterator i = _servers.begin(); i != _servers.end(); ++i) {
366                 root->add_child("Server")->add_child_text (*i);
367         }
368
369         root->add_child("OnlyServersEncode")->add_child_text (_only_servers_encode ? "1" : "0");
370         root->add_child("TMSProtocol")->add_child_text (raw_convert<string> (_tms_protocol));
371         root->add_child("TMSIP")->add_child_text (_tms_ip);
372         root->add_child("TMSPath")->add_child_text (_tms_path);
373         root->add_child("TMSUser")->add_child_text (_tms_user);
374         root->add_child("TMSPassword")->add_child_text (_tms_password);
375         if (_cinema_sound_processor) {
376                 root->add_child("CinemaSoundProcessor")->add_child_text (_cinema_sound_processor->id ());
377         }
378         if (_language) {
379                 root->add_child("Language")->add_child_text (_language.get());
380         }
381         if (_default_container) {
382                 root->add_child("DefaultContainer")->add_child_text (_default_container->id ());
383         }
384         if (_default_dcp_content_type) {
385                 root->add_child("DefaultDCPContentType")->add_child_text (_default_dcp_content_type->isdcf_name ());
386         }
387         root->add_child("DCPIssuer")->add_child_text (_dcp_issuer);
388         root->add_child("DCPCreator")->add_child_text (_dcp_creator);
389
390         _default_isdcf_metadata.as_xml (root->add_child ("ISDCFMetadata"));
391
392         root->add_child("DefaultStillLength")->add_child_text (raw_convert<string> (_default_still_length));
393         root->add_child("DefaultJ2KBandwidth")->add_child_text (raw_convert<string> (_default_j2k_bandwidth));
394         root->add_child("DefaultAudioDelay")->add_child_text (raw_convert<string> (_default_audio_delay));
395         root->add_child("DefaultInterop")->add_child_text (_default_interop ? "1" : "0");
396         root->add_child("MailServer")->add_child_text (_mail_server);
397         root->add_child("MailPort")->add_child_text (raw_convert<string> (_mail_port));
398         root->add_child("MailUser")->add_child_text (_mail_user);
399         root->add_child("MailPassword")->add_child_text (_mail_password);
400         root->add_child("KDMSubject")->add_child_text (_kdm_subject);
401         root->add_child("KDMFrom")->add_child_text (_kdm_from);
402         BOOST_FOREACH (string i, _kdm_cc) {
403                 root->add_child("KDMCC")->add_child_text (i);
404         }
405         root->add_child("KDMBCC")->add_child_text (_kdm_bcc);
406         root->add_child("KDMEmail")->add_child_text (_kdm_email);
407
408         root->add_child("CheckForUpdates")->add_child_text (_check_for_updates ? "1" : "0");
409         root->add_child("CheckForTestUpdates")->add_child_text (_check_for_test_updates ? "1" : "0");
410
411         root->add_child("MaximumJ2KBandwidth")->add_child_text (raw_convert<string> (_maximum_j2k_bandwidth));
412         root->add_child("AllowAnyDCPFrameRate")->add_child_text (_allow_any_dcp_frame_rate ? "1" : "0");
413         root->add_child("LogTypes")->add_child_text (raw_convert<string> (_log_types));
414         root->add_child("AutomaticAudioAnalysis")->add_child_text (_automatic_audio_analysis ? "1" : "0");
415 #ifdef DCPOMATIC_WINDOWS
416         root->add_child("Win32Console")->add_child_text (_win32_console ? "1" : "0");
417 #endif
418
419         xmlpp::Element* signer = root->add_child ("Signer");
420         DCPOMATIC_ASSERT (_signer_chain);
421         BOOST_FOREACH (dcp::Certificate const & i, _signer_chain->root_to_leaf ()) {
422                 signer->add_child("Certificate")->add_child_text (i.certificate (true));
423         }
424         signer->add_child("PrivateKey")->add_child_text (_signer_chain->key().get ());
425
426         xmlpp::Element* decryption = root->add_child ("Decryption");
427         DCPOMATIC_ASSERT (_decryption_chain);
428         BOOST_FOREACH (dcp::Certificate const & i, _decryption_chain->root_to_leaf ()) {
429                 decryption->add_child("Certificate")->add_child_text (i.certificate (true));
430         }
431         decryption->add_child("PrivateKey")->add_child_text (_decryption_chain->key().get ());
432
433         for (vector<boost::filesystem::path>::const_iterator i = _history.begin(); i != _history.end(); ++i) {
434                 root->add_child("History")->add_child_text (i->string ());
435         }
436
437         BOOST_FOREACH (dcp::EncryptedKDM i, _dkdms) {
438                 root->add_child("DKDM")->add_child_text (i.as_xml ());
439         }
440
441         root->add_child("CinemasFile")->add_child_text (_cinemas_file.string());
442
443         try {
444                 doc.write_to_file_formatted (path("config.xml").string ());
445         } catch (xmlpp::exception& e) {
446                 string s = e.what ();
447                 trim (s);
448                 throw FileError (s, path("config.xml"));
449         }
450 }
451
452 void
453 Config::write_cinemas_xml () const
454 {
455         xmlpp::Document doc;
456         xmlpp::Element* root = doc.create_root_node ("Cinemas");
457         root->add_child("Version")->add_child_text ("1");
458
459         for (list<shared_ptr<Cinema> >::const_iterator i = _cinemas.begin(); i != _cinemas.end(); ++i) {
460                 (*i)->as_xml (root->add_child ("Cinema"));
461         }
462
463         try {
464                 doc.write_to_file_formatted (_cinemas_file.string ());
465         } catch (xmlpp::exception& e) {
466                 string s = e.what ();
467                 trim (s);
468                 throw FileError (s, _cinemas_file);
469         }
470 }
471
472 boost::filesystem::path
473 Config::default_directory_or (boost::filesystem::path a) const
474 {
475         if (_default_directory.empty()) {
476                 return a;
477         }
478
479         boost::system::error_code ec;
480         bool const e = boost::filesystem::exists (_default_directory, ec);
481         if (ec || !e) {
482                 return a;
483         }
484
485         return _default_directory;
486 }
487
488 void
489 Config::drop ()
490 {
491         delete _instance;
492         _instance = 0;
493 }
494
495 void
496 Config::changed (Property what)
497 {
498         Changed (what);
499 }
500
501 void
502 Config::set_kdm_email_to_default ()
503 {
504         _kdm_subject = _("KDM delivery: $CPL_NAME");
505
506         _kdm_email = _(
507                 "Dear Projectionist\n\n"
508                 "Please find attached KDMs for $CPL_NAME.\n\n"
509                 "Cinema: $CINEMA_NAME\n"
510                 "Screen(s): $SCREENS\n\n"
511                 "The KDMs are valid from $START_TIME until $END_TIME.\n\n"
512                 "Best regards,\nDCP-o-matic"
513                 );
514 }
515
516 void
517 Config::reset_kdm_email ()
518 {
519         set_kdm_email_to_default ();
520         changed ();
521 }
522
523 void
524 Config::add_to_history (boost::filesystem::path p)
525 {
526         /* Remove existing instances of this path in the history */
527         _history.erase (remove (_history.begin(), _history.end(), p), _history.end ());
528
529         _history.insert (_history.begin (), p);
530         if (_history.size() > HISTORY_SIZE) {
531                 _history.pop_back ();
532         }
533
534         changed ();
535 }
536
537 bool
538 Config::have_existing (string file)
539 {
540         return boost::filesystem::exists (path (file, false));
541 }
542
543 void
544 Config::read_cinemas (cxml::Document const & f)
545 {
546         _cinemas.clear ();
547         list<cxml::NodePtr> cin = f.node_children ("Cinema");
548         for (list<cxml::NodePtr>::iterator i = cin.begin(); i != cin.end(); ++i) {
549                 /* Slightly grotty two-part construction of Cinema here so that we can use
550                    shared_from_this.
551                 */
552                 shared_ptr<Cinema> cinema (new Cinema (*i));
553                 cinema->read_screens (*i);
554                 _cinemas.push_back (cinema);
555         }
556 }
557
558 void
559 Config::set_cinemas_file (boost::filesystem::path file)
560 {
561         _cinemas_file = file;
562
563         if (boost::filesystem::exists (_cinemas_file)) {
564                 /* Existing file; read it in */
565                 cxml::Document f ("Cinemas");
566                 f.read_file (_cinemas_file);
567                 read_cinemas (f);
568         }
569
570         changed (OTHER);
571 }