EtherGuard-VPN/device/indextable.go

99 lines
1.8 KiB
Go
Raw Normal View History

2019-01-02 01:55:51 +01:00
/* SPDX-License-Identifier: MIT
*
* Copyright (C) 2017-2020 WireGuard LLC. All Rights Reserved.
*/
2019-03-03 04:04:41 +01:00
package device
2017-06-24 15:34:17 +02:00
import (
"crypto/rand"
"encoding/binary"
2017-06-24 15:34:17 +02:00
"sync"
)
type IndexTableEntry struct {
peer *Peer
handshake *Handshake
2018-05-13 18:23:40 +02:00
keypair *Keypair
}
2017-06-24 15:34:17 +02:00
type IndexTable struct {
sync.RWMutex
table map[uint32]IndexTableEntry
2017-06-24 15:34:17 +02:00
}
func randUint32() (uint32, error) {
2018-05-13 18:23:40 +02:00
var integer [4]byte
_, err := rand.Read(integer[:])
// Arbitrary endianness; both are intrinsified by the Go compiler.
return binary.LittleEndian.Uint32(integer[:]), err
2017-06-24 15:34:17 +02:00
}
func (table *IndexTable) Init() {
table.Lock()
defer table.Unlock()
table.table = make(map[uint32]IndexTableEntry)
2017-06-24 15:34:17 +02:00
}
func (table *IndexTable) Delete(index uint32) {
table.Lock()
defer table.Unlock()
delete(table.table, index)
}
2018-05-13 18:23:40 +02:00
func (table *IndexTable) SwapIndexForKeypair(index uint32, keypair *Keypair) {
table.Lock()
defer table.Unlock()
2018-05-13 18:23:40 +02:00
entry, ok := table.table[index]
if !ok {
return
}
table.table[index] = IndexTableEntry{
peer: entry.peer,
keypair: keypair,
handshake: nil,
}
}
2018-05-13 18:23:40 +02:00
func (table *IndexTable) NewIndexForHandshake(peer *Peer, handshake *Handshake) (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
}
// check if index used
table.RLock()
_, ok := table.table[index]
table.RUnlock()
2017-06-24 15:34:17 +02:00
if ok {
continue
}
2018-05-13 18:23:40 +02:00
// check again while locked
2017-06-24 15:34:17 +02:00
table.Lock()
_, found := table.table[index]
if found {
table.Unlock()
continue
}
table.table[index] = IndexTableEntry{
peer: peer,
2018-05-13 18:23:40 +02:00
handshake: handshake,
keypair: nil,
}
table.Unlock()
return index, nil
2017-06-24 15:34:17 +02:00
}
}
func (table *IndexTable) Lookup(id uint32) IndexTableEntry {
table.RLock()
defer table.RUnlock()
return table.table[id]
2017-06-24 15:34:17 +02:00
}