wireguard-go/src/index.go

84 lines
1.5 KiB
Go
Raw Normal View History

2017-06-24 13:34:17 +00:00
package main
import (
"crypto/rand"
"sync"
)
/* Index=0 is reserved for unset indecies
2017-06-24 20:03:52 +00:00
*
* TODO: Rethink map[id] -> peer VS map[id] -> handshake and handshake <ref> peer
2017-06-24 13:34:17 +00:00
*
*/
type IndexTable struct {
mutex sync.RWMutex
keypairs map[uint32]*KeyPair
2017-06-24 20:03:52 +00:00
handshakes map[uint32]*Peer
2017-06-24 13:34:17 +00: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()
defer table.mutex.Unlock()
table.keypairs = make(map[uint32]*KeyPair)
2017-06-24 20:03:52 +00:00
table.handshakes = make(map[uint32]*Peer)
2017-06-24 13:34:17 +00:00
}
2017-06-24 20:03:52 +00:00
func (table *IndexTable) NewIndex(peer *Peer) (uint32, error) {
2017-06-24 13:34:17 +00:00
table.mutex.Lock()
defer table.mutex.Unlock()
for {
// generate random index
id, err := randUint32()
if err != nil {
return id, err
}
if id == 0 {
continue
}
// check if index used
_, ok := table.keypairs[id]
if ok {
continue
}
_, ok = table.handshakes[id]
if ok {
continue
}
2017-06-24 20:03:52 +00:00
// clean old index
2017-06-24 13:34:17 +00:00
2017-06-24 20:03:52 +00:00
delete(table.handshakes, peer.handshake.localIndex)
table.handshakes[id] = peer
2017-06-24 13:34:17 +00:00
return id, nil
}
}
func (table *IndexTable) LookupKeyPair(id uint32) *KeyPair {
table.mutex.RLock()
defer table.mutex.RUnlock()
return table.keypairs[id]
}
2017-06-24 20:03:52 +00:00
func (table *IndexTable) LookupHandshake(id uint32) *Peer {
2017-06-24 13:34:17 +00:00
table.mutex.RLock()
defer table.mutex.RUnlock()
return table.handshakes[id]
}