iface_mgr.h 40 KB

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