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