Extract all uses of DCP-o-matic name to allow branding.
[dcpomatic.git] / src / lib / encode_server_finder.cc
1 /*
2     Copyright (C) 2013-2021 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21
22 #include "config.h"
23 #include "constants.h"
24 #include "cross.h"
25 #include "dcpomatic_socket.h"
26 #include "encode_server_description.h"
27 #include "encode_server_finder.h"
28 #include "exceptions.h"
29 #include "variant.h"
30 #include <dcp/raw_convert.h>
31 #include <libcxml/cxml.h>
32 #include <boost/bind/placeholders.hpp>
33 #include <boost/lambda/lambda.hpp>
34 #include <iostream>
35
36 #include "i18n.h"
37
38
39 using std::cout;
40 using std::list;
41 using std::make_shared;
42 using std::shared_ptr;
43 using std::string;
44 using std::vector;
45 using std::weak_ptr;
46 using boost::optional;
47 using boost::scoped_array;
48 #if BOOST_VERSION >= 106100
49 using namespace boost::placeholders;
50 #endif
51 using dcp::raw_convert;
52
53
54 EncodeServerFinder* EncodeServerFinder::_instance = 0;
55
56
57 EncodeServerFinder::EncodeServerFinder ()
58         : _stop (false)
59 {
60         Config::instance()->Changed.connect (boost::bind (&EncodeServerFinder::config_changed, this, _1));
61 }
62
63
64 void
65 EncodeServerFinder::start ()
66 {
67         _search_thread = boost::thread (boost::bind(&EncodeServerFinder::search_thread, this));
68         _listen_thread = boost::thread (boost::bind(&EncodeServerFinder::listen_thread, this));
69 #ifdef DCPOMATIC_LINUX
70         pthread_setname_np (_search_thread.native_handle(), "encode-server-search");
71         pthread_setname_np (_listen_thread.native_handle(), "encode-server-listen");
72 #endif
73 }
74
75
76 EncodeServerFinder::~EncodeServerFinder ()
77 {
78         stop ();
79 }
80
81
82 void
83 EncodeServerFinder::stop ()
84 {
85         boost::this_thread::disable_interruption dis;
86
87         _stop = true;
88
89         _search_condition.notify_all ();
90         try {
91                 _search_thread.join();
92         } catch (...) {}
93
94         _listen_io_service.stop ();
95         try {
96                 _listen_thread.join ();
97         } catch (...) {}
98
99         boost::mutex::scoped_lock lm (_servers_mutex);
100         _servers.clear ();
101 }
102
103
104 void
105 EncodeServerFinder::search_thread ()
106 try
107 {
108         start_of_thread ("EncodeServerFinder-search");
109
110         boost::system::error_code error;
111         boost::asio::io_service io_service;
112         boost::asio::ip::udp::socket socket (io_service);
113         socket.open (boost::asio::ip::udp::v4(), error);
114         if (error) {
115                 throw NetworkError ("failed to set up broadcast socket");
116         }
117
118         socket.set_option (boost::asio::ip::udp::socket::reuse_address(true));
119         socket.set_option (boost::asio::socket_base::broadcast(true));
120
121         string const data = DCPOMATIC_HELLO;
122         int const interval = 10;
123
124         while (!_stop) {
125                 if (Config::instance()->use_any_servers()) {
126                         /* Broadcast to look for servers */
127                         try {
128                                 boost::asio::ip::udp::endpoint end_point (boost::asio::ip::address_v4::broadcast(), HELLO_PORT);
129                                 socket.send_to (boost::asio::buffer(data.c_str(), data.size() + 1), end_point);
130                         } catch (...) {
131
132                         }
133                 }
134
135                 /* Query our `definite' servers (if there are any) */
136                 for (auto const& i: Config::instance()->servers()) {
137                         try {
138                                 boost::asio::ip::udp::resolver resolver (io_service);
139                                 boost::asio::ip::udp::resolver::query query (i, raw_convert<string>(HELLO_PORT));
140                                 boost::asio::ip::udp::endpoint end_point (*resolver.resolve(query));
141                                 socket.send_to (boost::asio::buffer(data.c_str(), data.size() + 1), end_point);
142                         } catch (...) {
143
144                         }
145                 }
146
147                 /* Discard servers that we haven't seen for a while */
148                 bool removed = false;
149                 {
150                         boost::mutex::scoped_lock lm (_servers_mutex);
151
152                         auto i = _servers.begin();
153                         while (i != _servers.end()) {
154                                 if (i->last_seen_seconds() > 2 * interval) {
155                                         auto j = i;
156                                         ++j;
157                                         _servers.erase (i);
158                                         i = j;
159                                         removed = true;
160                                 } else {
161                                         ++i;
162                                 }
163                         }
164                 }
165
166                 if (removed) {
167                         emit (boost::bind(boost::ref(ServersListChanged)));
168                 }
169
170                 boost::mutex::scoped_lock lm (_search_condition_mutex);
171                 _search_condition.timed_wait (lm, boost::get_system_time() + boost::posix_time::seconds(interval));
172         }
173 }
174 catch (...)
175 {
176         store_current ();
177 }
178
179
180 void
181 EncodeServerFinder::listen_thread ()
182 try {
183         start_of_thread ("EncodeServerFinder-listen");
184
185         using namespace boost::asio::ip;
186
187         try {
188                 _listen_acceptor.reset (
189                         new tcp::acceptor (_listen_io_service, tcp::endpoint(tcp::v4(), is_batch_converter ? BATCH_SERVER_PRESENCE_PORT : MAIN_SERVER_PRESENCE_PORT))
190                         );
191         } catch (...) {
192                 boost::throw_exception(NetworkError(variant::insert_dcpomatic(_("Could not listen for remote encode servers.  Perhaps another instance of %1 is running."))));
193         }
194
195         start_accept ();
196         _listen_io_service.run ();
197 }
198 catch (...)
199 {
200         store_current ();
201 }
202
203
204 void
205 EncodeServerFinder::start_accept ()
206 {
207         _accept_socket = make_shared<Socket>();
208
209         _listen_acceptor->async_accept (
210                 _accept_socket->socket(),
211                 boost::bind(&EncodeServerFinder::handle_accept, this, boost::asio::placeholders::error)
212                 );
213 }
214
215
216 void
217 EncodeServerFinder::handle_accept (boost::system::error_code ec)
218 {
219         if (ec) {
220                 start_accept ();
221                 return;
222         }
223
224         string server_available;
225
226         try {
227                 uint32_t length;
228                 _accept_socket->read (reinterpret_cast<uint8_t*>(&length), sizeof(uint32_t));
229                 length = ntohl (length);
230
231                 if (length > 65536) {
232                         start_accept();
233                         return;
234                 }
235
236                 scoped_array<char> buffer(new char[length]);
237                 _accept_socket->read (reinterpret_cast<uint8_t*>(buffer.get()), length);
238                 server_available = buffer.get();
239         } catch (NetworkError&) {
240                 /* Maybe the server went away; let's just try again */
241                 start_accept();
242                 return;
243         }
244
245         auto xml = make_shared<cxml::Document>("ServerAvailable");
246         xml->read_string(server_available);
247
248         auto const ip = _accept_socket->socket().remote_endpoint().address().to_string();
249         bool changed = false;
250         {
251                 boost::mutex::scoped_lock lm (_servers_mutex);
252                 auto i = _servers.begin();
253                 while (i != _servers.end() && i->host_name() != ip) {
254                         ++i;
255                 }
256
257                 if (i != _servers.end()) {
258                         i->set_seen();
259                 } else {
260                         EncodeServerDescription sd (ip, xml->number_child<int>("Threads"), xml->optional_number_child<int>("Version").get_value_or(0));
261                         _servers.push_back (sd);
262                         changed = true;
263                 }
264         }
265
266         if (changed) {
267                 emit (boost::bind(boost::ref (ServersListChanged)));
268         }
269
270         start_accept ();
271 }
272
273
274 EncodeServerFinder*
275 EncodeServerFinder::instance ()
276 {
277         if (!_instance) {
278                 _instance = new EncodeServerFinder ();
279                 _instance->start ();
280         }
281
282         return _instance;
283 }
284
285
286 void
287 EncodeServerFinder::drop ()
288 {
289         delete _instance;
290         _instance = nullptr;
291 }
292
293
294 list<EncodeServerDescription>
295 EncodeServerFinder::servers () const
296 {
297         boost::mutex::scoped_lock lm (_servers_mutex);
298         return _servers;
299 }
300
301
302 void
303 EncodeServerFinder::config_changed (Config::Property what)
304 {
305         if (what == Config::USE_ANY_SERVERS || what == Config::SERVERS) {
306                 {
307                         boost::mutex::scoped_lock lm (_servers_mutex);
308                         _servers.clear ();
309                 }
310                 ServersListChanged ();
311                 _search_condition.notify_all ();
312         }
313 }