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