-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathoid.go
More file actions
126 lines (94 loc) · 2.36 KB
/
oid.go
File metadata and controls
126 lines (94 loc) · 2.36 KB
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
package snmp
import (
"errors"
"fmt"
"io"
"strconv"
"strings"
)
// ObjectIdentifier represents an SNMP OID.
type ObjectIdentifier []uint
// ParseOID parses and returns an ObjectIdentifier and an error.
func ParseOID(str string) (ObjectIdentifier, error) {
parts := strings.Split(strings.Trim(str, "."), ".")
oid := ObjectIdentifier{}
for _, part := range parts {
n, err := strconv.ParseUint(part, 10, 64)
if err != nil {
return nil, err
}
oid = append(oid, uint(n))
}
return oid, nil
}
// MustParseOID parses a string and returns an ObjectIdentifier.
// It panics if an error is encountered.
func MustParseOID(str string) ObjectIdentifier {
oid, err := ParseOID(str)
if err != nil {
panic(err)
}
return oid
}
// encodeOIDUint encodes a uint using base 128.
func encodeOIDUint(i uint) []byte {
var b []byte
if i < 128 {
return []byte{byte(i)}
}
b = append(b, byte(i)%128)
i /= 128
for i > 0 {
b = append(b, 128+byte(i)%128)
i /= 128
}
return reverseSlice(b)
}
// Encode encodes an ObjectIdentifier with the proper header.
func (oid ObjectIdentifier) Encode() ([]byte, error) {
if len(oid) < 2 {
return nil, errors.New("snmp: invalid ObjectIdentifier length")
}
if oid[0] != 1 && oid[1] != 3 {
return nil, errors.New("ObjectIdentifier does not start with .1.3")
}
b := make([]byte, 0, len(oid)+1)
b = append(b, 0x2b)
for i := 2; i < len(oid); i++ {
b = append(b, encodeOIDUint(oid[i])...)
}
return append(encodeHeaderSequence(0x6, len(b)), b...), nil
}
// decodeOID decodes an OID up to length bytes from r.
// It returns the SNMP data type, the number of bytes read, and an error.
func decodeOID(length int, r io.Reader) (ObjectIdentifier, int, error) {
bytesRead := 0
// Read into a buffer
b := make([]byte, length)
n, err := r.Read(b)
bytesRead += n
if err != nil {
return nil, bytesRead, err
}
oid := ObjectIdentifier{uint(b[0]) / 40, uint(b[0]) % 40}
for i := 1; i < length; i++ {
val := uint(0)
for b[i] >= 128 {
val += uint(b[i]) - 128
val *= 128
i++
}
val += uint(b[i])
oid = append(oid, val)
}
return oid, bytesRead, nil
}
// String returns the string representation of an ObjectIdentifer.
// This value can be parsed into the original OID as well.
func (oid ObjectIdentifier) String() string {
str := ""
for _, part := range oid {
str += fmt.Sprintf(".%d", part)
}
return str
}