forked from slayercat/GoSNMPServer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathagentcontrolSubAgent.go
394 lines (361 loc) · 10.9 KB
/
agentcontrolSubAgent.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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package GoSNMPServer
import "strings"
import "fmt"
import "sort"
import "github.com/slayercat/gosnmp"
import "github.com/pkg/errors"
type SubAgent struct {
// ContextName selects from SNMPV3 ContextName or SNMPV1/V2c community for switch from SubAgent...
// set to nil means all requests will gets here(of default)
CommunityIDs []string
// OIDs for Read/Write actions
OIDs []*PDUValueControlItem
// UserErrorMarkPacket decides if shll treat user returned error as generr
UserErrorMarkPacket bool
Logger ILogger
master *MasterAgent
}
func (t *SubAgent) SyncConfig() error {
sort.Sort(byOID(t.OIDs))
t.Logger.Infof("Total OIDs of %v: %v", t.CommunityIDs, len(t.OIDs))
for id, each := range t.OIDs {
t.Logger.Infof("OIDs of %v: %v", t.CommunityIDs, each.OID)
if id != 0 && t.OIDs[id].OID == t.OIDs[id-1].OID {
verr := fmt.Sprintf("community %v: meet duplicate oid %v", t.CommunityIDs, each.OID)
t.Logger.Errorf(verr)
return errors.New(verr)
}
}
return nil
}
func (t *SubAgent) Serve(i *gosnmp.SnmpPacket) (*gosnmp.SnmpPacket, error) {
switch i.PDUType {
case gosnmp.GetRequest:
return t.serveGetRequest(i)
case gosnmp.GetNextRequest, gosnmp.GetBulkRequest:
return t.serveGetNextRequest(i)
case gosnmp.SetRequest:
return t.serveSetRequest(i)
case gosnmp.Trap, gosnmp.SNMPv2Trap, gosnmp.InformRequest:
return t.serveTrap(i)
default:
return nil, errors.WithStack(ErrUnsupportedOperation)
}
}
func (t *SubAgent) checkPermission(whichPDU *PDUValueControlItem, request *gosnmp.SnmpPacket) PermissionAllowance {
if whichPDU.OnCheckPermission == nil {
return PermissionAllowanceAllowed
}
return whichPDU.OnCheckPermission(request.Version, request.PDUType, getPktContextOrCommunity(request))
}
func (t *SubAgent) getPDU(Name string, Type gosnmp.Asn1BER, Value interface{}) gosnmp.SnmpPDU {
return gosnmp.SnmpPDU{
Name: Name,
Type: Type,
Value: Value,
Logger: &SnmpLoggerAdapter{t.Logger},
}
}
func (t *SubAgent) getPDUHelloVariable() gosnmp.SnmpPDU {
// Return a variable. Usually for failture login try count.
// 1.3.6.1.6.3.15.1.1.4.0 => http://oidref.com/1.3.6.1.6.3.15.1.1.4.0
// usmStatsUnknownEngineIDs
return t.getPDU(
"1.3.6.1.6.3.15.1.1.4.0",
gosnmp.Counter32,
uint32(0),
)
}
func (t *SubAgent) getPDUEndOfMibView(Name string) gosnmp.SnmpPDU {
return t.getPDU(
Name,
gosnmp.EndOfMibView,
nil,
)
}
func (t *SubAgent) getPDUNoSuchInstance(Name string) gosnmp.SnmpPDU {
return t.getPDU(
Name,
gosnmp.NoSuchInstance,
nil,
)
}
func (t *SubAgent) getPDUNil(Name string) gosnmp.SnmpPDU {
return t.getPDU(
Name,
gosnmp.Null,
nil,
)
}
func (t *SubAgent) getPDUOctetString(Name, str string) gosnmp.SnmpPDU {
return t.getPDU(
Name,
gosnmp.OctetString,
str,
)
}
func (t *SubAgent) getForPDUValueControlResult(item *PDUValueControlItem,
i *gosnmp.SnmpPacket) (pdu gosnmp.SnmpPDU, errret gosnmp.SNMPError) {
if t.checkPermission(item, i) != PermissionAllowanceAllowed {
return t.getPDUNil(item.OID), gosnmp.NoAccess
}
if item.OnGet == nil {
return t.getPDUNil(item.OID), gosnmp.ResourceUnavailable
}
defer func() {
// panic in onset
if err := recover(); err != nil {
pdu = t.getPDUOctetString(item.OID, fmt.Sprintf("ERROR: %+v", err))
if t.UserErrorMarkPacket {
errret = gosnmp.GenErr
}
return
}
}()
valtoRet, err := item.OnGet()
if err != nil {
if t.UserErrorMarkPacket {
errret = gosnmp.GenErr
} else {
errret = gosnmp.NoError
}
return t.getPDUOctetString(item.OID, fmt.Sprintf("ERROR: %+v", err)), errret
}
return gosnmp.SnmpPDU{
Name: item.OID,
Type: item.Type,
Value: valtoRet,
Logger: &SnmpLoggerAdapter{t.Logger},
}, gosnmp.NoError
}
func (t *SubAgent) trapForPDUValueControlResult(item *PDUValueControlItem,
i *gosnmp.SnmpPacket, varItem gosnmp.SnmpPDU) (pdu gosnmp.SnmpPDU, errret gosnmp.SNMPError) {
if t.checkPermission(item, i) != PermissionAllowanceAllowed {
return t.getPDUNil(item.OID), gosnmp.NoAccess
}
if item.OnTrap == nil {
return t.getPDUNil(item.OID), gosnmp.ResourceUnavailable
}
defer func() {
// panic in onset
if err := recover(); err != nil {
pdu = t.getPDUOctetString(item.OID, fmt.Sprintf("ERROR: %+v", err))
if t.UserErrorMarkPacket {
errret = gosnmp.GenErr
}
return
}
}()
isInform := false
if i.PDUType == gosnmp.InformRequest {
isInform = true
}
valtoRet, err := item.OnTrap(isInform, varItem)
if err != nil {
if t.UserErrorMarkPacket {
errret = gosnmp.GenErr
} else {
errret = gosnmp.NoError
}
return t.getPDUOctetString(item.OID, fmt.Sprintf("ERROR: %+v", err)), errret
}
return gosnmp.SnmpPDU{
Name: item.OID,
Type: item.Type,
Value: valtoRet,
Logger: &SnmpLoggerAdapter{t.Logger},
}, gosnmp.NoError
}
func (t *SubAgent) serveGetRequest(i *gosnmp.SnmpPacket) (*gosnmp.SnmpPacket, error) {
var ret gosnmp.SnmpPacket = copySnmpPacket(i)
t.Logger.Debugf("before copy: %v...After copy:%v",
i.SecurityParameters.(*gosnmp.UsmSecurityParameters),
ret.SecurityParameters.(*gosnmp.UsmSecurityParameters))
ret.PDUType = gosnmp.GetResponse
ret.Variables = []gosnmp.SnmpPDU{}
t.Logger.Debugf("i.Version == %v len(i.Variables) = %v.", i.Version, len(i.Variables))
if i.Version == gosnmp.Version3 && len(i.Variables) == 0 {
// SNMP V3 hello packet
mb, _ := t.master.getUsmSecurityParametersFromUser("")
ret.SecurityParameters = mb
ret.PDUType = gosnmp.Report
ret.Variables = append(ret.Variables, t.getPDUHelloVariable())
return &ret, nil
}
for id, varItem := range i.Variables {
item, _ := t.getForPDUValueControl(varItem.Name)
if item == nil {
if ret.Error == gosnmp.NoError {
ret.Error = gosnmp.NoSuchName
ret.ErrorIndex = uint8(id)
}
ret.Variables = append(ret.Variables, t.getPDUNoSuchInstance(varItem.Name))
continue
}
ctl, snmperr := t.getForPDUValueControlResult(item, i)
if snmperr != gosnmp.NoError && ret.Error == gosnmp.NoError {
ret.Error = snmperr
ret.ErrorIndex = uint8(id)
}
ret.Variables = append(ret.Variables, ctl)
}
return &ret, nil
}
func (t *SubAgent) serveTrap(i *gosnmp.SnmpPacket) (*gosnmp.SnmpPacket, error) {
var ret gosnmp.SnmpPacket = copySnmpPacket(i)
t.Logger.Debugf("before copy: %v...After copy:%v",
i.SecurityParameters.(*gosnmp.UsmSecurityParameters),
ret.SecurityParameters.(*gosnmp.UsmSecurityParameters))
ret.PDUType = gosnmp.GetResponse
ret.Variables = []gosnmp.SnmpPDU{}
t.Logger.Debugf("i.Version == %v len(i.Variables) = %v.", i.Version, len(i.Variables))
for id, varItem := range i.Variables {
item, _ := t.getForPDUValueControl(varItem.Name)
if item == nil {
if ret.Error == gosnmp.NoError {
ret.Error = gosnmp.NoSuchName
ret.ErrorIndex = uint8(id)
}
ret.Variables = append(ret.Variables, t.getPDUNoSuchInstance(varItem.Name))
continue
}
ctl, snmperr := t.trapForPDUValueControlResult(item, i, varItem)
if snmperr != gosnmp.NoError && ret.Error == gosnmp.NoError {
ret.Error = snmperr
ret.ErrorIndex = uint8(id)
}
ret.Variables = append(ret.Variables, ctl)
}
if i.PDUType == gosnmp.InformRequest {
return &ret, nil
} else {
return nil, nil
}
}
func (t *SubAgent) serveGetNextRequest(i *gosnmp.SnmpPacket) (*gosnmp.SnmpPacket, error) {
var ret gosnmp.SnmpPacket = copySnmpPacket(i)
ret.PDUType = gosnmp.GetResponse
ret.Variables = []gosnmp.SnmpPDU{}
length := len(i.Variables)
queryForOid := i.Variables[length-1].Name
queryForOidStriped := strings.TrimLeft(queryForOid, ".0")
t.Logger.Debugf("serveGetNextRequest of %v", queryForOid)
item, id := t.getForPDUValueControl(queryForOidStriped)
t.Logger.Debugf("t.getForPDUValueControl. query_for_oid=%v item=%v id=%v", queryForOid, item, id)
if item != nil {
id += 1
}
if id >= len(t.OIDs) {
// NOT find for the last
ret.Variables = append(ret.Variables, t.getPDUEndOfMibView(queryForOid))
return &ret, nil
}
if i.MaxRepetitions != 0 {
length = int(i.MaxRepetitions)
}
if length+id > len(t.OIDs) {
length = len(t.OIDs) - id
}
t.Logger.Debugf("i.Variables[id: length]. id=%v length =%v. len(t.OIDs)=%v", id, length, len(t.OIDs))
iid := id
for {
if iid >= len(t.OIDs) {
break
}
item := t.OIDs[iid]
if len(ret.Variables) >= length {
break
}
if item.NonWalkable || item.OnGet == nil {
t.Logger.Debugf("getnext: oid=%v. skip for non walkable", item.OID)
iid += 1
continue // skip non-walkable items
}
ctl, snmperr := t.getForPDUValueControlResult(item, i)
if snmperr != gosnmp.NoError && ret.Error == gosnmp.NoError {
ret.Error = snmperr
ret.ErrorIndex = uint8(iid)
}
t.Logger.Debugf("getnext: append oid=%v. result=%v err=%v", item.OID, ctl, snmperr)
ret.Variables = append(ret.Variables, ctl)
iid += 1
}
if len(ret.Variables) == 0 {
// NOT find for the last
ret.Variables = append(ret.Variables, t.getPDUEndOfMibView(queryForOid))
}
return &ret, nil
}
// serveSetRequest for SetReqeust.
// will just Return GetResponse for Fullily SUCCESS
func (t *SubAgent) serveSetRequest(i *gosnmp.SnmpPacket) (*gosnmp.SnmpPacket, error) {
var ret gosnmp.SnmpPacket = copySnmpPacket(i)
ret.PDUType = gosnmp.GetResponse
ret.Variables = []gosnmp.SnmpPDU{}
for id, varItem := range i.Variables {
item, _ := t.getForPDUValueControl(varItem.Name)
if item == nil {
if ret.Error == gosnmp.NoError {
ret.Error = gosnmp.NoSuchName
ret.ErrorIndex = uint8(id)
}
ret.Variables = append(ret.Variables, t.getPDUNoSuchInstance(varItem.Name))
continue
}
if t.checkPermission(item, i) != PermissionAllowanceAllowed {
if ret.Error == gosnmp.NoError {
ret.Error = gosnmp.NoAccess
ret.ErrorIndex = uint8(id)
}
ret.Variables = append(ret.Variables, t.getPDUNil(varItem.Name))
continue
}
if item.OnSet == nil {
if ret.Error == gosnmp.NoError {
ret.Error = gosnmp.ReadOnly
ret.ErrorIndex = uint8(id)
}
ret.Variables = append(ret.Variables, t.getPDUNil(varItem.Name))
continue
}
func() {
defer func() {
// panic in onset
if err := recover(); err != nil {
if t.UserErrorMarkPacket && ret.Error == gosnmp.NoError {
ret.Error = gosnmp.GenErr
ret.ErrorIndex = uint8(id)
}
ret.Variables = append(ret.Variables,
t.getPDUOctetString(varItem.Name, fmt.Sprintf("ERROR: %+v", err)))
}
}()
if err := item.OnSet(varItem.Value); err != nil {
if t.UserErrorMarkPacket && ret.Error == gosnmp.NoError {
ret.Error = gosnmp.GenErr
ret.ErrorIndex = uint8(id)
}
ret.Variables = append(ret.Variables,
t.getPDUOctetString(varItem.Name, fmt.Sprintf("ERROR: %+v", err)))
return
} else {
ret.Variables = append(ret.Variables, varItem)
}
}()
}
return &ret, nil
}
func (t *SubAgent) getForPDUValueControl(oid string) (*PDUValueControlItem, int) {
toQuery := oidToByteString(oid)
i := sort.Search(len(t.OIDs), func(i int) bool {
thisOid := oidToByteString(t.OIDs[i].OID)
return thisOid >= toQuery
})
if i < len(t.OIDs) {
thisOid := oidToByteString(t.OIDs[i].OID)
if thisOid == toQuery {
return t.OIDs[i], i
}
}
return nil, i
}