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