forked from kiwiirc/identd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
identdlookup.go
105 lines (85 loc) · 2.1 KB
/
identdlookup.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
package main
import "sync"
// Combine 2 ports into a single int. Eg. 65535, 65535 = 6553565535
func combinePorts(port1, port2 int) uint64 {
return uint64((port1 * 100000) + port2)
}
// Split a combined int into 2 ports. Eg. 6553565535 = 65535, 65535
func splitPorts(inp uint64) (int, int) {
port1 := inp / 100000
port2 := inp - (port1 * 100000)
return int(port1), int(port2)
}
type IdentdEntry struct {
Key uint64
LocalPort int
RemotePort int
Inet string
Username string
AppID string
}
type IdentdLookup struct {
sync.Mutex
// Entries[inet][combined port] = IdentdEntry
Entries map[string]map[uint64]*IdentdEntry
}
func MakeIdentdLookup() *IdentdLookup {
return &IdentdLookup{Entries: make(map[string]map[uint64]*IdentdEntry)}
}
func (l *IdentdLookup) Lookup(localPort, remotePort int, inet string) *IdentdEntry {
l.Lock()
defer l.Unlock()
inetEntries := l.Entries[inet]
if inetEntries == nil {
inetEntries, _ = l.Entries["0.0.0.0"]
}
if inetEntries == nil {
return nil
}
key := combinePorts(localPort, remotePort)
entry, _ := inetEntries[key]
return entry
}
func (l *IdentdLookup) AddEntry(localPort, remotePort int, inet string, username string, appID string) *IdentdEntry {
key := combinePorts(localPort, remotePort)
entry := &IdentdEntry{
Key: key,
LocalPort: localPort,
RemotePort: remotePort,
Inet: inet,
Username: username,
AppID: appID,
}
l.Lock()
inetEntries := l.Entries[inet]
if inetEntries == nil {
l.Entries[inet] = make(map[uint64]*IdentdEntry)
inetEntries = l.Entries[inet]
}
inetEntries[key] = entry
l.Unlock()
return entry
}
func (l *IdentdLookup) RemoveEntry(entry *IdentdEntry) {
l.Lock()
defer l.Unlock()
inetEntries := l.Entries[entry.Inet]
if inetEntries == nil {
return
}
delete(inetEntries, entry.Key)
if len(inetEntries) == 0 {
delete(l.Entries, entry.Inet)
}
}
func (l *IdentdLookup) ClearAppID(appID string) {
l.Lock()
defer l.Unlock()
for _, inetEntries := range l.Entries {
for key, entry := range inetEntries {
if entry.AppID == appID {
delete(inetEntries, key)
}
}
}
}