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