ManagedRoute.hpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_MANAGEDROUTE_HPP
  14. #define ZT_MANAGEDROUTE_HPP
  15. #include "../node/InetAddress.hpp"
  16. #include "../node/Utils.hpp"
  17. #include "../node/SharedPtr.hpp"
  18. #include "../node/Atomic.hpp"
  19. #include <stdexcept>
  20. #include <vector>
  21. #include <map>
  22. #include <cstdlib>
  23. #include <cstring>
  24. namespace ZeroTier {
  25. /**
  26. * A ZT-managed route that used C++ RAII semantics to automatically clean itself up on deallocate
  27. */
  28. class ManagedRoute
  29. {
  30. friend class SharedPtr<ManagedRoute>;
  31. public:
  32. ZT_INLINE ManagedRoute(const InetAddress &target,const InetAddress &via,const char *device)
  33. {
  34. _target = target;
  35. _via = via;
  36. if (via.ss_family == AF_INET)
  37. _via.setPort(32);
  38. else if (via.ss_family == AF_INET6)
  39. _via.setPort(128);
  40. Utils::scopy(_device,sizeof(_device),device);
  41. _systemDevice[0] = (char)0;
  42. }
  43. ZT_INLINE ~ManagedRoute() { this->remove(); }
  44. /**
  45. * Set or update currently set route
  46. *
  47. * This must be called periodically for routes that shadow others so that
  48. * shadow routes can be updated. In some cases it has no effect
  49. *
  50. * @return True if route add/update was successful
  51. */
  52. bool sync();
  53. /**
  54. * Remove and clear this ManagedRoute
  55. *
  56. * This does nothing if this ManagedRoute is not set or has already been
  57. * removed. If this is not explicitly called it is called automatically on
  58. * destruct.
  59. */
  60. void remove();
  61. ZT_INLINE const InetAddress &target() const { return _target; }
  62. ZT_INLINE const InetAddress &via() const { return _via; }
  63. ZT_INLINE const char *device() const { return _device; }
  64. private:
  65. ZT_INLINE ManagedRoute(const ManagedRoute &) {}
  66. ZT_INLINE ManagedRoute &operator=(const ManagedRoute &) { return *this; }
  67. InetAddress _target;
  68. InetAddress _via;
  69. InetAddress _systemVia; // for route overrides
  70. std::map<InetAddress,bool> _applied; // routes currently applied
  71. char _device[128];
  72. char _systemDevice[128]; // for route overrides
  73. Atomic<int> __refCount;
  74. };
  75. } // namespace ZeroTier
  76. #endif