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