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