forked from gosnmp/gosnmp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
marshal.go
523 lines (449 loc) · 13.5 KB
/
marshal.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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
// Copyright 2012-2014 The GoSNMP Authors. All rights reserved. Use of this
// source code is governed by a BSD-style license that can be found in the
// LICENSE file.
package gosnmp
import (
"bytes"
"encoding/asn1"
"encoding/binary"
"fmt"
"io/ioutil"
"log"
"sync/atomic"
"time"
)
//
// Remaining globals and definitions located here.
// See http://www.rane.com/note161.html for a succint description of the SNMP
// protocol.
//
// SnmpVersion 1 and 2c implemented, 3 planned
type SnmpVersion uint8
// SnmpVersion 1 and 2c implemented, 3 planned
const (
Version1 SnmpVersion = 0x0
Version2c SnmpVersion = 0x1
)
// SnmpPacket struct represents the entire SNMP Message or Sequence at the
// application layer.
type SnmpPacket struct {
Version SnmpVersion
Community string
PDUType PDUType
RequestID uint32
Error uint8
ErrorIndex uint8
NonRepeaters uint8
MaxRepetitions uint8
Variables []SnmpPDU
}
// VarBind struct represents an SNMP Varbind.
type VarBind struct {
Name asn1.ObjectIdentifier
Value asn1.RawValue
}
// PDUType describes which SNMP Protocol Data Unit is being sent.
type PDUType byte
// The currently supported PDUType's
const (
Sequence PDUType = 0x30
GetRequest PDUType = 0xa0
GetNextRequest PDUType = 0xa1
GetResponse PDUType = 0xa2
SetRequest PDUType = 0xa3
Trap PDUType = 0xa4
GetBulkRequest PDUType = 0xa5
)
const (
rxBufSize = 65536
)
// Logger is an interface used for debugging. Both Print and
// Printf have the same interfaces as Package Log in the std library. The
// Logger interface is small to give you flexibility in how you do
// your debugging.
//
// For verbose logging to stdout:
//
// gosnmp_logger = log.New(os.Stdout, "", 0)
type Logger interface {
Print(v ...interface{})
Printf(format string, v ...interface{})
}
// slog is a global variable that is used for debug logging
var slog Logger
// generic "sender"
func (x *GoSNMP) send(pdus []SnmpPDU, packetOut *SnmpPacket) (result *SnmpPacket, err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("recover: %v", e)
}
}()
if x.Conn == nil {
return nil, fmt.Errorf("&GoSNMP.Conn is missing. Provide a connection or use Connect()")
}
if x.Logger == nil {
x.Logger = log.New(ioutil.Discard, "", 0)
}
slog = x.Logger // global variable for debug logging
finalDeadline := time.Now().Add(x.Timeout)
if x.Retries < 0 {
x.Retries = 0
}
allReqIDs := make([]uint32, 0, x.Retries+1)
for retries := 0; ; retries++ {
if retries > 0 {
if LoggingDisabled != true {
slog.Printf("Retry number %d. Last error was: %v", retries, err)
}
if time.Now().After(finalDeadline) {
err = fmt.Errorf("Request timeout (after %d retries)", retries-1)
break
}
if retries > x.Retries {
// Report last error
break
}
}
err = nil
reqDeadline := time.Now().Add(x.Timeout / time.Duration(x.Retries+1))
x.Conn.SetDeadline(reqDeadline)
// Request ID is an atomic counter (started at a random value)
reqID := atomic.AddUint32(&(x.requestID), 1)
allReqIDs = append(allReqIDs, reqID)
var outBuf []byte
outBuf, err = packetOut.marshalMsg(pdus, packetOut.PDUType, reqID)
if err != nil {
// Don't retry - not going to get any better!
err = fmt.Errorf("marshal: %v", err)
break
}
_, err = x.Conn.Write(outBuf)
if err != nil {
err = fmt.Errorf("Error writing to socket: %s", err.Error())
continue
}
// FIXME: If our packet exceeds our buf size we'll get a partial read
// and this request, and the next will fail. The correct logic would be
// to realloc and read more if pack len > buff size.
resp := make([]byte, rxBufSize, rxBufSize)
var n int
n, err = x.Conn.Read(resp)
if err != nil {
err = fmt.Errorf("Error reading from UDP: %s", err.Error())
continue
}
result, err = unmarshal(resp[:n])
if err != nil {
err = fmt.Errorf("Unable to decode packet: %s", err.Error())
continue
}
if result == nil || len(result.Variables) < 1 {
err = fmt.Errorf("Unable to decode packet: nil")
continue
}
validID := false
for _, id := range allReqIDs {
if id == result.RequestID {
validID = true
}
}
if !validID {
err = fmt.Errorf("Out of order response")
continue
}
// Success!
return result, nil
}
// Return last error
return nil, err
}
// -- Marshalling Logic --------------------------------------------------------
// marshal an SNMP message
func (packet *SnmpPacket) marshalMsg(pdus []SnmpPDU,
pdutype PDUType, requestid uint32) ([]byte, error) {
buf := new(bytes.Buffer)
// version
buf.Write([]byte{2, 1, byte(packet.Version)})
// community
buf.Write([]byte{4, uint8(len(packet.Community))})
buf.WriteString(packet.Community)
// pdu
pdu, err := packet.marshalPDU(pdus, requestid)
if err != nil {
return nil, err
}
buf.Write(pdu)
// build up resulting msg - sequence, length then the tail (buf)
msg := new(bytes.Buffer)
msg.WriteByte(byte(Sequence))
bufLengthBytes, err2 := marshalLength(buf.Len())
if err2 != nil {
return nil, err2
}
msg.Write(bufLengthBytes)
buf.WriteTo(msg) // reverse logic - want to do msg.Write(buf)
return msg.Bytes(), nil
}
// marshal a PDU
func (packet *SnmpPacket) marshalPDU(pdus []SnmpPDU, requestid uint32) ([]byte, error) {
buf := new(bytes.Buffer)
// requestid
buf.Write([]byte{2, 4})
err := binary.Write(buf, binary.BigEndian, requestid)
if err != nil {
return nil, err
}
if packet.PDUType == GetBulkRequest {
// non repeaters
buf.Write([]byte{2, 1, packet.NonRepeaters})
// max repetitions
buf.Write([]byte{2, 1, packet.MaxRepetitions})
} else { // get and getnext have same packet format
// error
buf.Write([]byte{2, 1, 0})
// error index
buf.Write([]byte{2, 1, 0})
}
// varbind list
vbl, err := packet.marshalVBL(pdus)
if err != nil {
return nil, err
}
buf.Write(vbl)
// build up resulting pdu - request type, length, then the tail (buf)
pdu := new(bytes.Buffer)
pdu.WriteByte(byte(packet.PDUType))
bufLengthBytes, err2 := marshalLength(buf.Len())
if err2 != nil {
return nil, err2
}
pdu.Write(bufLengthBytes)
buf.WriteTo(pdu) // reverse logic - want to do pdu.Write(buf)
return pdu.Bytes(), nil
}
// marshal a varbind list
func (packet *SnmpPacket) marshalVBL(pdus []SnmpPDU) ([]byte, error) {
vblBuf := new(bytes.Buffer)
for _, pdu := range pdus {
vb, err := marshalVarbind(&pdu)
if err != nil {
return nil, err
}
vblBuf.Write(vb)
}
vblBytes := vblBuf.Bytes()
vblLengthBytes, err := marshalLength(len(vblBytes))
if err != nil {
return nil, err
}
// FIX does bytes.Buffer give better performance than byte slices?
result := []byte{byte(Sequence)}
result = append(result, vblLengthBytes...)
result = append(result, vblBytes...)
return result, nil
}
// marshal a varbind
func marshalVarbind(pdu *SnmpPDU) ([]byte, error) {
oid, err := marshalOID(pdu.Name)
if err != nil {
return nil, err
}
pduBuf := new(bytes.Buffer)
tmpBuf := new(bytes.Buffer)
// Marshal the PDU type into the appropriate BER
switch pdu.Type {
case Null:
pduBuf.Write([]byte{byte(Sequence), byte(len(oid) + 4)})
pduBuf.Write([]byte{byte(ObjectIdentifier), byte(len(oid))})
pduBuf.Write(oid)
pduBuf.Write([]byte{Null, 0x00})
case Integer:
// Oid
tmpBuf.Write([]byte{byte(ObjectIdentifier), byte(len(oid))})
tmpBuf.Write(oid)
// Integer
intBytes := []byte{byte(pdu.Value.(int))}
tmpBuf.Write([]byte{byte(Integer), byte(len(intBytes))})
tmpBuf.Write(intBytes)
// Sequence, length of oid + integer, then oid/integer data
pduBuf.WriteByte(byte(Sequence))
pduBuf.WriteByte(byte(len(oid) + len(intBytes) + 4))
pduBuf.Write(tmpBuf.Bytes())
default:
return nil, fmt.Errorf("Unable to marshal PDU: unknown BER type %d", pdu.Type)
}
return pduBuf.Bytes(), nil
}
// -- Unmarshalling Logic ------------------------------------------------------
func unmarshal(packet []byte) (*SnmpPacket, error) {
response := new(SnmpPacket)
response.Variables = make([]SnmpPDU, 0, 5)
// Start parsing the packet
cursor := 0
// First bytes should be 0x30
if PDUType(packet[0]) != Sequence {
return nil, fmt.Errorf("Invalid packet header\n")
}
length, cursor := parseLength(packet)
if len(packet) != length {
return nil, fmt.Errorf("Error verifying packet sanity: Got %d Expected: %d\n", len(packet), length)
}
if LoggingDisabled != true {
slog.Printf("Packet sanity verified, we got all the bytes (%d)", length)
}
// Parse SNMP Version
rawVersion, count, err := parseRawField(packet[cursor:], "version")
if err != nil {
return nil, fmt.Errorf("Error parsing SNMP packet version: %s", err.Error())
}
cursor += count
if version, ok := rawVersion.(int); ok {
response.Version = SnmpVersion(version)
if LoggingDisabled != true {
slog.Printf("Parsed version %d", version)
}
}
// Parse community
rawCommunity, count, err := parseRawField(packet[cursor:], "community")
cursor += count
if community, ok := rawCommunity.(string); ok {
response.Community = community
if LoggingDisabled != true {
slog.Printf("Parsed community %s", community)
}
}
// Parse SNMP packet type
requestType := PDUType(packet[cursor])
switch requestType {
// known, supported types
case GetResponse, GetNextRequest, GetBulkRequest:
response, err = unmarshalResponse(packet[cursor:], response, length, requestType)
if err != nil {
return nil, fmt.Errorf("Error in unmarshalResponse: %s", err.Error())
}
default:
return nil, fmt.Errorf("Unknown PDUType %#x")
}
return response, nil
}
func unmarshalResponse(packet []byte, response *SnmpPacket, length int, requestType PDUType) (*SnmpPacket, error) {
cursor := 0
dumpBytes1(packet, "SNMP Packet is GET RESPONSE", 16)
response.PDUType = requestType
getResponseLength, cursor := parseLength(packet)
if len(packet) != getResponseLength {
return nil, fmt.Errorf("Error verifying Response sanity: Got %d Expected: %d\n", len(packet), getResponseLength)
}
if LoggingDisabled != true {
slog.Printf("getResponseLength: %d", getResponseLength)
}
// Parse Request-ID
rawRequestID, count, err := parseRawField(packet[cursor:], "request id")
if err != nil {
return nil, fmt.Errorf("Error parsing SNMP packet request ID: %s", err.Error())
}
cursor += count
if requestid, ok := rawRequestID.(int); ok {
response.RequestID = uint32(requestid)
if LoggingDisabled != true {
slog.Printf("requestID: %d", response.RequestID)
}
}
if response.PDUType == GetBulkRequest {
// Parse Non Repeaters
rawNonRepeaters, count, err := parseRawField(packet[cursor:], "non repeaters")
if err != nil {
return nil, fmt.Errorf("Error parsing SNMP packet non repeaters: %s", err.Error())
}
cursor += count
if nonRepeaters, ok := rawNonRepeaters.(int); ok {
response.NonRepeaters = uint8(nonRepeaters)
}
// Parse Max Repetitions
rawMaxRepetitions, count, err := parseRawField(packet[cursor:], "max repetitions")
if err != nil {
return nil, fmt.Errorf("Error parsing SNMP packet max repetitions: %s", err.Error())
}
cursor += count
if maxRepetitions, ok := rawMaxRepetitions.(int); ok {
response.MaxRepetitions = uint8(maxRepetitions)
}
} else {
// Parse Error-Status
rawError, count, err := parseRawField(packet[cursor:], "error-status")
if err != nil {
return nil, fmt.Errorf("Error parsing SNMP packet error: %s", err.Error())
}
cursor += count
if errorStatus, ok := rawError.(int); ok {
response.Error = uint8(errorStatus)
if LoggingDisabled != true {
slog.Printf("errorStatus: %d", uint8(errorStatus))
}
}
// Parse Error-Index
rawErrorIndex, count, err := parseRawField(packet[cursor:], "error index")
if err != nil {
return nil, fmt.Errorf("Error parsing SNMP packet error index: %s", err.Error())
}
cursor += count
if errorindex, ok := rawErrorIndex.(int); ok {
response.ErrorIndex = uint8(errorindex)
if LoggingDisabled != true {
slog.Printf("error-index: %d", uint8(errorindex))
}
}
}
return unmarshalVBL(packet[cursor:], response, length)
}
// unmarshal a Varbind list
func unmarshalVBL(packet []byte, response *SnmpPacket,
length int) (*SnmpPacket, error) {
dumpBytes1(packet, "\n=== unmarshalVBL()", 32)
var cursor, cursorInc int
var vblLength int
if packet[cursor] != 0x30 {
return nil, fmt.Errorf("Expected a sequence when unmarshalling a VBL, got %x",
packet[cursor])
}
vblLength, cursor = parseLength(packet)
if len(packet) != vblLength {
return nil, fmt.Errorf("Error verifying: packet length %d vbl length %d\n",
len(packet), vblLength)
}
if LoggingDisabled != true {
slog.Printf("vblLength: %d", vblLength)
}
// Loop & parse Varbinds
for cursor < vblLength {
dumpBytes1(packet[cursor:], fmt.Sprintf("\nSTARTING a varbind. Cursor %d", cursor), 32)
if packet[cursor] != 0x30 {
return nil, fmt.Errorf("Expected a sequence when unmarshalling a VB, got %x", packet[cursor])
}
_, cursorInc = parseLength(packet[cursor:])
cursor += cursorInc
// Parse OID
rawOid, oidLength, err := parseRawField(packet[cursor:], "OID")
if err != nil {
return nil, fmt.Errorf("Error parsing OID Value: %s", err.Error())
}
cursor += oidLength
var oid []int
var ok bool
if oid, ok = rawOid.([]int); !ok {
return nil, fmt.Errorf("unable to type assert rawOid |%v| to []int", rawOid)
}
if LoggingDisabled != true {
slog.Printf("OID: %s", oidToString(oid))
}
// Parse Value
v, err := decodeValue(packet[cursor:], "value")
if err != nil {
return nil, fmt.Errorf("Error decoding value: %v", err)
}
valueLength, _ := parseLength(packet[cursor:])
cursor += valueLength
response.Variables = append(response.Variables, SnmpPDU{oidToString(oid), v.Type, v.Value})
}
return response, nil
}