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