summaryrefslogtreecommitdiffhomepage
path: root/src/device.go
blob: 9f1daa6295a15befa03469b4893c26a828fa2233 (plain)
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
package main

import (
	"math/rand"
	"sync"
)

/* TODO: Locking may be a little broad here
 */

type Device struct {
	mutex        sync.RWMutex
	peers        map[NoisePublicKey]*Peer
	sessions     map[uint32]*Handshake
	privateKey   NoisePrivateKey
	publicKey    NoisePublicKey
	fwMark       uint32
	listenPort   uint16
	routingTable RoutingTable
}

func (dev *Device) NewID(h *Handshake) uint32 {
	dev.mutex.Lock()
	defer dev.mutex.Unlock()
	for {
		id := rand.Uint32()
		_, ok := dev.sessions[id]
		if !ok {
			dev.sessions[id] = h
			return id
		}
	}
}

func (dev *Device) RemovePeer(key NoisePublicKey) {
	dev.mutex.Lock()
	defer dev.mutex.Unlock()
	peer, ok := dev.peers[key]
	if !ok {
		return
	}
	peer.mutex.Lock()
	dev.routingTable.RemovePeer(peer)
	delete(dev.peers, key)
}

func (dev *Device) RemoveAllAllowedIps(peer *Peer) {

}

func (dev *Device) RemoveAllPeers() {
	dev.mutex.Lock()
	defer dev.mutex.Unlock()

	for key, peer := range dev.peers {
		peer.mutex.Lock()
		dev.routingTable.RemovePeer(peer)
		delete(dev.peers, key)
		peer.mutex.Unlock()
	}
}