asio_link.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. // Copyright (C) 2010 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. // $Id$
  15. #ifndef __ASIO_LINK_H
  16. #define __ASIO_LINK_H 1
  17. // IMPORTANT NOTE: only very few ASIO headers files can be included in
  18. // this file. In particular, asio.hpp should never be included here.
  19. // See the description of the namespace below.
  20. #include <asio/ip/address.hpp>
  21. #include <functional>
  22. #include <string>
  23. #include <boost/function.hpp>
  24. #include <exceptions/exceptions.h>
  25. namespace asio {
  26. // forward declaration for IOService::get_io_service() below
  27. class io_service;
  28. }
  29. class AuthSrv;
  30. /// \namespace asio_link
  31. /// \brief A wrapper interface for the ASIO library.
  32. ///
  33. /// The \c asio_link namespace is used to define a set of wrapper interfaces
  34. /// for the ASIO library.
  35. ///
  36. /// BIND 10 uses the non-Boost version of ASIO because it's header-only,
  37. /// i.e., does not require a separate library object to be linked, and thus
  38. /// lowers the bar for introduction.
  39. ///
  40. /// But the advantage comes with its own costs: since the header-only version
  41. /// includes more definitions in public header files, it tends to trigger
  42. /// more compiler warnings for our own sources, and, depending on the
  43. /// compiler options, may make the build fail.
  44. ///
  45. /// We also found it may be tricky to use ASIO and standard C++ libraries
  46. /// in a single translation unit, i.e., a .cc file: depending on the order
  47. /// of including header files, ASIO may or may not work on some platforms.
  48. ///
  49. /// This wrapper interface is intended to centralize these
  50. /// problematic issues in a single sub module. Other BIND 10 modules should
  51. /// simply include \c asio_link.h and use the wrapper API instead of
  52. /// including ASIO header files and using ASIO-specific classes directly.
  53. ///
  54. /// This wrapper may be used for other IO libraries if and when we want to
  55. /// switch, but generality for that purpose is not the primary goal of
  56. /// this module. The resulting interfaces are thus straightforward mapping
  57. /// to the ASIO counterparts.
  58. ///
  59. /// Notes to developers:
  60. /// Currently the wrapper interface is specific to the authoritative
  61. /// server implementation. But the plan is to generalize it and have
  62. /// other modules use it.
  63. ///
  64. /// One obvious drawback of this approach is performance overhead
  65. /// due to the additional layer. We should eventually evaluate the cost
  66. /// of the wrapper abstraction in benchmark tests. Another drawback is
  67. /// that the wrapper interfaces don't provide all features of ASIO
  68. /// (at least for the moment). We should also re-evaluate the
  69. /// maintenance overhead of providing necessary wrappers as we develop
  70. /// more.
  71. ///
  72. /// On the other hand, we may be able to exploit the wrapper approach to
  73. /// simplify the interfaces (by limiting the usage) and unify performance
  74. /// optimization points.
  75. ///
  76. /// As for optimization, we may want to provide a custom allocator for
  77. /// the placeholder of callback handlers:
  78. /// http://think-async.com/Asio/asio-1.3.1/doc/asio/reference/asio_handler_allocate.html
  79. namespace asio_link {
  80. struct IOServiceImpl;
  81. /// \brief An exception that is thrown if an error occurs within the IO
  82. /// module. This is mainly intended to be a wrapper exception class for
  83. /// ASIO specific exceptions.
  84. class IOError : public isc::Exception {
  85. public:
  86. IOError(const char* file, size_t line, const char* what) :
  87. isc::Exception(file, line, what) {}
  88. };
  89. /// \brief The \c IOAddress class represents an IP addresses (version
  90. /// agnostic)
  91. ///
  92. /// This class is a wrapper for the ASIO \c ip::address class.
  93. class IOAddress {
  94. public:
  95. ///
  96. /// \name Constructors and Destructor
  97. ///
  98. /// This class is copyable. We use default versions of copy constructor
  99. /// and the assignment operator.
  100. /// We use the default destructor.
  101. //@{
  102. /// \brief Constructor from string.
  103. ///
  104. /// This constructor converts a textual representation of IPv4 and IPv6
  105. /// addresses into an IOAddress object.
  106. /// If \c address_str is not a valid representation of any type of
  107. /// address, an exception of class \c IOError will be thrown.
  108. /// This constructor allocates memory for the object, and if that fails
  109. /// a corresponding standard exception will be thrown.
  110. ///
  111. /// \param address_str Textual representation of address.
  112. IOAddress(const std::string& address_str);
  113. /// \brief Constructor from an ASIO \c ip::address object.
  114. ///
  115. /// This constructor is intended to be used within the wrapper
  116. /// implementation; user applications of the wrapper API won't use it.
  117. ///
  118. /// This constructor never throws an exception.
  119. ///
  120. /// \param asio_address The ASIO \c ip::address to be converted.
  121. IOAddress(const asio::ip::address& asio_adress);
  122. //@}
  123. /// \brief Convert the address to a string.
  124. ///
  125. /// This method is basically expected to be exception free, but
  126. /// generating the string will involve resource allocation,
  127. /// and if it fails the corresponding standard exception will be thrown.
  128. ///
  129. /// \return A string representation of the address.
  130. std::string toText() const;
  131. private:
  132. asio::ip::address asio_address_;
  133. };
  134. /// \brief The \c IOEndpoint class is an abstract base class to represent
  135. /// a communication endpoint.
  136. ///
  137. /// This class is a wrapper for the ASIO endpoint classes such as
  138. /// \c ip::tcp::endpoint and \c ip::udp::endpoint.
  139. ///
  140. /// Derived class implementations are completely hidden within the
  141. /// implementation. User applications only get access to concrete
  142. /// \c IOEndpoint objects via the abstract interfaces.
  143. class IOEndpoint {
  144. ///
  145. /// \name Constructors and Destructor
  146. ///
  147. /// Note: The copy constructor and the assignment operator are
  148. /// intentionally defined as private, making this class non-copyable.
  149. //@{
  150. private:
  151. IOEndpoint(const IOEndpoint& source);
  152. IOEndpoint& operator=(const IOEndpoint& source);
  153. protected:
  154. /// \brief The default constructor.
  155. ///
  156. /// This is intentionally defined as \c protected as this base class
  157. /// should never be instantiated (except as part of a derived class).
  158. IOEndpoint() {}
  159. public:
  160. /// The destructor.
  161. virtual ~IOEndpoint() {}
  162. //@}
  163. /// \brief Returns the address of the endpoint.
  164. ///
  165. /// This method returns an IOAddress object corresponding to \c this
  166. /// endpoint.
  167. /// Note that the return value is a real object, not a reference or
  168. /// a pointer.
  169. /// This is aligned with the interface of the ASIO counterpart:
  170. /// the \c address() method of \c ip::xxx::endpoint classes returns
  171. /// an \c ip::address object.
  172. /// This also means handling the address of an endpoint using this method
  173. /// can be expensive. If the address information is necessary in a
  174. /// performance sensitive context and there's a more efficient interface
  175. /// for that purpose, it's probably better to avoid using this method.
  176. ///
  177. /// This method never throws an exception.
  178. ///
  179. /// \return A copy of \c IOAddress object corresponding to the endpoint.
  180. virtual IOAddress getAddress() const = 0;
  181. /// \brief A polymorphic factory of endpoint from address and port.
  182. ///
  183. /// This method creates a new instance of (a derived class of)
  184. /// \c IOEndpoint object that identifies the pair of given address
  185. /// and port.
  186. /// The appropriate derived class is chosen based on the specified
  187. /// transport protocol. If the \c protocol doesn't specify a protocol
  188. /// supported in this implementation, an exception of class \c IOError
  189. /// will be thrown.
  190. ///
  191. /// Memory for the created object will be dynamically allocated. It's
  192. /// caller's responsibility to \c delete it later.
  193. /// If resource allocation for the new object fails, a corresponding
  194. /// standard exception will be thrown.
  195. ///
  196. /// \param protocol The transport protocol used for the endpoint.
  197. /// Currently, only \c IPPROTO_UDP and \c IPPROTO_TCP can be specified.
  198. /// \param address The (IP) address of the endpoint.
  199. /// \param port The transport port number of the endpoint
  200. /// \return A pointer to a newly created \c IOEndpoint object.
  201. static const IOEndpoint* create(int protocol,
  202. const IOAddress& address,
  203. unsigned short port);
  204. };
  205. /// \brief The \c IOSocket class is an abstract base class to represent
  206. /// various types of network sockets.
  207. ///
  208. /// This class is a wrapper for the ASIO socket classes such as
  209. /// \c ip::tcp::socket and \c ip::udp::socket.
  210. ///
  211. /// Derived class implementations are completely hidden within the
  212. /// implementation. User applications only get access to concrete
  213. /// \c IOSocket objects via the abstract interfaces.
  214. /// We may revisit this decision when we generalize the wrapper and more
  215. /// modules use it. Also, at that point we may define a separate (visible)
  216. /// derived class for testing purposes rather than providing factory methods
  217. /// (i.e., getDummy variants below).
  218. class IOSocket {
  219. ///
  220. /// \name Constructors and Destructor
  221. ///
  222. /// Note: The copy constructor and the assignment operator are
  223. /// intentionally defined as private, making this class non-copyable.
  224. //@{
  225. private:
  226. IOSocket(const IOSocket& source);
  227. IOSocket& operator=(const IOSocket& source);
  228. protected:
  229. /// \brief The default constructor.
  230. ///
  231. /// This is intentionally defined as \c protected as this base class
  232. /// should never be instantiated (except as part of a derived class).
  233. IOSocket() {}
  234. public:
  235. /// The destructor.
  236. virtual ~IOSocket() {}
  237. //@}
  238. /// \brief Return the "native" representation of the socket.
  239. ///
  240. /// In practice, this is the file descriptor of the socket for
  241. /// UNIX-like systems so the current implementation simply uses
  242. /// \c int as the type of the return value.
  243. /// We may have to need revisit this decision later.
  244. ///
  245. /// In general, the application should avoid using this method;
  246. /// it essentially discloses an implementation specific "handle" that
  247. /// can change the internal state of the socket (consider the
  248. /// application closes it, for example).
  249. /// But we sometimes need to perform very low-level operations that
  250. /// requires the native representation. Passing the file descriptor
  251. /// to a different process is one example.
  252. /// This method is provided as a necessary evil for such limited purposes.
  253. ///
  254. /// This method never throws an exception.
  255. ///
  256. /// \return The native representation of the socket. This is the socket
  257. /// file descriptor for UNIX-like systems.
  258. virtual int getNative() const = 0;
  259. /// \brief Return the transport protocol of the socket.
  260. ///
  261. /// Currently, it returns \c IPPROTO_UDP for UDP sockets, and
  262. /// \c IPPROTO_TCP for TCP sockets.
  263. ///
  264. /// This method never throws an exception.
  265. ///
  266. /// \return IPPROTO_UDP for UDP sockets
  267. /// \return IPPROTO_TCP for TCP sockets
  268. virtual int getProtocol() const = 0;
  269. /// \brief Return a non-usable "dummy" UDP socket for testing.
  270. ///
  271. /// This is a class method that returns a "mock" of UDP socket.
  272. /// This is not associated with any actual socket, and its only
  273. /// responsibility is to return \c IPPROTO_UDP from \c getProtocol().
  274. /// The only feasible usage of this socket is for testing so that
  275. /// the test code can prepare some "UDP data" even without opening any
  276. /// actual socket.
  277. ///
  278. /// This method never throws an exception.
  279. ///
  280. /// \return A reference to an \c IOSocket object whose \c getProtocol()
  281. /// returns \c IPPROTO_UDP.
  282. static IOSocket& getDummyUDPSocket();
  283. /// \brief Return a non-usable "dummy" TCP socket for testing.
  284. ///
  285. /// See \c getDummyUDPSocket(). This method is its TCP version.
  286. ///
  287. /// \return A reference to an \c IOSocket object whose \c getProtocol()
  288. /// returns \c IPPROTO_TCP.
  289. static IOSocket& getDummyTCPSocket();
  290. };
  291. /// \brief The \c IOMessage class encapsulates an incoming message received
  292. /// on a socket.
  293. ///
  294. /// An \c IOMessage object represents a tuple of a chunk of data
  295. /// (a UDP packet or some segment of TCP stream), the socket over which the
  296. /// data is passed, the information about the other end point of the
  297. /// communication, and perhaps more.
  298. ///
  299. /// The current design and interfaces of this class is tentative.
  300. /// It only provides a minimal level of support that is necessary for
  301. /// the current implementation of the authoritative server.
  302. /// A future version of this class will definitely support more.
  303. class IOMessage {
  304. ///
  305. /// \name Constructors and Destructor
  306. ///
  307. /// Note: The copy constructor and the assignment operator are
  308. /// intentionally defined as private, making this class non-copyable.
  309. //@{
  310. private:
  311. IOMessage(const IOMessage& source);
  312. IOMessage& operator=(const IOMessage& source);
  313. public:
  314. /// \brief Constructor from message information.
  315. ///
  316. /// This constructor needs to handle the ASIO \c ip::address class,
  317. /// and is intended to be used within this wrapper implementation.
  318. /// Once the \c IOMessage object is created, the application can
  319. /// get access to the information via the wrapper interface such as
  320. /// \c getRemoteAddress().
  321. ///
  322. /// This constructor never throws an exception.
  323. ///
  324. /// \param data A pointer to the message data.
  325. /// \param data_size The size of the message data in bytes.
  326. /// \param io_socket The socket over which the data is given.
  327. /// \param remote_endpoint The other endpoint of the socket, that is,
  328. /// the sender of the message.
  329. IOMessage(const void* data, size_t data_size, IOSocket& io_socket,
  330. const IOEndpoint& remote_endpoint);
  331. //@}
  332. /// \brief Returns a pointer to the received data.
  333. const void* getData() const { return (data_); }
  334. /// \brief Returns the size of the received data in bytes.
  335. size_t getDataSize() const { return (data_size_); }
  336. /// \brief Returns the socket on which the message arrives.
  337. const IOSocket& getSocket() const { return (io_socket_); }
  338. /// \brief Returns the endpoint that sends the message.
  339. const IOEndpoint& getRemoteEndpoint() const { return (remote_endpoint_); }
  340. private:
  341. const void* data_;
  342. const size_t data_size_;
  343. IOSocket& io_socket_;
  344. const IOEndpoint& remote_endpoint_;
  345. };
  346. /// \brief The \c IOService class is a wrapper for the ASIO \c io_service
  347. /// class.
  348. ///
  349. /// Currently, the interface of this class is very specific to the
  350. /// authoritative server implementation as indicated in the signature of
  351. /// the constructor, but the plan is to generalize it so that other BIND 10
  352. /// modules can use this interface, too.
  353. class IOService {
  354. ///
  355. /// \name Constructors and Destructor
  356. ///
  357. /// These are currently very specific to the authoritative server
  358. /// implementation.
  359. ///
  360. /// Note: The copy constructor and the assignment operator are
  361. /// intentionally defined as private, making this class non-copyable.
  362. //@{
  363. private:
  364. IOService(const IOService& source);
  365. IOService& operator=(const IOService& source);
  366. public:
  367. /// \brief The constructor with a specific IP address and port on which
  368. /// the services listen on.
  369. IOService(AuthSrv* auth_server, const char& port, const char& address);
  370. /// \brief The constructor with a specific port on which the services
  371. /// listen on.
  372. ///
  373. /// It effectively listens on "any" IPv4 and/or IPv6 addresses.
  374. /// IPv4/IPv6 services will be available if and only if \c use_ipv4
  375. /// or \c use_ipv6 is \c true, respectively.
  376. IOService(AuthSrv* auth_server, const char& port,
  377. const bool use_ipv4, const bool use_ipv6);
  378. /// \brief The destructor.
  379. ~IOService();
  380. //@}
  381. /// \brief Start the underlying event loop.
  382. ///
  383. /// This method does not return control to the caller until
  384. /// the \c stop() method is called via some handler.
  385. void run();
  386. /// \brief Stop the underlying event loop.
  387. ///
  388. /// This will return the control to the caller of the \c run() method.
  389. void stop();
  390. /// \brief Return the native \c io_service object used in this wrapper.
  391. ///
  392. /// This is a short term work around to support other BIND 10 modules
  393. /// that share the same \c io_service with the authoritative server.
  394. /// It will eventually be removed once the wrapper interface is
  395. /// generalized.
  396. asio::io_service& get_io_service();
  397. /// \brief A functor(-like) class that specifies a custom call back
  398. /// invoked from the event loop instead of the embedded authoritative
  399. /// server callbacks.
  400. ///
  401. /// Currently, the callback is intended to be used only for testing
  402. /// purposes. But we'll need a generic callback type like this to
  403. /// generalize the wrapper interface.
  404. typedef boost::function<void(const IOMessage& io_message)> IOCallBack;
  405. /// \brief Set the custom call back invoked from the event loop.
  406. ///
  407. /// Right now this method is only for testing, but will eventually be
  408. /// generalized.
  409. void setCallBack(IOCallBack callback);
  410. private:
  411. IOServiceImpl* impl_;
  412. };
  413. } // asio_link
  414. #endif // __ASIO_LINK_H
  415. // Local Variables:
  416. // mode: c++
  417. // End: