-
Notifications
You must be signed in to change notification settings - Fork 2
/
util.go
59 lines (53 loc) · 1.43 KB
/
util.go
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
package pcp
import (
crand "crypto/rand"
"math/rand"
"time"
log "github.com/sirupsen/logrus"
)
//Necessary for padding all messages to multiple of 4 octets
func addPadding(data []byte) (out []byte) {
length := len(data)
padding := 4 - (length % 4)
if padding > 0 {
empty := make([]byte, padding)
out = append(data, empty...)
}
return out
}
func concatCopyPreAllocate(slices [][]byte) []byte {
var totalLen int
for _, s := range slices {
totalLen += len(s)
}
tmp := make([]byte, totalLen)
var i int
for _, s := range slices {
i += copy(tmp[i:], s)
}
return tmp
}
func genRandomBytes(size int) (blk []byte, err error) {
blk = make([]byte, size)
_, err = crand.Read(blk)
return
}
func getRefreshTime(attempt int, lifetime uint32) int64 {
//Reset seed on each call to avoid non-pseudorandom intervals over prolonged usage
rand.Seed(time.Now().UnixNano())
t := time.Now()
//See 11.2.1 of RFC6887
max := t.Unix() + (5*int64(lifetime))/(1<<(attempt+3))
min := t.Unix() + (int64(lifetime))/(1<<(attempt+1))
var interval int64
if (max - min) > 0 {
interval = rand.Int63n(max-min) + min
}
if interval < 4 {
interval = t.Unix() + 4
}
log.Debug(max, min, max-min)
log.Debugf("max - current: %d min - current: %d random int: %d, lifetime: %d", max-t.Unix(), min-t.Unix(), interval-t.Unix(), lifetime)
log.Debugf("Refresh max: %d Refresh min: %d Time now: %d Interval: %d", max, min, t.Unix(), interval)
return interval
}