-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnatmap.go
103 lines (91 loc) · 2 KB
/
natmap.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
/*
* vc5/xvs load balancer. Copyright (C) 2021-present David Coles
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package xvs
import (
"errors"
"sync"
)
var mutex sync.RWMutex
type natmap map[[2]b4]uint16
func (f natmap) add(v, r b4) uint16 {
mutex.Lock()
defer mutex.Unlock()
k := [2]b4{v, r}
n := f[k]
f[k] = n // existing value if exists, 0 otherwise
return n
}
func (f natmap) get(v, r b4) uint16 {
mutex.RLock()
defer mutex.RUnlock()
k := [2]b4{v, r}
return f[k]
}
func (f natmap) all() map[[2]b4]uint16 {
mutex.RLock()
defer mutex.RUnlock()
m := map[[2]b4]uint16{}
for k, v := range f {
m[k] = v
}
return m
}
func (f natmap) index() (b bool, e error) {
mutex.Lock()
defer mutex.Unlock()
m := map[uint16]bool{}
var n uint16
for _, v := range f {
m[v] = true
}
for k, v := range f {
for v == 0 {
b = true
if n >= 65530 {
return b, errors.New("Too many hosts")
}
n++
if _, exists := m[n]; !exists {
v = n
f[k] = v
}
}
}
return b, e
}
func (f natmap) rips() map[b4]bool {
mutex.RLock()
defer mutex.RUnlock()
rips := map[b4]bool{}
for k, _ := range f {
r := k[1]
rips[r] = true
}
return rips
}
func (f natmap) clean(m map[[2]b4]bool) (c bool) {
mutex.Lock()
defer mutex.Unlock()
for k, _ := range f {
if _, exists := m[k]; !exists {
c = true
delete(f, k)
}
}
return
}