C++11 tidying.
[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 "encode_server_finder.h"
23 #include "exceptions.h"
24 #include "util.h"
25 #include "config.h"
26 #include "cross.h"
27 #include "encode_server_description.h"
28 #include "dcpomatic_socket.h"
29 #include <dcp/raw_convert.h>
30 #include <libcxml/cxml.h>
31 #include <boost/bind/placeholders.hpp>
32 #include <boost/lambda/lambda.hpp>
33 #include <iostream>
34
35 #include "i18n.h"
36
37
38 using std::cout;
39 using std::list;
40 using std::make_shared;
41 using std::shared_ptr;
42 using std::string;
43 using std::vector;
44 using std::weak_ptr;
45 using boost::optional;
46 using boost::scoped_array;
47 #if BOOST_VERSION >= 106100
48 using namespace boost::placeholders;
49 #endif
50 using dcp::raw_convert;
51
52
53 EncodeServerFinder* EncodeServerFinder::_instance = 0;
54
55
56 EncodeServerFinder::EncodeServerFinder ()
57         : _stop (false)
58 {
59         Config::instance()->Changed.connect (boost::bind (&EncodeServerFinder::config_changed, this, _1));
60 }
61
62
63 void
64 EncodeServerFinder::start ()
65 {
66         _search_thread = boost::thread (boost::bind(&EncodeServerFinder::search_thread, this));
67         _listen_thread = boost::thread (boost::bind(&EncodeServerFinder::listen_thread, this));
68 #ifdef DCPOMATIC_LINUX
69         pthread_setname_np (_search_thread.native_handle(), "encode-server-search");
70         pthread_setname_np (_listen_thread.native_handle(), "encode-server-listen");
71 #endif
72 }
73
74
75 EncodeServerFinder::~EncodeServerFinder ()
76 {
77         stop ();
78 }
79
80
81 void
82 EncodeServerFinder::stop ()
83 {
84         boost::this_thread::disable_interruption dis;
85
86         _stop = true;
87
88         _search_condition.notify_all ();
89         try {
90                 _search_thread.join();
91         } catch (...) {}
92
93         _listen_io_service.stop ();
94         try {
95                 _listen_thread.join ();
96         } catch (...) {}
97
98         boost::mutex::scoped_lock lm (_servers_mutex);
99         _servers.clear ();
100 }
101
102
103 void
104 EncodeServerFinder::search_thread ()
105 try
106 {
107         start_of_thread ("EncodeServerFinder-search");
108
109         boost::system::error_code error;
110         boost::asio::io_service io_service;
111         boost::asio::ip::udp::socket socket (io_service);
112         socket.open (boost::asio::ip::udp::v4(), error);
113         if (error) {
114                 throw NetworkError ("failed to set up broadcast socket");
115         }
116
117         socket.set_option (boost::asio::ip::udp::socket::reuse_address(true));
118         socket.set_option (boost::asio::socket_base::broadcast(true));
119
120         string const data = DCPOMATIC_HELLO;
121         int const interval = 10;
122
123         while (!_stop) {
124                 if (Config::instance()->use_any_servers()) {
125                         /* Broadcast to look for servers */
126                         try {
127                                 boost::asio::ip::udp::endpoint end_point (boost::asio::ip::address_v4::broadcast(), HELLO_PORT);
128                                 socket.send_to (boost::asio::buffer(data.c_str(), data.size() + 1), end_point);
129                         } catch (...) {
130
131                         }
132                 }
133
134                 /* Query our `definite' servers (if there are any) */
135                 for (auto const& i: Config::instance()->servers()) {
136                         try {
137                                 boost::asio::ip::udp::resolver resolver (io_service);
138                                 boost::asio::ip::udp::resolver::query query (i, raw_convert<string>(HELLO_PORT));
139                                 boost::asio::ip::udp::endpoint end_point (*resolver.resolve(query));
140                                 socket.send_to (boost::asio::buffer(data.c_str(), data.size() + 1), end_point);
141                         } catch (...) {
142
143                         }
144                 }
145
146                 /* Discard servers that we haven't seen for a while */
147                 bool removed = false;
148                 {
149                         boost::mutex::scoped_lock lm (_servers_mutex);
150
151                         auto i = _servers.begin();
152                         while (i != _servers.end()) {
153                                 if (i->last_seen_seconds() > 2 * interval) {
154                                         auto j = i;
155                                         ++j;
156                                         _servers.erase (i);
157                                         i = j;
158                                         removed = true;
159                                 } else {
160                                         ++i;
161                                 }
162                         }
163                 }
164
165                 if (removed) {
166                         emit (boost::bind(boost::ref(ServersListChanged)));
167                 }
168
169                 boost::mutex::scoped_lock lm (_search_condition_mutex);
170                 _search_condition.timed_wait (lm, boost::get_system_time() + boost::posix_time::seconds(interval));
171         }
172 }
173 catch (...)
174 {
175         store_current ();
176 }
177
178
179 void
180 EncodeServerFinder::listen_thread ()
181 try {
182         start_of_thread ("EncodeServerFinder-listen");
183
184         using namespace boost::asio::ip;
185
186         try {
187                 _listen_acceptor.reset (
188                         new tcp::acceptor (_listen_io_service, tcp::endpoint(tcp::v4(), is_batch_converter ? BATCH_SERVER_PRESENCE_PORT : MAIN_SERVER_PRESENCE_PORT))
189                         );
190         } catch (...) {
191                 boost::throw_exception (NetworkError (_("Could not listen for remote encode servers.  Perhaps another instance of DCP-o-matic is running.")));
192         }
193
194         start_accept ();
195         _listen_io_service.run ();
196 }
197 catch (...)
198 {
199         store_current ();
200 }
201
202
203 void
204 EncodeServerFinder::start_accept ()
205 {
206         auto socket = make_shared<Socket>();
207         _listen_acceptor->async_accept (
208                 socket->socket(),
209                 boost::bind(&EncodeServerFinder::handle_accept, this, boost::asio::placeholders::error, socket)
210                 );
211 }
212
213
214 void
215 EncodeServerFinder::handle_accept (boost::system::error_code ec, shared_ptr<Socket> socket)
216 {
217         if (ec) {
218                 start_accept ();
219                 return;
220         }
221
222         uint32_t length;
223         socket->read (reinterpret_cast<uint8_t*>(&length), sizeof(uint32_t));
224         length = ntohl (length);
225
226         scoped_array<char> buffer(new char[length]);
227         socket->read (reinterpret_cast<uint8_t*>(buffer.get()), length);
228
229         string s (buffer.get());
230         auto xml = make_shared<cxml::Document>("ServerAvailable");
231         xml->read_string (s);
232
233         auto const ip = socket->socket().remote_endpoint().address().to_string();
234         auto found = server_found (ip);
235         if (found) {
236                 (*found)->set_seen ();
237         } else {
238                 EncodeServerDescription sd (ip, xml->number_child<int>("Threads"), xml->optional_number_child<int>("Version").get_value_or(0));
239                 {
240                         boost::mutex::scoped_lock lm (_servers_mutex);
241                         _servers.push_back (sd);
242                 }
243                 emit (boost::bind(boost::ref (ServersListChanged)));
244         }
245
246         start_accept ();
247 }
248
249
250 optional<list<EncodeServerDescription>::iterator>
251 EncodeServerFinder::server_found (string ip)
252 {
253         boost::mutex::scoped_lock lm (_servers_mutex);
254         auto i = _servers.begin();
255         while (i != _servers.end() && i->host_name() != ip) {
256                 ++i;
257         }
258
259         if (i != _servers.end()) {
260                 return i;
261         }
262
263         return {};
264 }
265
266
267 EncodeServerFinder*
268 EncodeServerFinder::instance ()
269 {
270         if (!_instance) {
271                 _instance = new EncodeServerFinder ();
272                 _instance->start ();
273         }
274
275         return _instance;
276 }
277
278
279 void
280 EncodeServerFinder::drop ()
281 {
282         delete _instance;
283         _instance = nullptr;
284 }
285
286
287 list<EncodeServerDescription>
288 EncodeServerFinder::servers () const
289 {
290         boost::mutex::scoped_lock lm (_servers_mutex);
291         return _servers;
292 }
293
294
295 void
296 EncodeServerFinder::config_changed (Config::Property what)
297 {
298         if (what == Config::USE_ANY_SERVERS || what == Config::SERVERS) {
299                 {
300                         boost::mutex::scoped_lock lm (_servers_mutex);
301                         _servers.clear ();
302                 }
303                 ServersListChanged ();
304                 _search_condition.notify_all ();
305         }
306 }