]> git.sesse.net Git - casparcg/blob - protocol/util/AsyncEventServer.cpp
Fixed life-time issue in AsyncEventServer shutdown causing undefined behaviour
[casparcg] / protocol / util / AsyncEventServer.cpp
1 /*
2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>
3 *
4 * This file is part of CasparCG (www.casparcg.com).
5 *
6 * CasparCG is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * CasparCG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.
18 *
19 * Author: Robert Nagy, ronag89@gmail.com
20 */
21
22 #include "../StdAfx.h"
23
24 #include "AsyncEventServer.h"
25
26 #include <algorithm>
27 #include <array>
28 #include <string>
29 #include <set>
30 #include <memory>
31 #include <functional>
32
33 #include <boost/asio.hpp>
34 #include <boost/lexical_cast.hpp>
35
36 #include <tbb/mutex.h>
37 #include <tbb/concurrent_hash_map.h>
38 #include <tbb/concurrent_queue.h>
39
40 using boost::asio::ip::tcp;
41
42 namespace caspar { namespace IO {
43         
44 class connection;
45
46 typedef std::set<spl::shared_ptr<connection>> connection_set;
47
48 class connection : public spl::enable_shared_from_this<connection>
49 {   
50         typedef tbb::concurrent_hash_map<std::wstring, std::shared_ptr<void>> lifecycle_map_type;
51         typedef tbb::concurrent_queue<std::string>      send_queue;
52
53     const spl::shared_ptr<tcp::socket>                          socket_; 
54         std::shared_ptr<boost::asio::io_service>                service_;
55         const std::wstring                                                              listen_port_;
56         const spl::shared_ptr<connection_set>                   connection_set_;
57         protocol_strategy_factory<char>::ptr                    protocol_factory_;
58         std::shared_ptr<protocol_strategy<char>>                protocol_;
59
60         std::array<char, 32768>                                                 data_;
61         lifecycle_map_type                                                              lifecycle_bound_objects_;
62         send_queue                                                                              send_queue_;
63         bool                                                                                    is_writing_;
64
65         class connection_holder : public client_connection<char>
66         {
67                 std::weak_ptr<connection> connection_;
68         public:
69                 explicit connection_holder(std::weak_ptr<connection> conn) : connection_(std::move(conn))
70                 {}
71
72                 void send(std::basic_string<char>&& data) override
73                 {
74                         auto conn = connection_.lock();
75
76                         if (conn)
77                                 conn->send(std::move(data));
78                 }
79
80                 void disconnect() override
81                 {
82                         auto conn = connection_.lock();
83
84                         if (conn)
85                                 conn->disconnect();
86                 }
87
88                 std::wstring address() const override
89                 {
90                         auto conn = connection_.lock();
91
92                         if (conn)
93                                 return conn->ipv4_address();
94                         else
95                                 return L"[destroyed-connection]";
96                 }
97
98                 void add_lifecycle_bound_object(const std::wstring& key, const std::shared_ptr<void>& lifecycle_bound) override
99                 {
100                         auto conn = connection_.lock();
101
102                         if (conn)
103                                 return conn->add_lifecycle_bound_object(key, lifecycle_bound);
104                 }
105
106                 std::shared_ptr<void> remove_lifecycle_bound_object(const std::wstring& key) override
107                 {
108                         auto conn = connection_.lock();
109
110                         if (conn)
111                                 return conn->remove_lifecycle_bound_object(key);
112                         else
113                                 return std::shared_ptr<void>();
114                 }
115         };
116
117 public:
118         static spl::shared_ptr<connection> create(std::shared_ptr<boost::asio::io_service> service, spl::shared_ptr<tcp::socket> socket, const protocol_strategy_factory<char>::ptr& protocol, spl::shared_ptr<connection_set> connection_set)
119         {
120                 spl::shared_ptr<connection> con(new connection(std::move(service), std::move(socket), std::move(protocol), std::move(connection_set)));
121                 con->read_some();
122                 return con;
123     }
124
125         ~connection()
126         {
127                 CASPAR_LOG(info) << print() << L" connection destroyed.";
128         }
129
130         std::wstring print() const
131         {
132                 return L"async_event_server[:" + listen_port_ + L"]";
133         }
134
135         std::wstring address() const
136         {
137                 return u16(socket_->local_endpoint().address().to_string());
138         }
139         
140         std::wstring ipv4_address() const
141         {
142                 return socket_->is_open() ? u16(socket_->remote_endpoint().address().to_string()) : L"no-address";
143         }
144
145         void send(std::string&& data)
146         {
147                 send_queue_.push(std::move(data));
148                 auto self = shared_from_this();
149                 service_->dispatch([=] { self->do_write(); });
150         }
151
152         void disconnect()
153         {
154                 auto self = shared_from_this();
155                 service_->dispatch([=] { self->stop(); });
156         }
157
158         void add_lifecycle_bound_object(const std::wstring& key, const std::shared_ptr<void>& lifecycle_bound)
159         {
160                 //thread-safe tbb_concurrent_hash_map
161                 lifecycle_bound_objects_.insert(std::pair<std::wstring, std::shared_ptr<void>>(key, lifecycle_bound));
162         }
163         std::shared_ptr<void> remove_lifecycle_bound_object(const std::wstring& key)
164         {
165                 //thread-safe tbb_concurrent_hash_map
166                 lifecycle_map_type::const_accessor acc;
167                 if(lifecycle_bound_objects_.find(acc, key))
168                 {
169                         auto result = acc->second;
170                         lifecycle_bound_objects_.erase(acc);
171                         return result;
172                 }
173                 return std::shared_ptr<void>();
174         }
175
176 private:
177         void do_write() //always called from the asio-service-thread
178         {
179                 if(!is_writing_)
180                 {
181                         std::string data;
182                         if(send_queue_.try_pop(data))
183                         {
184                                 write_some(std::move(data));
185                         }
186                 }
187         }
188
189         void stop()     //always called from the asio-service-thread
190         {
191                 connection_set_->erase(shared_from_this());
192
193                 CASPAR_LOG(info) << print() << L" Client " << ipv4_address() << L" disconnected (" << connection_set_->size() << L" connections).";
194
195                 try
196                 {
197                         socket_->cancel();
198                         socket_->close();
199                 }
200                 catch(...)
201                 {
202                         CASPAR_LOG_CURRENT_EXCEPTION();
203                 }
204         }
205
206     connection(const std::shared_ptr<boost::asio::io_service>& service, const spl::shared_ptr<tcp::socket>& socket, const protocol_strategy_factory<char>::ptr& protocol_factory, const spl::shared_ptr<connection_set>& connection_set) 
207                 : socket_(socket)
208                 , service_(service)
209                 , listen_port_(socket_->is_open() ? boost::lexical_cast<std::wstring>(socket_->local_endpoint().port()) : L"no-port")
210                 , connection_set_(connection_set)
211                 , protocol_factory_(protocol_factory)
212                 , is_writing_(false)
213         {
214                 CASPAR_LOG(info) << print() << L" Accepted connection from " << ipv4_address() << L" (" << (connection_set_->size() + 1) << L" connections).";
215     }
216
217         protocol_strategy<char>& protocol()     //always called from the asio-service-thread
218         {
219                 if (!protocol_)
220                         protocol_ = protocol_factory_->create(spl::make_shared<connection_holder>(shared_from_this()));
221
222                 return *protocol_;
223         }
224                         
225     void handle_read(const boost::system::error_code& error, size_t bytes_transferred)  //always called from the asio-service-thread
226         {               
227                 if(!error)
228                 {
229                         try
230                         {
231                                 std::string data(data_.begin(), data_.begin() + bytes_transferred);
232
233                                 protocol().parse(data);
234                         }
235                         catch(...)
236                         {
237                                 CASPAR_LOG_CURRENT_EXCEPTION();
238                         }
239                         
240                         read_some();
241                 }  
242                 else if (error != boost::asio::error::operation_aborted)
243                         stop();         
244     }
245
246     void handle_write(const spl::shared_ptr<std::string>& str, const boost::system::error_code& error, size_t bytes_transferred)        //always called from the asio-service-thread
247         {
248                 if(!error)
249                 {
250                         if(bytes_transferred != str->size())
251                         {
252                                 str->assign(str->substr(bytes_transferred));
253                                 socket_->async_write_some(boost::asio::buffer(str->data(), str->size()), std::bind(&connection::handle_write, shared_from_this(), str, std::placeholders::_1, std::placeholders::_2));
254                         }
255                         else
256                         {
257                                 is_writing_ = false;
258                                 do_write();
259                         }
260                 }
261                 else if (error != boost::asio::error::operation_aborted)                
262                         stop();
263     }
264
265         void read_some()        //always called from the asio-service-thread
266         {
267                 socket_->async_read_some(boost::asio::buffer(data_.data(), data_.size()), std::bind(&connection::handle_read, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
268         }
269         
270         void write_some(std::string&& data)     //always called from the asio-service-thread
271         {
272                 is_writing_ = true;
273                 auto str = spl::make_shared<std::string>(std::move(data));
274                 socket_->async_write_some(boost::asio::buffer(str->data(), str->size()), std::bind(&connection::handle_write, shared_from_this(), str, std::placeholders::_1, std::placeholders::_2));
275         }
276
277         friend struct AsyncEventServer::implementation;
278 };
279
280 struct AsyncEventServer::implementation : public spl::enable_shared_from_this<implementation>
281 {
282         std::shared_ptr<boost::asio::io_service>        service_;
283         tcp::acceptor                                                           acceptor_;
284         protocol_strategy_factory<char>::ptr            protocol_factory_;
285         spl::shared_ptr<connection_set>                         connection_set_;
286         std::vector<lifecycle_factory_t>                        lifecycle_factories_;
287         tbb::mutex                                                                      mutex_;
288
289         implementation(std::shared_ptr<boost::asio::io_service> service, const protocol_strategy_factory<char>::ptr& protocol, unsigned short port)
290                 : service_(std::move(service))
291                 , acceptor_(*service_, tcp::endpoint(tcp::v4(), port))
292                 , protocol_factory_(protocol)
293         {
294         }
295
296         void stop()
297         {
298                 try
299                 {
300                         acceptor_.cancel();
301                         acceptor_.close();
302                 }
303                 catch (...)
304                 {
305                         CASPAR_LOG_CURRENT_EXCEPTION();
306                 }
307         }
308
309         ~implementation()
310         {
311                 auto conns_set = connection_set_;
312
313                 service_->post([conns_set]
314                 {
315                         auto connections = *conns_set;
316                         for (auto& connection : connections)
317                                 connection->stop();
318                 });
319         }
320                 
321         void start_accept() 
322         {
323                 spl::shared_ptr<tcp::socket> socket(new tcp::socket(*service_));
324                 acceptor_.async_accept(*socket, std::bind(&implementation::handle_accept, shared_from_this(), socket, std::placeholders::_1));
325     }
326
327         void handle_accept(const spl::shared_ptr<tcp::socket>& socket, const boost::system::error_code& error) 
328         {
329                 if (!acceptor_.is_open())
330                         return;
331                 
332         if (!error)
333                 {
334                         auto conn = connection::create(service_, socket, protocol_factory_, connection_set_);
335                         connection_set_->insert(conn);
336
337                         for (auto& lifecycle_factory : lifecycle_factories_)
338                         {
339                                 auto lifecycle_bound = lifecycle_factory(u8(conn->ipv4_address()));
340                                 conn->add_lifecycle_bound_object(lifecycle_bound.first, lifecycle_bound.second);
341                         }
342                 }
343                 start_accept();
344     }
345
346         void add_client_lifecycle_object_factory(const lifecycle_factory_t& factory)
347         {
348                 auto self = shared_from_this();
349                 service_->post([=]{ self->lifecycle_factories_.push_back(factory); });
350         }
351 };
352
353 AsyncEventServer::AsyncEventServer(
354                 std::shared_ptr<boost::asio::io_service> service, const protocol_strategy_factory<char>::ptr& protocol, unsigned short port)
355         : impl_(new implementation(std::move(service), protocol, port))
356 {
357         impl_->start_accept();
358 }
359
360 AsyncEventServer::~AsyncEventServer()
361 {
362         impl_->stop();
363 }
364
365 void AsyncEventServer::add_client_lifecycle_object_factory(const lifecycle_factory_t& factory) { impl_->add_client_lifecycle_object_factory(factory); }
366
367 }}