bef00702f800c8ae7d503304b058d6ee746d6b43
[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 "ui_signaller.h"
26 #include "dcpomatic_socket.h"
27 #include <libcxml/cxml.h>
28 #include <dcp/raw_convert.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 using dcp::raw_convert;
41
42 ServerFinder* ServerFinder::_instance = 0;
43
44 ServerFinder::ServerFinder ()
45         : _disabled (false)
46         , _broadcast_thread (0)
47         , _listen_thread (0)
48         , _stop (false)
49 {
50         _broadcast_thread = new boost::thread (boost::bind (&ServerFinder::broadcast_thread, this));
51         _listen_thread = new boost::thread (boost::bind (&ServerFinder::listen_thread, this));
52 }
53
54 ServerFinder::~ServerFinder ()
55 {
56         _stop = true;
57
58         _broadcast_thread->interrupt ();
59         _broadcast_thread->join ();
60
61         _listen_io_service.stop ();
62         _listen_thread->join ();
63 }
64
65 void
66 ServerFinder::broadcast_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                 try {
111                         boost::thread::sleep (boost::get_system_time() + boost::posix_time::seconds (10));
112                 } catch (boost::thread_interrupted& e) {
113                         return;
114                 }
115         }
116 }
117 catch (...)
118 {
119         store_current ();
120 }
121
122 void
123 ServerFinder::listen_thread ()
124 try {
125         using namespace boost::asio::ip;
126
127         try {
128                 _listen_acceptor.reset (new tcp::acceptor (_listen_io_service, tcp::endpoint (tcp::v4(), Config::instance()->server_port_base() + 1)));
129         } catch (...) {
130                 boost::throw_exception (NetworkError (_("Could not listen for remote encode servers.  Perhaps another instance of DCP-o-matic is running.")));
131         }
132
133         start_accept ();
134         _listen_io_service.run ();
135 }
136 catch (...)
137 {
138         store_current ();
139 }
140
141 void
142 ServerFinder::start_accept ()
143 {
144         shared_ptr<Socket> socket (new Socket ());
145         _listen_acceptor->async_accept (
146                 socket->socket(),
147                 boost::bind (&ServerFinder::handle_accept, this, boost::asio::placeholders::error, socket)
148                 );
149 }
150
151 void
152 ServerFinder::handle_accept (boost::system::error_code ec, shared_ptr<Socket> socket)
153 {
154         if (ec) {
155                 start_accept ();
156                 return;
157         }
158         
159         uint32_t length;
160         socket->read (reinterpret_cast<uint8_t*> (&length), sizeof (uint32_t));
161         length = ntohl (length);
162         
163         scoped_array<char> buffer (new char[length]);
164         socket->read (reinterpret_cast<uint8_t*> (buffer.get()), length);
165         
166         string s (buffer.get());
167         shared_ptr<cxml::Document> xml (new cxml::Document ("ServerAvailable"));
168         xml->read_string (s);
169         
170         string const ip = socket->socket().remote_endpoint().address().to_string ();
171         if (!server_found (ip)) {
172                 ServerDescription sd (ip, xml->number_child<int> ("Threads"));
173                 {
174                         boost::mutex::scoped_lock lm (_mutex);
175                         _servers.push_back (sd);
176                 }
177                 ui_signaller->emit (boost::bind (boost::ref (ServerFound), sd));
178         }
179
180         start_accept ();
181 }
182
183 bool
184 ServerFinder::server_found (string ip) const
185 {
186         boost::mutex::scoped_lock lm (_mutex);
187         list<ServerDescription>::const_iterator i = _servers.begin();
188         while (i != _servers.end() && i->host_name() != ip) {
189                 ++i;
190         }
191
192         return i != _servers.end ();
193 }
194
195 void
196 ServerFinder::connect (boost::function<void (ServerDescription)> fn)
197 {
198         if (_disabled) {
199                 return;
200         }
201         
202         boost::mutex::scoped_lock lm (_mutex);
203
204         /* Emit the current list of servers */
205         for (list<ServerDescription>::iterator i = _servers.begin(); i != _servers.end(); ++i) {
206                 fn (*i);
207         }
208
209         ServerFound.connect (fn);
210 }
211
212 ServerFinder*
213 ServerFinder::instance ()
214 {
215         if (!_instance) {
216                 _instance = new ServerFinder ();
217         }
218
219         return _instance;
220 }
221
222 void
223 ServerFinder::drop ()
224 {
225         delete _instance;
226         _instance = 0;
227 }