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