CppWAMP
C++11 client library for the WAMP protocol
udsacceptor.hpp
1 /*------------------------------------------------------------------------------
2  Copyright Butterfly Energy Systems 2014-2015, 2022.
3  Distributed under the Boost Software License, Version 1.0.
4  http://www.boost.org/LICENSE_1_0.txt
5 ------------------------------------------------------------------------------*/
6 
7 #ifndef CPPWAMP_INTERNAL_UDSACCEPTOR_HPP
8 #define CPPWAMP_INTERNAL_UDSACCEPTOR_HPP
9 
10 #include <cassert>
11 #include <memory>
12 #include <string>
13 #include <boost/asio/local/stream_protocol.hpp>
14 #include <boost/asio/strand.hpp>
15 #include "../asiodefs.hpp"
16 
17 namespace wamp
18 {
19 
20 namespace internal
21 {
22 
23 //------------------------------------------------------------------------------
24 class UdsAcceptor
25 {
26 public:
27  using Socket = boost::asio::local::stream_protocol::socket;
28  using SocketPtr = std::unique_ptr<Socket>;
29 
30  template <typename TExecutorOrStrand>
31  UdsAcceptor(TExecutorOrStrand&& exec, const std::string& path,
32  bool deleteFile)
33  : strand_(std::forward<TExecutorOrStrand>(exec)),
34  path_(path),
35  deleteFile_(deleteFile)
36  {}
37 
38  IoStrand& strand() {return strand_;}
39 
40  template <typename F>
41  void establish(F&& callback)
42  {
43  struct Accepted
44  {
45  UdsAcceptor* self;
46  typename std::decay<F>::type callback;
47 
48  void operator()(AsioErrorCode ec)
49  {
50  if (ec)
51  {
52  self->acceptor_.reset();
53  self->socket_.reset();
54  }
55  callback(ec, std::move(self->socket_));
56  }
57  };
58 
59  assert(!socket_ && "Accept already in progress");
60 
61  if (!acceptor_)
62  {
63  if (deleteFile_)
64  std::remove(path_.c_str());
65  acceptor_.reset(new uds::acceptor(strand_, path_));
66  }
67  socket_.reset(new Socket(strand_));
68 
69  // AsioListener will keep this object alive until completion.
70  acceptor_->async_accept(*socket_,
71  Accepted{this, std::forward<F>(callback)});
72  }
73 
74  void cancel()
75  {
76  if (acceptor_)
77  acceptor_->close();
78  }
79 
80 private:
81  using uds = boost::asio::local::stream_protocol;
82 
83  IoStrand strand_;
84  std::string path_;
85  bool deleteFile_;
86  std::unique_ptr<uds::acceptor> acceptor_;
87  SocketPtr socket_;
88 };
89 
90 } // namespace internal
91 
92 } // namespace wamp
93 
94 #endif // CPPWAMP_INTERNAL_UDSACCEPTOR_HPP
wamp::IoStrand
boost::asio::strand< AnyIoExecutor > IoStrand
Serializes I/O operations.
Definition: asiodefs.hpp:41
wamp
Definition: anyhandler.hpp:36
wamp::AsioErrorCode
boost::system::error_code AsioErrorCode
Type used by Boost.Asio for reporting errors.
Definition: asiodefs.hpp:44