iface_mgr.h 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. // Copyright (C) 2011-2013 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. #ifndef IFACE_MGR_H
  15. #define IFACE_MGR_H
  16. #include <asiolink/io_address.h>
  17. #include <dhcp/dhcp4.h>
  18. #include <dhcp/dhcp6.h>
  19. #include <dhcp/pkt4.h>
  20. #include <dhcp/pkt6.h>
  21. #include <dhcp/pkt_filter.h>
  22. #include <boost/noncopyable.hpp>
  23. #include <boost/scoped_array.hpp>
  24. #include <boost/shared_ptr.hpp>
  25. #include <list>
  26. namespace isc {
  27. namespace dhcp {
  28. /// @brief IfaceMgr exception thrown thrown when interface detection fails.
  29. class IfaceDetectError : public Exception {
  30. public:
  31. IfaceDetectError(const char* file, size_t line, const char* what) :
  32. isc::Exception(file, line, what) { };
  33. };
  34. /// @brief Exception thrown when it is not allowed to set new Packet Filter.
  35. class PacketFilterChangeDenied : public Exception {
  36. public:
  37. PacketFilterChangeDenied(const char* file, size_t line, const char* what) :
  38. isc::Exception(file, line, what) { };
  39. };
  40. /// @brief IfaceMgr exception thrown thrown when socket opening
  41. /// or configuration failed.
  42. class SocketConfigError : public Exception {
  43. public:
  44. SocketConfigError(const char* file, size_t line, const char* what) :
  45. isc::Exception(file, line, what) { };
  46. };
  47. /// @brief IfaceMgr exception thrown thrown when error occured during
  48. /// reading data from socket.
  49. class SocketReadError : public Exception {
  50. public:
  51. SocketReadError(const char* file, size_t line, const char* what) :
  52. isc::Exception(file, line, what) { };
  53. };
  54. /// @brief IfaceMgr exception thrown thrown when error occured during
  55. /// sedning data through socket.
  56. class SocketWriteError : public Exception {
  57. public:
  58. SocketWriteError(const char* file, size_t line, const char* what) :
  59. isc::Exception(file, line, what) { };
  60. };
  61. /// Holds information about socket.
  62. struct SocketInfo {
  63. uint16_t sockfd_; /// socket descriptor
  64. isc::asiolink::IOAddress addr_; /// bound address
  65. uint16_t port_; /// socket port
  66. uint16_t family_; /// IPv4 or IPv6
  67. /// @brief SocketInfo constructor.
  68. ///
  69. /// @param sockfd socket descriptor
  70. /// @param addr an address the socket is bound to
  71. /// @param port a port the socket is bound to
  72. SocketInfo(uint16_t sockfd, const isc::asiolink::IOAddress& addr,
  73. uint16_t port)
  74. :sockfd_(sockfd), addr_(addr), port_(port), family_(addr.getFamily()) { }
  75. };
  76. /// @brief Represents a single network interface
  77. ///
  78. /// Iface structure represents network interface with all useful
  79. /// information, like name, interface index, MAC address and
  80. /// list of assigned addresses
  81. class Iface {
  82. public:
  83. /// Maximum MAC address length (Infiniband uses 20 bytes)
  84. static const unsigned int MAX_MAC_LEN = 20;
  85. /// Type that defines list of addresses
  86. typedef std::vector<isc::asiolink::IOAddress> AddressCollection;
  87. /// @brief Type that holds a list of socket information.
  88. ///
  89. /// @warning The type of the container used here must guarantee
  90. /// that the iterators do not invalidate when erase() is called.
  91. /// This is because, the \ref closeSockets function removes
  92. /// elements selectively by calling erase on the element to be
  93. /// removed and further iterates through remaining elements.
  94. ///
  95. /// @todo: Add SocketCollectionConstIter type
  96. typedef std::list<SocketInfo> SocketCollection;
  97. /// @brief Iface constructor.
  98. ///
  99. /// Creates Iface object that represents network interface.
  100. ///
  101. /// @param name name of the interface
  102. /// @param ifindex interface index (unique integer identifier)
  103. Iface(const std::string& name, int ifindex);
  104. /// @brief Closes all open sockets on interface.
  105. void closeSockets();
  106. /// @brief Closes all IPv4 or IPv6 sockets.
  107. ///
  108. /// This function closes sockets of the specific 'type' and closes them.
  109. /// The 'type' of the socket indicates whether it is used to send IPv4
  110. /// or IPv6 packets. The allowed values of the parameter are AF_INET and
  111. /// AF_INET6 for IPv4 and IPv6 packets respectively. It is important
  112. /// to realize that the actual types of sockets may be different than
  113. /// AF_INET for IPv4 packets. This is because, historically the IfaceMgr
  114. /// always used AF_INET sockets for IPv4 traffic. This is no longer the
  115. /// case when the Direct IPv4 traffic must be supported. In order to support
  116. /// direct traffic, the IfaceMgr operates on raw sockets, e.g. AF_PACKET
  117. /// family sockets on Linux.
  118. ///
  119. /// @todo Replace the AF_INET and AF_INET6 values with an enum
  120. /// which will not be confused with the actual socket type.
  121. ///
  122. /// @param family type of the sockets to be closed (AF_INET or AF_INET6)
  123. ///
  124. /// @throw BadValue if family value is different than AF_INET or AF_INET6.
  125. void closeSockets(const uint16_t family);
  126. /// @brief Returns full interface name as "ifname/ifindex" string.
  127. ///
  128. /// @return string with interface name
  129. std::string getFullName() const;
  130. /// @brief Returns link-layer address a plain text.
  131. ///
  132. /// @return MAC address as a plain text (string)
  133. std::string getPlainMac() const;
  134. /// @brief Sets MAC address of the interface.
  135. ///
  136. /// @param mac pointer to MAC address buffer
  137. /// @param macLen length of mac address
  138. void setMac(const uint8_t* mac, size_t macLen);
  139. /// @brief Returns MAC length.
  140. ///
  141. /// @return length of MAC address
  142. size_t getMacLen() const { return mac_len_; }
  143. /// @brief Returns pointer to MAC address.
  144. ///
  145. /// Note: Returned pointer is only valid as long as the interface object
  146. /// that returned it.
  147. const uint8_t* getMac() const { return mac_; }
  148. /// @brief Sets flag_*_ fields based on bitmask value returned by OS
  149. ///
  150. /// @note Implementation of this method is OS-dependent as bits have
  151. /// different meaning on each OS.
  152. ///
  153. /// @param flags bitmask value returned by OS in interface detection
  154. void setFlags(uint32_t flags);
  155. /// @brief Returns interface index.
  156. ///
  157. /// @return interface index
  158. uint16_t getIndex() const { return ifindex_; }
  159. /// @brief Returns interface name.
  160. ///
  161. /// @return interface name
  162. std::string getName() const { return name_; };
  163. /// @brief Sets up hardware type of the interface.
  164. ///
  165. /// @param type hardware type
  166. void setHWType(uint16_t type ) { hardware_type_ = type; }
  167. /// @brief Returns hardware type of the interface.
  168. ///
  169. /// @return hardware type
  170. uint16_t getHWType() const { return hardware_type_; }
  171. /// @brief Returns all interfaces available on an interface.
  172. ///
  173. /// Care should be taken to not use this collection after Iface object
  174. /// ceases to exist. That is easy in most cases as Iface objects are
  175. /// created by IfaceMgr that is a singleton an is expected to be
  176. /// available at all time. We may revisit this if we ever decide to
  177. /// implement dynamic interface detection, but such fancy feature would
  178. /// mostly be useful for clients with wifi/vpn/virtual interfaces.
  179. ///
  180. /// @return collection of addresses
  181. const AddressCollection& getAddresses() const { return addrs_; }
  182. /// @brief Adds an address to an interface.
  183. ///
  184. /// This only adds an address to collection, it does not physically
  185. /// configure address on actual network interface.
  186. ///
  187. /// @param addr address to be added
  188. void addAddress(const isc::asiolink::IOAddress& addr) {
  189. addrs_.push_back(addr);
  190. }
  191. /// @brief Deletes an address from an interface.
  192. ///
  193. /// This only deletes address from collection, it does not physically
  194. /// remove address configuration from actual network interface.
  195. ///
  196. /// @param addr address to be removed.
  197. ///
  198. /// @return true if removal was successful (address was in collection),
  199. /// false otherwise
  200. bool delAddress(const isc::asiolink::IOAddress& addr);
  201. /// @brief Adds socket descriptor to an interface.
  202. ///
  203. /// @param sock SocketInfo structure that describes socket.
  204. void addSocket(const SocketInfo& sock) {
  205. sockets_.push_back(sock);
  206. }
  207. /// @brief Closes socket.
  208. ///
  209. /// Closes socket and removes corresponding SocketInfo structure
  210. /// from an interface.
  211. ///
  212. /// @param sockfd socket descriptor to be closed/removed.
  213. /// @return true if there was such socket, false otherwise
  214. bool delSocket(uint16_t sockfd);
  215. /// @brief Returns collection of all sockets added to interface.
  216. ///
  217. /// When new socket is created with @ref IfaceMgr::openSocket
  218. /// it is added to sockets collection on particular interface.
  219. /// If socket is opened by other means (e.g. function that does
  220. /// not use @ref IfaceMgr::openSocket) it will not be available
  221. /// in this collection. Note that functions like
  222. /// @ref IfaceMgr::openSocketFromIface use
  223. /// @ref IfaceMgr::openSocket internally.
  224. /// The returned reference is only valid during the lifetime of
  225. /// the IfaceMgr object that returned it.
  226. ///
  227. /// @return collection of sockets added to interface
  228. const SocketCollection& getSockets() const { return sockets_; }
  229. protected:
  230. /// Socket used to send data.
  231. SocketCollection sockets_;
  232. /// Network interface name.
  233. std::string name_;
  234. /// Interface index (a value that uniquely indentifies an interface).
  235. int ifindex_;
  236. /// List of assigned addresses.
  237. AddressCollection addrs_;
  238. /// Link-layer address.
  239. uint8_t mac_[MAX_MAC_LEN];
  240. /// Length of link-layer address (usually 6).
  241. size_t mac_len_;
  242. /// Hardware type.
  243. uint16_t hardware_type_;
  244. public:
  245. /// @todo: Make those fields protected once we start supporting more
  246. /// than just Linux
  247. /// Specifies if selected interface is loopback.
  248. bool flag_loopback_;
  249. /// Specifies if selected interface is up.
  250. bool flag_up_;
  251. /// Flag specifies if selected interface is running
  252. /// (e.g. cable plugged in, wifi associated).
  253. bool flag_running_;
  254. /// Flag specifies if selected interface is multicast capable.
  255. bool flag_multicast_;
  256. /// Flag specifies if selected interface is broadcast capable.
  257. bool flag_broadcast_;
  258. /// Interface flags (this value is as is returned by OS,
  259. /// it may mean different things on different OSes).
  260. uint32_t flags_;
  261. };
  262. /// @brief Handles network interfaces, transmission and reception.
  263. ///
  264. /// IfaceMgr is an interface manager class that detects available network
  265. /// interfaces, configured addresses, link-local addresses, and provides
  266. /// API for using sockets.
  267. ///
  268. class IfaceMgr : public boost::noncopyable {
  269. public:
  270. /// Defines callback used when commands are received over control session.
  271. typedef void (*SessionCallback) (void);
  272. /// @brief Packet reception buffer size
  273. ///
  274. /// RFC3315 states that server responses may be
  275. /// fragmented if they are over MTU. There is no
  276. /// text whether client's packets may be larger
  277. /// than 1500. For now, we can assume that
  278. /// we don't support packets larger than 1500.
  279. static const uint32_t RCVBUFSIZE = 1500;
  280. // TODO performance improvement: we may change this into
  281. // 2 maps (ifindex-indexed and name-indexed) and
  282. // also hide it (make it public make tests easier for now)
  283. /// Type that holds a list of interfaces.
  284. typedef std::list<Iface> IfaceCollection;
  285. /// IfaceMgr is a singleton class. This method returns reference
  286. /// to its sole instance.
  287. ///
  288. /// @return the only existing instance of interface manager
  289. static IfaceMgr& instance();
  290. /// @brief Check if packet be sent directly to the client having no address.
  291. ///
  292. /// Checks if IfaceMgr can send DHCPv4 packet to the client
  293. /// who hasn't got address assigned. If this is not supported
  294. /// broadcast address should be used to send response to
  295. /// the client.
  296. ///
  297. /// @return true if direct response is supported.
  298. bool isDirectResponseSupported() const;
  299. /// @brief Returns interface with specified interface index
  300. ///
  301. /// @param ifindex index of searched interface
  302. ///
  303. /// @return interface with requested index (or NULL if no such
  304. /// interface is present)
  305. ///
  306. Iface* getIface(int ifindex);
  307. /// @brief Returns interface with specified interface name
  308. ///
  309. /// @param ifname name of searched interface
  310. ///
  311. /// @return interface with requested name (or NULL if no such
  312. /// interface is present)
  313. ///
  314. Iface*
  315. getIface(const std::string& ifname);
  316. /// @brief Returns container with all interfaces.
  317. ///
  318. /// This reference is only valid as long as IfaceMgr is valid. However,
  319. /// since IfaceMgr is a singleton and is expected to be destroyed after
  320. /// main() function completes, you should not worry much about this.
  321. ///
  322. /// @return container with all interfaces.
  323. const IfaceCollection& getIfaces() { return ifaces_; }
  324. /// @brief Return most suitable socket for transmitting specified IPv6 packet.
  325. ///
  326. /// This method takes Pkt6 (see overloaded implementation that takes
  327. /// Pkt4) and chooses appropriate socket to send it. This method
  328. /// may throw BadValue if specified packet does not have outbound
  329. /// interface specified, no such interface exists, or specified
  330. /// interface does not have any appropriate sockets open.
  331. ///
  332. /// @param pkt a packet to be transmitted
  333. ///
  334. /// @return a socket descriptor
  335. uint16_t getSocket(const isc::dhcp::Pkt6& pkt);
  336. /// @brief Return most suitable socket for transmitting specified IPv6 packet.
  337. ///
  338. /// This method takes Pkt4 (see overloaded implementation that takes
  339. /// Pkt6) and chooses appropriate socket to send it. This method
  340. /// may throw BadValue if specified packet does not have outbound
  341. /// interface specified, no such interface exists, or specified
  342. /// interface does not have any appropriate sockets open.
  343. ///
  344. /// @param pkt a packet to be transmitted
  345. ///
  346. /// @return a socket descriptor
  347. uint16_t getSocket(const isc::dhcp::Pkt4& pkt);
  348. /// Debugging method that prints out all available interfaces.
  349. ///
  350. /// @param out specifies stream to print list of interfaces to
  351. void printIfaces(std::ostream& out = std::cout);
  352. /// @brief Sends an IPv6 packet.
  353. ///
  354. /// Sends an IPv6 packet. All parameters for actual transmission are specified in
  355. /// Pkt6 structure itself. That includes destination address, src/dst port
  356. /// and interface over which data will be sent.
  357. ///
  358. /// @param pkt packet to be sent
  359. ///
  360. /// @throw isc::BadValue if invalid interface specified in the packet.
  361. /// @throw isc::dhcp::SocketWriteError if sendmsg() failed to send packet.
  362. /// @return true if sending was successful
  363. bool send(const Pkt6Ptr& pkt);
  364. /// @brief Sends an IPv4 packet.
  365. ///
  366. /// Sends an IPv4 packet. All parameters for actual transmission are specified
  367. /// in Pkt4 structure itself. That includes destination address, src/dst
  368. /// port and interface over which data will be sent.
  369. ///
  370. /// @param pkt a packet to be sent
  371. ///
  372. /// @throw isc::BadValue if invalid interface specified in the packet.
  373. /// @throw isc::dhcp::SocketWriteError if sendmsg() failed to send packet.
  374. /// @return true if sending was successful
  375. bool send(const Pkt4Ptr& pkt);
  376. /// @brief Tries to receive IPv6 packet over open IPv6 sockets.
  377. ///
  378. /// Attempts to receive a single IPv6 packet of any of the open IPv6 sockets.
  379. /// If reception is successful and all information about its sender
  380. /// are obtained, Pkt6 object is created and returned.
  381. ///
  382. /// TODO Start using select() and add timeout to be able
  383. /// to not wait infinitely, but rather do something useful
  384. /// (e.g. remove expired leases)
  385. ///
  386. /// @param timeout_sec specifies integral part of the timeout (in seconds)
  387. /// @param timeout_usec specifies fractional part of the timeout
  388. /// (in microseconds)
  389. ///
  390. /// @throw isc::BadValue if timeout_usec is greater than one million
  391. /// @throw isc::dhcp::SocketReadError if error occured when receiving a packet.
  392. /// @return Pkt6 object representing received packet (or NULL)
  393. Pkt6Ptr receive6(uint32_t timeout_sec, uint32_t timeout_usec = 0);
  394. /// @brief Tries to receive IPv4 packet over open IPv4 sockets.
  395. ///
  396. /// Attempts to receive a single IPv4 packet of any of the open IPv4 sockets.
  397. /// If reception is successful and all information about its sender
  398. /// are obtained, Pkt4 object is created and returned.
  399. ///
  400. /// @param timeout_sec specifies integral part of the timeout (in seconds)
  401. /// @param timeout_usec specifies fractional part of the timeout
  402. /// (in microseconds)
  403. ///
  404. /// @throw isc::BadValue if timeout_usec is greater than one million
  405. /// @throw isc::dhcp::SocketReadError if error occured when receiving a packet.
  406. /// @return Pkt4 object representing received packet (or NULL)
  407. Pkt4Ptr receive4(uint32_t timeout_sec, uint32_t timeout_usec = 0);
  408. /// Opens UDP/IP socket and binds it to address, interface and port.
  409. ///
  410. /// Specific type of socket (UDP/IPv4 or UDP/IPv6) depends on passed addr
  411. /// family.
  412. ///
  413. /// @param ifname name of the interface
  414. /// @param addr address to be bound.
  415. /// @param port UDP port.
  416. /// @param receive_bcast configure IPv4 socket to receive broadcast messages.
  417. /// This parameter is ignored for IPv6 sockets.
  418. /// @param send_bcast configure IPv4 socket to send broadcast messages.
  419. /// This parameter is ignored for IPv6 sockets.
  420. ///
  421. /// Method will throw if socket creation, socket binding or multicast
  422. /// join fails.
  423. ///
  424. /// @return socket descriptor, if socket creation, binding and multicast
  425. /// group join were all successful.
  426. int openSocket(const std::string& ifname,
  427. const isc::asiolink::IOAddress& addr,
  428. const uint16_t port,
  429. const bool receive_bcast = false,
  430. const bool send_bcast = false);
  431. /// @brief Opens UDP/IP socket and binds it to interface specified.
  432. ///
  433. /// This method differs from \ref openSocket in that it does not require
  434. /// the specification of a local address to which socket will be bound.
  435. /// Instead, the method searches through the addresses on the specified
  436. /// interface and selects one that matches the address family.
  437. ///
  438. /// @param ifname name of the interface
  439. /// @param port UDP port
  440. /// @param family address family (AF_INET or AF_INET6)
  441. /// @return socket descriptor, if socket creation, binding and multicast
  442. /// group join were all successful.
  443. /// @throw isc::Unexpected if failed to create and bind socket.
  444. /// @throw isc::BadValue if there is no address on specified interface
  445. /// that belongs to given family.
  446. int openSocketFromIface(const std::string& ifname,
  447. const uint16_t port,
  448. const uint8_t family);
  449. /// @brief Opens UDP/IP socket and binds to address specified
  450. ///
  451. /// This methods differs from \ref openSocket in that it does not require
  452. /// the specification of the interface to which the socket will be bound.
  453. ///
  454. /// @param addr address to be bound
  455. /// @param port UDP port
  456. /// @return socket descriptor, if socket creation, binding and multicast
  457. /// group join were all successful.
  458. /// @throw isc::Unexpected if failed to create and bind socket
  459. /// @throw isc::BadValue if specified address is not available on
  460. /// any interface
  461. int openSocketFromAddress(const isc::asiolink::IOAddress& addr,
  462. const uint16_t port);
  463. /// @brief Opens UDP/IP socket to be used to connect to remote address
  464. ///
  465. /// This method identifies the local address to be used to connect to the
  466. /// remote address specified as argument. Once the local address is
  467. /// identified, \ref openSocket is called to open a socket and bind it to
  468. /// the interface, address and port.
  469. ///
  470. /// @param remote_addr remote address to connect to
  471. /// @param port UDP port
  472. /// @return socket descriptor, if socket creation, binding and multicast
  473. /// group join were all successful.
  474. /// @throw isc::Unexpected if failed to create and bind socket
  475. int openSocketFromRemoteAddress(const isc::asiolink::IOAddress& remote_addr,
  476. const uint16_t port);
  477. /// Opens IPv6 sockets on detected interfaces.
  478. ///
  479. /// Will throw exception if socket creation fails.
  480. ///
  481. /// @param port specifies port number (usually DHCP6_SERVER_PORT)
  482. ///
  483. /// @throw SocketOpenFailure if tried and failed to open socket.
  484. /// @return true if any sockets were open
  485. bool openSockets6(const uint16_t port = DHCP6_SERVER_PORT);
  486. /// Opens IPv4 sockets on detected interfaces.
  487. /// Will throw exception if socket creation fails.
  488. ///
  489. /// @param port specifies port number (usually DHCP4_SERVER_PORT)
  490. /// @param use_bcast configure sockets to support broadcast messages.
  491. ///
  492. /// @throw SocketOpenFailure if tried and failed to open socket.
  493. /// @return true if any sockets were open
  494. bool openSockets4(const uint16_t port = DHCP4_SERVER_PORT,
  495. const bool use_bcast = true);
  496. /// @brief Closes all open sockets.
  497. /// Is used in destructor, but also from Dhcpv4Srv and Dhcpv6Srv classes.
  498. void closeSockets();
  499. /// @brief Closes all IPv4 or IPv6 sockets.
  500. ///
  501. /// This function closes sockets of the specific 'type' and closes them.
  502. /// The 'type' of the socket indicates whether it is used to send IPv4
  503. /// or IPv6 packets. The allowed values of the parameter are AF_INET and
  504. /// AF_INET6 for IPv4 and IPv6 packets respectively. It is important
  505. /// to realize that the actual types of sockets may be different than
  506. /// AF_INET for IPv4 packets. This is because, historically the IfaceMgr
  507. /// always used AF_INET sockets for IPv4 traffic. This is no longer the
  508. /// case when the Direct IPv4 traffic must be supported. In order to support
  509. /// direct traffic, the IfaceMgr operates on raw sockets, e.g. AF_PACKET
  510. /// family sockets on Linux.
  511. ///
  512. /// @todo Replace the AF_INET and AF_INET6 values with an enum
  513. /// which will not be confused with the actual socket type.
  514. ///
  515. /// @param family type of the sockets to be closed (AF_INET or AF_INET6)
  516. ///
  517. /// @throw BadValue if family value is different than AF_INET or AF_INET6.
  518. void closeSockets(const uint16_t family);
  519. /// @brief Returns number of detected interfaces.
  520. ///
  521. /// @return number of detected interfaces
  522. uint16_t countIfaces() { return ifaces_.size(); }
  523. /// @brief Sets session socket and a callback
  524. ///
  525. /// Specifies session socket and a callback that will be called
  526. /// when data will be received over that socket.
  527. ///
  528. /// @param socketfd socket descriptor
  529. /// @param callback callback function
  530. void set_session_socket(int socketfd, SessionCallback callback) {
  531. session_socket_ = socketfd;
  532. session_callback_ = callback;
  533. }
  534. /// @brief Set Packet Filter object to handle send/receive packets.
  535. ///
  536. /// Packet Filters expose low-level functions handling sockets opening
  537. /// and sending/receiving packets through those sockets. This function
  538. /// sets custom Packet Filter (represented by a class derived from PktFilter)
  539. /// to be used by IfaceMgr. Note that there must be no IPv4 sockets open
  540. /// when this function is called. Call closeSockets(AF_INET) to close
  541. /// all hanging IPv4 sockets opened by the current packet filter object.
  542. ///
  543. /// @param packet_filter new packet filter to be used by IfaceMgr to send/receive
  544. /// packets and open sockets.
  545. ///
  546. /// @throw InvalidPacketFilter if provided packet filter object is NULL.
  547. /// @throw PacketFilterChangeDenied if there are open IPv4 sockets
  548. void setPacketFilter(const PktFilterPtr& packet_filter);
  549. /// @brief Set Packet Filter object to handle send/receive packets.
  550. ///
  551. /// This function sets Packet Filter object to be used by IfaceMgr,
  552. /// appropriate for the current OS. Setting the argument to 'true'
  553. /// indicates that function should set a packet filter class
  554. /// which supports direct responses to clients having no address
  555. /// assigned yet. Filters picked by this function will vary, depending
  556. /// on the OS being used. There is no guarantee that there is an
  557. /// implementation that supports this feature on a particular OS.
  558. /// If there isn't, the PktFilterInet object will be set. If the
  559. /// argument is set to 'false', PktFilterInet object instance will
  560. /// be set as the Packet Filter regrdaless of the OS type.
  561. ///
  562. /// @param direct_response_desired specifies whether the Packet Filter
  563. /// object being set should support direct traffic to the host
  564. /// not having address assigned.
  565. void setMatchingPacketFilter(const bool direct_response_desired = false);
  566. /// A value of socket descriptor representing "not specified" state.
  567. static const int INVALID_SOCKET = -1;
  568. // don't use private, we need derived classes in tests
  569. protected:
  570. /// @brief Protected constructor.
  571. ///
  572. /// Protected constructor. This is a singleton class. We don't want
  573. /// anyone to create instances of IfaceMgr. Use instance() method instead.
  574. IfaceMgr();
  575. virtual ~IfaceMgr();
  576. /// @brief Opens IPv4 socket.
  577. ///
  578. /// Please do not use this method directly. Use openSocket instead.
  579. ///
  580. /// This method may throw exception if socket creation fails.
  581. ///
  582. /// @param iface reference to interface structure.
  583. /// @param addr an address the created socket should be bound to
  584. /// @param port a port that created socket should be bound to
  585. /// @param receive_bcast configure socket to receive broadcast messages
  586. /// @param send_bcast configure socket to send broadcast messages.
  587. ///
  588. /// @return socket descriptor
  589. int openSocket4(Iface& iface, const isc::asiolink::IOAddress& addr,
  590. const uint16_t port, const bool receive_bcast = false,
  591. const bool send_bcast = false);
  592. /// @brief Opens IPv6 socket.
  593. ///
  594. /// Please do not use this method directly. Use openSocket instead.
  595. ///
  596. /// This method may throw exception if socket creation fails.
  597. ///
  598. /// @param iface reference to interface structure.
  599. /// @param addr an address the created socket should be bound to
  600. /// @param port a port that created socket should be bound to
  601. ///
  602. /// @return socket descriptor
  603. int openSocket6(Iface& iface, const isc::asiolink::IOAddress& addr, uint16_t port);
  604. /// @brief Adds an interface to list of known interfaces.
  605. ///
  606. /// @param iface reference to Iface object.
  607. void addInterface(const Iface& iface) {
  608. ifaces_.push_back(iface);
  609. }
  610. /// @brief Detects network interfaces.
  611. ///
  612. /// This method will eventually detect available interfaces. For now
  613. /// it offers stub implementation. First interface name and link-local
  614. /// IPv6 address is read from interfaces.txt file.
  615. void
  616. detectIfaces();
  617. /// @brief Stub implementation of network interface detection.
  618. ///
  619. /// This implementations reads a single line from interfaces.txt file
  620. /// and pretends to detect such interface. First interface name and
  621. /// link-local IPv6 address or IPv4 address is read from the
  622. /// interfaces.txt file.
  623. void
  624. stubDetectIfaces();
  625. // TODO: having 2 maps (ifindex->iface and ifname->iface would)
  626. // probably be better for performance reasons
  627. /// List of available interfaces
  628. IfaceCollection ifaces_;
  629. // TODO: Also keep this interface on Iface once interface detection
  630. // is implemented. We may need it e.g. to close all sockets on
  631. // specific interface
  632. //int recvsock_; // TODO: should be fd_set eventually, but we have only
  633. //int sendsock_; // 2 sockets for now. Will do for until next release
  634. // We can't use the same socket, as receiving socket
  635. // is bound to multicast address. And we all know what happens
  636. // to people who try to use multicast as source address.
  637. /// Length of the control_buf_ array
  638. size_t control_buf_len_;
  639. /// Control-buffer, used in transmission and reception.
  640. boost::scoped_array<char> control_buf_;
  641. /// @brief A wrapper for OS-specific operations before sending IPv4 packet
  642. ///
  643. /// @param m message header (will be later used for sendmsg() call)
  644. /// @param control_buf buffer to be used during transmission
  645. /// @param control_buf_len buffer length
  646. /// @param pkt packet to be sent
  647. void os_send4(struct msghdr& m, boost::scoped_array<char>& control_buf,
  648. size_t control_buf_len, const Pkt4Ptr& pkt);
  649. /// @brief OS-specific operations during IPv4 packet reception
  650. ///
  651. /// @param m message header (was used during recvmsg() call)
  652. /// @param pkt packet received (some fields will be set here)
  653. ///
  654. /// @return true if successful, false otherwise
  655. bool os_receive4(struct msghdr& m, Pkt4Ptr& pkt);
  656. /// Socket descriptor of the session socket.
  657. int session_socket_;
  658. /// A callback that will be called when data arrives over session_socket_.
  659. SessionCallback session_callback_;
  660. private:
  661. /// @brief Joins IPv6 multicast group on a socket.
  662. ///
  663. /// Socket must be created and bound to an address. Note that this
  664. /// address is different than the multicast address. For example DHCPv6
  665. /// server should bind its socket to link-local address (fe80::1234...)
  666. /// and later join ff02::1:2 multicast group.
  667. ///
  668. /// @param sock socket fd (socket must be bound)
  669. /// @param ifname interface name (for link-scoped multicast groups)
  670. /// @param mcast multicast address to join (e.g. "ff02::1:2")
  671. ///
  672. /// @return true if multicast join was successful
  673. ///
  674. bool
  675. joinMulticast(int sock, const std::string& ifname,
  676. const std::string& mcast);
  677. /// @brief Identifies local network address to be used to
  678. /// connect to remote address.
  679. ///
  680. /// This method identifies local network address that can be used
  681. /// to connect to remote address specified.
  682. /// It first creates socket and makes attempt to connect
  683. /// to remote location via this socket. If connection
  684. /// is established successfully, the local address to which
  685. /// socket is bound is returned.
  686. ///
  687. /// @param remote_addr remote address to connect to
  688. /// @param port port to be used
  689. /// @return local address to be used to connect to remote address
  690. /// @throw isc::Unexpected if unable to identify local address
  691. isc::asiolink::IOAddress
  692. getLocalAddress(const isc::asiolink::IOAddress& remote_addr,
  693. const uint16_t port);
  694. /// Holds instance of a class derived from PktFilter, used by the
  695. /// IfaceMgr to open sockets and send/receive packets through these
  696. /// sockets. It is possible to supply custom object using
  697. /// setPacketFilter class. Various Packet Filters differ mainly by using
  698. /// different types of sockets, e.g. SOCK_DGRAM, SOCK_RAW and different
  699. /// families, e.g. AF_INET, AF_PACKET etc. Another possible type of
  700. /// Packet Filter is the one used for unit testing, which doesn't
  701. /// open sockets but rather mimics their behavior (mock object).
  702. PktFilterPtr packet_filter_;
  703. };
  704. }; // namespace isc::dhcp
  705. }; // namespace isc
  706. #endif // IFACE_MGR_H