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