1
0
mirror of https://git.zx2c4.com/wireguard-go synced 2024-11-15 01:05:15 +01:00
wireguard-go/src/index.go

103 lines
1.7 KiB
Go
Raw Normal View History

2017-06-24 15:34:17 +02:00
package main
import (
"crypto/rand"
"sync"
)
/* Index=0 is reserved for unset indecies
2017-06-24 22:03:52 +02:00
*
* TODO: Rethink map[id] -> peer VS map[id] -> handshake and handshake <ref> peer
2017-06-24 15:34:17 +02:00
*
*/
type IndexTableEntry struct {
peer *Peer
handshake *Handshake
keyPair *KeyPair
}
2017-06-24 15:34:17 +02:00
type IndexTable struct {
mutex sync.RWMutex
table map[uint32]IndexTableEntry
2017-06-24 15:34:17 +02:00
}
func randUint32() (uint32, error) {
var buff [4]byte
_, err := rand.Read(buff[:])
id := uint32(buff[0])
id <<= 8
id |= uint32(buff[1])
id <<= 8
id |= uint32(buff[2])
id <<= 8
id |= uint32(buff[3])
return id, err
}
func (table *IndexTable) Init() {
table.mutex.Lock()
table.table = make(map[uint32]IndexTableEntry)
table.mutex.Unlock()
2017-06-24 15:34:17 +02:00
}
func (table *IndexTable) Delete(index uint32) {
if index == 0 {
return
}
table.mutex.Lock()
delete(table.table, index)
table.mutex.Unlock()
}
func (table *IndexTable) Insert(key uint32, value IndexTableEntry) {
2017-06-24 15:34:17 +02:00
table.mutex.Lock()
table.table[key] = value
table.mutex.Unlock()
}
func (table *IndexTable) NewIndex(peer *Peer) (uint32, error) {
2017-06-24 15:34:17 +02:00
for {
// generate random index
index, err := randUint32()
2017-06-24 15:34:17 +02:00
if err != nil {
return index, err
2017-06-24 15:34:17 +02:00
}
if index == 0 {
2017-06-24 15:34:17 +02:00
continue
}
// check if index used
table.mutex.RLock()
_, ok := table.table[index]
2017-06-24 15:34:17 +02:00
if ok {
continue
}
table.mutex.RUnlock()
2017-06-24 15:34:17 +02:00
// replace index
2017-06-24 15:34:17 +02:00
table.mutex.Lock()
_, found := table.table[index]
if found {
table.mutex.Unlock()
continue
}
table.table[index] = IndexTableEntry{
peer: peer,
handshake: &peer.handshake,
keyPair: nil,
}
table.mutex.Unlock()
return index, nil
2017-06-24 15:34:17 +02:00
}
}
func (table *IndexTable) Lookup(id uint32) IndexTableEntry {
2017-06-24 15:34:17 +02:00
table.mutex.RLock()
defer table.mutex.RUnlock()
return table.table[id]
2017-06-24 15:34:17 +02:00
}