ipmath.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. #include "ipmath.h"
  2. namespace {
  3. constexpr auto IPV4_BITS = 32;
  4. constexpr auto IPV6_BITS = 128;
  5. const ui128 MAX_IPV4_ADDR = Max<ui32>();
  6. const ui128 MAX_IPV6_ADDR = Max<ui128>();
  7. TStringBuf TypeToString(TIpv6Address::TIpType type) {
  8. switch (type) {
  9. case TIpv6Address::Ipv4:
  10. return TStringBuf("IPv4");
  11. case TIpv6Address::Ipv6:
  12. return TStringBuf("IPv6");
  13. default:
  14. return TStringBuf("UNKNOWN");
  15. }
  16. }
  17. size_t MaxPrefixLenForType(TIpv6Address::TIpType type) {
  18. switch (type) {
  19. case TIpv6Address::Ipv4:
  20. return IPV4_BITS;
  21. case TIpv6Address::Ipv6:
  22. return IPV6_BITS;
  23. case TIpv6Address::LAST:
  24. ythrow yexception() << "invalid type";
  25. }
  26. }
  27. template <ui8 ADDR_LEN>
  28. ui128 LowerBoundForPrefix(ui128 value, ui8 prefixLen) {
  29. const int shift = ADDR_LEN - prefixLen;
  30. const ui128 shifted = (shift < 128) ? (ui128{1} << shift) : 0;
  31. ui128 mask = ~(shifted - 1);
  32. return value & mask;
  33. }
  34. template <ui8 ADDR_LEN>
  35. ui128 UpperBoundForPrefix(ui128 value, ui8 prefixLen) {
  36. const int shift = ADDR_LEN - prefixLen;
  37. const ui128 shifted = (shift < 128) ? (ui128{1} << shift) : 0;
  38. ui128 mask = shifted - 1;
  39. return value | mask;
  40. }
  41. auto LowerBoundForPrefix4 = LowerBoundForPrefix<IPV4_BITS>;
  42. auto LowerBoundForPrefix6 = LowerBoundForPrefix<IPV6_BITS>;
  43. auto UpperBoundForPrefix4 = UpperBoundForPrefix<IPV4_BITS>;
  44. auto UpperBoundForPrefix6 = UpperBoundForPrefix<IPV6_BITS>;
  45. TIpv6Address IpFromStringSafe(const TString& s) {
  46. bool ok{};
  47. auto addr = TIpv6Address::FromString(s, ok);
  48. Y_ENSURE(ok, "Failed to parse an IP address from " << s);
  49. return addr;
  50. }
  51. /// it's different from TIpv6Address::IsValid for 0.0.0.0
  52. bool IsValid(TIpv6Address addr) {
  53. switch (addr.Type()) {
  54. case TIpv6Address::Ipv4:
  55. case TIpv6Address::Ipv6:
  56. return true;
  57. case TIpv6Address::LAST:
  58. return false;
  59. }
  60. }
  61. bool HasNext(TIpv6Address addr) {
  62. switch (addr.Type()) {
  63. case TIpv6Address::Ipv4:
  64. return ui128(addr) != MAX_IPV4_ADDR;
  65. case TIpv6Address::Ipv6:
  66. return ui128(addr) != MAX_IPV6_ADDR;
  67. case TIpv6Address::LAST:
  68. return false;
  69. }
  70. }
  71. TIpv6Address Next(TIpv6Address addr) {
  72. return {ui128(addr) + 1, addr.Type()};
  73. }
  74. } // namespace
  75. TIpv6Address LowerBoundForPrefix(TIpv6Address value, ui8 prefixLen) {
  76. auto type = value.Type();
  77. switch (type) {
  78. case TIpv6Address::Ipv4:
  79. return {LowerBoundForPrefix4(value, prefixLen), type};
  80. case TIpv6Address::Ipv6:
  81. return {LowerBoundForPrefix6(value, prefixLen), type};
  82. default:
  83. ythrow yexception() << "invalid type";
  84. }
  85. }
  86. TIpv6Address UpperBoundForPrefix(TIpv6Address value, ui8 prefixLen) {
  87. auto type = value.Type();
  88. switch (type) {
  89. case TIpv6Address::Ipv4:
  90. return {UpperBoundForPrefix4(value, prefixLen), type};
  91. case TIpv6Address::Ipv6:
  92. return {UpperBoundForPrefix6(value, prefixLen), type};
  93. default:
  94. ythrow yexception() << "invalid type";
  95. }
  96. }
  97. TIpAddressRange::TIpAddressRangeBuilder::operator TIpAddressRange() {
  98. return Build();
  99. }
  100. TIpAddressRange TIpAddressRange::TIpAddressRangeBuilder::Build() {
  101. return TIpAddressRange{Start_, End_};
  102. }
  103. TIpAddressRange::TIpAddressRangeBuilder::TIpAddressRangeBuilder(const TString& from)
  104. : TIpAddressRangeBuilder{IpFromStringSafe(from)}
  105. {
  106. }
  107. TIpAddressRange::TIpAddressRangeBuilder::TIpAddressRangeBuilder(TIpv6Address from) {
  108. Y_ENSURE_EX(IsValid(from), TInvalidIpRangeException() << "Address " << from.ToString() << " is invalid");
  109. Start_ = from;
  110. End_ = Start_;
  111. }
  112. TIpAddressRange::TIpAddressRangeBuilder& TIpAddressRange::TIpAddressRangeBuilder::To(const TString& to) {
  113. End_ = IpFromStringSafe(to);
  114. return *this;
  115. }
  116. TIpAddressRange::TIpAddressRangeBuilder& TIpAddressRange::TIpAddressRangeBuilder::To(TIpv6Address to) {
  117. Y_ENSURE_EX(IsValid(to), TInvalidIpRangeException() << "Address " << to.ToString() << " is invalid");
  118. End_ = to;
  119. return *this;
  120. }
  121. TIpAddressRange::TIpAddressRangeBuilder& TIpAddressRange::TIpAddressRangeBuilder::WithPrefix(ui8 len) {
  122. Y_ENSURE_EX(IsValid(Start_), TInvalidIpRangeException() << "Start value must be set before prefix");
  123. const auto type = Start_.Type();
  124. const auto maxLen = MaxPrefixLenForType(type);
  125. Y_ENSURE_EX(len <= maxLen, TInvalidIpRangeException() << "Maximum prefix length for this address type is "
  126. << maxLen << ", but requested " << (ui32)len);
  127. const auto lowerBound = LowerBoundForPrefix(Start_, len);
  128. Y_ENSURE_EX(Start_ == lowerBound, TInvalidIpRangeException() << "Cannot create IP range from start address "
  129. << Start_ << " with prefix length " << (ui32)len);
  130. End_ = UpperBoundForPrefix(Start_, len);
  131. return *this;
  132. }
  133. void TIpAddressRange::Init(TIpv6Address from, TIpv6Address to) {
  134. Start_ = from;
  135. End_ = to;
  136. Y_ENSURE_EX(Start_ <= End_, TInvalidIpRangeException() << "Invalid IP address range: from " << Start_ << " to " << End_);
  137. Y_ENSURE_EX(Start_.Type() == End_.Type(), TInvalidIpRangeException()
  138. << "Address type mismtach: start address type is " << TypeToString(Start_.Type())
  139. << " end type is " << TypeToString(End_.Type()));
  140. }
  141. TIpAddressRange::TIpAddressRange(TIpv6Address start, TIpv6Address end) {
  142. Y_ENSURE_EX(IsValid(start), TInvalidIpRangeException() << "start address " << start.ToString() << " is invalid");
  143. Y_ENSURE_EX(IsValid(end), TInvalidIpRangeException() << "end address " << end.ToString() << " is invalid");
  144. Init(start, end);
  145. }
  146. TIpAddressRange::TIpAddressRange(const TString& start, const TString& end) {
  147. auto startAddr = IpFromStringSafe(start);
  148. auto endAddr = IpFromStringSafe(end);
  149. Init(startAddr, endAddr);
  150. }
  151. TIpAddressRange::~TIpAddressRange() {
  152. }
  153. TIpAddressRange::TIpType TIpAddressRange::Type() const {
  154. return Start_.Type();
  155. }
  156. ui128 TIpAddressRange::Size() const {
  157. return ui128(End_) - ui128(Start_) + 1;
  158. }
  159. bool TIpAddressRange::IsSingle() const {
  160. return Start_ == End_;
  161. }
  162. bool TIpAddressRange::Contains(const TIpAddressRange& other) const {
  163. return Start_ <= other.Start_ && End_ >= other.End_;
  164. }
  165. bool TIpAddressRange::Contains(const TIpv6Address& addr) const {
  166. return Start_ <= addr && End_ >= addr;
  167. }
  168. bool TIpAddressRange::Overlaps(const TIpAddressRange& other) const {
  169. return Start_ <= other.End_ && other.Start_ <= End_;
  170. }
  171. bool TIpAddressRange::IsConsecutive(const TIpAddressRange& other) const {
  172. return (HasNext(End_) && Next(End_) == other.Start_)
  173. || (HasNext(other.End_) && Next(other.End_) == Start_);
  174. }
  175. TIpAddressRange TIpAddressRange::Union(const TIpAddressRange& other) const {
  176. Y_ENSURE(IsConsecutive(other) || Overlaps(other), "Can merge only consecutive or overlapping ranges");
  177. Y_ENSURE(other.Start_.Type() == Start_.Type(), "Cannot merge ranges of addresses of different types");
  178. auto s = Start_;
  179. auto e = End_;
  180. s = {Min<ui128>(Start_, other.Start_), Start_.Type()};
  181. e = {Max<ui128>(End_, other.End_), End_.Type()};
  182. return {s, e};
  183. }
  184. TIpAddressRange TIpAddressRange::FromCidrString(const TString& str) {
  185. if (auto result = TryFromCidrString(str)) {
  186. return *result;
  187. }
  188. ythrow TInvalidIpRangeException() << "Cannot parse " << str << " as a CIDR string";
  189. }
  190. TMaybe<TIpAddressRange> TIpAddressRange::TryFromCidrString(const TString& str) {
  191. auto idx = str.rfind('/');
  192. if (idx == TString::npos) {
  193. return Nothing();
  194. }
  195. TStringBuf sb{str};
  196. TStringBuf address, prefix;
  197. sb.SplitAt(idx, address, prefix);
  198. prefix.Skip(1);
  199. ui8 prefixLen{};
  200. if (!::TryFromString(prefix, prefixLen)) {
  201. return Nothing();
  202. }
  203. return TIpAddressRange::From(TString{address})
  204. .WithPrefix(prefixLen);
  205. }
  206. TIpAddressRange TIpAddressRange::FromRangeString(const TString& str) {
  207. if (auto result = TryFromRangeString(str)) {
  208. return *result;
  209. }
  210. ythrow TInvalidIpRangeException() << "Cannot parse " << str << " as a range string";
  211. }
  212. TMaybe<TIpAddressRange> TIpAddressRange::TryFromRangeString(const TString& str) {
  213. auto idx = str.find('-');
  214. if (idx == TString::npos) {
  215. return Nothing();
  216. }
  217. TStringBuf sb{str};
  218. TStringBuf start, end;
  219. sb.SplitAt(idx, start, end);
  220. end.Skip(1);
  221. return TIpAddressRange::From(TString{start}).To(TString{end});
  222. }
  223. TIpAddressRange TIpAddressRange::FromString(const TString& str) {
  224. if (auto result = TryFromString(str)) {
  225. return *result;
  226. }
  227. ythrow TInvalidIpRangeException() << "Cannot parse an IP address from " << str;
  228. }
  229. TMaybe<TIpAddressRange> TIpAddressRange::TryFromString(const TString& str) {
  230. if (auto idx = str.find('/'); idx != TString::npos) {
  231. return TryFromCidrString(str);
  232. } else if (idx = str.find('-'); idx != TString::npos) {
  233. return TryFromRangeString(str);
  234. } else {
  235. bool ok{};
  236. auto addr = TIpv6Address::FromString(str, ok);
  237. if (!ok) {
  238. return Nothing();
  239. }
  240. return TIpAddressRange::From(addr);
  241. }
  242. }
  243. TString TIpAddressRange::ToRangeString() const {
  244. bool ok{};
  245. return TStringBuilder() << Start_.ToString(ok) << "-" << End_.ToString(ok);
  246. }
  247. TIpAddressRange::TIterator TIpAddressRange::begin() const {
  248. return Begin();
  249. }
  250. TIpAddressRange::TIterator TIpAddressRange::Begin() const {
  251. return TIpAddressRange::TIterator{Start_};
  252. }
  253. TIpAddressRange::TIterator TIpAddressRange::end() const {
  254. return End();
  255. }
  256. TIpAddressRange::TIterator TIpAddressRange::End() const {
  257. return TIpAddressRange::TIterator{{ui128(End_) + 1, End_.Type()}};
  258. }
  259. TIpAddressRange::TIpAddressRangeBuilder TIpAddressRange::From(TIpv6Address from) {
  260. return TIpAddressRangeBuilder{from};
  261. }
  262. TIpAddressRange::TIpAddressRangeBuilder TIpAddressRange::From(const TString& from) {
  263. return TIpAddressRangeBuilder{from};
  264. }
  265. bool operator==(const TIpAddressRange& lhs, const TIpAddressRange& rhs) {
  266. return lhs.Start_ == rhs.Start_ && lhs.End_ == rhs.End_;
  267. }
  268. bool operator!=(const TIpAddressRange& lhs, const TIpAddressRange& rhs) {
  269. return !(lhs == rhs);
  270. }
  271. TIpAddressRange::TIterator::TIterator(TIpv6Address val) noexcept
  272. : Current_{val}
  273. {
  274. }
  275. bool TIpAddressRange::TIterator::operator==(const TIpAddressRange::TIterator& other) noexcept {
  276. return Current_ == other.Current_;
  277. }
  278. bool TIpAddressRange::TIterator::operator!=(const TIpAddressRange::TIterator& other) noexcept {
  279. return !(*this == other);
  280. }
  281. TIpAddressRange::TIterator& TIpAddressRange::TIterator::operator++() noexcept {
  282. ui128 numeric = Current_;
  283. Current_ = {numeric + 1, Current_.Type()};
  284. return *this;
  285. }
  286. const TIpv6Address& TIpAddressRange::TIterator::operator*() noexcept {
  287. return Current_;
  288. }