Be more careful about allowing possibly-trouble-causing characters in DCP filenames.
[dcpomatic.git] / src / lib / util.cc
1 /*
2     Copyright (C) 2012-2016 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/lib/util.cc
22  *  @brief Some utility functions and classes.
23  */
24
25 #include "util.h"
26 #include "exceptions.h"
27 #include "dcp_content_type.h"
28 #include "filter.h"
29 #include "cinema_sound_processor.h"
30 #include "config.h"
31 #include "ratio.h"
32 #include "job.h"
33 #include "cross.h"
34 #include "video_content.h"
35 #include "rect.h"
36 #include "digester.h"
37 #include "audio_processor.h"
38 #include "compose.hpp"
39 #include <dcp/locale_convert.h>
40 #include <dcp/util.h>
41 #include <dcp/raw_convert.h>
42 #include <dcp/picture_asset.h>
43 #include <dcp/sound_asset.h>
44 #include <dcp/subtitle_asset.h>
45 extern "C" {
46 #include <libavfilter/avfilter.h>
47 #include <libavcodec/avcodec.h>
48 }
49 #include <curl/curl.h>
50 #ifdef DCPOMATIC_GRAPHICS_MAGICK
51 #include <Magick++.h>
52 #endif
53 #include <glib.h>
54 #include <pangomm/init.h>
55 #include <boost/algorithm/string.hpp>
56 #include <boost/range/algorithm/replace_if.hpp>
57 #include <boost/thread.hpp>
58 #include <boost/filesystem.hpp>
59 #ifdef DCPOMATIC_WINDOWS
60 #include <boost/locale.hpp>
61 #include <dbghelp.h>
62 #endif
63 #include <signal.h>
64 #include <iomanip>
65 #include <iostream>
66 #include <fstream>
67 #include <climits>
68 #include <stdexcept>
69 #ifdef DCPOMATIC_POSIX
70 #include <execinfo.h>
71 #include <cxxabi.h>
72 #endif
73
74 #include "i18n.h"
75
76 using std::string;
77 using std::setfill;
78 using std::ostream;
79 using std::endl;
80 using std::vector;
81 using std::min;
82 using std::max;
83 using std::map;
84 using std::list;
85 using std::multimap;
86 using std::istream;
87 using std::pair;
88 using std::cout;
89 using std::bad_alloc;
90 using std::set_terminate;
91 using boost::shared_ptr;
92 using boost::thread;
93 using boost::optional;
94 using boost::lexical_cast;
95 using boost::bad_lexical_cast;
96 using dcp::Size;
97 using dcp::raw_convert;
98 using dcp::locale_convert;
99
100 /** Path to our executable, required by the stacktrace stuff and filled
101  *  in during App::onInit().
102  */
103 string program_name;
104 static boost::thread::id ui_thread;
105 static boost::filesystem::path backtrace_file;
106
107 /** Convert some number of seconds to a string representation
108  *  in hours, minutes and seconds.
109  *
110  *  @param s Seconds.
111  *  @return String of the form H:M:S (where H is hours, M
112  *  is minutes and S is seconds).
113  */
114 string
115 seconds_to_hms (int s)
116 {
117         int m = s / 60;
118         s -= (m * 60);
119         int h = m / 60;
120         m -= (h * 60);
121
122         char buffer[64];
123         snprintf (buffer, sizeof(buffer), "%d:%02d:%02d", h, m, s);
124         return buffer;
125 }
126
127 /** @param s Number of seconds.
128  *  @return String containing an approximate description of s (e.g. "about 2 hours")
129  */
130 string
131 seconds_to_approximate_hms (int s)
132 {
133         int m = s / 60;
134         s -= (m * 60);
135         int h = m / 60;
136         m -= (h * 60);
137
138         string ap;
139
140         bool const hours = h > 0;
141         bool const minutes = h < 6 && m > 0;
142         bool const seconds = h == 0 && m < 10 && s > 0;
143
144         if (hours) {
145                 if (m > 30 && !minutes) {
146                         /// TRANSLATORS: h here is an abbreviation for hours
147                         ap += locale_convert<string>(h + 1) + _("h");
148                 } else {
149                         /// TRANSLATORS: h here is an abbreviation for hours
150                         ap += locale_convert<string>(h) + _("h");
151                 }
152
153                 if (minutes || seconds) {
154                         ap += N_(" ");
155                 }
156         }
157
158         if (minutes) {
159                 /* Minutes */
160                 if (s > 30 && !seconds) {
161                         /// TRANSLATORS: m here is an abbreviation for minutes
162                         ap += locale_convert<string>(m + 1) + _("m");
163                 } else {
164                         /// TRANSLATORS: m here is an abbreviation for minutes
165                         ap += locale_convert<string>(m) + _("m");
166                 }
167
168                 if (seconds) {
169                         ap += N_(" ");
170                 }
171         }
172
173         if (seconds) {
174                 /* Seconds */
175                 /// TRANSLATORS: s here is an abbreviation for seconds
176                 ap += locale_convert<string>(s) + _("s");
177         }
178
179         return ap;
180 }
181
182 double
183 seconds (struct timeval t)
184 {
185         return t.tv_sec + (double (t.tv_usec) / 1e6);
186 }
187
188 #ifdef DCPOMATIC_WINDOWS
189
190 /** Resolve symbol name and source location given the path to the executable */
191 int
192 addr2line (void const * const addr)
193 {
194         char addr2line_cmd[512] = { 0 };
195         sprintf (addr2line_cmd, "addr2line -f -p -e %.256s %p > %s", program_name.c_str(), addr, backtrace_file.string().c_str());
196         return system(addr2line_cmd);
197 }
198
199 /** This is called when C signals occur on Windows (e.g. SIGSEGV)
200  *  (NOT C++ exceptions!).  We write a backtrace to backtrace_file by dark means.
201  *  Adapted from code here: http://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c/
202  */
203 LONG WINAPI
204 exception_handler(struct _EXCEPTION_POINTERS * info)
205 {
206         FILE* f = fopen_boost (backtrace_file, "w");
207         fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
208         fclose(f);
209
210         if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
211                 CONTEXT* context = info->ContextRecord;
212                 SymInitialize (GetCurrentProcess (), 0, true);
213
214                 STACKFRAME frame = { 0 };
215
216                 /* setup initial stack frame */
217 #if _WIN64
218                 frame.AddrPC.Offset    = context->Rip;
219                 frame.AddrStack.Offset = context->Rsp;
220                 frame.AddrFrame.Offset = context->Rbp;
221 #else
222                 frame.AddrPC.Offset    = context->Eip;
223                 frame.AddrStack.Offset = context->Esp;
224                 frame.AddrFrame.Offset = context->Ebp;
225 #endif
226                 frame.AddrPC.Mode      = AddrModeFlat;
227                 frame.AddrStack.Mode   = AddrModeFlat;
228                 frame.AddrFrame.Mode   = AddrModeFlat;
229
230                 while (
231                         StackWalk (
232                                 IMAGE_FILE_MACHINE_I386,
233                                 GetCurrentProcess (),
234                                 GetCurrentThread (),
235                                 &frame,
236                                 context,
237                                 0,
238                                 SymFunctionTableAccess,
239                                 SymGetModuleBase,
240                                 0
241                                 )
242                         ) {
243                         addr2line((void *) frame.AddrPC.Offset);
244                 }
245         } else {
246 #ifdef _WIN64
247                 addr2line ((void *) info->ContextRecord->Rip);
248 #else
249                 addr2line ((void *) info->ContextRecord->Eip);
250 #endif
251         }
252
253         return EXCEPTION_CONTINUE_SEARCH;
254 }
255 #endif
256
257 void
258 set_backtrace_file (boost::filesystem::path p)
259 {
260         backtrace_file = p;
261 }
262
263 /** This is called when there is an unhandled exception.  Any
264  *  backtrace in this function is useless on Windows as the stack has
265  *  already been unwound from the throw; we have the gdb wrap hack to
266  *  cope with that.
267  */
268 void
269 terminate ()
270 {
271         try {
272                 static bool tried_throw = false;
273                 // try once to re-throw currently active exception
274                 if (!tried_throw) {
275                         tried_throw = true;
276                         throw;
277                 }
278         }
279         catch (const std::exception &e) {
280                 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
281                           << e.what() << std::endl;
282         }
283         catch (...) {
284                 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
285                           << std::endl;
286         }
287
288         abort();
289 }
290
291 void
292 dcpomatic_setup_path_encoding ()
293 {
294 #ifdef DCPOMATIC_WINDOWS
295         /* Dark voodoo which, I think, gets boost::filesystem::path to
296            correctly convert UTF-8 strings to paths, and also paths
297            back to UTF-8 strings (on path::string()).
298
299            After this, constructing boost::filesystem::paths from strings
300            converts from UTF-8 to UTF-16 inside the path.  Then
301            path::string().c_str() gives UTF-8 and
302            path::c_str()          gives UTF-16.
303
304            This is all Windows-only.  AFAICT Linux/OS X use UTF-8 everywhere,
305            so things are much simpler.
306         */
307         std::locale::global (boost::locale::generator().generate (""));
308         boost::filesystem::path::imbue (std::locale ());
309 #endif
310 }
311
312 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
313  *  Must be called from the UI thread, if there is one.
314  */
315 void
316 dcpomatic_setup ()
317 {
318 #ifdef DCPOMATIC_WINDOWS
319         boost::filesystem::path p = g_get_user_config_dir ();
320         p /= "backtrace.txt";
321         set_backtrace_file (p);
322         SetUnhandledExceptionFilter(exception_handler);
323 #endif
324
325         avfilter_register_all ();
326
327 #ifdef DCPOMATIC_OSX
328         /* Add our lib directory to the libltdl search path so that
329            xmlsec can find xmlsec1-openssl.
330         */
331         boost::filesystem::path lib = app_contents ();
332         lib /= "lib";
333         setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
334 #endif
335
336         set_terminate (terminate);
337
338         Pango::init ();
339         dcp::init ();
340
341         Ratio::setup_ratios ();
342         PresetColourConversion::setup_colour_conversion_presets ();
343         VideoContentScale::setup_scales ();
344         DCPContentType::setup_dcp_content_types ();
345         Filter::setup_filters ();
346         CinemaSoundProcessor::setup_cinema_sound_processors ();
347         AudioProcessor::setup_audio_processors ();
348
349         curl_global_init (CURL_GLOBAL_ALL);
350
351 #ifdef DCPOMATIC_GRAPHICS_MAGICK
352         Magick::InitializeMagick (0);
353 #endif
354
355         ui_thread = boost::this_thread::get_id ();
356 }
357
358 #ifdef DCPOMATIC_WINDOWS
359 boost::filesystem::path
360 mo_path ()
361 {
362         wchar_t buffer[512];
363         GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
364         boost::filesystem::path p (buffer);
365         p = p.parent_path ();
366         p = p.parent_path ();
367         p /= "locale";
368         return p;
369 }
370 #endif
371
372 #ifdef DCPOMATIC_OSX
373 boost::filesystem::path
374 mo_path ()
375 {
376         return "DCP-o-matic 2.app/Contents/Resources";
377 }
378 #endif
379
380 void
381 dcpomatic_setup_gettext_i18n (string lang)
382 {
383 #ifdef DCPOMATIC_LINUX
384         lang += ".UTF8";
385 #endif
386
387         if (!lang.empty ()) {
388                 /* Override our environment language.  Note that the caller must not
389                    free the string passed into putenv().
390                 */
391                 string s = String::compose ("LANGUAGE=%1", lang);
392                 putenv (strdup (s.c_str ()));
393                 s = String::compose ("LANG=%1", lang);
394                 putenv (strdup (s.c_str ()));
395                 s = String::compose ("LC_ALL=%1", lang);
396                 putenv (strdup (s.c_str ()));
397         }
398
399         setlocale (LC_ALL, "");
400         textdomain ("libdcpomatic2");
401
402 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
403         bindtextdomain ("libdcpomatic2", mo_path().string().c_str());
404         bind_textdomain_codeset ("libdcpomatic2", "UTF8");
405 #endif
406
407 #ifdef DCPOMATIC_LINUX
408         bindtextdomain ("libdcpomatic2", LINUX_LOCALE_PREFIX);
409 #endif
410 }
411
412 /** Compute a digest of the first and last `size' bytes of a set of files. */
413 string
414 digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
415 {
416         boost::scoped_array<char> buffer (new char[size]);
417         Digester digester;
418
419         /* Head */
420         boost::uintmax_t to_do = size;
421         char* p = buffer.get ();
422         int i = 0;
423         while (i < int64_t (files.size()) && to_do > 0) {
424                 FILE* f = fopen_boost (files[i], "rb");
425                 if (!f) {
426                         throw OpenFileError (files[i].string(), errno, true);
427                 }
428
429                 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
430                 fread (p, 1, this_time, f);
431                 p += this_time;
432                 to_do -= this_time;
433                 fclose (f);
434
435                 ++i;
436         }
437         digester.add (buffer.get(), size - to_do);
438
439         /* Tail */
440         to_do = size;
441         p = buffer.get ();
442         i = files.size() - 1;
443         while (i >= 0 && to_do > 0) {
444                 FILE* f = fopen_boost (files[i], "rb");
445                 if (!f) {
446                         throw OpenFileError (files[i].string(), errno, true);
447                 }
448
449                 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
450                 dcpomatic_fseek (f, -this_time, SEEK_END);
451                 fread (p, 1, this_time, f);
452                 p += this_time;
453                 to_do -= this_time;
454                 fclose (f);
455
456                 --i;
457         }
458         digester.add (buffer.get(), size - to_do);
459
460         return digester.get ();
461 }
462
463 /** Round a number up to the nearest multiple of another number.
464  *  @param c Index.
465  *  @param s Array of numbers to round, indexed by c.
466  *  @param t Multiple to round to.
467  *  @return Rounded number.
468  */
469 int
470 stride_round_up (int c, int const * stride, int t)
471 {
472         int const a = stride[c] + (t - 1);
473         return a - (a % t);
474 }
475
476 /** Trip an assert if the caller is not in the UI thread */
477 void
478 ensure_ui_thread ()
479 {
480         DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
481 }
482
483 string
484 audio_channel_name (int c)
485 {
486         DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
487
488         /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
489         /// enhancement channel (sub-woofer).
490         string const channels[] = {
491                 _("Left"),
492                 _("Right"),
493                 _("Centre"),
494                 _("Lfe (sub)"),
495                 _("Left surround"),
496                 _("Right surround"),
497                 _("Hearing impaired"),
498                 _("Visually impaired"),
499                 _("Left centre"),
500                 _("Right centre"),
501                 _("Left rear surround"),
502                 _("Right rear surround"),
503                 _("D-BOX primary"),
504                 _("D-BOX secondary"),
505                 _("Unused"),
506                 _("Unused")
507         };
508
509         return channels[c];
510 }
511
512 string
513 short_audio_channel_name (int c)
514 {
515         DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
516
517         /// TRANSLATORS: these are short names of audio channels; Lfe is the low-frequency
518         /// enhancement channel (sub-woofer).  HI is the hearing-impaired audio track and
519         /// VI is the visually-impaired audio track (audio describe).  DBP is the D-BOX
520         /// primary channel and DBS is the D-BOX secondary channel.
521         string const channels[] = {
522                 _("L"),
523                 _("R"),
524                 _("C"),
525                 _("Lfe"),
526                 _("Ls"),
527                 _("Rs"),
528                 _("HI"),
529                 _("VI"),
530                 _("Lc"),
531                 _("Rc"),
532                 _("BsL"),
533                 _("BsR"),
534                 _("DBP"),
535                 _("DBS"),
536                 "",
537                 ""
538         };
539
540         return channels[c];
541 }
542
543
544 bool
545 valid_image_file (boost::filesystem::path f)
546 {
547         if (boost::starts_with (f.leaf().string(), "._")) {
548                 return false;
549         }
550
551         string ext = f.extension().string();
552         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
553         return (
554                 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
555                 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
556                 ext == ".j2c" || ext == ".j2k" || ext == ".jp2"
557                 );
558 }
559
560 bool
561 valid_sound_file (boost::filesystem::path f)
562 {
563         if (boost::starts_with (f.leaf().string(), "._")) {
564                 return false;
565         }
566
567         string ext = f.extension().string();
568         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
569         return (ext == ".wav" || ext == ".mp3" || ext == ".aif" || ext == ".aiff");
570 }
571
572 bool
573 valid_j2k_file (boost::filesystem::path f)
574 {
575         string ext = f.extension().string();
576         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
577         return (ext == ".j2k" || ext == ".j2c" || ext == ".jp2");
578 }
579
580 string
581 tidy_for_filename (string f)
582 {
583         boost::replace_if (f, boost::is_any_of ("\\/:"), '_');
584         return f;
585 }
586
587 dcp::Size
588 fit_ratio_within (float ratio, dcp::Size full_frame)
589 {
590         if (ratio < full_frame.ratio ()) {
591                 return dcp::Size (lrintf (full_frame.height * ratio), full_frame.height);
592         }
593
594         return dcp::Size (full_frame.width, lrintf (full_frame.width / ratio));
595 }
596
597 void *
598 wrapped_av_malloc (size_t s)
599 {
600         void* p = av_malloc (s);
601         if (!p) {
602                 throw bad_alloc ();
603         }
604         return p;
605 }
606
607 map<string, string>
608 split_get_request (string url)
609 {
610         enum {
611                 AWAITING_QUESTION_MARK,
612                 KEY,
613                 VALUE
614         } state = AWAITING_QUESTION_MARK;
615
616         map<string, string> r;
617         string k;
618         string v;
619         for (size_t i = 0; i < url.length(); ++i) {
620                 switch (state) {
621                 case AWAITING_QUESTION_MARK:
622                         if (url[i] == '?') {
623                                 state = KEY;
624                         }
625                         break;
626                 case KEY:
627                         if (url[i] == '=') {
628                                 v.clear ();
629                                 state = VALUE;
630                         } else {
631                                 k += url[i];
632                         }
633                         break;
634                 case VALUE:
635                         if (url[i] == '&') {
636                                 r.insert (make_pair (k, v));
637                                 k.clear ();
638                                 state = KEY;
639                         } else {
640                                 v += url[i];
641                         }
642                         break;
643                 }
644         }
645
646         if (state == VALUE) {
647                 r.insert (make_pair (k, v));
648         }
649
650         return r;
651 }
652
653 string
654 video_asset_filename (shared_ptr<dcp::PictureAsset> asset, int reel_index, int reel_count, optional<string> summary)
655 {
656         dcp::NameFormat::Map values;
657         values['t'] = "j2c";
658         values['r'] = raw_convert<string> (reel_index + 1);
659         values['n'] = raw_convert<string> (reel_count);
660         if (summary) {
661                 values['c'] = careful_string_filter (summary.get());
662         }
663         return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
664 }
665
666 string
667 audio_asset_filename (shared_ptr<dcp::SoundAsset> asset, int reel_index, int reel_count, optional<string> summary)
668 {
669         dcp::NameFormat::Map values;
670         values['t'] = "pcm";
671         values['r'] = raw_convert<string> (reel_index + 1);
672         values['n'] = raw_convert<string> (reel_count);
673         if (summary) {
674                 values['c'] = careful_string_filter (summary.get());
675         }
676         return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
677 }
678
679 float
680 relaxed_string_to_float (string s)
681 {
682         try {
683                 boost::algorithm::replace_all (s, ",", ".");
684                 return lexical_cast<float> (s);
685         } catch (bad_lexical_cast) {
686                 boost::algorithm::replace_all (s, ".", ",");
687                 return lexical_cast<float> (s);
688         }
689 }
690
691 string
692 careful_string_filter (string s)
693 {
694         /* Filter out `bad' characters which `may' cause problems with some systems (either for DCP name or filename).
695            There's no apparent list of what really is allowed, so this is a guess.
696            Safety first and all that.
697         */
698
699         string out;
700         string const allowed = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_%.";
701         for (size_t i = 0; i < s.size(); ++i) {
702                 if (allowed.find (s[i]) != string::npos) {
703                         out += s[i];
704                 }
705         }
706
707         return out;
708 }