forked from loxilb-io/loxilib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tlpm.go
469 lines (404 loc) · 10.7 KB
/
tlpm.go
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
// SPDX-License-Identifier: Apache 2.0
// Copyright (c) 2022 NetLOX Inc
package loxilib
import (
"encoding/binary"
"errors"
"fmt"
"net"
)
// return codes
const (
TrieSuccess = -iota
TrieErrGeneric
TrieErrExists
TrieErrNoEnt
TrieErrNoMem
TrieErrUnknown
TrieErrPrefix
)
// constants
const (
TrieJmpLength = 8
PrefixArrLenfth = (1 << (TrieJmpLength + 1)) - 1
PrefixArrNbits = ((PrefixArrLenfth + TrieJmpLength) & ^TrieJmpLength) / TrieJmpLength
PtrArrLength = (1 << TrieJmpLength)
PtrArrNBits = ((PtrArrLength + TrieJmpLength) & ^TrieJmpLength) / TrieJmpLength
)
// TrieData - Any user data to be associated with a trie node
type TrieData interface {
// Empty Interface
}
// TrieIterIntf - Interface implementation needed for trie users to
// traverse and convert data
type TrieIterIntf interface {
TrieNodeWalker(b string)
TrieData2String(d TrieData) string
}
type trieVar struct {
prefix [16]byte
}
type trieState struct {
trieData TrieData
lastMatchLevel int
lastMatchPfxLen int
lastMatchEmpty bool
lastMatchTv trieVar
matchFound bool
maxLevels int
errCode int
}
// TrieRoot - root of a trie data structure
type TrieRoot struct {
v6 bool
prefixArr [PrefixArrNbits]uint8
ptrArr [PtrArrNBits]uint8
prefixData [PrefixArrLenfth]TrieData
ptrData [PtrArrLength]*TrieRoot
}
// TrieInit - Initialize a trie root
func TrieInit(v6 bool) *TrieRoot {
var root = new(TrieRoot)
root.v6 = v6
return root
}
func prefix2TrieVar(ipPrefix net.IP, pIndex int) trieVar {
var tv trieVar
if ipPrefix.To4() != nil {
ipAddr := binary.BigEndian.Uint32(ipPrefix.To4())
tv.prefix[0] = (uint8((ipAddr >> 24)) & 0xff)
tv.prefix[1] = (uint8((ipAddr >> 16)) & 0xff)
tv.prefix[2] = (uint8((ipAddr >> 8)) & 0xff)
tv.prefix[3] = (uint8(ipAddr) & 0xff)
} else {
for i := 0; i < 16; i++ {
tv.prefix[i] = uint8(ipPrefix[i])
}
}
return tv
}
func grabByte(tv *trieVar, pIndex int) (uint8, error) {
if pIndex > 15 {
return 0xff, errors.New("Out of range")
}
return tv.prefix[pIndex], nil
}
func cidr2TrieVar(cidr string, tv *trieVar) (pfxLen int) {
_, ipNet, err := net.ParseCIDR(cidr)
if err != nil {
return -1
}
pfx := ipNet.IP.Mask(ipNet.Mask)
pfxLen, _ = ipNet.Mask.Size()
*tv = prefix2TrieVar(pfx, 0)
return pfxLen
}
func shrinkPrefixArrDat(arr []TrieData, startPos int) {
if startPos < 0 || startPos >= len(arr) {
return
}
for i := startPos; i < len(arr)-1; i++ {
arr[i] = arr[i+1]
}
}
func shrinkPtrArrDat(arr []*TrieRoot, startPos int) {
if startPos < 0 || startPos >= len(arr) {
return
}
for i := startPos; i < len(arr)-1; i++ {
arr[i] = arr[i+1]
}
}
func expPrefixArrDat(arr []TrieData, startPos int) {
if startPos < 0 || startPos >= len(arr) {
return
}
for i := len(arr) - 2; i >= startPos; i-- {
arr[i+1] = arr[i]
}
}
func expPtrArrDat(arr []*TrieRoot, startPos int) {
if startPos < 0 || startPos >= len(arr) {
return
}
for i := len(arr) - 2; i >= startPos; i-- {
arr[i+1] = arr[i]
}
}
func (t *TrieRoot) addTrieInt(tv *trieVar, currLevel int, rPfxLen int, ts *trieState) int {
if rPfxLen < 0 || ts.errCode != 0 {
return -1
}
// This assumes stride of length 8
var cval uint8 = tv.prefix[currLevel]
var nextRoot *TrieRoot
if rPfxLen > TrieJmpLength {
rPfxLen -= TrieJmpLength
ptrIdx := CountSetBitsInArr(t.ptrArr[:], int(cval)-1)
if IsBitSetInArr(t.ptrArr[:], int(cval)) == true {
nextRoot = t.ptrData[ptrIdx]
if nextRoot == nil {
ts.errCode = TrieErrUnknown
return -1
}
} else {
// If no pointer exists, then allocate it
// Make pointer references
nextRoot = new(TrieRoot)
if t.ptrData[ptrIdx] != nil {
expPtrArrDat(t.ptrData[:], ptrIdx)
t.ptrData[ptrIdx] = nil
}
t.ptrData[ptrIdx] = nextRoot
SetBitInArr(t.ptrArr[:], int(cval))
}
return nextRoot.addTrieInt(tv, currLevel+1, rPfxLen, ts)
} else {
shftBits := TrieJmpLength - rPfxLen
basePos := (1 << rPfxLen) - 1
// Find value relevant to currently remaining prefix len
cval = cval >> shftBits
idx := basePos + int(cval)
if IsBitSetInArr(t.prefixArr[:], idx) == true {
return TrieErrExists
}
pfxIdx := CountSetBitsInArr(t.prefixArr[:], idx)
if t.prefixData[pfxIdx] != 0 {
expPrefixArrDat(t.prefixData[:], pfxIdx)
t.prefixData[pfxIdx] = 0
}
SetBitInArr(t.prefixArr[:], idx)
t.prefixData[pfxIdx] = ts.trieData
return 0
}
}
func (t *TrieRoot) deleteTrieInt(tv *trieVar, currLevel int, rPfxLen int, ts *trieState) int {
if rPfxLen < 0 || ts.errCode != 0 {
return -1
}
// This assumes stride of length 8
var cval uint8 = tv.prefix[currLevel]
var nextRoot *TrieRoot
if rPfxLen > TrieJmpLength {
rPfxLen -= TrieJmpLength
ptrIdx := CountSetBitsInArr(t.ptrArr[:], int(cval)-1)
if IsBitSetInArr(t.ptrArr[:], int(cval)) == false {
ts.matchFound = false
return -1
}
nextRoot = t.ptrData[ptrIdx]
if nextRoot == nil {
ts.matchFound = false
ts.errCode = TrieErrUnknown
return -1
}
nextRoot.deleteTrieInt(tv, currLevel+1, rPfxLen, ts)
if ts.matchFound == true && ts.lastMatchEmpty == true {
t.ptrData[ptrIdx] = nil
shrinkPtrArrDat(t.ptrData[:], ptrIdx)
UnSetBitInArr(t.ptrArr[:], int(cval))
}
if ts.lastMatchEmpty == true {
if CountAllSetBitsInArr(t.prefixArr[:]) == 0 &&
CountAllSetBitsInArr(t.ptrArr[:]) == 0 {
ts.lastMatchEmpty = true
} else {
ts.lastMatchEmpty = false
}
}
if ts.errCode != 0 {
return -1
}
return 0
} else {
shftBits := TrieJmpLength - rPfxLen
basePos := (1 << rPfxLen) - 1
// Find value relevant to currently remaining prefix len
cval = cval >> shftBits
idx := basePos + int(cval)
if IsBitSetInArr(t.prefixArr[:], idx) == false {
ts.matchFound = false
return TrieErrNoEnt
}
pfxIdx := CountSetBitsInArr(t.prefixArr[:], idx-1)
// Note - This assumes that prefix data should be non-zero
if t.prefixData[pfxIdx] != 0 {
t.prefixData[pfxIdx] = 0
shrinkPrefixArrDat(t.prefixData[:], pfxIdx)
UnSetBitInArr(t.prefixArr[:], idx)
ts.matchFound = true
if CountAllSetBitsInArr(t.prefixArr[:]) == 0 &&
CountAllSetBitsInArr(t.ptrArr[:]) == 0 {
ts.lastMatchEmpty = true
}
return 0
}
ts.matchFound = false
ts.errCode = TrieErrUnknown
return -1
}
}
func (t *TrieRoot) findTrieInt(tv *trieVar, currLevel int, ts *trieState) int {
var idx int = 0
if ts.errCode != 0 {
return -1
}
// This assumes stride of length 8
var cval uint8 = tv.prefix[currLevel]
for rPfxLen := TrieJmpLength; rPfxLen >= 0; rPfxLen-- {
shftBits := TrieJmpLength - rPfxLen
basePos := (1 << rPfxLen) - 1
// Find value relevant to currently remaining prefix len
cval = cval >> shftBits
idx = basePos + int(cval)
pfxVal := (idx - basePos) << shftBits
if IsBitSetInArr(t.prefixArr[:], idx) == true {
ts.lastMatchLevel = currLevel
ts.lastMatchPfxLen = 8*currLevel + rPfxLen
ts.matchFound = true
ts.lastMatchTv.prefix[currLevel] = byte(pfxVal)
break
}
}
cval = tv.prefix[currLevel]
ptrIdx := CountSetBitsInArr(t.ptrArr[:], int(cval)-1)
if IsBitSetInArr(t.ptrArr[:], int(cval)) == true {
if t.ptrData[ptrIdx] != nil {
nextRoot := t.ptrData[ptrIdx]
ts.lastMatchTv.prefix[currLevel] = byte(cval)
nextRoot.findTrieInt(tv, currLevel+1, ts)
}
}
if ts.lastMatchLevel == currLevel {
pfxIdx := CountSetBitsInArr(t.prefixArr[:], idx-1)
ts.trieData = t.prefixData[pfxIdx]
}
return 0
}
func (t *TrieRoot) walkTrieInt(tv *trieVar, level int, ts *trieState, tf TrieIterIntf) int {
var p int
var pfxIdx int
var pfxStr string
n := 1
pfxLen := 0
basePos := 0
for p = 0; p < PrefixArrLenfth; p++ {
if n <= 0 {
pfxLen++
n = 1 << pfxLen
basePos = n - 1
}
if IsBitSetInArr(t.prefixArr[:], p) == true {
shftBits := TrieJmpLength - pfxLen
pLevelPfxLen := level * TrieJmpLength
cval := (p - basePos) << shftBits
if p == 0 {
pfxIdx = 0
} else {
pfxIdx = CountSetBitsInArr(t.prefixArr[:], p-1)
}
pfxStr = ""
for i := 0; i < ts.maxLevels; i++ {
var pfxVal = int(tv.prefix[i])
var apStr string = "."
if i == level {
pfxVal = cval
}
if i == ts.maxLevels-1 {
apStr = ""
}
pfxStr += fmt.Sprintf("%d%s", pfxVal, apStr)
}
td := tf.TrieData2String(t.prefixData[pfxIdx])
tf.TrieNodeWalker(fmt.Sprintf("%20s/%d : %s", pfxStr, int(pfxLen)+pLevelPfxLen, td))
}
n--
}
for p = 0; p < PtrArrLength; p++ {
if IsBitSetInArr(t.ptrArr[:], p) == true {
cval := p
ptrIdx := CountSetBitsInArr(t.ptrArr[:], p-1)
if t.ptrData[ptrIdx] != nil {
nextRoot := t.ptrData[ptrIdx]
tv.prefix[level] = byte(cval)
nextRoot.walkTrieInt(tv, level+1, ts, tf)
}
}
}
return 0
}
// AddTrie - Add a trie entry
// cidr is the route in cidr format and data is any user-defined data
// returns 0 on success or non-zero error code on error
func (t *TrieRoot) AddTrie(cidr string, data TrieData) int {
var tv trieVar
var ts = trieState{data, 0, 0, false, trieVar{}, false, 4, 0}
pfxLen := cidr2TrieVar(cidr, &tv)
if pfxLen < 0 {
return TrieErrPrefix
}
ret := t.addTrieInt(&tv, 0, pfxLen, &ts)
if ret != 0 || ts.errCode != 0 {
return ret
}
return 0
}
// DelTrie - Delete a trie entry
// cidr is the route in cidr format
// returns 0 on success or non-zero error code on error
func (t *TrieRoot) DelTrie(cidr string) int {
var tv trieVar
var ts = trieState{0, 0, 0, false, trieVar{}, false, 4, 0}
pfxLen := cidr2TrieVar(cidr, &tv)
if pfxLen < 0 {
return TrieErrPrefix
}
ret := t.deleteTrieInt(&tv, 0, pfxLen, &ts)
if ret != 0 || ts.errCode != 0 {
return TrieErrNoEnt
}
return 0
}
// FindTrie - Lookup matching route as per longest prefix match
// IP is the IP address in string format
// returns the following :
// 1. 0 on success or non-zero error code on error
// 2. matching route in *net.IPNet form
// 3. user-defined data associated with the trie entry
func (t *TrieRoot) FindTrie(IP string) (int, *net.IPNet, TrieData) {
var tv trieVar
var ts = trieState{0, 0, 0, false, trieVar{}, false, 4, 0}
var cidr string
if t.v6 == false {
cidr = IP + "/32"
} else {
cidr = IP + "/128"
}
pfxLen := cidr2TrieVar(cidr, &tv)
if pfxLen < 0 {
return TrieErrPrefix, nil, 0
}
t.findTrieInt(&tv, 0, &ts)
if ts.matchFound == true {
if t.v6 == false {
var res net.IP
for i := 0; i < 4; i++ {
res = append(res, ts.lastMatchTv.prefix[i])
}
mask := net.CIDRMask(ts.lastMatchPfxLen, 32)
ipnet := net.IPNet{IP: res, Mask: mask}
return 0, &ipnet, ts.trieData
} else {
var res net.IP = ts.lastMatchTv.prefix[:]
mask := net.CIDRMask(ts.lastMatchPfxLen, 128)
ipnet := net.IPNet{IP: res, Mask: mask}
return 0, &ipnet, ts.trieData
}
}
return TrieErrNoEnt, nil, 0
}
// Trie2String - stringify the trie table
func (t *TrieRoot) Trie2String(tf TrieIterIntf) {
var ts = trieState{0, 0, 0, false, trieVar{}, false, 4, 0}
t.walkTrieInt(&trieVar{}, 0, &ts, tf)
}