-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathpdu.go
99 lines (83 loc) · 1.81 KB
/
pdu.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
package snmp
import (
"io"
)
// PDU represents an SNMP PDU.
type PDU struct {
rawSequence []DataType
requestID int
err int
errIndex int
varbinds []Varbind
}
func (p PDU) Varbinds() []Varbind {
return p.varbinds
}
func newPDU(requestID int, err int, errIndex int, varbinds []Varbind) PDU {
varbindsSequence := Sequence{}
for _, v := range varbinds {
varbindsSequence = append(varbindsSequence, Sequence{
v.OID, v.value,
})
}
rawSequence := []DataType{
Int(requestID),
Int(err),
Int(errIndex),
varbindsSequence,
}
return PDU{
rawSequence: rawSequence,
requestID: requestID,
err: err,
errIndex: errIndex,
varbinds: varbinds,
}
}
func decodePDU(length int, r io.Reader) (PDU, int, error) {
pdu := PDU{}
seqBytes := 0
bytesRead := 0
for seqBytes < length {
item, read, err := decode(r)
if read > 0 && item != nil {
pdu.rawSequence = append(pdu.rawSequence, item)
bytesRead += read
seqBytes += read
}
if err != nil {
return pdu, bytesRead, err
}
}
reqID, ok := pdu.rawSequence[0].(Int)
if !ok {
return pdu, bytesRead, ErrDecodingType
}
pdu.requestID = int(reqID)
errorCode, ok := pdu.rawSequence[1].(Int)
if !ok {
return pdu, bytesRead, ErrDecodingType
}
pdu.err = int(errorCode)
errIndex, ok := pdu.rawSequence[2].(Int)
if !ok {
return pdu, bytesRead, ErrDecodingType
}
pdu.errIndex = int(errIndex)
varbindSeq, ok := pdu.rawSequence[3].(Sequence)
if !ok {
return pdu, bytesRead, ErrDecodingType
}
for _, varbindElem := range varbindSeq {
varbindPair, ok := varbindElem.(Sequence)
if !ok {
return pdu, bytesRead, ErrDecodingType
}
oid, ok := varbindPair[0].(ObjectIdentifier)
if ok {
val := varbindPair[1]
pdu.varbinds = append(pdu.varbinds, NewVarbind(oid, val))
}
}
return pdu, bytesRead, nil
}