summaryrefslogtreecommitdiffhomepage
path: root/src/index.go
blob: 83a7e297997da4e36b85b64d6202437152856160 (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main

import (
	"crypto/rand"
	"sync"
)

/* Index=0 is reserved for unset indecies
 *
 */

type IndexTable struct {
	mutex      sync.RWMutex
	keypairs   map[uint32]*KeyPair
	handshakes map[uint32]*Handshake
}

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)
	table.handshakes = make(map[uint32]*Handshake)
}

func (table *IndexTable) NewIndex(handshake *Handshake) (uint32, error) {
	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
		}

		// update the index

		delete(table.handshakes, handshake.localIndex)
		handshake.localIndex = id
		table.handshakes[id] = handshake
		return id, nil
	}
}

func (table *IndexTable) LookupKeyPair(id uint32) *KeyPair {
	table.mutex.RLock()
	defer table.mutex.RUnlock()
	return table.keypairs[id]
}

func (table *IndexTable) LookupHandshake(id uint32) *Handshake {
	table.mutex.RLock()
	defer table.mutex.RUnlock()
	return table.handshakes[id]
}