iface_mgr.h 46 KB

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