iface_mgr.h 41 KB

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