-
Notifications
You must be signed in to change notification settings - Fork 48
/
util.go
136 lines (118 loc) · 2.32 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package snmpgo
import (
"bytes"
"encoding/hex"
"encoding/json"
"fmt"
"math"
"math/rand"
"net"
"regexp"
"strings"
"sync"
"time"
)
var random *rand.Rand
var randOnce sync.Once
func initRandom() {
random = rand.New(rand.NewSource(time.Now().UnixNano()))
}
var reqMutex sync.Mutex
func genRequestId() int {
randOnce.Do(initRandom)
reqMutex.Lock()
val := int(random.Int31())
reqMutex.Unlock()
return val
}
func genSalt32() int32 {
randOnce.Do(initRandom)
reqMutex.Lock()
val := random.Int31()
reqMutex.Unlock()
return val
}
func genSalt64() int64 {
randOnce.Do(initRandom)
reqMutex.Lock()
val := random.Int63()
reqMutex.Unlock()
return val
}
var mesId int = math.MaxInt32 - 1
var mesMutex sync.Mutex
func genMessageId() (id int) {
randOnce.Do(initRandom)
mesMutex.Lock()
mesId++
if mesId == math.MaxInt32 {
reqMutex.Lock()
mesId = int(random.Int31())
reqMutex.Unlock()
}
id = mesId
mesMutex.Unlock()
return
}
func retry(retries int, f func() error) (err error) {
for i := 0; i <= retries; i++ {
err = f()
switch e := err.(type) {
case net.Error:
if e.Timeout() {
continue
}
case *notInTimeWindowError:
err = e.error
continue
}
return
}
return
}
func confirmedType(t PduType) bool {
if t == GetRequest || t == GetNextRequest || t == SetRequest ||
t == GetBulkRequest || t == InformRequest {
return true
}
return false
}
func engineIdToBytes(engineId string) ([]byte, error) {
b, err := hex.DecodeString(engineId)
if l := len(b); err != nil || (l < 5 || l > 32) {
return nil, &ArgumentError{
Value: engineId,
Message: "EngineId must be a hexadecimal string and length is range 5..32",
}
}
return b, nil
}
var hexPrefix *regexp.Regexp = regexp.MustCompile(`^0[xX]`)
func stripHexPrefix(s string) string {
return hexPrefix.ReplaceAllString(s, "")
}
func toHexStr(a []byte, sep string) string {
s := make([]string, len(a))
for i, b := range a {
s[i] = fmt.Sprintf("%02x", b)
}
return strings.Join(s, sep)
}
func escape(s interface{}) string {
r, _ := json.Marshal(s)
return string(r)
}
func xor(a, b []byte) []byte {
c := make([]byte, len(a))
for i := 0; i < len(a); i++ {
c[i] = a[i] ^ b[i]
}
return c
}
func padding(b []byte, size int) []byte {
pad := size - (len(b) % size)
if pad > 0 {
b = append(b, bytes.Repeat([]byte{0x00}, pad)...)
}
return b
}