iface_mgr.h 45 KB

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