Accept chains in files as well as individual certificates.
[dcpomatic.git] / src / tools / dcpomatic_kdm_cli.cc
1 /*
2     Copyright (C) 2013-2018 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 /** @file  src/tools/dcpomatic_kdm_cli.cc
22  *  @brief Command-line program to generate KDMs.
23  */
24
25 #include "lib/film.h"
26 #include "lib/cinema.h"
27 #include "lib/screen_kdm.h"
28 #include "lib/cinema_kdms.h"
29 #include "lib/config.h"
30 #include "lib/exceptions.h"
31 #include "lib/emailer.h"
32 #include "lib/dkdm_wrapper.h"
33 #include "lib/screen.h"
34 #include <dcp/certificate.h>
35 #include <dcp/decrypted_kdm.h>
36 #include <dcp/encrypted_kdm.h>
37 #include <getopt.h>
38 #include <iostream>
39
40 using std::string;
41 using std::cout;
42 using std::cerr;
43 using std::list;
44 using std::vector;
45 using std::runtime_error;
46 using boost::shared_ptr;
47 using boost::optional;
48 using boost::bind;
49 using boost::dynamic_pointer_cast;
50
51 static void
52 help ()
53 {
54         cerr << "Syntax: " << program_name << " [OPTION] <FILM|CPL-ID|DKDM>\n"
55                 "  -h, --help                               show this help\n"
56                 "  -o, --output                             output file or directory\n"
57                 "  -K, --filename-format                    filename format for KDMs\n"
58                 "  -Z, --container-name-format              filename format for ZIP containers\n"
59                 "  -f, --valid-from                         valid from time (in local time zone of the cinema) (e.g. \"2013-09-28 01:41:51\") or \"now\"\n"
60                 "  -t, --valid-to                           valid to time (in local time zone of the cinema) (e.g. \"2014-09-28 01:41:51\")\n"
61                 "  -d, --valid-duration                     valid duration (e.g. \"1 day\", \"4 hours\", \"2 weeks\")\n"
62                 "  -F, --formulation                        modified-transitional-1, multiple-modified-transitional-1, dci-any or dci-specific [default modified-transitional-1]\n"
63                 "  -a, --disable-forensic-marking-picture   disable forensic of pictures essences\n"
64                 "  -a, --disable-forensic-marking-audio     disable forensic of audio essences (optionally above a given channel, e.g 12)\n"
65                 "  -z, --zip                                ZIP each cinema's KDMs into its own file\n"
66                 "  -v, --verbose                            be verbose\n"
67                 "  -c, --cinema                             specify a cinema, either by name or email address\n"
68                 "  -S, --screen                             screen description\n"
69                 "  -C, --certificate                        file containing projector certificate\n"
70                 "  -T, --trusted-device                     file containing a trusted device's certificate\n"
71                 "      --list-cinemas                       list known cinemas from the DCP-o-matic settings\n"
72                 "      --list-dkdm-cpls                     list CPLs for which DCP-o-matic has DKDMs\n\n"
73                 "CPL-ID must be the ID of a CPL that is mentioned in DCP-o-matic's DKDM list.\n\n"
74                 "For example:\n\n"
75                 "Create KDMs for my_great_movie to play in all of Fred's Cinema's screens for the next two weeks and zip them up.\n"
76                 "(Fred's Cinema must have been set up in DCP-o-matic's KDM window)\n\n"
77                 "\t" << program_name << " -c \"Fred's Cinema\" -f now -d \"2 weeks\" -z my_great_movie\n\n";
78 }
79
80 static void
81 error (string m)
82 {
83         cerr << program_name << ": " << m << "\n";
84         exit (EXIT_FAILURE);
85 }
86
87 static boost::posix_time::ptime
88 time_from_string (string t)
89 {
90         if (t == "now") {
91                 return boost::posix_time::second_clock::local_time ();
92         }
93
94         return boost::posix_time::time_from_string (t);
95 }
96
97 static boost::posix_time::time_duration
98 duration_from_string (string d)
99 {
100         int N;
101         char unit_buf[64] = "\0";
102         sscanf (d.c_str(), "%d %63s", &N, unit_buf);
103         string const unit (unit_buf);
104
105         if (N == 0) {
106                 cerr << "Could not understand duration \"" << d << "\"\n";
107                 exit (EXIT_FAILURE);
108         }
109
110         if (unit == "year" || unit == "years") {
111                 return boost::posix_time::time_duration (N * 24 * 365, 0, 0, 0);
112         } else if (unit == "week" || unit == "weeks") {
113                 return boost::posix_time::time_duration (N * 24 * 7, 0, 0, 0);
114         } else if (unit == "day" || unit == "days") {
115                 return boost::posix_time::time_duration (N * 24, 0, 0, 0);
116         } else if (unit == "hour" || unit == "hours") {
117                 return boost::posix_time::time_duration (N, 0, 0, 0);
118         }
119
120         cerr << "Could not understand duration \"" << d << "\"\n";
121         exit (EXIT_FAILURE);
122 }
123
124 static bool
125 always_overwrite ()
126 {
127         return true;
128 }
129
130 void
131 write_files (
132         list<ScreenKDM> screen_kdms,
133         bool zip,
134         boost::filesystem::path output,
135         dcp::NameFormat container_name_format,
136         dcp::NameFormat filename_format,
137         dcp::NameFormat::Map values,
138         bool verbose
139         )
140 {
141         if (zip) {
142                 int const N = CinemaKDMs::write_zip_files (
143                         CinemaKDMs::collect (screen_kdms),
144                         output,
145                         container_name_format,
146                         filename_format,
147                         values,
148                         bind (&always_overwrite)
149                         );
150
151                 if (verbose) {
152                         cout << "Wrote " << N << " ZIP files to " << output << "\n";
153                 }
154         } else {
155                 int const N = ScreenKDM::write_files (
156                         screen_kdms, output, filename_format, values,
157                         bind (&always_overwrite)
158                         );
159
160                 if (verbose) {
161                         cout << "Wrote " << N << " KDM files to " << output << "\n";
162                 }
163         }
164 }
165
166 shared_ptr<Cinema>
167 find_cinema (string cinema_name)
168 {
169         list<shared_ptr<Cinema> > cinemas = Config::instance()->cinemas ();
170         list<shared_ptr<Cinema> >::const_iterator i = cinemas.begin();
171         while (
172                 i != cinemas.end() &&
173                 (*i)->name != cinema_name &&
174                 find ((*i)->emails.begin(), (*i)->emails.end(), cinema_name) == (*i)->emails.end()) {
175
176                 ++i;
177         }
178
179         if (i == cinemas.end ()) {
180                 cerr << program_name << ": could not find cinema \"" << cinema_name << "\"\n";
181                 exit (EXIT_FAILURE);
182         }
183
184         return *i;
185 }
186
187 void
188 from_film (
189         list<shared_ptr<Screen> > screens,
190         boost::filesystem::path film_dir,
191         bool verbose,
192         boost::filesystem::path output,
193         dcp::NameFormat container_name_format,
194         dcp::NameFormat filename_format,
195         boost::posix_time::ptime valid_from,
196         boost::posix_time::ptime valid_to,
197         dcp::Formulation formulation,
198         bool disable_forensic_marking_picture,
199         optional<int> disable_forensic_marking_audio,
200         bool zip
201         )
202 {
203         shared_ptr<Film> film;
204         try {
205                 film.reset (new Film (film_dir));
206                 film->read_metadata ();
207                 if (verbose) {
208                         cout << "Read film " << film->name () << "\n";
209                 }
210         } catch (std::exception& e) {
211                 cerr << program_name << ": error reading film `" << film_dir.string() << "' (" << e.what() << ")\n";
212                 exit (EXIT_FAILURE);
213         }
214
215         /* XXX: allow specification of this */
216         vector<CPLSummary> cpls = film->cpls ();
217         if (cpls.empty ()) {
218                 error ("no CPLs found in film");
219         } else if (cpls.size() > 1) {
220                 error ("more than one CPL found in film");
221         }
222
223         boost::filesystem::path cpl = cpls.front().cpl_file;
224
225         dcp::NameFormat::Map values;
226         values['f'] = film->name();
227         values['b'] = dcp::LocalTime(valid_from).date() + " " + dcp::LocalTime(valid_from).time_of_day(true, false);
228         values['e'] = dcp::LocalTime(valid_to).date() + " " + dcp::LocalTime(valid_to).time_of_day(true, false);
229
230         try {
231                 list<ScreenKDM> screen_kdms = film->make_kdms (
232                         screens, cpl, valid_from, valid_to, formulation, disable_forensic_marking_picture, disable_forensic_marking_audio
233                         );
234
235                 write_files (screen_kdms, zip, output, container_name_format, filename_format, values, verbose);
236         } catch (FileError& e) {
237                 cerr << program_name << ": " << e.what() << " (" << e.file().string() << ")\n";
238                 exit (EXIT_FAILURE);
239         } catch (KDMError& e) {
240                 cerr << program_name << ": " << e.what() << "\n";
241                 exit (EXIT_FAILURE);
242         } catch (runtime_error& e) {
243                 cerr << program_name << ": " << e.what() << "\n";
244                 exit (EXIT_FAILURE);
245         }
246 }
247
248 optional<dcp::EncryptedKDM>
249 sub_find_dkdm (shared_ptr<DKDMGroup> group, string cpl_id)
250 {
251         BOOST_FOREACH (shared_ptr<DKDMBase> i, group->children()) {
252                 shared_ptr<DKDMGroup> g = dynamic_pointer_cast<DKDMGroup>(i);
253                 if (g) {
254                         optional<dcp::EncryptedKDM> dkdm = sub_find_dkdm (g, cpl_id);
255                         if (dkdm) {
256                                 return dkdm;
257                         }
258                 } else {
259                         shared_ptr<DKDM> d = dynamic_pointer_cast<DKDM>(i);
260                         assert (d);
261                         if (d->dkdm().cpl_id() == cpl_id) {
262                                 return d->dkdm();
263                         }
264                 }
265         }
266
267         return optional<dcp::EncryptedKDM>();
268 }
269
270 optional<dcp::EncryptedKDM>
271 find_dkdm (string cpl_id)
272 {
273         return sub_find_dkdm (Config::instance()->dkdms(), cpl_id);
274 }
275
276 dcp::EncryptedKDM
277 kdm_from_dkdm (
278         dcp::DecryptedKDM dkdm,
279         dcp::Certificate target,
280         vector<string> trusted_devices,
281         dcp::LocalTime valid_from,
282         dcp::LocalTime valid_to,
283         dcp::Formulation formulation,
284         bool disable_forensic_marking_picture,
285         optional<int> disable_forensic_marking_audio
286         )
287 {
288         /* Signer for new KDM */
289         shared_ptr<const dcp::CertificateChain> signer = Config::instance()->signer_chain ();
290         if (!signer->valid ()) {
291                 error ("signing certificate chain is invalid.");
292         }
293
294         /* Make a new empty KDM and add the keys from the DKDM to it */
295         dcp::DecryptedKDM kdm (
296                 valid_from,
297                 valid_to,
298                 dkdm.annotation_text().get_value_or(""),
299                 dkdm.content_title_text(),
300                 dcp::LocalTime().as_string()
301                 );
302
303         BOOST_FOREACH (dcp::DecryptedKDMKey const & j, dkdm.keys()) {
304                 kdm.add_key(j);
305         }
306
307         return kdm.encrypt (signer, target, trusted_devices, formulation, disable_forensic_marking_picture, disable_forensic_marking_audio);
308 }
309
310 void
311 from_dkdm (
312         list<shared_ptr<Screen> > screens,
313         dcp::DecryptedKDM dkdm,
314         bool verbose,
315         boost::filesystem::path output,
316         dcp::NameFormat container_name_format,
317         dcp::NameFormat filename_format,
318         boost::posix_time::ptime valid_from,
319         boost::posix_time::ptime valid_to,
320         dcp::Formulation formulation,
321         bool disable_forensic_marking_picture,
322         optional<int> disable_forensic_marking_audio,
323         bool zip
324         )
325 {
326         dcp::NameFormat::Map values;
327         values['f'] = dkdm.annotation_text().get_value_or("");
328         values['b'] = dcp::LocalTime(valid_from).date() + " " + dcp::LocalTime(valid_from).time_of_day(true, false);
329         values['e'] = dcp::LocalTime(valid_to).date() + " " + dcp::LocalTime(valid_to).time_of_day(true, false);
330
331         try {
332                 list<ScreenKDM> screen_kdms;
333                 BOOST_FOREACH (shared_ptr<Screen> i, screens) {
334                         if (!i->recipient) {
335                                 continue;
336                         }
337
338                         screen_kdms.push_back (
339                                 ScreenKDM (
340                                         i,
341                                         kdm_from_dkdm (
342                                                 dkdm,
343                                                 i->recipient.get(),
344                                                 i->trusted_device_thumbprints(),
345                                                 dcp::LocalTime(valid_from, i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute()),
346                                                 dcp::LocalTime(valid_to, i->cinema->utc_offset_hour(), i->cinema->utc_offset_minute()),
347                                                 formulation,
348                                                 disable_forensic_marking_picture,
349                                                 disable_forensic_marking_audio
350                                                 )
351                                         )
352                                 );
353                 }
354                 write_files (screen_kdms, zip, output, container_name_format, filename_format, values, verbose);
355         } catch (FileError& e) {
356                 cerr << program_name << ": " << e.what() << " (" << e.file().string() << ")\n";
357                 exit (EXIT_FAILURE);
358         } catch (KDMError& e) {
359                 cerr << program_name << ": " << e.what() << "\n";
360                 exit (EXIT_FAILURE);
361         }
362 }
363
364 void
365 dump_dkdm_group (shared_ptr<DKDMGroup> group, int indent)
366 {
367         if (indent > 0) {
368                 for (int i = 0; i < indent; ++i) {
369                         cout << " ";
370                 }
371                 cout << group->name() << "\n";
372         }
373         BOOST_FOREACH (shared_ptr<DKDMBase> i, group->children()) {
374                 shared_ptr<DKDMGroup> g = dynamic_pointer_cast<DKDMGroup>(i);
375                 if (g) {
376                         dump_dkdm_group (g, indent + 2);
377                 } else {
378                         for (int j = 0; j < indent; ++j) {
379                                 cout << " ";
380                         }
381                         shared_ptr<DKDM> d = dynamic_pointer_cast<DKDM>(i);
382                         assert(d);
383                         cout << d->dkdm().cpl_id() << "\n";
384                 }
385         }
386 }
387
388 int main (int argc, char* argv[])
389 {
390         boost::filesystem::path output = ".";
391         dcp::NameFormat container_name_format = Config::instance()->kdm_container_name_format();
392         dcp::NameFormat filename_format = Config::instance()->kdm_filename_format();
393         optional<string> cinema_name;
394         shared_ptr<Cinema> cinema;
395         string screen_description = "";
396         list<shared_ptr<Screen> > screens;
397         optional<dcp::EncryptedKDM> dkdm;
398         optional<boost::posix_time::ptime> valid_from;
399         optional<boost::posix_time::ptime> valid_to;
400         bool zip = false;
401         bool list_cinemas = false;
402         bool list_dkdm_cpls = false;
403         optional<string> duration_string;
404         bool verbose = false;
405         dcp::Formulation formulation = dcp::MODIFIED_TRANSITIONAL_1;
406         bool disable_forensic_marking_picture = false;
407         optional<int> disable_forensic_marking_audio;
408
409         program_name = argv[0];
410
411         int option_index = 0;
412         while (true) {
413                 static struct option long_options[] = {
414                         { "help", no_argument, 0, 'h'},
415                         { "output", required_argument, 0, 'o'},
416                         { "filename-format", required_argument, 0, 'K'},
417                         { "container-name-format", required_argument, 0, 'Z'},
418                         { "valid-from", required_argument, 0, 'f'},
419                         { "valid-to", required_argument, 0, 't'},
420                         { "valid-duration", required_argument, 0, 'd'},
421                         { "formulation", required_argument, 0, 'F' },
422                         { "disable-forensic-marking-picture", no_argument, 0, 'p' },
423                         { "disable-forensic-marking-audio", optional_argument, 0, 'a' },
424                         { "zip", no_argument, 0, 'z' },
425                         { "verbose", no_argument, 0, 'v' },
426                         { "cinema", required_argument, 0, 'c' },
427                         { "screen", required_argument, 0, 'S' },
428                         { "certificate", required_argument, 0, 'C' },
429                         { "trusted-device", required_argument, 0, 'T' },
430                         { "list-cinemas", no_argument, 0, 'B' },
431                         { "list-dkdm-cpls", no_argument, 0, 'D' },
432                         { 0, 0, 0, 0 }
433                 };
434
435                 int c = getopt_long (argc, argv, "ho:K:Z:f:t:d:F:pa::zvc:S:C:T:BD", long_options, &option_index);
436
437                 if (c == -1) {
438                         break;
439                 }
440
441                 switch (c) {
442                 case 'h':
443                         help ();
444                         exit (EXIT_SUCCESS);
445                 case 'o':
446                         output = optarg;
447                         break;
448                 case 'K':
449                         filename_format = dcp::NameFormat (optarg);
450                         break;
451                 case 'Z':
452                         container_name_format = dcp::NameFormat (optarg);
453                         break;
454                 case 'f':
455                         valid_from = time_from_string (optarg);
456                         break;
457                 case 't':
458                         valid_to = time_from_string (optarg);
459                         break;
460                 case 'd':
461                         duration_string = optarg;
462                         break;
463                 case 'F':
464                         if (string (optarg) == "modified-transitional-1") {
465                                 formulation = dcp::MODIFIED_TRANSITIONAL_1;
466                         } else if (string (optarg) == "multiple-modified-transitional-1") {
467                                 formulation = dcp::MULTIPLE_MODIFIED_TRANSITIONAL_1;
468                         } else if (string (optarg) == "dci-any") {
469                                 formulation = dcp::DCI_ANY;
470                         } else if (string (optarg) == "dci-specific") {
471                                 formulation = dcp::DCI_SPECIFIC;
472                         } else {
473                                 error ("unrecognised KDM formulation " + string (optarg));
474                         }
475                         break;
476                 case 'p':
477                         disable_forensic_marking_picture = true;
478                         break;
479                 case 'a':
480                         disable_forensic_marking_audio = 0;
481                         if (optarg == 0 && argv[optind] != 0 && argv[optind][0] != '-') {
482                                 disable_forensic_marking_audio = atoi (argv[optind++]);
483                         } else if (optarg) {
484                                 disable_forensic_marking_audio = atoi (optarg);
485                         }
486                         break;
487                 case 'z':
488                         zip = true;
489                         break;
490                 case 'v':
491                         verbose = true;
492                         break;
493                 case 'c':
494                         /* This could be a cinema to search for in the configured list or the name of a cinema being
495                            built up on-the-fly in the option.  Cater for both possilibities here by storing the name
496                            (for lookup) and by creating a Cinema which the next Screen will be added to.
497                         */
498                         cinema_name = optarg;
499                         cinema = shared_ptr<Cinema> (new Cinema (optarg, list<string>(), "", 0, 0));
500                         break;
501                 case 'S':
502                         screen_description = optarg;
503                         break;
504                 case 'C':
505                 {
506                         /* Make a new screen and add it to the current cinema */
507                         dcp::CertificateChain chain (dcp::file_to_string(optarg));
508                         shared_ptr<Screen> screen (new Screen (screen_description, chain.leaf(), vector<TrustedDevice>()));
509                         if (cinema) {
510                                 cinema->add_screen (screen);
511                         }
512                         screens.push_back (screen);
513                         break;
514                 }
515                 case 'T':
516                         /* A trusted device ends up in the last screen we made */
517                         if (!screens.empty ()) {
518                                 screens.back()->trusted_devices.push_back(TrustedDevice(dcp::Certificate(dcp::file_to_string(optarg))));
519                         }
520                         break;
521                 case 'B':
522                         list_cinemas = true;
523                         break;
524                 case 'D':
525                         list_dkdm_cpls = true;
526                         break;
527                 }
528         }
529
530         if (list_cinemas) {
531                 list<boost::shared_ptr<Cinema> > cinemas = Config::instance()->cinemas ();
532                 for (list<boost::shared_ptr<Cinema> >::const_iterator i = cinemas.begin(); i != cinemas.end(); ++i) {
533                         cout << (*i)->name << " (" << Emailer::address_list ((*i)->emails) << ")\n";
534                 }
535                 exit (EXIT_SUCCESS);
536         }
537
538         if (list_dkdm_cpls) {
539                 dump_dkdm_group (Config::instance()->dkdms(), 0);
540                 exit (EXIT_SUCCESS);
541         }
542
543         if (!duration_string && !valid_to) {
544                 error ("you must specify a --valid-duration or --valid-to");
545         }
546
547         if (!valid_from) {
548                 error ("you must specify --valid-from");
549                 exit (EXIT_FAILURE);
550         }
551
552         if (optind >= argc) {
553                 help ();
554                 exit (EXIT_FAILURE);
555         }
556
557         if (screens.empty()) {
558                 if (!cinema_name) {
559                         error ("you must specify either a cinema or one or more screens using certificate files");
560                 }
561
562                 screens = find_cinema (*cinema_name)->screens ();
563         }
564
565         if (duration_string) {
566                 valid_to = valid_from.get() + duration_from_string (*duration_string);
567         }
568
569         dcpomatic_setup_path_encoding ();
570         dcpomatic_setup ();
571
572         if (verbose) {
573                 cout << "Making KDMs valid from " << valid_from.get() << " to " << valid_to.get() << "\n";
574         }
575
576         string const thing = argv[optind];
577         if (boost::filesystem::is_directory(thing) && boost::filesystem::is_regular_file(boost::filesystem::path(thing) / "metadata.xml")) {
578                 from_film (
579                         screens,
580                         thing,
581                         verbose,
582                         output,
583                         container_name_format,
584                         filename_format,
585                         *valid_from,
586                         *valid_to,
587                         formulation,
588                         disable_forensic_marking_picture,
589                         disable_forensic_marking_audio,
590                         zip
591                         );
592         } else {
593                 if (boost::filesystem::is_regular_file(thing)) {
594                         dkdm = dcp::EncryptedKDM (dcp::file_to_string (thing));
595                 } else {
596                         dkdm = find_dkdm (thing);
597                 }
598
599                 if (!dkdm) {
600                         error ("could not find film or CPL ID corresponding to " + thing);
601                 }
602
603                 from_dkdm (
604                         screens,
605                         dcp::DecryptedKDM (*dkdm, Config::instance()->decryption_chain()->key().get()),
606                         verbose,
607                         output,
608                         container_name_format,
609                         filename_format,
610                         *valid_from,
611                         *valid_to,
612                         formulation,
613                         disable_forensic_marking_picture,
614                         disable_forensic_marking_audio,
615                         zip
616                         );
617         }
618
619         return 0;
620 }