diff options
| author | Carl Hetherington <cth@carlh.net> | 2020-03-16 00:44:31 +0100 |
|---|---|---|
| committer | Carl Hetherington <cth@carlh.net> | 2020-04-06 15:57:14 +0200 |
| commit | a1f7bf2d9e5610075fbd898cdf52f4f8373741f2 (patch) | |
| tree | 5539cea37bebe3347408b9404ac3d9aa5cd5fe1b /src/lib | |
| parent | adddda49c17e87198253d9c900dcef0f5fb2e175 (diff) | |
Add disk writer tool.
Diffstat (limited to 'src/lib')
| -rw-r--r-- | src/lib/copy_to_drive_job.cc | 92 | ||||
| -rw-r--r-- | src/lib/copy_to_drive_job.h | 40 | ||||
| -rw-r--r-- | src/lib/cross.cc | 538 | ||||
| -rw-r--r-- | src/lib/cross.h | 43 | ||||
| -rw-r--r-- | src/lib/cross_common.cc | 51 | ||||
| -rw-r--r-- | src/lib/cross_linux.cc | 340 | ||||
| -rw-r--r-- | src/lib/cross_osx.cc | 472 | ||||
| -rw-r--r-- | src/lib/cross_windows.cc | 568 | ||||
| -rw-r--r-- | src/lib/dcpomatic_log.h | 2 | ||||
| -rw-r--r-- | src/lib/disk_writer_messages.h | 77 | ||||
| -rw-r--r-- | src/lib/exceptions.cc | 17 | ||||
| -rw-r--r-- | src/lib/exceptions.h | 42 | ||||
| -rw-r--r-- | src/lib/file_log.cc | 9 | ||||
| -rw-r--r-- | src/lib/file_log.h | 1 | ||||
| -rw-r--r-- | src/lib/log.h | 3 | ||||
| -rw-r--r-- | src/lib/log_entry.cc | 17 | ||||
| -rw-r--r-- | src/lib/log_entry.h | 3 | ||||
| -rw-r--r-- | src/lib/nanomsg.cc | 145 | ||||
| -rw-r--r-- | src/lib/nanomsg.h | 48 | ||||
| -rw-r--r-- | src/lib/state.cc | 14 | ||||
| -rw-r--r-- | src/lib/wscript | 17 |
21 files changed, 1976 insertions, 563 deletions
diff --git a/src/lib/copy_to_drive_job.cc b/src/lib/copy_to_drive_job.cc new file mode 100644 index 000000000..b7bb5a60d --- /dev/null +++ b/src/lib/copy_to_drive_job.cc @@ -0,0 +1,92 @@ +/* + Copyright (C) 2019-2020 Carl Hetherington <cth@carlh.net> + + This file is part of DCP-o-matic. + + DCP-o-matic is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + DCP-o-matic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with DCP-o-matic. If not, see <http://www.gnu.org/licenses/>. + +*/ + +#include "disk_writer_messages.h" +#include "copy_to_drive_job.h" +#include "compose.hpp" +#include "exceptions.h" +#include <dcp/raw_convert.h> +#include <nanomsg/nn.h> +#include <unistd.h> +#include <fcntl.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <iostream> + +#include "i18n.h" + +using std::string; +using std::cout; +using std::min; +using boost::shared_ptr; +using dcp::raw_convert; + +CopyToDriveJob::CopyToDriveJob (boost::filesystem::path dcp, Drive drive, Nanomsg& nanomsg) + : Job (shared_ptr<Film>()) + , _dcp (dcp) + , _drive (drive) + , _nanomsg (nanomsg) +{ + +} + +string +CopyToDriveJob::name () const +{ + return String::compose (_("Copying %1 to %2"), _dcp.filename().string(), _drive.description()); +} + +string +CopyToDriveJob::json_name () const +{ + return N_("copy"); +} + +void +CopyToDriveJob::run () +{ + if (!_nanomsg.nonblocking_send(String::compose("W\n%1\n%2\n", _dcp.string(), _drive.internal_name()))) { + throw CopyError ("Could not communicate with writer process", 0); + } + + bool formatting = false; + while (true) { + string s = _nanomsg.blocking_get (); + if (s == DISK_WRITER_OK) { + set_state (FINISHED_OK); + return; + } else if (s == DISK_WRITER_ERROR) { + string const m = _nanomsg.blocking_get (); + string const n = _nanomsg.blocking_get (); + throw CopyError (m, raw_convert<int>(n)); + } else if (s == DISK_WRITER_FORMATTING) { + sub ("Formatting drive"); + set_progress_unknown (); + formatting = true; + } else if (s == DISK_WRITER_PROGRESS) { + if (formatting) { + sub ("Copying DCP"); + formatting = false; + } + set_progress (raw_convert<float>(_nanomsg.blocking_get())); + } + } +} diff --git a/src/lib/copy_to_drive_job.h b/src/lib/copy_to_drive_job.h new file mode 100644 index 000000000..1a1a99f44 --- /dev/null +++ b/src/lib/copy_to_drive_job.h @@ -0,0 +1,40 @@ +/* + Copyright (C) 2019-2020 Carl Hetherington <cth@carlh.net> + + This file is part of DCP-o-matic. + + DCP-o-matic is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + DCP-o-matic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with DCP-o-matic. If not, see <http://www.gnu.org/licenses/>. + +*/ + +#include "cross.h" +#include "job.h" +#include "nanomsg.h" + +class CopyToDriveJob : public Job +{ +public: + CopyToDriveJob (boost::filesystem::path dcp, Drive drive, Nanomsg& nanomsg); + + std::string name () const; + std::string json_name () const; + void run (); + +private: + void count (boost::filesystem::path dir, uint64_t& total_bytes); + void copy (boost::filesystem::path from, boost::filesystem::path to, uint64_t& total_remaining, uint64_t total); + boost::filesystem::path _dcp; + Drive _drive; + Nanomsg& _nanomsg; +}; diff --git a/src/lib/cross.cc b/src/lib/cross.cc deleted file mode 100644 index 5d35d5a4b..000000000 --- a/src/lib/cross.cc +++ /dev/null @@ -1,538 +0,0 @@ -/* - Copyright (C) 2012-2018 Carl Hetherington <cth@carlh.net> - - This file is part of DCP-o-matic. - - DCP-o-matic is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - DCP-o-matic is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with DCP-o-matic. If not, see <http://www.gnu.org/licenses/>. - -*/ - -#include "cross.h" -#include "compose.hpp" -#include "log.h" -#include "dcpomatic_log.h" -#include "config.h" -#include "exceptions.h" -extern "C" { -#include <libavformat/avio.h> -} -#include <boost/algorithm/string.hpp> -#ifdef DCPOMATIC_LINUX -#include <unistd.h> -#include <mntent.h> -#endif -#ifdef DCPOMATIC_WINDOWS -#include <windows.h> -#undef DATADIR -#include <shlwapi.h> -#include <shellapi.h> -#include <fcntl.h> -#endif -#ifdef DCPOMATIC_OSX -#include <sys/sysctl.h> -#include <mach-o/dyld.h> -#include <IOKit/pwr_mgt/IOPMLib.h> -#endif -#ifdef DCPOMATIC_POSIX -#include <sys/types.h> -#include <ifaddrs.h> -#include <netinet/in.h> -#include <arpa/inet.h> -#endif -#include <fstream> - -#include "i18n.h" - -using std::pair; -using std::list; -using std::ifstream; -using std::string; -using std::wstring; -using std::make_pair; -using std::runtime_error; -using boost::shared_ptr; - -/** @param s Number of seconds to sleep for */ -void -dcpomatic_sleep_seconds (int s) -{ -#ifdef DCPOMATIC_POSIX - sleep (s); -#endif -#ifdef DCPOMATIC_WINDOWS - Sleep (s * 1000); -#endif -} - -void -dcpomatic_sleep_milliseconds (int ms) -{ -#ifdef DCPOMATIC_POSIX - usleep (ms * 1000); -#endif -#ifdef DCPOMATIC_WINDOWS - Sleep (ms); -#endif -} - -/** @return A string of CPU information (model name etc.) */ -string -cpu_info () -{ - string info; - -#ifdef DCPOMATIC_LINUX - /* This use of ifstream is ok; the filename can never - be non-Latin - */ - ifstream f ("/proc/cpuinfo"); - while (f.good ()) { - string l; - getline (f, l); - if (boost::algorithm::starts_with (l, "model name")) { - string::size_type const c = l.find (':'); - if (c != string::npos) { - info = l.substr (c + 2); - } - } - } -#endif - -#ifdef DCPOMATIC_OSX - char buffer[64]; - size_t N = sizeof (buffer); - if (sysctlbyname ("machdep.cpu.brand_string", buffer, &N, 0, 0) == 0) { - info = buffer; - } -#endif - -#ifdef DCPOMATIC_WINDOWS - HKEY key; - if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &key) != ERROR_SUCCESS) { - return info; - } - - DWORD type; - DWORD data; - if (RegQueryValueEx (key, L"ProcessorNameString", 0, &type, 0, &data) != ERROR_SUCCESS) { - return info; - } - - if (type != REG_SZ) { - return info; - } - - wstring value (data / sizeof (wchar_t), L'\0'); - if (RegQueryValueEx (key, L"ProcessorNameString", 0, 0, reinterpret_cast<LPBYTE> (&value[0]), &data) != ERROR_SUCCESS) { - RegCloseKey (key); - return info; - } - - info = string (value.begin(), value.end()); - - RegCloseKey (key); - -#endif - - return info; -} - -#ifdef DCPOMATIC_OSX -/** @return Path of the Contents directory in the .app */ -boost::filesystem::path -app_contents () -{ - uint32_t size = 1024; - char buffer[size]; - if (_NSGetExecutablePath (buffer, &size)) { - throw runtime_error ("_NSGetExecutablePath failed"); - } - - boost::filesystem::path path (buffer); - path = boost::filesystem::canonical (path); - path = path.parent_path (); - path = path.parent_path (); - return path; -} -#endif - -boost::filesystem::path -shared_path () -{ -#ifdef DCPOMATIC_LINUX - char const * p = getenv ("DCPOMATIC_LINUX_SHARE_PREFIX"); - if (p) { - return p; - } - return boost::filesystem::canonical (LINUX_SHARE_PREFIX); -#endif -#ifdef DCPOMATIC_WINDOWS - wchar_t dir[512]; - GetModuleFileName (GetModuleHandle (0), dir, sizeof (dir)); - PathRemoveFileSpec (dir); - boost::filesystem::path path = dir; - return path.parent_path(); -#endif -#ifdef DCPOMATIC_OSX - return app_contents() / "Resources"; -#endif -} - -void -run_ffprobe (boost::filesystem::path content, boost::filesystem::path out) -{ -#ifdef DCPOMATIC_WINDOWS - SECURITY_ATTRIBUTES security; - security.nLength = sizeof (security); - security.bInheritHandle = TRUE; - security.lpSecurityDescriptor = 0; - - HANDLE child_stderr_read; - HANDLE child_stderr_write; - if (!CreatePipe (&child_stderr_read, &child_stderr_write, &security, 0)) { - LOG_ERROR_NC ("ffprobe call failed (could not CreatePipe)"); - return; - } - - wchar_t dir[512]; - GetModuleFileName (GetModuleHandle (0), dir, sizeof (dir)); - PathRemoveFileSpec (dir); - SetCurrentDirectory (dir); - - STARTUPINFO startup_info; - ZeroMemory (&startup_info, sizeof (startup_info)); - startup_info.cb = sizeof (startup_info); - startup_info.hStdError = child_stderr_write; - startup_info.dwFlags |= STARTF_USESTDHANDLES; - - wchar_t command[512]; - wcscpy (command, L"ffprobe.exe \""); - - wchar_t file[512]; - MultiByteToWideChar (CP_UTF8, 0, content.string().c_str(), -1, file, sizeof(file)); - wcscat (command, file); - - wcscat (command, L"\""); - - PROCESS_INFORMATION process_info; - ZeroMemory (&process_info, sizeof (process_info)); - if (!CreateProcess (0, command, 0, 0, TRUE, CREATE_NO_WINDOW, 0, 0, &startup_info, &process_info)) { - LOG_ERROR_NC (N_("ffprobe call failed (could not CreateProcess)")); - return; - } - - FILE* o = fopen_boost (out, "w"); - if (!o) { - LOG_ERROR_NC (N_("ffprobe call failed (could not create output file)")); - return; - } - - CloseHandle (child_stderr_write); - - while (true) { - char buffer[512]; - DWORD read; - if (!ReadFile(child_stderr_read, buffer, sizeof(buffer), &read, 0) || read == 0) { - break; - } - fwrite (buffer, read, 1, o); - } - - fclose (o); - - WaitForSingleObject (process_info.hProcess, INFINITE); - CloseHandle (process_info.hProcess); - CloseHandle (process_info.hThread); - CloseHandle (child_stderr_read); -#endif - -#ifdef DCPOMATIC_LINUX - string ffprobe = "ffprobe \"" + content.string() + "\" 2> \"" + out.string() + "\""; - LOG_GENERAL (N_("Probing with %1"), ffprobe); - system (ffprobe.c_str ()); -#endif - -#ifdef DCPOMATIC_OSX - boost::filesystem::path path = app_contents(); - path /= "MacOS"; - path /= "ffprobe"; - - string ffprobe = "\"" + path.string() + "\" \"" + content.string() + "\" 2> \"" + out.string() + "\""; - LOG_GENERAL (N_("Probing with %1"), ffprobe); - system (ffprobe.c_str ()); -#endif -} - -list<pair<string, string> > -mount_info () -{ - list<pair<string, string> > m; - -#ifdef DCPOMATIC_LINUX - FILE* f = setmntent ("/etc/mtab", "r"); - if (!f) { - return m; - } - - while (true) { - struct mntent* mnt = getmntent (f); - if (!mnt) { - break; - } - - m.push_back (make_pair (mnt->mnt_dir, mnt->mnt_type)); - } - - endmntent (f); -#endif - - return m; -} - -boost::filesystem::path -openssl_path () -{ -#ifdef DCPOMATIC_WINDOWS - wchar_t dir[512]; - GetModuleFileName (GetModuleHandle (0), dir, sizeof (dir)); - PathRemoveFileSpec (dir); - - boost::filesystem::path path = dir; - path /= "openssl.exe"; - return path; -#endif - -#ifdef DCPOMATIC_OSX - boost::filesystem::path path = app_contents(); - path /= "MacOS"; - path /= "openssl"; - return path; -#endif - -#ifdef DCPOMATIC_LINUX - return "dcpomatic2_openssl"; -#endif - -} - -/* Apparently there is no way to create an ofstream using a UTF-8 - filename under Windows. We are hence reduced to using fopen - with this wrapper. -*/ -FILE * -fopen_boost (boost::filesystem::path p, string t) -{ -#ifdef DCPOMATIC_WINDOWS - wstring w (t.begin(), t.end()); - /* c_str() here should give a UTF-16 string */ - return _wfopen (p.c_str(), w.c_str ()); -#else - return fopen (p.c_str(), t.c_str ()); -#endif -} - -int -dcpomatic_fseek (FILE* stream, int64_t offset, int whence) -{ -#ifdef DCPOMATIC_WINDOWS - return _fseeki64 (stream, offset, whence); -#else - return fseek (stream, offset, whence); -#endif -} - -void -Waker::nudge () -{ -#ifdef DCPOMATIC_WINDOWS - boost::mutex::scoped_lock lm (_mutex); - SetThreadExecutionState (ES_SYSTEM_REQUIRED); -#endif -} - -Waker::Waker () -{ -#ifdef DCPOMATIC_OSX - boost::mutex::scoped_lock lm (_mutex); - /* We should use this */ - // IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, CFSTR ("Encoding DCP"), &_assertion_id); - /* but it's not available on 10.5, so we use this */ - IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &_assertion_id); -#endif -} - -Waker::~Waker () -{ -#ifdef DCPOMATIC_OSX - boost::mutex::scoped_lock lm (_mutex); - IOPMAssertionRelease (_assertion_id); -#endif -} - -void -start_tool (boost::filesystem::path dcpomatic, string executable, -#ifdef DCPOMATIC_OSX - string app -#else - string -#endif - ) -{ -#if defined(DCPOMATIC_LINUX) || defined(DCPOMATIC_WINDOWS) - boost::filesystem::path batch = dcpomatic.parent_path() / executable; -#endif - -#ifdef DCPOMATIC_OSX - boost::filesystem::path batch = dcpomatic.parent_path (); - batch = batch.parent_path (); // MacOS - batch = batch.parent_path (); // Contents - batch = batch.parent_path (); // DCP-o-matic.app - batch = batch.parent_path (); // Applications - batch /= app; - batch /= "Contents"; - batch /= "MacOS"; - batch /= executable; -#endif - -#if defined(DCPOMATIC_LINUX) || defined(DCPOMATIC_OSX) - pid_t pid = fork (); - if (pid == 0) { - int const r = system (batch.string().c_str()); - exit (WEXITSTATUS (r)); - } -#endif - -#ifdef DCPOMATIC_WINDOWS - STARTUPINFO startup_info; - ZeroMemory (&startup_info, sizeof (startup_info)); - startup_info.cb = sizeof (startup_info); - - PROCESS_INFORMATION process_info; - ZeroMemory (&process_info, sizeof (process_info)); - - wchar_t cmd[512]; - MultiByteToWideChar (CP_UTF8, 0, batch.string().c_str(), -1, cmd, sizeof(cmd)); - CreateProcess (0, cmd, 0, 0, FALSE, 0, 0, 0, &startup_info, &process_info); -#endif -} - -void -start_batch_converter (boost::filesystem::path dcpomatic) -{ - start_tool (dcpomatic, "dcpomatic2_batch", "DCP-o-matic\\ 2\\ Batch\\ Converter.app"); -} - -void -start_player (boost::filesystem::path dcpomatic) -{ - start_tool (dcpomatic, "dcpomatic2_player", "DCP-o-matic\\ 2\\ Player.app"); -} - -uint64_t -thread_id () -{ -#ifdef DCPOMATIC_WINDOWS - return (uint64_t) GetCurrentThreadId (); -#else - return (uint64_t) pthread_self (); -#endif -} - -int -avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags) -{ -#ifdef DCPOMATIC_WINDOWS - int const length = (file.string().length() + 1) * 2; - char* utf8 = new char[length]; - WideCharToMultiByte (CP_UTF8, 0, file.c_str(), -1, utf8, length, 0, 0); - int const r = avio_open (s, utf8, flags); - delete[] utf8; - return r; -#else - return avio_open (s, file.c_str(), flags); -#endif -} - -#ifdef DCPOMATIC_WINDOWS -void -maybe_open_console () -{ - if (Config::instance()->win32_console ()) { - AllocConsole(); - - HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE); - int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT); - FILE* hf_out = _fdopen(hCrt, "w"); - setvbuf(hf_out, NULL, _IONBF, 1); - *stdout = *hf_out; - - HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE); - hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT); - FILE* hf_in = _fdopen(hCrt, "r"); - setvbuf(hf_in, NULL, _IONBF, 128); - *stdin = *hf_in; - } -} -#endif - -boost::filesystem::path -home_directory () -{ -#if defined(DCPOMATIC_LINUX) || defined(DCPOMATIC_OSX) - return getenv("HOME"); -#endif -#ifdef DCPOMATIC_WINDOWS - return boost::filesystem::path(getenv("HOMEDRIVE")) / boost::filesystem::path(getenv("HOMEPATH")); -#endif -} - -string -command_and_read (string cmd) -{ -#ifdef DCPOMATIC_LINUX - FILE* pipe = popen (cmd.c_str(), "r"); - if (!pipe) { - throw runtime_error ("popen failed"); - } - - string result; - char buffer[128]; - try { - while (fgets(buffer, sizeof(buffer), pipe)) { - result += buffer; - } - } catch (...) { - pclose (pipe); - throw; - } - - pclose (pipe); - return result; -#endif - - return ""; -} - -/** @return true if this process is a 32-bit one running on a 64-bit-capable OS */ -bool -running_32_on_64 () -{ -#ifdef DCPOMATIC_WINDOWS - BOOL p; - IsWow64Process (GetCurrentProcess(), &p); - return p; -#endif - /* XXX: assuming nobody does this on Linux / OS X */ - return false; -} diff --git a/src/lib/cross.h b/src/lib/cross.h index 584fa2b42..20bab38a2 100644 --- a/src/lib/cross.h +++ b/src/lib/cross.h @@ -1,5 +1,5 @@ /* - Copyright (C) 2012-2018 Carl Hetherington <cth@carlh.net> + Copyright (C) 2012-2020 Carl Hetherington <cth@carlh.net> This file is part of DCP-o-matic. @@ -30,6 +30,7 @@ #endif #include <boost/filesystem.hpp> #include <boost/thread/mutex.hpp> +#include <boost/optional.hpp> #ifdef DCPOMATIC_WINDOWS #define WEXITSTATUS(w) (w) @@ -44,6 +45,7 @@ extern std::string cpu_info (); extern void run_ffprobe (boost::filesystem::path, boost::filesystem::path); extern std::list<std::pair<std::string, std::string> > mount_info (); extern boost::filesystem::path openssl_path (); +extern boost::filesystem::path disk_writer_path (); #ifdef DCPOMATIC_OSX extern boost::filesystem::path app_contents (); #endif @@ -60,6 +62,15 @@ extern int avio_open_boost (AVIOContext** s, boost::filesystem::path file, int f extern boost::filesystem::path home_directory (); extern std::string command_and_read (std::string cmd); extern bool running_32_on_64 (); +extern void unprivileged (); +extern boost::filesystem::path config_path (); + +class PrivilegeEscalator +{ +public: + PrivilegeEscalator (); + ~PrivilegeEscalator (); +}; /** @class Waker * @brief A class which tries to keep the computer awake on various operating systems. @@ -82,4 +93,34 @@ private: #endif }; +class Drive +{ +public: + Drive (std::string internal_name, uint64_t size, bool mounted, boost::optional<std::string> vendor, boost::optional<std::string> model) + : _internal_name(internal_name) + , _size(size) + , _mounted(mounted) + , _vendor(vendor) + , _model(model) + {} + + std::string description () const; + std::string internal_name () const { + return _internal_name; + } + bool mounted () const { + return _mounted; + } + +private: + std::string _internal_name; + /** size in bytes */ + uint64_t _size; + bool _mounted; + boost::optional<std::string> _vendor; + boost::optional<std::string> _model; +}; + +std::vector<Drive> get_drives (); + #endif diff --git a/src/lib/cross_common.cc b/src/lib/cross_common.cc new file mode 100644 index 000000000..b3a39402a --- /dev/null +++ b/src/lib/cross_common.cc @@ -0,0 +1,51 @@ +/* + Copyright (C) 2012-2020 Carl Hetherington <cth@carlh.net> + + This file is part of DCP-o-matic. + + DCP-o-matic is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + DCP-o-matic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with DCP-o-matic. If not, see <http://www.gnu.org/licenses/>. + +*/ + +#include "cross.h" +#include "compose.hpp" + +#include "i18n.h" + +using std::string; + +string +Drive::description () const +{ + char gb[64]; + snprintf(gb, 64, "%.1f", _size / 1000000000.0); + + string name; + if (_vendor) { + name += *_vendor; + } + if (_model) { + if (name.size() > 0) { + name += " " + *_model; + } else { + name = *_model; + } + } + if (name.size() == 0) { + name = _("Unknown"); + } + + return String::compose("%1 (%2 GB) [%3]", name, gb, _internal_name); +} + diff --git a/src/lib/cross_linux.cc b/src/lib/cross_linux.cc new file mode 100644 index 000000000..406087917 --- /dev/null +++ b/src/lib/cross_linux.cc @@ -0,0 +1,340 @@ +/* + Copyright (C) 2012-2020 Carl Hetherington <cth@carlh.net> + + This file is part of DCP-o-matic. + + DCP-o-matic is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + DCP-o-matic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with DCP-o-matic. If not, see <http://www.gnu.org/licenses/>. + +*/ + +#include "cross.h" +#include "compose.hpp" +#include "log.h" +#include "dcpomatic_log.h" +#include "config.h" +#include "exceptions.h" +#include <dcp/raw_convert.h> +#include <glib.h> +extern "C" { +#include <libavformat/avio.h> +} +#include <boost/algorithm/string.hpp> +#include <boost/foreach.hpp> +#include <boost/dll/runtime_symbol_info.hpp> +#include <unistd.h> +#include <mntent.h> +#include <sys/types.h> +#include <ifaddrs.h> +#include <netinet/in.h> +#include <arpa/inet.h> +#include <fstream> + +#include "i18n.h" + +using std::pair; +using std::list; +using std::ifstream; +using std::string; +using std::wstring; +using std::make_pair; +using std::vector; +using std::cerr; +using std::cout; +using std::runtime_error; +using boost::shared_ptr; +using boost::optional; + +/** @param s Number of seconds to sleep for */ +void +dcpomatic_sleep_seconds (int s) +{ + sleep (s); +} + +void +dcpomatic_sleep_milliseconds (int ms) +{ + usleep (ms * 1000); +} + +/** @return A string of CPU information (model name etc.) */ +string +cpu_info () +{ + string info; + + /* This use of ifstream is ok; the filename can never + be non-Latin + */ + ifstream f ("/proc/cpuinfo"); + while (f.good ()) { + string l; + getline (f, l); + if (boost::algorithm::starts_with (l, "model name")) { + string::size_type const c = l.find (':'); + if (c != string::npos) { + info = l.substr (c + 2); + } + } + } + + return info; +} + +boost::filesystem::path +shared_path () +{ + char const * p = getenv ("DCPOMATIC_LINUX_SHARE_PREFIX"); + if (p) { + return p; + } + return boost::filesystem::canonical (LINUX_SHARE_PREFIX); +} + +void +run_ffprobe (boost::filesystem::path content, boost::filesystem::path out) +{ + string ffprobe = "ffprobe \"" + content.string() + "\" 2> \"" + out.string() + "\""; + LOG_GENERAL (N_("Probing with %1"), ffprobe); + system (ffprobe.c_str ()); +} + +list<pair<string, string> > +mount_info () +{ + list<pair<string, string> > m; + + FILE* f = setmntent ("/etc/mtab", "r"); + if (!f) { + return m; + } + + while (true) { + struct mntent* mnt = getmntent (f); + if (!mnt) { + break; + } + + m.push_back (make_pair (mnt->mnt_dir, mnt->mnt_type)); + } + + endmntent (f); + + return m; +} + +boost::filesystem::path +openssl_path () +{ + return "dcpomatic2_openssl"; +} + +boost::filesystem::path +disk_writer_path () +{ + return boost::dll::program_location().parent_path() / "dcpomatic2_disk_writer"; +} + +/* Apparently there is no way to create an ofstream using a UTF-8 + filename under Windows. We are hence reduced to using fopen + with this wrapper. +*/ +FILE * +fopen_boost (boost::filesystem::path p, string t) +{ + return fopen (p.c_str(), t.c_str ()); +} + +int +dcpomatic_fseek (FILE* stream, int64_t offset, int whence) +{ + return fseek (stream, offset, whence); +} + +void +Waker::nudge () +{ + +} + +Waker::Waker () +{ + +} + +Waker::~Waker () +{ + +} + +void +start_tool (boost::filesystem::path dcpomatic, string executable, string) +{ + boost::filesystem::path batch = dcpomatic.parent_path() / executable; + + pid_t pid = fork (); + if (pid == 0) { + int const r = system (batch.string().c_str()); + exit (WEXITSTATUS (r)); + } +} + +void +start_batch_converter (boost::filesystem::path dcpomatic) +{ + start_tool (dcpomatic, "dcpomatic2_batch", "DCP-o-matic\\ 2\\ Batch\\ Converter.app"); +} + +void +start_player (boost::filesystem::path dcpomatic) +{ + start_tool (dcpomatic, "dcpomatic2_player", "DCP-o-matic\\ 2\\ Player.app"); +} + +uint64_t +thread_id () +{ + return (uint64_t) pthread_self (); +} + +int +avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags) +{ + return avio_open (s, file.c_str(), flags); +} + + +boost::filesystem::path +home_directory () +{ + return getenv("HOME"); +} + +string +command_and_read (string cmd) +{ + FILE* pipe = popen (cmd.c_str(), "r"); + if (!pipe) { + throw runtime_error ("popen failed"); + } + + string result; + char buffer[128]; + try { + while (fgets(buffer, sizeof(buffer), pipe)) { + result += buffer; + } + } catch (...) { + pclose (pipe); + throw; + } + + pclose (pipe); + return result; +} + +/** @return true if this process is a 32-bit one running on a 64-bit-capable OS */ +bool +running_32_on_64 () +{ + /* I'm assuming nobody does this on Linux */ + return false; +} + +vector<Drive> +get_drives () +{ + vector<Drive> drives; + + using namespace boost::filesystem; + list<string> mounted_devices; + std::ifstream f("/proc/mounts"); + string line; + while (f.good()) { + getline(f, line); + vector<string> bits; + boost::algorithm::split (bits, line, boost::is_any_of(" ")); + if (bits.size() > 0 && boost::algorithm::starts_with(bits[0], "/dev/")) { + mounted_devices.push_back(bits[0]); + LOG_DISK("Mounted device %1", bits[0]); + } + } + + for (directory_iterator i = directory_iterator("/sys/block"); i != directory_iterator(); ++i) { + string const name = i->path().filename().string(); + path device_type_file("/sys/block/" + name + "/device/type"); + optional<string> device_type; + if (exists(device_type_file)) { + device_type = dcp::file_to_string (device_type_file); + boost::trim(*device_type); + } + /* Device type 5 is "SCSI_TYPE_ROM" in blkdev.h; seems usually to be a CD/DVD drive */ + if (!boost::algorithm::starts_with(name, "loop") && (!device_type || *device_type != "5")) { + uint64_t const size = dcp::raw_convert<uint64_t>(dcp::file_to_string(*i / "size")) * 512; + if (size == 0) { + continue; + } + bool mounted = false; + optional<string> vendor; + try { + vendor = dcp::file_to_string("/sys/block/" + name + "/device/vendor"); + boost::trim(*vendor); + } catch (...) {} + optional<string> model; + try { + model = dcp::file_to_string("/sys/block/" + name + "/device/model"); + boost::trim(*model); + } catch (...) {} + BOOST_FOREACH (string j, mounted_devices) { + if (boost::algorithm::starts_with(j, "/dev/" + name)) { + mounted = true; + } + } + drives.push_back(Drive("/dev/" + i->path().filename().string(), size, mounted, vendor, model)); + LOG_DISK("Block device %1 size %2 %3 vendor %4 model %5", name, size, mounted ? "mounted" : "not mounted", vendor.get_value_or("[none]"), model.get_value_or("[none]")); + } + } + + return drives; +} + +void +unprivileged () +{ + uid_t ruid, euid, suid; + if (getresuid(&ruid, &euid, &suid) == -1) { + cerr << "getresuid() failed.\n"; + exit (EXIT_FAILURE); + } + seteuid (ruid); +} + +PrivilegeEscalator::~PrivilegeEscalator () +{ + unprivileged (); +} + +PrivilegeEscalator::PrivilegeEscalator () +{ + seteuid (0); +} + +boost::filesystem::path +config_path () +{ + boost::filesystem::path p; + p /= g_get_user_config_dir (); + p /= "dcpomatic2"; + return p; +} diff --git a/src/lib/cross_osx.cc b/src/lib/cross_osx.cc new file mode 100644 index 000000000..fa12fb380 --- /dev/null +++ b/src/lib/cross_osx.cc @@ -0,0 +1,472 @@ +/* + Copyright (C) 2012-2020 Carl Hetherington <cth@carlh.net> + + This file is part of DCP-o-matic. + + DCP-o-matic is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + DCP-o-matic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with DCP-o-matic. If not, see <http://www.gnu.org/licenses/>. + +*/ + +#include "cross.h" +#include "compose.hpp" +#include "log.h" +#include "dcpomatic_log.h" +#include "config.h" +#include "exceptions.h" +#include <dcp/raw_convert.h> +#include <glib.h> +extern "C" { +#include <libavformat/avio.h> +} +#include <boost/algorithm/string.hpp> +#include <boost/foreach.hpp> +#include <boost/dll/runtime_symbol_info.hpp> +#include <boost/regex.hpp> +#include <sys/sysctl.h> +#include <mach-o/dyld.h> +#include <IOKit/pwr_mgt/IOPMLib.h> +#include <IOKit/storage/IOMedia.h> +#include <DiskArbitration/DADisk.h> +#include <DiskArbitration/DiskArbitration.h> +#include <CoreFoundation/CFURL.h> +#include <sys/types.h> +#include <ifaddrs.h> +#include <netinet/in.h> +#include <arpa/inet.h> +#include <fstream> +#include <cstring> + +#include "i18n.h" + +using std::pair; +using std::list; +using std::ifstream; +using std::string; +using std::wstring; +using std::make_pair; +using std::vector; +using std::cerr; +using std::cout; +using std::runtime_error; +using boost::shared_ptr; +using boost::optional; + +/** @param s Number of seconds to sleep for */ +void +dcpomatic_sleep_seconds (int s) +{ + sleep (s); +} + +void +dcpomatic_sleep_milliseconds (int ms) +{ + usleep (ms * 1000); +} + +/** @return A string of CPU information (model name etc.) */ +string +cpu_info () +{ + string info; + + char buffer[64]; + size_t N = sizeof (buffer); + if (sysctlbyname ("machdep.cpu.brand_string", buffer, &N, 0, 0) == 0) { + info = buffer; + } + + return info; +} + +/** @return Path of the Contents directory in the .app */ +boost::filesystem::path +app_contents () +{ + return boost::dll::program_location().parent_path().parent_path(); +} + +boost::filesystem::path +shared_path () +{ + return app_contents() / "Resources"; +} + +void +run_ffprobe (boost::filesystem::path content, boost::filesystem::path out) +{ + boost::filesystem::path path = app_contents(); + path /= "MacOS"; + path /= "ffprobe"; + + string ffprobe = "\"" + path.string() + "\" \"" + content.string() + "\" 2> \"" + out.string() + "\""; + LOG_GENERAL (N_("Probing with %1"), ffprobe); + system (ffprobe.c_str ()); +} + +list<pair<string, string> > +mount_info () +{ + list<pair<string, string> > m; + return m; +} + +boost::filesystem::path +openssl_path () +{ + boost::filesystem::path path = app_contents(); + path /= "MacOS"; + path /= "openssl"; + return path; +} + +boost::filesystem::path +disk_writer_path () +{ + boost::filesystem::path path = app_contents(); + path /= "MacOS"; + path /= "dcpomatic2_disk_writer"; + return path; +} + +/* Apparently there is no way to create an ofstream using a UTF-8 + filename under Windows. We are hence reduced to using fopen + with this wrapper. +*/ +FILE * +fopen_boost (boost::filesystem::path p, string t) +{ + return fopen (p.c_str(), t.c_str ()); +} + +int +dcpomatic_fseek (FILE* stream, int64_t offset, int whence) +{ + return fseek (stream, offset, whence); +} + +void +Waker::nudge () +{ + +} + +Waker::Waker () +{ + boost::mutex::scoped_lock lm (_mutex); + /* We should use this */ + // IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, CFSTR ("Encoding DCP"), &_assertion_id); + /* but it's not available on 10.5, so we use this */ + IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &_assertion_id); +} + +Waker::~Waker () +{ + boost::mutex::scoped_lock lm (_mutex); + IOPMAssertionRelease (_assertion_id); +} + +void +start_tool (boost::filesystem::path dcpomatic, string executable, string app) +{ + boost::filesystem::path batch = dcpomatic.parent_path (); + batch = batch.parent_path (); // MacOS + batch = batch.parent_path (); // Contents + batch = batch.parent_path (); // DCP-o-matic.app + batch = batch.parent_path (); // Applications + batch /= app; + batch /= "Contents"; + batch /= "MacOS"; + batch /= executable; + + pid_t pid = fork (); + if (pid == 0) { + int const r = system (batch.string().c_str()); + exit (WEXITSTATUS (r)); + } +} + +void +start_batch_converter (boost::filesystem::path dcpomatic) +{ + start_tool (dcpomatic, "dcpomatic2_batch", "DCP-o-matic\\ 2\\ Batch\\ Converter.app"); +} + +void +start_player (boost::filesystem::path dcpomatic) +{ + start_tool (dcpomatic, "dcpomatic2_player", "DCP-o-matic\\ 2\\ Player.app"); +} + +uint64_t +thread_id () +{ + return (uint64_t) pthread_self (); +} + +int +avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags) +{ + return avio_open (s, file.c_str(), flags); +} + +boost::filesystem::path +home_directory () +{ + return getenv("HOME"); +} + +string +command_and_read (string cmd) +{ + return ""; +} + +/** @return true if this process is a 32-bit one running on a 64-bit-capable OS */ +bool +running_32_on_64 () +{ + /* I'm assuming nobody does this on OS X */ + return false; +} + +static optional<string> +get_vendor (CFDictionaryRef& description) +{ + void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceVendorKey); + if (!str) { + return optional<string>(); + } + + string s = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8); + boost::algorithm::trim (s); + return s; +} + +static optional<string> +get_model (CFDictionaryRef& description) +{ + void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceModelKey); + if (!str) { + return optional<string>(); + } + + string s = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8); + boost::algorithm::trim (s); + return s; +} + +struct MediaPath +{ + bool real; ///< true for a "real" disk, false for a synthesized APFS one + std::string prt; ///< "PRT" entry from the media path +}; + +static optional<MediaPath> +analyse_media_path (CFDictionaryRef& description) +{ + using namespace boost::algorithm; + + void const* str = CFDictionaryGetValue (description, kDADiskDescriptionMediaPathKey); + if (!str) { + return optional<MediaPath>(); + } + + string path(CFStringGetCStringPtr((CFStringRef) str, kCFStringEncodingUTF8)); + MediaPath mp; + if (starts_with(path, "IODeviceTree:")) { + mp.real = true; + } else if (starts_with(path, "IOService:")) { + mp.real = false; + } else { + return optional<MediaPath>(); + } + + vector<string> bits; + split(bits, path, boost::is_any_of("/")); + BOOST_FOREACH (string i, bits) { + if (starts_with(i, "PRT")) { + mp.prt = i; + } + } + + return mp; +} + +static bool +is_whole_drive (DADiskRef& disk) +{ + io_service_t service = DADiskCopyIOMedia (disk); + CFTypeRef whole_media_ref = IORegistryEntryCreateCFProperty (service, CFSTR(kIOMediaWholeKey), kCFAllocatorDefault, 0); + bool whole_media = false; + if (whole_media_ref) { + whole_media = CFBooleanGetValue((CFBooleanRef) whole_media_ref); + CFRelease (whole_media_ref); + } + IOObjectRelease (service); + return whole_media; +} + +static bool +is_mounted (CFDictionaryRef& description) +{ + CFURLRef volume_path_key = (CFURLRef) CFDictionaryGetValue (description, kDADiskDescriptionVolumePathKey); + char mount_path_buffer[1024]; + return CFURLGetFileSystemRepresentation(volume_path_key, false, (UInt8 *) mount_path_buffer, sizeof(mount_path_buffer)); +} + +/* Here follows some rather intricate and (probably) fragile code to find the list of available + * "real" drives on macOS that we might want to write a DCP to. + * + * We use the Disk Arbitration framework to give us a series of devices (/dev/disk0, /dev/disk1, + * /dev/disk1s1 and so on) and we use the API to gather useful information about these devices into + * a vector of Disk structs. + * + * Then we read the Disks that we found and try to derive a list of drives that we should offer to the + * user, with details of whether those drives are currently mounted or not. + * + * At the basic level we find the "disk"-level devices, looking at whether any of their partitions are mounted. + * + * This is complicated enormously by recent-ish macOS versions' habit of making `synthesized' volumes which + * reflect data in `real' partitions. So, for example, we might have a real (physical) drive /dev/disk2 with + * a partition /dev/disk2s2 whose content is made into a synthesized /dev/disk3, itself containing some partitions + * which are mounted. /dev/disk2s2 is not considered to be mounted, in this case. So we need to know that + * disk2s2 is related to disk3 so we can consider disk2s2 as mounted if any parts of disk3 are. In order to do + * this I am picking out what looks like a suitable identifier prefixed with PRT from the MediaContentKey. + * If disk2s2 and disk3 have the same PRT code I am assuming they are linked. + * + * Lots of this is guesswork and may be broken. In my defence the documentation that I have been able to + * unearth is, to put it impolitely, crap. + */ + +struct Disk +{ + string device; + optional<string> vendor; + optional<string> model; + bool real; + string prt; + bool whole; + bool mounted; + unsigned long size; +}; + +static void +disk_appeared (DADiskRef disk, void* context) +{ + const char* bsd_name = DADiskGetBSDName (disk); + if (!bsd_name) { + return; + } + LOG_DISK("%1 appeared", bsd_name); + + Disk this_disk; + + this_disk.device = string("/dev/") + bsd_name; + + CFDictionaryRef description = DADiskCopyDescription (disk); + + this_disk.vendor = get_vendor (description); + this_disk.model = get_model (description); + LOG_DISK("Vendor/model: %1 %2", this_disk.vendor.get_value_or("[none]"), this_disk.model.get_value_or("[none]")); + + optional<MediaPath> media_path = analyse_media_path (description); + if (!media_path) { + LOG_DISK("Finding media path for %1 failed", bsd_name); + return; + } + + this_disk.real = media_path->real; + this_disk.prt = media_path->prt; + this_disk.whole = is_whole_drive (disk); + this_disk.mounted = is_mounted (description); + LOG_DISK("%1 prt %2 whole %3 mounted %4", this_disk.real ? "Real" : "Synth", this_disk.prt, this_disk.whole ? "whole" : "part", this_disk.mounted ? "mounted" : "unmounted"); + + CFNumberGetValue ((CFNumberRef) CFDictionaryGetValue (description, kDADiskDescriptionMediaSizeKey), kCFNumberLongType, &this_disk.size); + CFRelease (description); + + reinterpret_cast<vector<Disk>*>(context)->push_back(this_disk); +} + +vector<Drive> +get_drives () +{ + using namespace boost::algorithm; + vector<Disk> disks; + + DASessionRef session = DASessionCreate(kCFAllocatorDefault); + if (!session) { + return vector<Drive>(); + } + + DARegisterDiskAppearedCallback (session, NULL, disk_appeared, &disks); + CFRunLoopRef run_loop = CFRunLoopGetCurrent (); + DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode); + CFRunLoopStop (run_loop); + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.05, 0); + DAUnregisterCallback(session, (void *) disk_appeared, &disks); + CFRelease(session); + + /* Mark disks containing mounted partitions as themselves mounted */ + BOOST_FOREACH (Disk& i, disks) { + if (!i.whole) { + continue; + } + BOOST_FOREACH (Disk& j, disks) { + if (j.mounted && starts_with(j.device, i.device)) { + LOG_DISK("Marking %1 as mounted because %2 is", i.device, j.device); + i.mounted = true; + } + } + } + + /* Make a list of the PRT codes of mounted, synthesized disks */ + vector<string> mounted_synths; + BOOST_FOREACH (Disk& i, disks) { + if (!i.real && i.mounted) { + LOG_DISK("Found a mounted synth %1 with %2", i.device, i.prt); + mounted_synths.push_back (i.prt); + } + } + + /* Mark containers of those mounted synths as themselves mounted */ + BOOST_FOREACH (Disk& i, disks) { + if (i.real && find(mounted_synths.begin(), mounted_synths.end(), i.prt) != mounted_synths.end()) { + LOG_DISK("Marking %1 (%2) as mounted because it contains a mounted synth", i.device, i.prt); + i.mounted = true; + } + } + + vector<Drive> drives; + BOOST_FOREACH (Disk& i, disks) { + if (i.whole) { + /* A whole disk that is not a container for a mounted synth */ + LOG_DISK("Adding drive: %1 %2 %3 %4 %5", i.device, i.size, i.mounted ? "mounted" : "unmounted", i.vendor.get_value_or("[none]"), i.model.get_value_or("[none]")); + drives.push_back(Drive(i.device, i.size, i.mounted, i.vendor, i.model)); + } + } + return drives; +} + +boost::filesystem::path +config_path () +{ + boost::filesystem::path p; + p /= g_get_home_dir (); + p /= "Library"; + p /= "Preferences"; + p /= "com.dcpomatic"; + p /= "2"; + return p; +} diff --git a/src/lib/cross_windows.cc b/src/lib/cross_windows.cc new file mode 100644 index 000000000..169435a51 --- /dev/null +++ b/src/lib/cross_windows.cc @@ -0,0 +1,568 @@ +/* + Copyright (C) 2012-2020 Carl Hetherington <cth@carlh.net> + + This file is part of DCP-o-matic. + + DCP-o-matic is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + DCP-o-matic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with DCP-o-matic. If not, see <http://www.gnu.org/licenses/>. + +*/ + +#include "cross.h" +#include "compose.hpp" +#include "log.h" +#include "dcpomatic_log.h" +#include "config.h" +#include "exceptions.h" +#include "dcpomatic_assert.h" +#include <dcp/raw_convert.h> +#include <glib.h> +extern "C" { +#include <libavformat/avio.h> +} +#include <boost/algorithm/string.hpp> +#include <boost/foreach.hpp> +#include <boost/dll/runtime_symbol_info.hpp> +#include <windows.h> +#include <winternl.h> +#include <winioctl.h> +#include <ntdddisk.h> +#include <setupapi.h> +#undef DATADIR +#include <shlwapi.h> +#include <shellapi.h> +#include <fcntl.h> +#include <fstream> + +#include "i18n.h" + +using std::pair; +using std::list; +using std::ifstream; +using std::string; +using std::wstring; +using std::make_pair; +using std::vector; +using std::cerr; +using std::cout; +using std::runtime_error; +using boost::shared_ptr; +using boost::optional; + +/** @param s Number of seconds to sleep for */ +void +dcpomatic_sleep_seconds (int s) +{ + Sleep (s * 1000); +} + +void +dcpomatic_sleep_milliseconds (int ms) +{ + Sleep (ms); +} + +/** @return A string of CPU information (model name etc.) */ +string +cpu_info () +{ + string info; + + HKEY key; + if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &key) != ERROR_SUCCESS) { + return info; + } + + DWORD type; + DWORD data; + if (RegQueryValueEx (key, L"ProcessorNameString", 0, &type, 0, &data) != ERROR_SUCCESS) { + return info; + } + + if (type != REG_SZ) { + return info; + } + + wstring value (data / sizeof (wchar_t), L'\0'); + if (RegQueryValueEx (key, L"ProcessorNameString", 0, 0, reinterpret_cast<LPBYTE> (&value[0]), &data) != ERROR_SUCCESS) { + RegCloseKey (key); + return info; + } + + info = string (value.begin(), value.end()); + + RegCloseKey (key); + + return info; +} + +void +run_ffprobe (boost::filesystem::path content, boost::filesystem::path out) +{ + SECURITY_ATTRIBUTES security; + security.nLength = sizeof (security); + security.bInheritHandle = TRUE; + security.lpSecurityDescriptor = 0; + + HANDLE child_stderr_read; + HANDLE child_stderr_write; + if (!CreatePipe (&child_stderr_read, &child_stderr_write, &security, 0)) { + LOG_ERROR_NC ("ffprobe call failed (could not CreatePipe)"); + return; + } + + wchar_t dir[512]; + GetModuleFileName (GetModuleHandle (0), dir, sizeof (dir)); + PathRemoveFileSpec (dir); + SetCurrentDirectory (dir); + + STARTUPINFO startup_info; + ZeroMemory (&startup_info, sizeof (startup_info)); + startup_info.cb = sizeof (startup_info); + startup_info.hStdError = child_stderr_write; + startup_info.dwFlags |= STARTF_USESTDHANDLES; + + wchar_t command[512]; + wcscpy (command, L"ffprobe.exe \""); + + wchar_t file[512]; + MultiByteToWideChar (CP_UTF8, 0, content.string().c_str(), -1, file, sizeof(file)); + wcscat (command, file); + + wcscat (command, L"\""); + + PROCESS_INFORMATION process_info; + ZeroMemory (&process_info, sizeof (process_info)); + if (!CreateProcess (0, command, 0, 0, TRUE, CREATE_NO_WINDOW, 0, 0, &startup_info, &process_info)) { + LOG_ERROR_NC (N_("ffprobe call failed (could not CreateProcess)")); + return; + } + + FILE* o = fopen_boost (out, "w"); + if (!o) { + LOG_ERROR_NC (N_("ffprobe call failed (could not create output file)")); + return; + } + + CloseHandle (child_stderr_write); + + while (true) { + char buffer[512]; + DWORD read; + if (!ReadFile(child_stderr_read, buffer, sizeof(buffer), &read, 0) || read == 0) { + break; + } + fwrite (buffer, read, 1, o); + } + + fclose (o); + + WaitForSingleObject (process_info.hProcess, INFINITE); + CloseHandle (process_info.hProcess); + CloseHandle (process_info.hThread); + CloseHandle (child_stderr_read); +} + +list<pair<string, string> > +mount_info () +{ + list<pair<string, string> > m; + return m; +} + +static boost::filesystem::path +executable_path () +{ + return boost::dll::program_location().parent_path(); +} + +boost::filesystem::path +shared_path () +{ + return executable_path().parent_path(); +} + +boost::filesystem::path +openssl_path () +{ + return executable_path() / "openssl.exe"; +} + +boost::filesystem::path +disk_writer_path () +{ + return executable_path() / "dcpomatic2_disk_writer.exe"; +} + +/* Apparently there is no way to create an ofstream using a UTF-8 + filename under Windows. We are hence reduced to using fopen + with this wrapper. +*/ +FILE * +fopen_boost (boost::filesystem::path p, string t) +{ + wstring w (t.begin(), t.end()); + /* c_str() here should give a UTF-16 string */ + return _wfopen (p.c_str(), w.c_str ()); +} + +int +dcpomatic_fseek (FILE* stream, int64_t offset, int whence) +{ + return _fseeki64 (stream, offset, whence); +} + +void +Waker::nudge () +{ + boost::mutex::scoped_lock lm (_mutex); + SetThreadExecutionState (ES_SYSTEM_REQUIRED); +} + +Waker::Waker () +{ + +} + +Waker::~Waker () +{ + +} + +void +start_tool (boost::filesystem::path dcpomatic, string executable, string) +{ + boost::filesystem::path batch = dcpomatic.parent_path() / executable; + + STARTUPINFO startup_info; + ZeroMemory (&startup_info, sizeof (startup_info)); + startup_info.cb = sizeof (startup_info); + + PROCESS_INFORMATION process_info; + ZeroMemory (&process_info, sizeof (process_info)); + + wchar_t cmd[512]; + MultiByteToWideChar (CP_UTF8, 0, batch.string().c_str(), -1, cmd, sizeof(cmd)); + CreateProcess (0, cmd, 0, 0, FALSE, 0, 0, 0, &startup_info, &process_info); +} + +void +start_batch_converter (boost::filesystem::path dcpomatic) +{ + start_tool (dcpomatic, "dcpomatic2_batch", "DCP-o-matic\\ 2\\ Batch\\ Converter.app"); +} + +void +start_player (boost::filesystem::path dcpomatic) +{ + start_tool (dcpomatic, "dcpomatic2_player", "DCP-o-matic\\ 2\\ Player.app"); +} + +uint64_t +thread_id () +{ + return (uint64_t) GetCurrentThreadId (); +} + +static string +wchar_to_utf8 (wchar_t const * s) +{ + int const length = (wcslen(s) + 1) * 2; + char* utf8 = new char[length]; + WideCharToMultiByte (CP_UTF8, 0, s, -1, utf8, length, 0, 0); + string u (utf8); + delete[] utf8; + return u; +} + +int +avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags) +{ + return avio_open (s, wchar_to_utf8(file.c_str()).c_str(), flags); +} + +void +maybe_open_console () +{ + if (Config::instance()->win32_console ()) { + AllocConsole(); + + HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE); + int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT); + FILE* hf_out = _fdopen(hCrt, "w"); + setvbuf(hf_out, NULL, _IONBF, 1); + *stdout = *hf_out; + + HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE); + hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT); + FILE* hf_in = _fdopen(hCrt, "r"); + setvbuf(hf_in, NULL, _IONBF, 128); + *stdin = *hf_in; + } +} + +boost::filesystem::path +home_directory () +{ + return boost::filesystem::path(getenv("HOMEDRIVE")) / boost::filesystem::path(getenv("HOMEPATH")); +} + +string +command_and_read (string) +{ + return ""; +} + +/** @return true if this process is a 32-bit one running on a 64-bit-capable OS */ +bool +running_32_on_64 () +{ + BOOL p; + IsWow64Process (GetCurrentProcess(), &p); + return p; +} + +static optional<string> +get_friendly_name (HDEVINFO device_info, SP_DEVINFO_DATA* device_info_data) +{ + wchar_t buffer[MAX_PATH]; + ZeroMemory (&buffer, sizeof(buffer)); + bool r = SetupDiGetDeviceRegistryPropertyW ( + device_info, device_info_data, SPDRP_FRIENDLYNAME, 0, reinterpret_cast<PBYTE>(buffer), sizeof(buffer), 0 + ); + if (!r) { + return optional<string>(); + } + return wchar_to_utf8 (buffer); +} + +static const GUID GUID_DEVICE_INTERFACE_DISK = { + 0x53F56307L, 0xB6BF, 0x11D0, { 0x94, 0xF2, 0x00, 0xA0, 0xC9, 0x1E, 0xFB, 0x8B } +}; + +static optional<int> +get_device_number (HDEVINFO device_info, SP_DEVINFO_DATA* device_info_data) +{ + /* Find the Windows path to the device */ + + SP_DEVICE_INTERFACE_DATA device_interface_data; + device_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); + + BOOL r = SetupDiEnumDeviceInterfaces (device_info, device_info_data, &GUID_DEVICE_INTERFACE_DISK, 0, &device_interface_data); + if (!r) { + LOG_DISK("SetupDiEnumDeviceInterfaces failed (%1)", GetLastError()); + return optional<int>(); + } + + /* Find out how much space we need for our SP_DEVICE_INTERFACE_DETAIL_DATA_W */ + DWORD size; + r = SetupDiGetDeviceInterfaceDetailW(device_info, &device_interface_data, 0, 0, &size, 0); + PSP_DEVICE_INTERFACE_DETAIL_DATA_W device_detail_data = static_cast<PSP_DEVICE_INTERFACE_DETAIL_DATA_W> (malloc(size)); + if (!device_detail_data) { + LOG_DISK_NC("malloc failed"); + return optional<int>(); + } + + device_detail_data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W); + + /* And get the path */ + r = SetupDiGetDeviceInterfaceDetailW (device_info, &device_interface_data, device_detail_data, size, &size, 0); + if (!r) { + LOG_DISK_NC("SetupDiGetDeviceInterfaceDetailW failed"); + free (device_detail_data); + return optional<int>(); + } + + /* Open it. We would not be allowed GENERIC_READ access here but specifying 0 for + dwDesiredAccess allows us to query some metadata. + */ + HANDLE device = CreateFileW ( + device_detail_data->DevicePath, 0, + FILE_SHARE_READ | FILE_SHARE_WRITE, 0, + OPEN_EXISTING, 0, 0 + ); + + free (device_detail_data); + + if (device == INVALID_HANDLE_VALUE) { + LOG_DISK("CreateFileW failed with %1", GetLastError()); + return optional<int>(); + } + + /* Get the device number */ + STORAGE_DEVICE_NUMBER device_number; + r = DeviceIoControl ( + device, IOCTL_STORAGE_GET_DEVICE_NUMBER, 0, 0, + &device_number, sizeof(device_number), &size, 0 + ); + + CloseHandle (device); + + if (!r) { + return optional<int>(); + } + + return device_number.DeviceNumber; +} + +/** Take a volume path (with a trailing \) and add any disk numbers related to that volume + * to @ref disks. + */ +static void +add_volume_disk_number (wchar_t* volume, vector<int>& disks) +{ + /* Strip trailing \ */ + size_t const len = wcslen (volume); + DCPOMATIC_ASSERT (len > 0); + volume[len - 1] = L'\0'; + + HANDLE handle = CreateFileW ( + volume, 0, + FILE_SHARE_READ | FILE_SHARE_WRITE, 0, + OPEN_EXISTING, 0, 0 + ); + + DCPOMATIC_ASSERT (handle != INVALID_HANDLE_VALUE); + + VOLUME_DISK_EXTENTS extents; + DWORD size; + BOOL r = DeviceIoControl (handle, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, 0, 0, &extents, sizeof(extents), &size, 0); + CloseHandle (handle); + if (!r) { + return; + } + DCPOMATIC_ASSERT (extents.NumberOfDiskExtents == 1); + return disks.push_back (extents.Extents[0].DiskNumber); +} + +/* Return a list of disk numbers that contain volumes; i.e. a list of disk numbers that should + * not be offered as targets to write to as they are "mounted" (whatever that means on Windows). + */ +vector<int> +disk_numbers_with_volumes () +{ + vector<int> disks; + + wchar_t volume_name[512]; + HANDLE volume = FindFirstVolumeW (volume_name, sizeof(volume_name) / sizeof(wchar_t)); + if (volume == INVALID_HANDLE_VALUE) { + return disks; + } + + add_volume_disk_number (volume_name, disks); + while (true) { + if (!FindNextVolumeW(volume, volume_name, sizeof(volume_name) / sizeof(wchar_t))) { + break; + } + add_volume_disk_number (volume_name, disks); + } + FindVolumeClose (volume); + + return disks; +} + +vector<Drive> +get_drives () +{ + vector<Drive> drives; + + vector<int> disks_to_ignore = disk_numbers_with_volumes (); + + /* Get a `device information set' containing information about all disks */ + HDEVINFO device_info = SetupDiGetClassDevsA (&GUID_DEVICE_INTERFACE_DISK, 0, 0, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); + if (device_info == INVALID_HANDLE_VALUE) { + LOG_DISK_NC ("SetupDiClassDevsA failed"); + return drives; + } + + int i = 0; + while (true) { + /* Find out about the next disk */ + SP_DEVINFO_DATA device_info_data; + device_info_data.cbSize = sizeof(SP_DEVINFO_DATA); + if (!SetupDiEnumDeviceInfo(device_info, i, &device_info_data)) { + DWORD e = GetLastError(); + if (e != ERROR_NO_MORE_ITEMS) { + LOG_DISK ("SetupDiEnumDeviceInfo failed (%1)", GetLastError()); + } + break; + } + ++i; + + optional<string> const friendly_name = get_friendly_name (device_info, &device_info_data); + optional<int> device_number = get_device_number (device_info, &device_info_data); + if (!device_number) { + continue; + } + + string const physical_drive = String::compose("\\\\.\\PHYSICALDRIVE%1", *device_number); + + HANDLE device = CreateFileA ( + physical_drive.c_str(), 0, + FILE_SHARE_READ | FILE_SHARE_WRITE, 0, + OPEN_EXISTING, 0, 0 + ); + + if (device == INVALID_HANDLE_VALUE) { + LOG_DISK_NC("Could not open PHYSICALDRIVE"); + continue; + } + + DISK_GEOMETRY geom; + DWORD returned; + BOOL r = DeviceIoControl ( + device, IOCTL_DISK_GET_DRIVE_GEOMETRY, 0, 0, + &geom, sizeof(geom), &returned, 0 + ); + + if (r && find(disks_to_ignore.begin(), disks_to_ignore.end(), *device_number) == disks_to_ignore.end()) { + uint64_t const disk_size = geom.Cylinders.QuadPart * geom.TracksPerCylinder * geom.SectorsPerTrack * geom.BytesPerSector; + drives.push_back (Drive(physical_drive, disk_size, false, friendly_name, optional<string>())); + } + + CloseHandle (device); + } + + return drives; +} + +string +Drive::description () const +{ + char gb[64]; + snprintf(gb, 64, "%.1f", _size / 1000000000.0); + + string name; + if (_vendor) { + name += *_vendor; + } + if (_model) { + if (name.size() > 0) { + name += " " + *_model; + } + } + if (name.size() == 0) { + name = _("Unknown"); + } + + return String::compose("%1 (%2 GB) [%3]", name, gb, _internal_name); +} + +boost::filesystem::path +config_path () +{ + boost::filesystem::path p; + p /= g_get_user_config_dir (); + p /= "dcpomatic2"; + return p; +} diff --git a/src/lib/dcpomatic_log.h b/src/lib/dcpomatic_log.h index dbc850036..382a586d4 100644 --- a/src/lib/dcpomatic_log.h +++ b/src/lib/dcpomatic_log.h @@ -36,3 +36,5 @@ extern boost::shared_ptr<Log> dcpomatic_log; #define LOG_DEBUG_PLAYER(...) dcpomatic_log->log(String::compose(__VA_ARGS__), LogEntry::TYPE_DEBUG_PLAYER); #define LOG_DEBUG_THREED(...) dcpomatic_log->log(String::compose(__VA_ARGS__), LogEntry::TYPE_DEBUG_THREED); #define LOG_DEBUG_THREED_NC(...) dcpomatic_log->log(__VA_ARGS__, LogEntry::TYPE_DEBUG_THREED); +#define LOG_DISK(...) dcpomatic_log->log(String::compose(__VA_ARGS__), LogEntry::TYPE_DISK); +#define LOG_DISK_NC(...) dcpomatic_log->log(__VA_ARGS__, LogEntry::TYPE_DISK); diff --git a/src/lib/disk_writer_messages.h b/src/lib/disk_writer_messages.h new file mode 100644 index 000000000..61cdbcfbd --- /dev/null +++ b/src/lib/disk_writer_messages.h @@ -0,0 +1,77 @@ +/* + Copyright (C) 2020 Carl Hetherington <cth@carlh.net> + + This file is part of DCP-o-matic. + + DCP-o-matic is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + DCP-o-matic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with DCP-o-matic. If not, see <http://www.gnu.org/licenses/>. + +*/ + +/* dcpomatic_disk_writer receives + +DCP pathname\n +Internal name of drive to write to\n + + Then responds with one of the following. +*/ + +/** Write finished and everything was OK, e.g. + +D\n + +*/ +#define DISK_WRITER_OK "D" + +/** There was an error. Following this will come + +error message\n +error number\n + +e.g. + +E\n +Disc full\n +42\n + +*/ +#define DISK_WRITER_ERROR "E" + +/** The disk writer is formatting the drive. It is not possible + * to give progress reports on this so the writer just tells us + * it's happening. This is finished when DISK_WRITER_PROGRESS + * messages start arriving + */ +#define DISK_WRITER_FORMATTING "F" + +/** Some progress has been made in the main "copy" part of the task. + * Following this will come + +progress as a float from 0 to 1\n + +e.g. + +P\n +0.3\n + +*/ +#define DISK_WRITER_PROGRESS "P" + +/** dcpomatic_disk_writer may also receive + +Q\n + +as a request to quit. +*/ +#define DISK_WRITER_QUIT "Q" + diff --git a/src/lib/exceptions.cc b/src/lib/exceptions.cc index ba3d4a05c..d394ad4b2 100644 --- a/src/lib/exceptions.cc +++ b/src/lib/exceptions.cc @@ -114,3 +114,20 @@ GLError::GLError (char const * last, int e) { } + +CopyError::CopyError (string m, int n) + : runtime_error (String::compose("%1 (%2)", m, n)) + , _message (m) + , _number (n) +{ + +} + +VerifyError::VerifyError (string m, int n) + : runtime_error (String::compose("%1 (%2)", m, n)) + , _message (m) + , _number (n) +{ + +} + diff --git a/src/lib/exceptions.h b/src/lib/exceptions.h index 73b8cc85a..0f8a2eda2 100644 --- a/src/lib/exceptions.h +++ b/src/lib/exceptions.h @@ -314,5 +314,47 @@ public: GLError (char const * last, int e); }; +/** @class CopyError + * @brief An error which occurs when copying a DCP to a distribution drive. + */ +class CopyError : public std::runtime_error +{ +public: + CopyError (std::string s, int n); + virtual ~CopyError () throw () {} + + std::string message () const { + return _message; + } + + int number () const { + return _number; + } + +private: + std::string _message; + int _number; +}; +/** @class VerifyError + * @brief An error which occurs when verifying a DCP that we copied to a distribution drive. + */ +class VerifyError : public std::runtime_error +{ +public: + VerifyError (std::string s, int n); + virtual ~VerifyError () throw () {} + + std::string message () const { + return _message; + } + + int number () const { + return _number; + } + +private: + std::string _message; + int _number; +}; #endif diff --git a/src/lib/file_log.cc b/src/lib/file_log.cc index f6eaa58f8..b9aa84c3d 100644 --- a/src/lib/file_log.cc +++ b/src/lib/file_log.cc @@ -23,6 +23,7 @@ #include "config.h" #include <cstdio> #include <iostream> +#include <cerrno> using std::cout; using std::string; @@ -36,12 +37,18 @@ FileLog::FileLog (boost::filesystem::path file) set_types (Config::instance()->log_types()); } +FileLog::FileLog (boost::filesystem::path file, int types) + : _file (file) +{ + set_types (types); +} + void FileLog::do_log (shared_ptr<const LogEntry> entry) { FILE* f = fopen_boost (_file, "a"); if (!f) { - cout << "(could not log to " << _file.string() << "): " << entry.get() << "\n"; + cout << "(could not log to " << _file.string() << " error " << errno << "): " << entry->get() << "\n"; return; } diff --git a/src/lib/file_log.h b/src/lib/file_log.h index 53fbe4f76..613dd0939 100644 --- a/src/lib/file_log.h +++ b/src/lib/file_log.h @@ -24,6 +24,7 @@ class FileLog : public Log { public: explicit FileLog (boost::filesystem::path file); + FileLog (boost::filesystem::path file, int types); std::string head_and_tail (int amount = 1024) const; diff --git a/src/lib/log.h b/src/lib/log.h index b102a2d65..416f4259d 100644 --- a/src/lib/log.h +++ b/src/lib/log.h @@ -46,6 +46,9 @@ public: void dcp_log (dcp::NoteType type, std::string message); void set_types (int types); + int types () const { + return _types; + } /** @param amount Approximate number of bytes to return; the returned value * may be shorter or longer than this. diff --git a/src/lib/log_entry.cc b/src/lib/log_entry.cc index 54f9bfc53..4aff47c73 100644 --- a/src/lib/log_entry.cc +++ b/src/lib/log_entry.cc @@ -24,14 +24,15 @@ #include "i18n.h" -int const LogEntry::TYPE_GENERAL = 0x1; -int const LogEntry::TYPE_WARNING = 0x2; -int const LogEntry::TYPE_ERROR = 0x4; -int const LogEntry::TYPE_DEBUG_THREED = 0x8; -int const LogEntry::TYPE_DEBUG_ENCODE = 0x10; -int const LogEntry::TYPE_TIMING = 0x20; -int const LogEntry::TYPE_DEBUG_EMAIL = 0x40; -int const LogEntry::TYPE_DEBUG_PLAYER = 0x80; +int const LogEntry::TYPE_GENERAL = 0x001; +int const LogEntry::TYPE_WARNING = 0x002; +int const LogEntry::TYPE_ERROR = 0x004; +int const LogEntry::TYPE_DEBUG_THREED = 0x008; +int const LogEntry::TYPE_DEBUG_ENCODE = 0x010; +int const LogEntry::TYPE_TIMING = 0x020; +int const LogEntry::TYPE_DEBUG_EMAIL = 0x040; +int const LogEntry::TYPE_DEBUG_PLAYER = 0x080; +int const LogEntry::TYPE_DISK = 0x100; using std::string; diff --git a/src/lib/log_entry.h b/src/lib/log_entry.h index c15a006d1..d4992de86 100644 --- a/src/lib/log_entry.h +++ b/src/lib/log_entry.h @@ -1,5 +1,5 @@ /* - Copyright (C) 2015 Carl Hetherington <cth@carlh.net> + Copyright (C) 2015-2020 Carl Hetherington <cth@carlh.net> This file is part of DCP-o-matic. @@ -36,6 +36,7 @@ public: static const int TYPE_TIMING; static const int TYPE_DEBUG_EMAIL; static const int TYPE_DEBUG_PLAYER; + static const int TYPE_DISK; explicit LogEntry (int type); virtual ~LogEntry () {} diff --git a/src/lib/nanomsg.cc b/src/lib/nanomsg.cc new file mode 100644 index 000000000..57220cd54 --- /dev/null +++ b/src/lib/nanomsg.cc @@ -0,0 +1,145 @@ +/* + Copyright (C) 2020 Carl Hetherington <cth@carlh.net> + + This file is part of DCP-o-matic. + + DCP-o-matic is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + DCP-o-matic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with DCP-o-matic. If not, see <http://www.gnu.org/licenses/>. + +*/ + +#include "nanomsg.h" +#include "dcpomatic_log.h" +#include <nanomsg/nn.h> +#include <nanomsg/pair.h> +#include <stdexcept> +#include <cerrno> + +using std::string; +using std::runtime_error; +using boost::optional; + +#define NANOMSG_URL "ipc:///tmp/dcpomatic.ipc" + +Nanomsg::Nanomsg (bool server) +{ + _socket = nn_socket (AF_SP, NN_PAIR); + if (_socket < 0) { + throw runtime_error("Could not set up nanomsg socket"); + } + if (server) { + if (nn_bind(_socket, NANOMSG_URL) < 0) { + throw runtime_error(String::compose("Could not bind nanomsg socket (%1)", errno)); + } + } else { + if (nn_connect(_socket, NANOMSG_URL) < 0) { + throw runtime_error(String::compose("Could not connect nanomsg socket (%1)", errno)); + } + } +} + +void +Nanomsg::blocking_send (string s) +{ + int const r = nn_send (_socket, s.c_str(), s.length(), 0); + if (r < 0) { + throw runtime_error(String::compose("Could not send to nanomsg socket (%1)", errno)); + } else if (r != int(s.length())) { + throw runtime_error("Could not send to nanomsg socket (message too big)"); + } +} + +bool +Nanomsg::nonblocking_send (string s) +{ + int const r = nn_send (_socket, s.c_str(), s.length(), NN_DONTWAIT); + if (r < 0) { + if (errno == EAGAIN) { + return false; + } + throw runtime_error(String::compose("Could not send to nanomsg socket (%1)", errno)); + } else if (r != int(s.length())) { + throw runtime_error("Could not send to nanomsg socket (message too big)"); + } + + return true; +} + +optional<string> +Nanomsg::get_from_pending () +{ + if (_pending.empty()) { + return optional<string>(); + } + + string const l = _pending.back(); + _pending.pop_back(); + return l; +} + +void +Nanomsg::recv_and_parse (bool blocking) +{ + char* buf = 0; + int const received = nn_recv (_socket, &buf, NN_MSG, blocking ? 0 : NN_DONTWAIT); + if (received < 0) + { + if (!blocking && errno == EAGAIN) { + return; + } + + throw runtime_error ("Could not communicate with subprocess"); + } + + char* p = buf; + for (int i = 0; i < received; ++i) { + if (*p == '\n') { + _pending.push_front (_current); + _current = ""; + } else { + _current += *p; + } + ++p; + } + nn_freemsg (buf); +} + +string +Nanomsg::blocking_get () +{ + optional<string> l = get_from_pending (); + if (l) { + return *l; + } + + recv_and_parse (true); + + l = get_from_pending (); + if (!l) { + throw runtime_error ("Could not communicate with subprocess"); + } + + return *l; +} + +optional<string> +Nanomsg::nonblocking_get () +{ + optional<string> l = get_from_pending (); + if (l) { + return *l; + } + + recv_and_parse (false); + return get_from_pending (); +} diff --git a/src/lib/nanomsg.h b/src/lib/nanomsg.h new file mode 100644 index 000000000..dc84a6ce7 --- /dev/null +++ b/src/lib/nanomsg.h @@ -0,0 +1,48 @@ +/* + Copyright (C) 2020 Carl Hetherington <cth@carlh.net> + + This file is part of DCP-o-matic. + + DCP-o-matic is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + DCP-o-matic is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with DCP-o-matic. If not, see <http://www.gnu.org/licenses/>. + +*/ + +#include <string> +#include <list> +#include <boost/optional.hpp> +#include <boost/noncopyable.hpp> + +class Nanomsg : public boost::noncopyable +{ +public: + explicit Nanomsg (bool server); + + void blocking_send (std::string s); + /** Try to send a message, returning true if successful, false + * if we should try again (EAGAIN) or throwing an exception on any other + * error. + */ + bool nonblocking_send (std::string s); + std::string blocking_get (); + boost::optional<std::string> nonblocking_get (); + +private: + boost::optional<std::string> get_from_pending (); + void recv_and_parse (bool blocking); + + int _socket; + std::list<std::string> _pending; + std::string _current; +}; + diff --git a/src/lib/state.cc b/src/lib/state.cc index abb197695..dd48516f4 100644 --- a/src/lib/state.cc +++ b/src/lib/state.cc @@ -1,5 +1,5 @@ /* - Copyright (C) 2018 Carl Hetherington <cth@carlh.net> + Copyright (C) 2018-2020 Carl Hetherington <cth@carlh.net> This file is part of DCP-o-matic. @@ -19,6 +19,7 @@ */ #include "state.h" +#include "cross.h" #include <glib.h> using std::string; @@ -34,16 +35,7 @@ State::path (string file, bool create_directories) if (override_path) { p = *override_path; } else { -#ifdef DCPOMATIC_OSX - p /= g_get_home_dir (); - p /= "Library"; - p /= "Preferences"; - p /= "com.dcpomatic"; - p /= "2"; -#else - p /= g_get_user_config_dir (); - p /= "dcpomatic2"; -#endif + p = config_path (); } boost::system::error_code ec; if (create_directories) { diff --git a/src/lib/wscript b/src/lib/wscript index a37d873a8..ca6786ef2 100644 --- a/src/lib/wscript +++ b/src/lib/wscript @@ -53,7 +53,7 @@ sources = """ content.cc content_factory.cc create_cli.cc - cross.cc + cross_common.cc crypto.cc curl_uploader.cc datasat_ap2x.cc @@ -197,15 +197,26 @@ def build(bld): """ if bld.env.TARGET_OSX: - obj.framework = ['IOKit', 'Foundation'] + obj.framework = ['IOKit', 'Foundation', 'DiskArbitration'] obj.source = sources + ' version.cc' if bld.env.VARIANT == 'swaroop-theater' or bld.env.VARIANT == 'swaroop-studio': obj.source += ' swaroop_spl.cc swaroop_spl_entry.cc' + if bld.env.ENABLE_DISK: + obj.source += ' copy_to_drive_job.cc nanomsg.cc' + obj.uselib += ' LWEXT4 NANOMSG' + if bld.env.TARGET_LINUX: + obj.uselib += ' POLKIT' + if bld.env.TARGET_WINDOWS: - obj.uselib += ' WINSOCK2 DBGHELP SHLWAPI MSWSOCK BOOST_LOCALE' + obj.uselib += ' WINSOCK2 DBGHELP SHLWAPI MSWSOCK BOOST_LOCALE SETUPAPI' + obj.source += ' cross_windows.cc' + if bld.env.TARGET_OSX: + obj.source += ' cross_osx.cc' + if bld.env.TARGET_LINUX: + obj.source += ' cross_linux.cc' if bld.env.STATIC_DCPOMATIC: obj.uselib += ' XMLPP' |
