Move ServerDescription into its own header.
[dcpomatic.git] / src / lib / server_finder.cc
1 /*
2     Copyright (C) 2013-2015 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include "server_finder.h"
21 #include "exceptions.h"
22 #include "util.h"
23 #include "config.h"
24 #include "cross.h"
25 #include "server_description.h"
26 #include "dcpomatic_socket.h"
27 #include "raw_convert.h"
28 #include <libcxml/cxml.h>
29 #include <boost/lambda/lambda.hpp>
30
31 #include "i18n.h"
32
33 using std::string;
34 using std::list;
35 using std::vector;
36 using std::cout;
37 using boost::shared_ptr;
38 using boost::scoped_array;
39 using boost::weak_ptr;
40
41 ServerFinder* ServerFinder::_instance = 0;
42
43 ServerFinder::ServerFinder ()
44         : _disabled (false)
45         , _search_thread (0)
46         , _listen_thread (0)
47         , _stop (false)
48 {
49         _search_thread = new boost::thread (boost::bind (&ServerFinder::search_thread, this));
50         _listen_thread = new boost::thread (boost::bind (&ServerFinder::listen_thread, this));
51         Config::instance()->Changed.connect (boost::bind (&ServerFinder::config_changed, this, _1));
52 }
53
54 ServerFinder::~ServerFinder ()
55 {
56         _stop = true;
57
58         _search_condition.notify_all ();
59         _search_thread->join ();
60
61         _listen_io_service.stop ();
62         _listen_thread->join ();
63 }
64
65 void
66 ServerFinder::search_thread ()
67 try
68 {
69         boost::system::error_code error;
70         boost::asio::io_service io_service;
71         boost::asio::ip::udp::socket socket (io_service);
72         socket.open (boost::asio::ip::udp::v4(), error);
73         if (error) {
74                 throw NetworkError ("failed to set up broadcast socket");
75         }
76
77         socket.set_option (boost::asio::ip::udp::socket::reuse_address (true));
78         socket.set_option (boost::asio::socket_base::broadcast (true));
79
80         string const data = DCPOMATIC_HELLO;
81
82         while (!_stop) {
83                 if (Config::instance()->use_any_servers ()) {
84                         /* Broadcast to look for servers */
85                         try {
86                                 boost::asio::ip::udp::endpoint end_point (boost::asio::ip::address_v4::broadcast(), Config::instance()->server_port_base() + 1);
87                                 socket.send_to (boost::asio::buffer (data.c_str(), data.size() + 1), end_point);
88                         } catch (...) {
89
90                         }
91                 }
92
93                 /* Query our `definite' servers (if there are any) */
94                 vector<string> servers = Config::instance()->servers ();
95                 for (vector<string>::const_iterator i = servers.begin(); i != servers.end(); ++i) {
96                         if (server_found (*i)) {
97                                 /* Don't bother asking a server that we already know about */
98                                 continue;
99                         }
100                         try {
101                                 boost::asio::ip::udp::resolver resolver (io_service);
102                                 boost::asio::ip::udp::resolver::query query (*i, raw_convert<string> (Config::instance()->server_port_base() + 1));
103                                 boost::asio::ip::udp::endpoint end_point (*resolver.resolve (query));
104                                 socket.send_to (boost::asio::buffer (data.c_str(), data.size() + 1), end_point);
105                         } catch (...) {
106
107                         }
108                 }
109
110                 boost::mutex::scoped_lock lm (_search_condition_mutex);
111                 _search_condition.timed_wait (lm, boost::get_system_time() + boost::posix_time::seconds (10));
112         }
113 }
114 catch (...)
115 {
116         store_current ();
117 }
118
119 void
120 ServerFinder::listen_thread ()
121 try {
122         using namespace boost::asio::ip;
123
124         try {
125                 _listen_acceptor.reset (new tcp::acceptor (_listen_io_service, tcp::endpoint (tcp::v4(), Config::instance()->server_port_base() + 1)));
126         } catch (...) {
127                 boost::throw_exception (NetworkError (_("Could not listen for remote encode servers.  Perhaps another instance of DCP-o-matic is running.")));
128         }
129
130         start_accept ();
131         _listen_io_service.run ();
132 }
133 catch (...)
134 {
135         store_current ();
136 }
137
138 void
139 ServerFinder::start_accept ()
140 {
141         shared_ptr<Socket> socket (new Socket ());
142         _listen_acceptor->async_accept (
143                 socket->socket(),
144                 boost::bind (&ServerFinder::handle_accept, this, boost::asio::placeholders::error, socket)
145                 );
146 }
147
148 void
149 ServerFinder::handle_accept (boost::system::error_code ec, shared_ptr<Socket> socket)
150 {
151         if (ec) {
152                 start_accept ();
153                 return;
154         }
155
156         uint32_t length;
157         socket->read (reinterpret_cast<uint8_t*> (&length), sizeof (uint32_t));
158         length = ntohl (length);
159
160         scoped_array<char> buffer (new char[length]);
161         socket->read (reinterpret_cast<uint8_t*> (buffer.get()), length);
162
163         string s (buffer.get());
164         shared_ptr<cxml::Document> xml (new cxml::Document ("ServerAvailable"));
165         xml->read_string (s);
166
167         string const ip = socket->socket().remote_endpoint().address().to_string ();
168         if (!server_found (ip) && xml->optional_number_child<int>("Version").get_value_or (0) == SERVER_LINK_VERSION) {
169                 ServerDescription sd (ip, xml->number_child<int> ("Threads"));
170                 {
171                         boost::mutex::scoped_lock lm (_mutex);
172                         _servers.push_back (sd);
173                 }
174                 emit (boost::bind (boost::ref (ServersListChanged)));
175         }
176
177         start_accept ();
178 }
179
180 bool
181 ServerFinder::server_found (string ip) const
182 {
183         boost::mutex::scoped_lock lm (_mutex);
184         list<ServerDescription>::const_iterator i = _servers.begin();
185         while (i != _servers.end() && i->host_name() != ip) {
186                 ++i;
187         }
188
189         return i != _servers.end ();
190 }
191
192 ServerFinder*
193 ServerFinder::instance ()
194 {
195         if (!_instance) {
196                 _instance = new ServerFinder ();
197         }
198
199         return _instance;
200 }
201
202 void
203 ServerFinder::drop ()
204 {
205         delete _instance;
206         _instance = 0;
207 }
208
209 list<ServerDescription>
210 ServerFinder::servers () const
211 {
212         boost::mutex::scoped_lock lm (_mutex);
213         return _servers;
214 }
215
216 void
217 ServerFinder::config_changed (Config::Property what)
218 {
219         if (what == Config::USE_ANY_SERVERS || what == Config::SERVERS) {
220                 {
221                         boost::mutex::scoped_lock lm (_mutex);
222                         _servers.clear ();
223                 }
224                 ServersListChanged ();
225                 search_now ();
226         }
227 }
228
229 void
230 ServerFinder::search_now ()
231 {
232         _search_condition.notify_all ();
233 }