-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIPv6Network.cs
304 lines (264 loc) · 11 KB
/
IPv6Network.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
using System.Globalization;
using System.Text;
namespace WireguardAllowedIPs.Core;
public class IPv6Network : IPNetwork
{
private enum ParseState
{
ReadyForData,
InSeparator
}
public override string AddressRepresentation => GetAddressString();
public UInt128 AddressValue => (UInt128)(
((UInt128)AddressBytes![0] << 120) |
((UInt128)AddressBytes![1] << 112) |
((UInt128)AddressBytes![2] << 104) |
((UInt128)AddressBytes![3] << 96) |
((UInt128)AddressBytes![4] << 88) |
((UInt128)AddressBytes![5] << 80) |
((UInt128)AddressBytes![6] << 72) |
((UInt128)AddressBytes![7] << 64) |
((UInt128)AddressBytes![8] << 56) |
((UInt128)AddressBytes![9] << 48) |
((UInt128)AddressBytes![10] << 40) |
((UInt128)AddressBytes![11] << 32) |
((UInt128)AddressBytes![12] << 24) |
((UInt128)AddressBytes![13] << 16) |
((UInt128)AddressBytes![14] << 8) |
((UInt128)AddressBytes![15])
);
public IPv6Network(byte[] bytes, int cidr) : base(cidr)
{
if (bytes.Length != 16)
throw new ArgumentException("An IPv6 address always consists of 128 bits (16 bytes)");
if (cidr < 0 || cidr > 128)
throw new ArgumentOutOfRangeException(nameof(cidr), "CIDR must be between 0 and 128 (both inclusive)");
AddressBytes = bytes;
}
public IPv6Network(UInt128 value, int cidr) : this([
(byte)(value >> 120),
(byte)((value >> 112) & 0xFF),
(byte)((value >> 104) & 0xFF),
(byte)((value >> 96) & 0xFF),
(byte)((value >> 88) & 0xFF),
(byte)((value >> 80) & 0xFF),
(byte)((value >> 72) & 0xFF),
(byte)((value >> 64) & 0xFF),
(byte)((value >> 56) & 0xFF),
(byte)((value >> 48) & 0xFF),
(byte)((value >> 40) & 0xFF),
(byte)((value >> 32) & 0xFF),
(byte)((value >> 24) & 0xFF),
(byte)((value >> 16) & 0xFF),
(byte)((value >> 8) & 0xFF),
(byte)(value & 0xFF)
], cidr)
{ }
public IPv6Network(string addressString, int cidr) : this(ParseAddressString(addressString), cidr)
{ }
public UInt128 GetHostMask() => Cidr == 0 ? UInt128.MaxValue : (UInt128.One << (128 - Cidr)) - 1;
public UInt128 GetNetworkMask() => ~GetHostMask();
public UInt128 GetLowAddressValue() => AddressValue & GetNetworkMask();
public UInt128 GetHighAddressValue() => AddressValue | GetHostMask();
private static ArgumentException DifferentTypeException() => new("other", $"Can only compare to another instance of {nameof(IPv6Network)}");
public override bool Contains(IPNetwork other)
{
if (other is IPv6Network ip)
{
return ip.GetLowAddressValue() >= GetLowAddressValue()
&& ip.GetHighAddressValue() <= GetHighAddressValue();
}
throw DifferentTypeException();
}
public override bool Overlaps(IPNetwork other)
{
if (other is IPv6Network ip)
{
return UInt128.Max(ip.GetLowAddressValue(), GetLowAddressValue()) <=
UInt128.Min(ip.GetHighAddressValue(), GetHighAddressValue());
}
throw DifferentTypeException();
}
// Adapted from python sources
// https://github.com/python/cpython/blob/8ac20e5404127d68624339c0b318abe2d14fe514/Lib/ipaddress.py#L200
public override IPNetwork[] SummarizeAddressRangeWith(IPNetwork other)
{
if (other is IPv6Network ip)
{
if (Cidr != 128 || ip.Cidr != 128)
throw new ArgumentException("Can only construct an address range between two /128 addresses");
UInt128 first = AddressValue;
UInt128 last = ip.AddressValue;
if (ip.AddressValue < AddressValue)
(first, last) = (last, first);
List<IPv6Network> list = [];
while (first <= last)
{
int nbits = Math.Min(Util.CountRighthandZeroBits128(first), Util.BitLength128(last - first + 1) - 1);
list.Add(new IPv6Network(first, 128 - nbits));
try
{
checked
{
first += UInt128.One << nbits;
}
}
catch (OverflowException)
{
break;
}
}
return [.. list];
}
throw DifferentTypeException();
}
public override bool Equals(object? obj)
{
if (obj is IPv6Network ip)
return ip.AddressValue == AddressValue && ip.Cidr == Cidr;
return false;
}
public override int GetHashCode()
{
return HashCode.Combine(AddressValue, Cidr);
}
private string GetAddressString(bool excludeZeroSegments = true)
{
StringBuilder sb = new();
// Transform 16 bytes into 8 x 16-bit segments
ushort[] segments = new ushort[8];
for (int i = 0; i < 8; i++)
{
ushort value = (ushort)((AddressBytes![i * 2] << 8) | AddressBytes![i * 2 + 1]);
segments[i] = value;
}
List<(int, int)> zeroSections = [];
bool inZeroSection = false;
int currentCounter = 0;
// Find all indices at which zeros occur. The second integer indicates the additional zeros afterwards.
for (int i = 0; i < segments.Length; i++)
{
if (segments[i] == 0)
{
if (inZeroSection)
{
currentCounter++;
}
else
{
currentCounter = 0;
inZeroSection = true;
}
continue;
}
if (inZeroSection)
{
zeroSections.Add((i - 1 - currentCounter, currentCounter));
}
inZeroSection = false;
}
if (inZeroSection)
zeroSections.Add((segments.Length - 1 - currentCounter, currentCounter));
// Select the longest continous streak of zeros, which will become '::'
(int, int)? longest = zeroSections.Count > 0 ? zeroSections.MaxBy((x) => x.Item2) : null;
bool tillEnd = longest != null && longest.Value.Item1 + longest.Value.Item2 == 7;
for (int i = 0; i < segments.Length; i++)
{
if (excludeZeroSegments && longest != null)
{
if (longest.Value.Item1 == i)
{
sb.Append(':');
continue;
}
else if (i > longest.Value.Item1 && i <= longest.Value.Item1 + longest.Value.Item2)
continue;
}
if (i != 0)
sb.Append(':');
sb.AppendFormat("{0:x}", segments[i]);
}
// If the last segment is part of a zero-streak, we need to fill up a missing colon
if (tillEnd)
sb.Append(':');
return sb.ToString();
}
public static byte[] ParseAddressString(string addressString)
{
const int maxSegments = 8;
using StringReader sr = new(addressString);
int charValue;
List<string> partA = [];
List<string> partB = [];
bool hasSeenDoubleSeparator = false;
List<string> getList() => hasSeenDoubleSeparator ? partB : partA;
bool checkSegmentCount() => partA.Count + partB.Count <= maxSegments;
StringBuilder buffer = new();
ParseState state = ParseState.ReadyForData;
while ((charValue = sr.Read()) != -1)
{
char character = (char)charValue;
switch (state)
{
case ParseState.ReadyForData:
{
if (char.IsWhiteSpace(character))
continue; // Ignore whitespace
else if (char.IsAsciiHexDigit(character))
{
buffer.Append(character);
}
else if (character == ':')
{
if (buffer.Length > 0)
getList().Add(buffer.ToString()); // We finished the previous segment
buffer.Clear();
if (!checkSegmentCount())
throw new FormatException("Too many segments in IPv6 address.");
state = ParseState.InSeparator;
}
else
throw new FormatException("Invalid character in address.");
}
break;
case ParseState.InSeparator:
{
if (char.IsWhiteSpace(character))
continue; // Ignore whitespace
else if (character == ':') // we have a double :: separator
{
if (hasSeenDoubleSeparator)
throw new FormatException("Invalid IPv6 address format: Saw '::' twice");
hasSeenDoubleSeparator = true;
}
else if (char.IsAsciiHexDigit(character))
{
buffer.Append(character); // Add current digit to next segment
state = ParseState.ReadyForData;
}
else
throw new FormatException("Invalid character in address.");
}
break;
default:
throw new Exception("This should not happen :c");
}
}
if (buffer.Length > 0)
getList().Add(buffer.ToString());
if (!checkSegmentCount())
throw new FormatException("Too many segments in IPv6 address.");
int missingSegments = maxSegments - partA.Count - partB.Count;
if (!hasSeenDoubleSeparator && missingSegments > 0)
throw new FormatException("Invalid IPv6 address (Missing segments).");
List<byte> bytes = [];
foreach (string value in partA.Concat(Enumerable.Repeat("0000", missingSegments)).Concat(partB))
{
if (!ushort.TryParse(value, NumberStyles.HexNumber, null, out ushort v))
throw new FormatException("Invalid hex value for IPv6 segment.");
bytes.Add((byte)(v >> 8));
bytes.Add((byte)(v & 0xFF));
}
return [.. bytes];
}
}