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