iface_mgr.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. // Copyright (C) 2011 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 <list>
  17. #include <boost/shared_ptr.hpp>
  18. #include <boost/scoped_array.hpp>
  19. #include <boost/noncopyable.hpp>
  20. #include <asiolink/io_address.h>
  21. #include <dhcp/dhcp6.h>
  22. #include <dhcp/dhcp4.h>
  23. #include <dhcp/pkt4.h>
  24. #include <dhcp/pkt6.h>
  25. namespace isc {
  26. namespace dhcp {
  27. /// @brief handles network interfaces, transmission and reception
  28. ///
  29. /// IfaceMgr is an interface manager class that detects available network
  30. /// interfaces, configured addresses, link-local addresses, and provides
  31. /// API for using sockets.
  32. ///
  33. class IfaceMgr : public boost::noncopyable {
  34. public:
  35. /// type that defines list of addresses
  36. typedef std::vector<isc::asiolink::IOAddress> AddressCollection;
  37. /// maximum MAC address length (Infiniband uses 20 bytes)
  38. static const unsigned int MAX_MAC_LEN = 20;
  39. /// @brief Packet reception buffer size
  40. ///
  41. /// RFC3315 states that server responses may be
  42. /// fragmented if they are over MTU. There is no
  43. /// text whether client's packets may be larger
  44. /// than 1500. For now, we can assume that
  45. /// we don't support packets larger than 1500.
  46. static const uint32_t RCVBUFSIZE = 1500;
  47. /// Holds information about socket.
  48. struct SocketInfo {
  49. uint16_t sockfd_; /// socket descriptor
  50. isc::asiolink::IOAddress addr_; /// bound address
  51. uint16_t port_; /// socket port
  52. uint16_t family_; /// IPv4 or IPv6
  53. /// @brief SocketInfo constructor.
  54. ///
  55. /// @param sockfd socket descriptor
  56. /// @param addr an address the socket is bound to
  57. /// @param port a port the socket is bound to
  58. SocketInfo(uint16_t sockfd, const isc::asiolink::IOAddress& addr,
  59. uint16_t port)
  60. :sockfd_(sockfd), addr_(addr), port_(port), family_(addr.getFamily()) { }
  61. };
  62. /// type that holds a list of socket informations
  63. typedef std::list<SocketInfo> SocketCollection;
  64. /// @brief represents a single network interface
  65. ///
  66. /// Iface structure represents network interface with all useful
  67. /// information, like name, interface index, MAC address and
  68. /// list of assigned addresses
  69. class Iface {
  70. public:
  71. /// @brief Iface constructor.
  72. ///
  73. /// Creates Iface object that represents network interface.
  74. ///
  75. /// @param name name of the interface
  76. /// @param ifindex interface index (unique integer identifier)
  77. Iface(const std::string& name, int ifindex);
  78. /// @brief Returns full interface name as "ifname/ifindex" string.
  79. ///
  80. /// @return string with interface name
  81. std::string getFullName() const;
  82. /// @brief Returns link-layer address a plain text.
  83. ///
  84. /// @return MAC address as a plain text (string)
  85. std::string getPlainMac() const;
  86. /// @brief Sets MAC address of the interface.
  87. ///
  88. /// @param mac pointer to MAC address buffer
  89. /// @param macLen length of mac address
  90. void setMac(const uint8_t* mac, size_t macLen);
  91. /// @brief Returns MAC length.
  92. ///
  93. /// @return length of MAC address
  94. size_t getMacLen() const { return mac_len_; }
  95. /// @brief Returns pointer to MAC address.
  96. ///
  97. /// Note: Returned pointer is only valid as long as the interface object
  98. /// that returned it.
  99. const uint8_t* getMac() const { return mac_; }
  100. /// @brief Sets flag_*_ fields based on bitmask value returned by OS
  101. ///
  102. /// Note: Implementation of this method is OS-dependent as bits have
  103. /// different meaning on each OS.
  104. ///
  105. /// @param flags bitmask value returned by OS in interface detection
  106. void setFlags(uint32_t flags);
  107. /// @brief Returns interface index.
  108. ///
  109. /// @return interface index
  110. uint16_t getIndex() const { return ifindex_; }
  111. /// @brief Returns interface name.
  112. ///
  113. /// @return interface name
  114. std::string getName() const { return name_; };
  115. /// @brief Sets up hardware type of the interface.
  116. ///
  117. /// @param type hardware type
  118. void setHWType(uint16_t type ) { hardware_type_ = type; }
  119. /// @brief Returns hardware type of the interface.
  120. ///
  121. /// @return hardware type
  122. uint16_t getHWType() const { return hardware_type_; }
  123. /// @brief Returns all interfaces available on an interface.
  124. ///
  125. /// Care should be taken to not use this collection after Iface object
  126. /// ceases to exist. That is easy in most cases as Iface objects are
  127. /// created by IfaceMgr that is a singleton an is expected to be
  128. /// available at all time. We may revisit this if we ever decide to
  129. /// implement dynamic interface detection, but such fancy feature would
  130. /// mostly be useful for clients with wifi/vpn/virtual interfaces.
  131. ///
  132. /// @return collection of addresses
  133. const AddressCollection& getAddresses() const { return addrs_; }
  134. /// @brief Adds an address to an interface.
  135. ///
  136. /// This only adds an address to collection, it does not physically
  137. /// configure address on actual network interface.
  138. ///
  139. /// @param addr address to be added
  140. void addAddress(const isc::asiolink::IOAddress& addr) {
  141. addrs_.push_back(addr);
  142. }
  143. /// @brief Deletes an address from an interface.
  144. ///
  145. /// This only deletes address from collection, it does not physically
  146. /// remove address configuration from actual network interface.
  147. ///
  148. /// @param addr address to be removed.
  149. ///
  150. /// @return true if removal was successful (address was in collection),
  151. /// false otherwise
  152. bool delAddress(const isc::asiolink::IOAddress& addr);
  153. /// @brief Adds socket descriptor to an interface.
  154. ///
  155. /// @param sock SocketInfo structure that describes socket.
  156. void addSocket(const SocketInfo& sock)
  157. { sockets_.push_back(sock); }
  158. /// @brief Closes socket.
  159. ///
  160. /// Closes socket and removes corresponding SocketInfo structure
  161. /// from an interface.
  162. ///
  163. /// @param sockfd socket descriptor to be closed/removed.
  164. /// @return true if there was such socket, false otherwise
  165. bool delSocket(uint16_t sockfd);
  166. /// socket used to sending data
  167. /// TODO: this should be protected
  168. SocketCollection sockets_;
  169. protected:
  170. /// network interface name
  171. std::string name_;
  172. /// interface index (a value that uniquely indentifies an interface)
  173. int ifindex_;
  174. /// list of assigned addresses
  175. AddressCollection addrs_;
  176. /// link-layer address
  177. uint8_t mac_[MAX_MAC_LEN];
  178. /// length of link-layer address (usually 6)
  179. size_t mac_len_;
  180. /// hardware type
  181. uint16_t hardware_type_;
  182. public:
  183. /// @todo: Make those fields protected once we start supporting more
  184. /// than just Linux
  185. /// specifies if selected interface is loopback
  186. bool flag_loopback_;
  187. /// specifies if selected interface is up
  188. bool flag_up_;
  189. /// flag specifies if selected interface is running
  190. /// (e.g. cable plugged in, wifi associated)
  191. bool flag_running_;
  192. /// flag specifies if selected interface is multicast capable
  193. bool flag_multicast_;
  194. /// flag specifies if selected interface is broadcast capable
  195. bool flag_broadcast_;
  196. /// interface flags (this value is as is returned by OS,
  197. /// it may mean different things on different OSes)
  198. uint32_t flags_;
  199. };
  200. // TODO performance improvement: we may change this into
  201. // 2 maps (ifindex-indexed and name-indexed) and
  202. // also hide it (make it public make tests easier for now)
  203. /// type that holds a list of interfaces
  204. typedef std::list<Iface> IfaceCollection;
  205. /// IfaceMgr is a singleton class. This method returns reference
  206. /// to its sole instance.
  207. ///
  208. /// @return the only existing instance of interface manager
  209. static IfaceMgr& instance();
  210. /// @brief Returns interface with specified interface index
  211. ///
  212. /// @param ifindex index of searched interface
  213. ///
  214. /// @return interface with requested index (or NULL if no such
  215. /// interface is present)
  216. ///
  217. Iface* getIface(int ifindex);
  218. /// @brief Returns interface with specified interface name
  219. ///
  220. /// @param ifname name of searched interface
  221. ///
  222. /// @return interface with requested name (or NULL if no such
  223. /// interface is present)
  224. ///
  225. Iface*
  226. getIface(const std::string& ifname);
  227. /// @brief Returns container with all interfaces.
  228. ///
  229. /// This reference is only valid as long as IfaceMgr is valid. However,
  230. /// since IfaceMgr is a singleton and is expected to be destroyed after
  231. /// main() function completes, you should not worry much about this.
  232. ///
  233. /// @return container with all interfaces.
  234. const IfaceCollection& getIfaces() { return ifaces_; }
  235. /// @brief Return most suitable socket for transmitting specified IPv6 packet.
  236. ///
  237. /// This method takes Pkt6 (see overloaded implementation that takes
  238. /// Pkt4) and chooses appropriate socket to send it. This method
  239. /// may throw BadValue if specified packet does not have outbound
  240. /// interface specified, no such interface exists, or specified
  241. /// interface does not have any appropriate sockets open.
  242. ///
  243. /// @param pkt a packet to be transmitted
  244. ///
  245. /// @return a socket descriptor
  246. uint16_t getSocket(const isc::dhcp::Pkt6& pkt);
  247. /// @brief Return most suitable socket for transmitting specified IPv6 packet.
  248. ///
  249. /// This method takes Pkt4 (see overloaded implementation that takes
  250. /// Pkt6) and chooses appropriate socket to send it. This method
  251. /// may throw BadValue if specified packet does not have outbound
  252. /// interface specified, no such interface exists, or specified
  253. /// interface does not have any appropriate sockets open.
  254. ///
  255. /// @param pkt a packet to be transmitted
  256. ///
  257. /// @return a socket descriptor
  258. uint16_t getSocket(const isc::dhcp::Pkt4& pkt);
  259. /// debugging method that prints out all available interfaces
  260. ///
  261. /// @param out specifies stream to print list of interfaces to
  262. void
  263. printIfaces(std::ostream& out = std::cout);
  264. /// @brief Sends an IPv6 packet.
  265. ///
  266. /// Sends an IPv6 packet. All parameters for actual transmission are specified in
  267. /// Pkt6 structure itself. That includes destination address, src/dst port
  268. /// and interface over which data will be sent.
  269. ///
  270. /// @param pkt packet to be sent
  271. ///
  272. /// @return true if sending was successful
  273. bool send(const Pkt6Ptr& pkt);
  274. /// @brief Sends an IPv4 packet.
  275. ///
  276. /// Sends an IPv4 packet. All parameters for actual transmission are specified
  277. /// in Pkt4 structure itself. That includes destination address, src/dst
  278. /// port and interface over which data will be sent.
  279. ///
  280. /// @param pkt a packet to be sent
  281. ///
  282. /// @return true if sending was successful
  283. bool send(const Pkt4Ptr& pkt);
  284. /// @brief Tries to receive IPv6 packet over open IPv6 sockets.
  285. ///
  286. /// Attempts to receive a single IPv6 packet of any of the open IPv6 sockets.
  287. /// If reception is successful and all information about its sender
  288. /// are obtained, Pkt6 object is created and returned.
  289. ///
  290. /// TODO Start using select() and add timeout to be able
  291. /// to not wait infinitely, but rather do something useful
  292. /// (e.g. remove expired leases)
  293. ///
  294. /// @return Pkt6 object representing received packet (or NULL)
  295. Pkt6Ptr receive6();
  296. /// @brief Tries to receive IPv4 packet over open IPv4 sockets.
  297. ///
  298. /// Attempts to receive a single IPv4 packet of any of the open IPv4 sockets.
  299. /// If reception is successful and all information about its sender
  300. /// are obtained, Pkt4 object is created and returned.
  301. ///
  302. /// TODO Start using select() and add timeout to be able
  303. /// to not wait infinitely, but rather do something useful
  304. /// (e.g. remove expired leases)
  305. ///
  306. /// @return Pkt4 object representing received packet (or NULL)
  307. Pkt4Ptr receive4();
  308. /// Opens UDP/IP socket and binds it to address, interface and port.
  309. ///
  310. /// Specific type of socket (UDP/IPv4 or UDP/IPv6) depends on passed addr
  311. /// family.
  312. ///
  313. /// @param ifname name of the interface
  314. /// @param addr address to be bound.
  315. /// @param port UDP port.
  316. ///
  317. /// Method will throw if socket creation, socket binding or multicast
  318. /// join fails.
  319. ///
  320. /// @return socket descriptor, if socket creation, binding and multicast
  321. /// group join were all successful.
  322. int openSocket(const std::string& ifname,
  323. const isc::asiolink::IOAddress& addr,
  324. const uint16_t port);
  325. /// @brief Opens UDP/IP socket and binds it to interface specified.
  326. ///
  327. /// This method differs from \ref openSocket such that it allows
  328. /// not to specify local address to which socket will be bound.
  329. /// Instead, method searches through addresses on specified
  330. /// interface and selects one that matches address family.
  331. ///
  332. /// @param ifname name of the interface
  333. /// @param port UDP port
  334. /// @param family address family (AF_INET or AF_INET6)
  335. /// @return socket descriptor, if socket creation, binding and multicast
  336. /// group join were all successful.
  337. /// @throw isc::Unexpected if failed to create and bind socket.
  338. int openSocketFromIface(const std::string& ifname,
  339. const uint16_t port,
  340. const uint8_t family);
  341. /// @brief Opens UDP/IP socket and binds to address specified
  342. ///
  343. /// This methods differs from \ref openSocket such that it allows
  344. /// not to specify interface to which socket will be bound.
  345. ///
  346. /// @param addr address to be bound
  347. /// @param port UDP port
  348. /// @return socket descriptor, if socket creation, binding and multicast
  349. /// group join were all successful.
  350. /// @throw isc::Unexpected if failed to create and bind socket
  351. int openSocketFromAddress(const isc::asiolink::IOAddress& addr,
  352. const uint16_t port);
  353. /// @brief Opens UDP/IP socket to be used to connect to remote address
  354. ///
  355. /// This method identifies local address to be used to connect
  356. /// to remote address specified as argument.
  357. /// Once local address is idetified \ref openSocket is called
  358. /// to open socket and bind it to interface, address and port.
  359. ///
  360. /// @param remote_addr remote address to connect to
  361. /// @param port UDP port
  362. /// @return socket descriptor, if socket creation, binding and multicast
  363. /// group join were all successful.
  364. /// @throw isc::Unexpected if failed to create and bind socket
  365. int openSocketFromRemoteAddress(const isc::asiolink::IOAddress& remote_addr,
  366. const uint16_t port);
  367. /// Opens IPv6 sockets on detected interfaces.
  368. ///
  369. /// Will throw exception if socket creation fails.
  370. ///
  371. /// @param port specifies port number (usually DHCP6_SERVER_PORT)
  372. ///
  373. /// @return true if any sockets were open
  374. bool openSockets6(const uint16_t port = DHCP6_SERVER_PORT);
  375. /// @brief Closes all open sockets.
  376. /// Is used in destructor, but also from Dhcpv4_srv and Dhcpv6_srv classes.
  377. void closeSockets();
  378. /// Opens IPv4 sockets on detected interfaces.
  379. /// Will throw exception if socket creation fails.
  380. ///
  381. /// @param port specifies port number (usually DHCP4_SERVER_PORT)
  382. ///
  383. /// @return true if any sockets were open
  384. bool openSockets4(const uint16_t port = DHCP4_SERVER_PORT);
  385. /// @brief returns number of detected interfaces
  386. ///
  387. /// @return number of detected interfaces
  388. uint16_t countIfaces() { return ifaces_.size(); }
  389. // don't use private, we need derived classes in tests
  390. protected:
  391. /// @brief Protected constructor.
  392. ///
  393. /// Protected constructor. This is a singleton class. We don't want
  394. /// anyone to create instances of IfaceMgr. Use instance() method instead.
  395. IfaceMgr();
  396. virtual ~IfaceMgr();
  397. /// @brief Opens IPv4 socket.
  398. ///
  399. /// Please do not use this method directly. Use openSocket instead.
  400. ///
  401. /// This method may throw exception if socket creation fails.
  402. ///
  403. /// @param iface reference to interface structure.
  404. /// @param addr an address the created socket should be bound to
  405. /// @param port a port that created socket should be bound to
  406. ///
  407. /// @return socket descriptor
  408. int openSocket4(Iface& iface, const isc::asiolink::IOAddress& addr, uint16_t port);
  409. /// @brief Opens IPv6 socket.
  410. ///
  411. /// Please do not use this method directly. Use openSocket instead.
  412. ///
  413. /// This method may throw exception if socket creation fails.
  414. ///
  415. /// @param iface reference to interface structure.
  416. /// @param addr an address the created socket should be bound to
  417. /// @param port a port that created socket should be bound to
  418. ///
  419. /// @return socket descriptor
  420. int openSocket6(Iface& iface, const isc::asiolink::IOAddress& addr, uint16_t port);
  421. /// @brief Adds an interface to list of known interfaces.
  422. ///
  423. /// @param iface reference to Iface object.
  424. void addInterface(const Iface& iface) {
  425. ifaces_.push_back(iface);
  426. }
  427. /// @brief Detects network interfaces.
  428. ///
  429. /// This method will eventually detect available interfaces. For now
  430. /// it offers stub implementation. First interface name and link-local
  431. /// IPv6 address is read from intefaces.txt file.
  432. void
  433. detectIfaces();
  434. /// @brief Stub implementation of network interface detection.
  435. ///
  436. /// This implementations reads a single line from interfaces.txt file
  437. /// and pretends to detect such interface. First interface name and
  438. /// link-local IPv6 address or IPv4 address is read from the
  439. /// intefaces.txt file.
  440. void
  441. stubDetectIfaces();
  442. // TODO: having 2 maps (ifindex->iface and ifname->iface would)
  443. // probably be better for performance reasons
  444. /// List of available interfaces
  445. IfaceCollection ifaces_;
  446. /// a pointer to a sole instance of this class (a singleton)
  447. static IfaceMgr * instance_;
  448. // TODO: Also keep this interface on Iface once interface detection
  449. // is implemented. We may need it e.g. to close all sockets on
  450. // specific interface
  451. //int recvsock_; // TODO: should be fd_set eventually, but we have only
  452. //int sendsock_; // 2 sockets for now. Will do for until next release
  453. // we can't use the same socket, as receiving socket
  454. // is bound to multicast address. And we all know what happens
  455. // to people who try to use multicast as source address.
  456. /// length of the control_buf_ array
  457. size_t control_buf_len_;
  458. /// control-buffer, used in transmission and reception
  459. boost::scoped_array<char> control_buf_;
  460. /// @brief A wrapper for OS-specific operations before sending IPv4 packet
  461. ///
  462. /// @param m message header (will be later used for sendmsg() call)
  463. /// @param control_buf buffer to be used during transmission
  464. /// @param control_buf_len buffer length
  465. /// @param pkt packet to be sent
  466. void os_send4(struct msghdr& m, boost::scoped_array<char>& control_buf,
  467. size_t control_buf_len, const Pkt4Ptr& pkt);
  468. /// @brief OS-specific operations during IPv4 packet reception
  469. ///
  470. /// @param m message header (was used during recvmsg() call)
  471. /// @param pkt packet received (some fields will be set here)
  472. ///
  473. /// @return true if successful, false otherwise
  474. bool os_receive4(struct msghdr& m, Pkt4Ptr& pkt);
  475. private:
  476. /// @brief Creates a single instance of this class (a singleton implementation)
  477. static void
  478. instanceCreate();
  479. /// @brief Joins IPv6 multicast group on a socket.
  480. ///
  481. /// Socket must be created and bound to an address. Note that this
  482. /// address is different than the multicast address. For example DHCPv6
  483. /// server should bind its socket to link-local address (fe80::1234...)
  484. /// and later join ff02::1:2 multicast group.
  485. ///
  486. /// @param sock socket fd (socket must be bound)
  487. /// @param ifname interface name (for link-scoped multicast groups)
  488. /// @param mcast multicast address to join (e.g. "ff02::1:2")
  489. ///
  490. /// @return true if multicast join was successful
  491. ///
  492. bool
  493. joinMulticast(int sock, const std::string& ifname,
  494. const std::string& mcast);
  495. /// @brief Identifies local network address to be used to
  496. /// connect to remote address.
  497. ///
  498. /// This method identifies local network address that can be used
  499. /// to connect to remote address specified.
  500. /// It first creates socket and makes attempt to connect
  501. /// to remote location via this socket. If connection
  502. /// is established successfully, the local address to which
  503. /// socket is bound is returned.
  504. ///
  505. /// @param remote_addr remote address to connect to
  506. /// @param port port to be used
  507. /// @return local address to be used to connect to remote address
  508. /// @throw isc::Unexpected if unable to indentify local address
  509. isc::asiolink::IOAddress
  510. getLocalAddress(const isc::asiolink::IOAddress& remote_addr,
  511. const uint16_t port);
  512. };
  513. }; // namespace isc::dhcp
  514. }; // namespace isc
  515. #endif