iface_mgr.h 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  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 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* getIface(const std::string& ifname);
  378. /// @brief Returns container with all interfaces.
  379. ///
  380. /// This reference is only valid as long as IfaceMgr is valid. However,
  381. /// since IfaceMgr is a singleton and is expected to be destroyed after
  382. /// main() function completes, you should not worry much about this.
  383. ///
  384. /// @return container with all interfaces.
  385. const IfaceCollection& getIfaces() { return (ifaces_); }
  386. /// @brief Removes detected interfaces.
  387. ///
  388. /// This method removes all detected interfaces. This method should be
  389. /// used by unit tests to supply a custom set of interfaces. For example:
  390. /// a unit test may create a pool of fake interfaces and use the custom
  391. /// @c PktFilter class to mimic socket operation on these interfaces.
  392. void clearIfaces();
  393. /// @brief Detects network interfaces.
  394. ///
  395. /// This method will eventually detect available interfaces. For now
  396. /// it offers stub implementation. First interface name and link-local
  397. /// IPv6 address is read from interfaces.txt file.
  398. void detectIfaces();
  399. /// @brief Return most suitable socket for transmitting specified IPv6 packet.
  400. ///
  401. /// This method takes Pkt6 (see overloaded implementation that takes
  402. /// Pkt4) 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::Pkt6& pkt);
  411. /// @brief Return most suitable socket for transmitting specified IPv4 packet.
  412. ///
  413. /// This method takes Pkt4 (see overloaded implementation that takes
  414. /// Pkt6) and chooses appropriate socket to send it. This method
  415. /// may throw BadValue if specified packet does not have outbound
  416. /// interface specified, no such interface exists, or specified
  417. /// interface does not have any appropriate sockets open.
  418. ///
  419. /// @param pkt a packet to be transmitted
  420. ///
  421. /// @return A structure describing a socket.
  422. SocketInfo getSocket(const isc::dhcp::Pkt4& pkt);
  423. /// Debugging method that prints out all available interfaces.
  424. ///
  425. /// @param out specifies stream to print list of interfaces to
  426. void printIfaces(std::ostream& out = std::cout);
  427. /// @brief Sends an IPv6 packet.
  428. ///
  429. /// Sends an IPv6 packet. All parameters for actual transmission are specified in
  430. /// Pkt6 structure itself. That includes destination address, src/dst port
  431. /// and interface over which data will be sent.
  432. ///
  433. /// @param pkt 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 Pkt6Ptr& pkt);
  439. /// @brief Sends an IPv4 packet.
  440. ///
  441. /// Sends an IPv4 packet. All parameters for actual transmission are specified
  442. /// in Pkt4 structure itself. That includes destination address, src/dst
  443. /// port and interface over which data will be sent.
  444. ///
  445. /// @param pkt a packet to be sent
  446. ///
  447. /// @throw isc::BadValue if invalid interface specified in the packet.
  448. /// @throw isc::dhcp::SocketWriteError if sendmsg() failed to send packet.
  449. /// @return true if sending was successful
  450. bool send(const Pkt4Ptr& pkt);
  451. /// @brief Tries to receive IPv6 packet over open IPv6 sockets.
  452. ///
  453. /// Attempts to receive a single IPv6 packet of any of the open IPv6 sockets.
  454. /// If reception is successful and all information about its sender
  455. /// are obtained, Pkt6 object is created and returned.
  456. ///
  457. /// TODO Start using select() and add timeout to be able
  458. /// to not wait infinitely, but rather do something useful
  459. /// (e.g. remove expired leases)
  460. ///
  461. /// @param timeout_sec specifies integral part of the timeout (in seconds)
  462. /// @param timeout_usec specifies fractional part of the timeout
  463. /// (in microseconds)
  464. ///
  465. /// @throw isc::BadValue if timeout_usec is greater than one million
  466. /// @throw isc::dhcp::SocketReadError if error occured when receiving a packet.
  467. /// @return Pkt6 object representing received packet (or NULL)
  468. Pkt6Ptr receive6(uint32_t timeout_sec, uint32_t timeout_usec = 0);
  469. /// @brief Tries to receive IPv4 packet over open IPv4 sockets.
  470. ///
  471. /// Attempts to receive a single IPv4 packet of any of the open IPv4 sockets.
  472. /// If reception is successful and all information about its sender
  473. /// are obtained, Pkt4 object is created and returned.
  474. ///
  475. /// @param timeout_sec specifies integral part of the timeout (in seconds)
  476. /// @param timeout_usec specifies fractional part of the timeout
  477. /// (in microseconds)
  478. ///
  479. /// @throw isc::BadValue if timeout_usec is greater than one million
  480. /// @throw isc::dhcp::SocketReadError if error occured when receiving a packet.
  481. /// @return Pkt4 object representing received packet (or NULL)
  482. Pkt4Ptr receive4(uint32_t timeout_sec, uint32_t timeout_usec = 0);
  483. /// Opens UDP/IP socket and binds it to address, interface and port.
  484. ///
  485. /// Specific type of socket (UDP/IPv4 or UDP/IPv6) depends on passed addr
  486. /// family.
  487. ///
  488. /// @param ifname name of the interface
  489. /// @param addr address to be bound.
  490. /// @param port UDP port.
  491. /// @param receive_bcast configure IPv4 socket to receive broadcast
  492. /// messages or IPv6 socket to join multicast group.
  493. /// @param send_bcast configure IPv4 socket to send broadcast messages.
  494. /// This parameter is ignored for IPv6 sockets.
  495. ///
  496. /// Method will throw if socket creation, socket binding or multicast
  497. /// join fails.
  498. ///
  499. /// @return socket descriptor, if socket creation, binding and multicast
  500. /// group join were all successful.
  501. int openSocket(const std::string& ifname,
  502. const isc::asiolink::IOAddress& addr,
  503. const uint16_t port,
  504. const bool receive_bcast = false,
  505. const bool send_bcast = false);
  506. /// @brief Opens UDP/IP socket and binds it to interface specified.
  507. ///
  508. /// This method differs from \ref openSocket in that it does not require
  509. /// the specification of a local address to which socket will be bound.
  510. /// Instead, the method searches through the addresses on the specified
  511. /// interface and selects one that matches the address family.
  512. ///
  513. /// @note This method does not join the socket to the multicast group.
  514. ///
  515. /// @param ifname name of the interface
  516. /// @param port UDP port
  517. /// @param family address family (AF_INET or AF_INET6)
  518. /// @return socket descriptor, if socket creation and binding was
  519. /// successful.
  520. /// @throw isc::Unexpected if failed to create and bind socket.
  521. /// @throw isc::BadValue if there is no address on specified interface
  522. /// that belongs to given family.
  523. int openSocketFromIface(const std::string& ifname,
  524. const uint16_t port,
  525. const uint8_t family);
  526. /// @brief Opens UDP/IP socket and binds to address specified
  527. ///
  528. /// This methods differs from \ref openSocket in that it does not require
  529. /// the specification of the interface to which the socket will be bound.
  530. ///
  531. /// @note This method does not join the socket to the multicast group.
  532. ///
  533. /// @param addr address to be bound
  534. /// @param port UDP port
  535. /// @return socket descriptor, if socket creation and binding was
  536. /// successful.
  537. /// @throw isc::Unexpected if failed to create and bind socket
  538. /// @throw isc::BadValue if specified address is not available on
  539. /// any interface
  540. int openSocketFromAddress(const isc::asiolink::IOAddress& addr,
  541. const uint16_t port);
  542. /// @brief Opens UDP/IP socket to be used to connect to remote address
  543. ///
  544. /// This method identifies the local address to be used to connect to the
  545. /// remote address specified as argument. Once the local address is
  546. /// identified, \ref openSocket is called to open a socket and bind it to
  547. /// the interface, address and port.
  548. ///
  549. /// @note This method does not join the socket to a multicast group.
  550. ///
  551. /// @param remote_addr remote address to connect to
  552. /// @param port UDP port
  553. /// @return socket descriptor, if socket creation and binding was
  554. /// successful.
  555. /// @throw isc::Unexpected if failed to create and bind socket
  556. int openSocketFromRemoteAddress(const isc::asiolink::IOAddress& remote_addr,
  557. const uint16_t port);
  558. /// @brief Opens IPv6 sockets on detected interfaces.
  559. ///
  560. /// On the systems with multiple interfaces, it is often desired that the
  561. /// failure to open a socket on a particular interface doesn't cause a
  562. /// fatal error and sockets should be opened on remaining interfaces.
  563. /// However, the warning about the failure for the particular socket should
  564. /// be communicated to the caller. The libdhcp++ is a common library with
  565. /// no logger associated with it. Most of the functions in this library
  566. /// communicate errors via exceptions. In case of openSockets6 function
  567. /// exception must not be thrown if the function is supposed to continue
  568. /// opening sockets, despite an error. Therefore, if such a behavior is
  569. /// desired, the error handler function can be passed as a parameter.
  570. /// This error handler is called (if present) with an error string.
  571. /// Typically, error handler will simply log an error using an application
  572. /// logger, but it can do more sophisticated error handling too.
  573. ///
  574. /// @todo It is possible that additional parameters will have to be added
  575. /// to the error handler, e.g. Iface if it was really supposed to do
  576. /// some more sophisticated error handling.
  577. ///
  578. /// If the error handler is not installed (is NULL), the exception is thrown
  579. /// for each failure (default behavior).
  580. ///
  581. /// @warning This function does not check if there has been any sockets
  582. /// already open by the @c IfaceMgr. Therefore a caller should call
  583. /// @c IfaceMgr::closeSockets(AF_INET6) before calling this function.
  584. /// If there are any sockets open, the function may either throw an
  585. /// exception or invoke an error handler on attempt to bind the new socket
  586. /// to the same address and port.
  587. ///
  588. /// @param port specifies port number (usually DHCP6_SERVER_PORT)
  589. /// @param error_handler A pointer to an error handler function which is
  590. /// called by the openSockets6 when it fails to open a socket. This
  591. /// parameter can be NULL to indicate that the callback should not be used.
  592. ///
  593. /// @throw SocketOpenFailure if tried and failed to open socket.
  594. /// @return true if any sockets were open
  595. bool openSockets6(const uint16_t port = DHCP6_SERVER_PORT,
  596. IfaceMgrErrorMsgCallback error_handler = NULL);
  597. /// @brief Opens IPv4 sockets on detected interfaces.
  598. ///
  599. /// This function attempts to open sockets on all interfaces which have been
  600. /// detected by @c IfaceMgr and meet the following conditions:
  601. /// - interface is not a local loopback,
  602. /// - interface is running (connected),
  603. /// - interface is up,
  604. /// - interface is active, e.g. selected from the configuration to be used
  605. /// to listen DHCPv4 messages,
  606. /// - interface has an IPv4 address assigned.
  607. ///
  608. /// The type of the socket being open depends on the selected Packet Filter
  609. /// represented by a class derived from @c isc::dhcp::PktFilter abstract
  610. /// class.
  611. ///
  612. /// It is possible to specify whether sockets should be broadcast capable.
  613. /// In most of the cases, the sockets should support broadcast traffic, e.g.
  614. /// DHCPv4 server and relay need to listen to broadcast messages sent by
  615. /// clients. If the socket has to be open on the particular interface, this
  616. /// interface must have broadcast flag set. If this condition is not met,
  617. /// the socket will be created in the unicast-only mode. If there are
  618. /// multiple broadcast-capable interfaces present, they may be all open
  619. /// in a broadcast mode only if the OS supports SO_BINDTODEVICE (bind socket
  620. /// to a device) socket option. If this option is not supported, only the
  621. /// first broadcast-capable socket will be opened in the broadcast mode.
  622. /// The error will be reported for sockets being opened on other interfaces.
  623. /// If the socket is bound to a device (interface), the broadcast traffic
  624. /// sent to this interface will be received on this interface only.
  625. /// This allows the DHCPv4 server or relay to detect the interface on which
  626. /// the broadcast message has been received. This interface is later used
  627. /// to send a response.
  628. ///
  629. /// On the systems with multiple interfaces, it is often desired that the
  630. /// failure to open a socket on a particular interface doesn't cause a
  631. /// fatal error and sockets should be opened on remaining interfaces.
  632. /// However, the warning about the failure for the particular socket should
  633. /// be communicated to the caller. The libdhcp++ is a common library with
  634. /// no logger associated with it. Most of the functions in this library
  635. /// communicate errors via exceptions. In case of openSockets4 function
  636. /// exception must not be thrown if the function is supposed to continue
  637. /// opening sockets, despite an error. Therefore, if such a behavior is
  638. /// desired, the error handler function can be passed as a parameter.
  639. /// This error handler is called (if present) with an error string.
  640. /// Typically, error handler will simply log an error using an application
  641. /// logger, but it can do more sophisticated error handling too.
  642. ///
  643. /// @todo It is possible that additional parameters will have to be added
  644. /// to the error handler, e.g. Iface if it was really supposed to do
  645. /// some more sophisticated error handling.
  646. ///
  647. /// If the error handler is not installed (is NULL), the exception is thrown
  648. /// for each failure (default behavior).
  649. ///
  650. /// @warning This function does not check if there has been any sockets
  651. /// already open by the @c IfaceMgr. Therefore a caller should call
  652. /// @c IfaceMgr::closeSockets(AF_INET) before calling this function.
  653. /// If there are any sockets open, the function may either throw an
  654. /// exception or invoke an error handler on attempt to bind the new socket
  655. /// to the same address and port.
  656. ///
  657. /// @param port specifies port number (usually DHCP4_SERVER_PORT)
  658. /// @param use_bcast configure sockets to support broadcast messages.
  659. /// @param error_handler A pointer to an error handler function which is
  660. /// called by the openSockets4 when it fails to open a socket. This
  661. /// parameter can be NULL to indicate that the callback should not be used.
  662. ///
  663. /// @throw SocketOpenFailure if tried and failed to open socket and callback
  664. /// function hasn't been specified.
  665. /// @return true if any sockets were open
  666. bool openSockets4(const uint16_t port = DHCP4_SERVER_PORT,
  667. const bool use_bcast = true,
  668. IfaceMgrErrorMsgCallback error_handler = NULL);
  669. /// @brief Closes all open sockets.
  670. /// Is used in destructor, but also from Dhcpv4Srv and Dhcpv6Srv classes.
  671. void closeSockets();
  672. /// @brief Closes all IPv4 or IPv6 sockets.
  673. ///
  674. /// This function closes sockets of the specific 'type' and closes them.
  675. /// The 'type' of the socket indicates whether it is used to send IPv4
  676. /// or IPv6 packets. The allowed values of the parameter are AF_INET and
  677. /// AF_INET6 for IPv4 and IPv6 packets respectively. It is important
  678. /// to realize that the actual types of sockets may be different than
  679. /// AF_INET for IPv4 packets. This is because, historically the IfaceMgr
  680. /// always used AF_INET sockets for IPv4 traffic. This is no longer the
  681. /// case when the Direct IPv4 traffic must be supported. In order to support
  682. /// direct traffic, the IfaceMgr operates on raw sockets, e.g. AF_PACKET
  683. /// family sockets on Linux.
  684. ///
  685. /// @todo Replace the AF_INET and AF_INET6 values with an enum
  686. /// which will not be confused with the actual socket type.
  687. ///
  688. /// @param family type of the sockets to be closed (AF_INET or AF_INET6)
  689. ///
  690. /// @throw BadValue if family value is different than AF_INET or AF_INET6.
  691. void closeSockets(const uint16_t family);
  692. /// @brief Returns number of detected interfaces.
  693. ///
  694. /// @return number of detected interfaces
  695. uint16_t countIfaces() { return ifaces_.size(); }
  696. /// @brief Sets session socket and a callback
  697. ///
  698. /// Specifies session socket and a callback that will be called
  699. /// when data will be received over that socket.
  700. ///
  701. /// @param socketfd socket descriptor
  702. /// @param callback callback function
  703. void set_session_socket(int socketfd, SessionCallback callback) {
  704. session_socket_ = socketfd;
  705. session_callback_ = callback;
  706. }
  707. /// @brief Set packet filter object to handle sending and receiving DHCPv4
  708. /// messages.
  709. ///
  710. /// Packet filter objects provide means for the @c IfaceMgr to open sockets
  711. /// for IPv4 packets reception and sending. This function sets custom packet
  712. /// filter (represented by a class derived from PktFilter) to be used by
  713. /// @c IfaceMgr. Note that there must be no IPv4 sockets open when this
  714. /// function is called. Call closeSockets(AF_INET) to close all hanging IPv4
  715. /// sockets opened by the current packet filter object.
  716. ///
  717. /// @param packet_filter A pointer to the new packet filter object to be
  718. /// used by @c IfaceMgr.
  719. ///
  720. /// @throw InvalidPacketFilter if provided packet filter object is NULL.
  721. /// @throw PacketFilterChangeDenied if there are open IPv4 sockets.
  722. void setPacketFilter(const PktFilterPtr& packet_filter);
  723. /// @brief Set packet filter object to handle sending and receving DHCPv6
  724. /// messages.
  725. ///
  726. /// Packet filter objects provide means for the @c IfaceMgr to open sockets
  727. /// for IPv6 packets reception and sending. This function sets the new
  728. /// instance of the packet filter which will be used by @c IfaceMgr to send
  729. /// and receive DHCPv6 messages, until replaced by another packet filter.
  730. ///
  731. /// It is required that DHCPv6 messages are send and received using methods
  732. /// of the same object that was used to open socket. Therefore, it is
  733. /// required that all IPv6 sockets are closed prior to calling this
  734. /// function. Call closeSockets(AF_INET6) to close all hanging IPv6 sockets
  735. /// opened by the current packet filter object.
  736. ///
  737. /// @param packet_filter A pointer to the new packet filter object to be
  738. /// used by @c IfaceMgr.
  739. ///
  740. /// @throw isc::dhcp::InvalidPacketFilter if specified object is NULL.
  741. /// @throw isc::dhcp::PacketFilterChangeDenied if there are open IPv6
  742. /// sockets.
  743. void setPacketFilter(const PktFilter6Ptr& packet_filter);
  744. /// @brief Set Packet Filter object to handle send/receive packets.
  745. ///
  746. /// This function sets Packet Filter object to be used by IfaceMgr,
  747. /// appropriate for the current OS. Setting the argument to 'true'
  748. /// indicates that function should set a packet filter class
  749. /// which supports direct responses to clients having no address
  750. /// assigned yet. Filters picked by this function will vary, depending
  751. /// on the OS being used. There is no guarantee that there is an
  752. /// implementation that supports this feature on a particular OS.
  753. /// If there isn't, the PktFilterInet object will be set. If the
  754. /// argument is set to 'false', PktFilterInet object instance will
  755. /// be set as the Packet Filter regrdaless of the OS type.
  756. ///
  757. /// @param direct_response_desired specifies whether the Packet Filter
  758. /// object being set should support direct traffic to the host
  759. /// not having address assigned.
  760. void setMatchingPacketFilter(const bool direct_response_desired = false);
  761. /// @brief Adds an interface to list of known interfaces.
  762. ///
  763. /// @param iface reference to Iface object.
  764. /// @note This function must be public because it has to be callable
  765. /// from unit tests.
  766. void addInterface(const Iface& iface) {
  767. ifaces_.push_back(iface);
  768. }
  769. /// @brief Checks if there is at least one socket of the specified family
  770. /// open.
  771. ///
  772. /// @param family A socket family.
  773. ///
  774. /// @return true if there is at least one socket open, false otherwise.
  775. bool hasOpenSocket(const uint16_t family) const;
  776. /// @brief Checks if there is a socket open and bound to an address.
  777. ///
  778. /// This function checks if one of the sockets opened by the IfaceMgr is
  779. /// bound to the IP address specified as the method parameter.
  780. ///
  781. /// @param addr Address of the socket being searched.
  782. ///
  783. /// @return true if there is a socket bound to the specified address.
  784. bool hasOpenSocket(const isc::asiolink::IOAddress& addr) const;
  785. /// A value of socket descriptor representing "not specified" state.
  786. static const int INVALID_SOCKET = -1;
  787. // don't use private, we need derived classes in tests
  788. protected:
  789. /// @brief Protected constructor.
  790. ///
  791. /// Protected constructor. This is a singleton class. We don't want
  792. /// anyone to create instances of IfaceMgr. Use instance() method instead.
  793. IfaceMgr();
  794. virtual ~IfaceMgr();
  795. /// @brief Opens IPv4 socket.
  796. ///
  797. /// Please do not use this method directly. Use openSocket instead.
  798. ///
  799. /// This method may throw exception if socket creation fails.
  800. ///
  801. /// @param iface reference to interface structure.
  802. /// @param addr an address the created socket should be bound to
  803. /// @param port a port that created socket should be bound to
  804. /// @param receive_bcast configure socket to receive broadcast messages
  805. /// @param send_bcast configure socket to send broadcast messages.
  806. ///
  807. /// @return socket descriptor
  808. int openSocket4(Iface& iface, const isc::asiolink::IOAddress& addr,
  809. const uint16_t port, const bool receive_bcast = false,
  810. const bool send_bcast = false);
  811. /// @brief Opens IPv6 socket.
  812. ///
  813. /// Please do not use this method directly. Use openSocket instead.
  814. ///
  815. /// This method may throw exception if socket creation fails.
  816. ///
  817. /// @param iface reference to interface structure.
  818. /// @param addr an address the created socket should be bound to
  819. /// @param port a port that created socket should be bound to
  820. /// @param join_multicast A boolean parameter which indicates whether
  821. /// socket should join All_DHCP_Relay_Agents_and_servers multicast
  822. /// group.
  823. ///
  824. /// @return socket descriptor
  825. int openSocket6(Iface& iface, const isc::asiolink::IOAddress& addr,
  826. uint16_t port, const bool join_multicast);
  827. /// @brief Stub implementation of network interface detection.
  828. ///
  829. /// This implementations reads a single line from interfaces.txt file
  830. /// and pretends to detect such interface. First interface name and
  831. /// link-local IPv6 address or IPv4 address is read from the
  832. /// interfaces.txt file.
  833. void
  834. stubDetectIfaces();
  835. // TODO: having 2 maps (ifindex->iface and ifname->iface would)
  836. // probably be better for performance reasons
  837. /// List of available interfaces
  838. IfaceCollection ifaces_;
  839. // TODO: Also keep this interface on Iface once interface detection
  840. // is implemented. We may need it e.g. to close all sockets on
  841. // specific interface
  842. //int recvsock_; // TODO: should be fd_set eventually, but we have only
  843. //int sendsock_; // 2 sockets for now. Will do for until next release
  844. // We can't use the same socket, as receiving socket
  845. // is bound to multicast address. And we all know what happens
  846. // to people who try to use multicast as source address.
  847. /// Length of the control_buf_ array
  848. size_t control_buf_len_;
  849. /// Control-buffer, used in transmission and reception.
  850. boost::scoped_array<char> control_buf_;
  851. /// @brief A wrapper for OS-specific operations before sending IPv4 packet
  852. ///
  853. /// @param m message header (will be later used for sendmsg() call)
  854. /// @param control_buf buffer to be used during transmission
  855. /// @param control_buf_len buffer length
  856. /// @param pkt packet to be sent
  857. void os_send4(struct msghdr& m, boost::scoped_array<char>& control_buf,
  858. size_t control_buf_len, const Pkt4Ptr& pkt);
  859. /// @brief OS-specific operations during IPv4 packet reception
  860. ///
  861. /// @param m message header (was used during recvmsg() call)
  862. /// @param pkt packet received (some fields will be set here)
  863. ///
  864. /// @return true if successful, false otherwise
  865. bool os_receive4(struct msghdr& m, Pkt4Ptr& pkt);
  866. /// Socket descriptor of the session socket.
  867. int session_socket_;
  868. /// A callback that will be called when data arrives over session_socket_.
  869. SessionCallback session_callback_;
  870. private:
  871. /// @brief Identifies local network address to be used to
  872. /// connect to remote address.
  873. ///
  874. /// This method identifies local network address that can be used
  875. /// to connect to remote address specified.
  876. /// It first creates socket and makes attempt to connect
  877. /// to remote location via this socket. If connection
  878. /// is established successfully, the local address to which
  879. /// socket is bound is returned.
  880. ///
  881. /// @param remote_addr remote address to connect to
  882. /// @param port port to be used
  883. /// @return local address to be used to connect to remote address
  884. /// @throw isc::Unexpected if unable to identify local address
  885. isc::asiolink::IOAddress
  886. getLocalAddress(const isc::asiolink::IOAddress& remote_addr,
  887. const uint16_t port);
  888. /// @brief Open an IPv6 socket with multicast support.
  889. ///
  890. /// This function opens socket(s) to allow reception of the DHCPv6 sent
  891. /// to multicast address. It opens an IPv6 socket, binds it to link-local
  892. /// address and joins multicast group (on non-Linux systems) or opens two
  893. /// IPv6 sockets and binds one of them to link-local address and another
  894. /// one to multicast address (on Linux systems).
  895. ///
  896. /// @note This function is intended to be called internally by the
  897. /// @c IfaceMgr::openSockets6. It is not intended to be called from any
  898. /// other function.
  899. ///
  900. /// @param iface Interface on which socket should be open.
  901. /// @param addr Link-local address to bind the socket to.
  902. /// @param port Port number to bind socket to.
  903. /// @param error_handler Error handler function to be called when an
  904. /// error occurs during opening a socket, or NULL if exception should
  905. /// be thrown upon error.
  906. bool openMulticastSocket(Iface& iface,
  907. const isc::asiolink::IOAddress addr,
  908. const uint16_t port,
  909. IfaceMgrErrorMsgCallback error_handler = NULL);
  910. /// Holds instance of a class derived from PktFilter, used by the
  911. /// IfaceMgr to open sockets and send/receive packets through these
  912. /// sockets. It is possible to supply custom object using
  913. /// setPacketFilter method. Various Packet Filters differ mainly by using
  914. /// different types of sockets, e.g. SOCK_DGRAM, SOCK_RAW and different
  915. /// families, e.g. AF_INET, AF_PACKET etc. Another possible type of
  916. /// Packet Filter is the one used for unit testing, which doesn't
  917. /// open sockets but rather mimics their behavior (mock object).
  918. PktFilterPtr packet_filter_;
  919. /// Holds instance of a class derived from PktFilter6, used by the
  920. /// IfaceMgr to manage sockets used to send and receive DHCPv6
  921. /// messages. It is possible to supply a custom object using
  922. /// setPacketFilter method.
  923. PktFilter6Ptr packet_filter6_;
  924. };
  925. }; // namespace isc::dhcp
  926. }; // namespace isc
  927. #endif // IFACE_MGR_H