forked from twsnmp/gosnmp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.go
813 lines (730 loc) · 21.1 KB
/
helper.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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
// Copyright 2012-2020 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.
// Copyright 2009 The Go 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"
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"log"
"math"
"math/big"
"net"
"os"
"strconv"
"strings"
)
// variable struct is used by decodeValue(), which is used for debugging
type variable struct {
Name []int
Type Asn1BER
Value interface{}
}
// -- helper functions (mostly) in alphabetical order --------------------------
// Check makes checking errors easy, so they actually get a minimal check
func (x *GoSNMP) Check(err error) {
if err != nil {
x.Logger.Printf("Check: %v\n", err)
os.Exit(1)
}
}
// Check makes checking errors easy, so they actually get a minimal check
func (packet *SnmpPacket) Check(err error) {
if err != nil {
packet.Logger.Printf("Check: %v\n", err)
os.Exit(1)
}
}
// Check makes checking errors easy, so they actually get a minimal check
func Check(err error) {
if err != nil {
log.Fatalf("Check: %v\n", err)
}
}
func (x *GoSNMP) decodeValue(data []byte, msg string) (*variable, error) {
retVal := &variable{}
if len(msg) > 0 {
x.logPrintf("decodeValue: msg: %s", msg)
}
if len(data) == 0 {
return nil, fmt.Errorf("err: zero byte buffer")
}
// values matching this mask have the type in subsequent byte
if data[0]&AsnExtensionID == AsnExtensionID {
if len(data) < 2 {
return nil, fmt.Errorf("bytes: % x err: truncated (data %d length %d)", data, len(data), 2)
}
data = data[1:]
}
switch Asn1BER(data[0]) {
case Integer:
// 0x02. signed
x.logPrint("decodeValue: type is Integer")
length, cursor := parseLength(data)
if length > len(data) {
return nil, fmt.Errorf("bytes: % x err: truncated (data %d length %d)", data, len(data), length)
}
var ret int
var err2 error
if ret, err2 = parseInt(data[cursor:length]); err2 != nil {
x.logPrintf("%v:", err2)
return nil, fmt.Errorf("bytes: % x err: %v", data, err2)
}
retVal.Type = Integer
retVal.Value = ret
case OctetString:
// 0x04
x.logPrint("decodeValue: type is OctetString")
length, cursor := parseLength(data)
if length > len(data) {
return nil, fmt.Errorf("bytes: % x err: truncated (data %d length %d)", data, len(data), length)
}
retVal.Type = OctetString
retVal.Value = string(data[cursor:length])
case Null:
// 0x05
x.logPrint("decodeValue: type is Null")
retVal.Type = Null
retVal.Value = nil
case ObjectIdentifier:
// 0x06
x.logPrint("decodeValue: type is ObjectIdentifier")
rawOid, _, err2 := parseRawField(x.Logger, data, "OID")
if err2 != nil {
return nil, fmt.Errorf("error parsing OID Value: %s", err2.Error())
}
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)
}
retVal.Type = ObjectIdentifier
retVal.Value = oidToString(oid)
case IPAddress:
// 0x40
x.logPrint("decodeValue: type is IPAddress")
retVal.Type = IPAddress
if len(data) < 2 {
return nil, fmt.Errorf("not enough data for ipv4 address: %x", data)
}
switch data[1] {
case 0: // real life, buggy devices returning bad data
retVal.Value = nil
return retVal, nil
case 4: // IPv4
if len(data) < 6 {
return nil, fmt.Errorf("not enough data for ipv4 address: %x", data)
}
retVal.Value = net.IPv4(data[2], data[3], data[4], data[5]).String()
case 16: // IPv6
if len(data) < 18 {
return nil, fmt.Errorf("not enough data for ipv6 address: %x", data)
}
d := make(net.IP, 16)
copy(d, data[2:17])
retVal.Value = d.String()
default:
return nil, fmt.Errorf("got ipaddress len %d, expected 4 or 16", data[1])
}
case Counter32:
// 0x41. unsigned
x.logPrint("decodeValue: type is Counter32")
length, cursor := parseLength(data)
if length > len(data) {
return nil, fmt.Errorf("not enough data for Counter32 %x (data %d length %d)", data, len(data), length)
}
ret, err2 := parseUint(data[cursor:length])
if err2 != nil {
x.logPrintf("decodeValue: err is %v", err2)
break
}
retVal.Type = Counter32
retVal.Value = ret
case Gauge32:
// 0x42. unsigned
x.logPrint("decodeValue: type is Gauge32")
length, cursor := parseLength(data)
if length > len(data) {
return nil, fmt.Errorf("not enough data for Gauge32 %x (data %d length %d)", data, len(data), length)
}
ret, err2 := parseUint(data[cursor:length])
if err2 != nil {
x.logPrintf("decodeValue: err is %v", err2)
break
}
retVal.Type = Gauge32
retVal.Value = ret
case TimeTicks:
// 0x43
x.logPrint("decodeValue: type is TimeTicks")
length, cursor := parseLength(data)
if length > len(data) {
return nil, fmt.Errorf("not enough data for TimeTicks %x (data %d length %d)", data, len(data), length)
}
ret, err2 := parseUint32(data[cursor:length])
if err2 != nil {
x.logPrintf("decodeValue: err is %v", err2)
break
}
retVal.Type = TimeTicks
retVal.Value = ret
case Opaque:
// 0x44
x.logPrint("decodeValue: type is Opaque")
length, cursor := parseLength(data)
if length > len(data) {
return nil, fmt.Errorf("not enough data for Opaque %x (data %d length %d)", data, len(data), length)
}
opaqueData := data[cursor:length]
// recursively decode opaque data
return x.decodeValue(opaqueData, msg)
case Counter64:
// 0x46
x.logPrint("decodeValue: type is Counter64")
length, cursor := parseLength(data)
if length > len(data) {
return nil, fmt.Errorf("not enough data for Counter64 %x (data %d length %d)", data, len(data), length)
}
ret, err2 := parseUint64(data[cursor:length])
if err2 != nil {
x.logPrintf("decodeValue: err is %v", err2)
break
}
retVal.Type = Counter64
retVal.Value = ret
case OpaqueFloat:
// 0x78
x.logPrint("decodeValue: type is OpaqueFloat")
length, cursor := parseLength(data)
if length > len(data) {
return nil, fmt.Errorf("not enough data for OpaqueFloat %x (data %d length %d)", data, len(data), length)
}
var err error
retVal.Type = OpaqueFloat
retVal.Value, err = parseFloat32(data[cursor:length])
if err != nil {
return nil, err
}
case OpaqueDouble:
// 0x79
x.logPrint("decodeValue: type is OpaqueDouble")
length, cursor := parseLength(data)
if length > len(data) {
return nil, fmt.Errorf("not enough data for OpaqueDouble %x (data %d length %d)", data, len(data), length)
}
var err error
retVal.Type = OpaqueDouble
retVal.Value, err = parseFloat64(data[cursor:length])
if err != nil {
return nil, err
}
case NoSuchObject:
// 0x80
x.logPrint("decodeValue: type is NoSuchObject")
retVal.Type = NoSuchObject
retVal.Value = nil
case NoSuchInstance:
// 0x81
x.logPrint("decodeValue: type is NoSuchInstance")
retVal.Type = NoSuchInstance
retVal.Value = nil
case EndOfMibView:
// 0x82
x.logPrint("decodeValue: type is EndOfMibView")
retVal.Type = EndOfMibView
retVal.Value = nil
default:
x.logPrintf("decodeValue: type %x isn't implemented", data[0])
retVal.Type = UnknownType
retVal.Value = nil
}
x.logPrintf("decodeValue: value is %#v", retVal.Value)
return retVal, nil
}
func marshalUvarInt(x uint32) []byte {
buf := make([]byte, 4)
binary.BigEndian.PutUint32(buf, x)
i := 0
for ; i < 3; i++ {
if buf[i] != 0 {
break
}
}
buf = buf[i:]
// if the highest bit in buf is set and x is not negative - prepend a byte to make it positive
if len(buf) > 0 && buf[0]&0x80 > 0 {
buf = append([]byte{0}, buf...)
}
return buf
}
func marshalBase128Int(out io.ByteWriter, n int64) (err error) {
if n == 0 {
err = out.WriteByte(0)
return
}
l := 0
for i := n; i > 0; i >>= 7 {
l++
}
for i := l - 1; i >= 0; i-- {
o := byte(n >> uint(i*7))
o &= 0x7f
if i != 0 {
o |= 0x80
}
err = out.WriteByte(o)
if err != nil {
return
}
}
return nil
}
/*
snmp Integer32 and INTEGER:
-2^31 and 2^31-1 inclusive (-2147483648 to 2147483647 decimal)
(FYI https://groups.google.com/forum/#!topic/comp.protocols.snmp/1xaAMzCe_hE)
versus:
snmp Counter32, Gauge32, TimeTicks, Unsigned32: (below)
non-negative integer, maximum value of 2^32-1 (4294967295 decimal)
*/
// marshalInt32 builds a byte representation of a signed 32 bit int in BigEndian form
// ie -2^31 and 2^31-1 inclusive (-2147483648 to 2147483647 decimal)
func marshalInt32(value int) (rs []byte, err error) {
rs = make([]byte, 4)
if 0 <= value && value <= 2147483647 {
binary.BigEndian.PutUint32(rs, uint32(value))
if value < 0x80 {
return rs[3:], nil
}
if value < 0x8000 {
return rs[2:], nil
}
if value < 0x800000 {
return rs[1:], nil
}
return rs, nil
}
if -2147483648 <= value && value < 0 {
value = ^value
binary.BigEndian.PutUint32(rs, uint32(value))
for k, v := range rs {
rs[k] = ^v
}
return rs, nil
}
return nil, fmt.Errorf("unable to marshal %d", value)
}
func marshalUint64(v interface{}) ([]byte, error) {
bs := make([]byte, 8)
source := v.(uint64)
binary.BigEndian.PutUint64(bs, source) // will panic on failure
// truncate leading zeros. Cleaner technique?
return bytes.TrimLeft(bs, "\x00"), nil
//return bs, nil
}
// Counter32, Gauge32, TimeTicks, Unsigned32
func marshalUint32(v interface{}) ([]byte, error) {
bs := make([]byte, 4)
var source uint32
switch val := v.(type) {
case uint32:
source = val
case uint:
source = uint32(val)
// We could do others here, but coercing from anything else is dangerous.
// Even uint could be 64 bits, though in practice nothing we work with here
// is.
default:
return nil, fmt.Errorf("unable to marshal %T to uint32", v)
}
binary.BigEndian.PutUint32(bs, source) // will panic on failure
// truncate leading zeros. Cleaner technique?
if source < 0x80 {
return bs[3:], nil
}
if source < 0x8000 {
return bs[2:], nil
}
if source < 0x800000 {
return bs[1:], nil
}
return bs, nil
}
func marshalFloat32(v interface{}) ([]byte, error) {
//func Float64bits(f float64) uint64
source := v.(float32)
i32 := math.Float32bits(source)
return marshalUint32(i32)
}
func marshalFloat64(v interface{}) ([]byte, error) {
//func Float64bits(f float64) uint64
source := v.(float64)
i64 := math.Float64bits(source)
return marshalUint64(i64)
}
// marshalLength builds a byte representation of length
//
// http://luca.ntop.org/Teaching/Appunti/asn1.html
//
// Length octets. There are two forms: short (for lengths between 0 and 127),
// and long definite (for lengths between 0 and 2^1008 -1).
//
// * Short form. One octet. Bit 8 has value "0" and bits 7-1 give the length.
// * Long form. Two to 127 octets. Bit 8 of first octet has value "1" and bits
// 7-1 give the number of additional length octets. Second and following
// octets give the length, base 256, most significant digit first.
func marshalLength(length int) ([]byte, error) {
// more convenient to pass length as int than uint64. Therefore check < 0
if length < 0 {
return nil, fmt.Errorf("length must be greater than zero")
} else if length < 127 {
return []byte{byte(length)}, nil
}
buf := new(bytes.Buffer)
err := binary.Write(buf, binary.BigEndian, uint64(length))
if err != nil {
return nil, err
}
bufBytes := buf.Bytes()
// strip leading zeros
for idx, octect := range bufBytes {
if octect != 00 {
bufBytes = bufBytes[idx:]
break
}
}
header := []byte{byte(128 | len(bufBytes))}
return append(header, bufBytes...), nil
}
func marshalObjectIdentifier(oid []int) (ret []byte, err error) {
out := new(bytes.Buffer)
if len(oid) < 2 || oid[0] > 6 || oid[1] >= 40 {
return nil, errors.New("invalid object identifier")
}
err = out.WriteByte(byte(oid[0]*40 + oid[1]))
if err != nil {
return
}
for i := 2; i < len(oid); i++ {
err = marshalBase128Int(out, int64(oid[i]))
if err != nil {
return
}
}
ret = out.Bytes()
return
}
func marshalOID(oid string) ([]byte, error) {
var err error
// Encode the oid
oid = strings.Trim(oid, ".")
oidParts := strings.Split(oid, ".")
oidBytes := make([]int, len(oidParts))
// Convert the string OID to an array of integers
for i := 0; i < len(oidParts); i++ {
oidBytes[i], err = strconv.Atoi(oidParts[i])
if err != nil {
return nil, fmt.Errorf("unable to parse OID: %s", err.Error())
}
}
mOid, err := marshalObjectIdentifier(oidBytes)
if err != nil {
return nil, fmt.Errorf("unable to marshal OID: %s", err.Error())
}
return mOid, err
}
func oidToString(oid []int) (ret string) {
oidAsString := make([]string, len(oid)+1)
// used for appending of the first dot
oidAsString[0] = ""
for i := range oid {
oidAsString[i+1] = strconv.Itoa(oid[i])
}
return strings.Join(oidAsString, ".")
}
// TODO no tests
func ipv4toBytes(ip net.IP) []byte {
return []byte(ip)[12:]
}
// parseBase128Int parses a base-128 encoded int from the given offset in the
// given byte slice. It returns the value and the new offset.
func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err error) {
offset = initOffset
for shifted := 0; offset < len(bytes); shifted++ {
if shifted > 4 {
err = fmt.Errorf("structural error: base 128 integer too large")
return
}
ret <<= 7
b := bytes[offset]
ret |= int(b & 0x7f)
offset++
if b&0x80 == 0 {
return
}
}
err = fmt.Errorf("syntax error: truncated base 128 integer")
return
}
// parseInt64 treats the given bytes as a big-endian, signed integer and
// returns the result.
func parseInt64(bytes []byte) (ret int64, err error) {
if len(bytes) > 8 {
// We'll overflow an int64 in this case.
err = errors.New("integer too large")
return
}
for bytesRead := 0; bytesRead < len(bytes); bytesRead++ {
ret <<= 8
ret |= int64(bytes[bytesRead])
}
// Shift up and down in order to sign extend the result.
ret <<= 64 - uint8(len(bytes))*8
ret >>= 64 - uint8(len(bytes))*8
return
}
// parseInt treats the given bytes as a big-endian, signed integer and returns
// the result.
func parseInt(bytes []byte) (int, error) {
ret64, err := parseInt64(bytes)
if err != nil {
return 0, err
}
if ret64 != int64(int(ret64)) {
return 0, errors.New("integer too large")
}
return int(ret64), nil
}
// parseLength parses and calculates an snmp packet length
//
// http://luca.ntop.org/Teaching/Appunti/asn1.html
//
// Length octets. There are two forms: short (for lengths between 0 and 127),
// and long definite (for lengths between 0 and 2^1008 -1).
//
// * Short form. One octet. Bit 8 has value "0" and bits 7-1 give the length.
// * Long form. Two to 127 octets. Bit 8 of first octet has value "1" and bits
// 7-1 give the number of additional length octets. Second and following
// octets give the length, base 256, most significant digit first.
func parseLength(bytes []byte) (length int, cursor int) {
switch {
case len(bytes) <= 2:
// handle null octet strings ie "0x04 0x00"
cursor = len(bytes)
length = len(bytes)
case int(bytes[1]) <= 127:
length = int(bytes[1])
length += 2
cursor += 2
default:
numOctets := int(bytes[1]) & 127
for i := 0; i < numOctets; i++ {
length <<= 8
length += int(bytes[2+i])
}
length += 2 + numOctets
cursor += 2 + numOctets
}
return length, cursor
}
// parseObjectIdentifier parses an OBJECT IDENTIFIER from the given bytes and
// returns it. An object identifier is a sequence of variable length integers
// that are assigned in a hierarchy.
func parseObjectIdentifier(bytes []byte) (s []int, err error) {
if len(bytes) == 0 {
return []int{0}, nil
}
// In the worst case, we get two elements from the first byte (which is
// encoded differently) and then every varint is a single byte long.
s = make([]int, len(bytes)+1)
// The first byte is 40*value1 + value2:
s[0] = int(bytes[0]) / 40
s[1] = int(bytes[0]) % 40
i := 2
for offset := 1; offset < len(bytes); i++ {
var v int
v, offset, err = parseBase128Int(bytes, offset)
if err != nil {
return
}
s[i] = v
}
s = s[0:i]
return
}
func parseRawField(logger Logger, data []byte, msg string) (interface{}, int, error) {
if len(data) == 0 {
return nil, 0, fmt.Errorf("empty data passed to parseRawField")
}
logger.Printf("parseRawField: %s", msg)
switch Asn1BER(data[0]) {
case Integer:
length, cursor := parseLength(data)
if length > len(data) {
return nil, 0, fmt.Errorf("not enough data for Integer (%d vs %d): %x", length, len(data), data)
}
i, err := parseInt(data[cursor:length])
if err != nil {
return nil, 0, fmt.Errorf("unable to parse raw INTEGER: %x err: %v", data, err)
}
return i, length, nil
case OctetString:
length, cursor := parseLength(data)
if length > len(data) {
return nil, 0, fmt.Errorf("not enough data for OctetString (%d vs %d): %x", length, len(data), data)
}
return string(data[cursor:length]), length, nil
case ObjectIdentifier:
length, cursor := parseLength(data)
if length > len(data) {
return nil, 0, fmt.Errorf("not enough data for OID (%d vs %d): %x", length, len(data), data)
}
oid, err := parseObjectIdentifier(data[cursor:length])
return oid, length, err
case IPAddress:
length, _ := parseLength(data)
if len(data) < 2 {
return nil, 0, fmt.Errorf("not enough data for ipv4 address: %x", data)
}
switch data[1] {
case 0: // real life, buggy devices returning bad data
return nil, length, nil
case 4: // IPv4
if len(data) < 6 {
return nil, 0, fmt.Errorf("not enough data for ipv4 address: %x", data)
}
return net.IPv4(data[2], data[3], data[4], data[5]).String(), length, nil
default:
return nil, 0, fmt.Errorf("got ipaddress len %d, expected 4", data[1])
}
case TimeTicks:
length, cursor := parseLength(data)
if length > len(data) {
return nil, 0, fmt.Errorf("not enough data for TimeTicks (%d vs %d): %x", length, len(data), data)
}
ret, err := parseUint(data[cursor:length])
if err != nil {
return nil, 0, fmt.Errorf("error in parseUint: %s", err)
}
return ret, length, nil
}
return nil, 0, fmt.Errorf("unknown field type: %x", data[0])
}
// parseUint64 treats the given bytes as a big-endian, unsigned integer and returns
// the result.
func parseUint64(bytes []byte) (ret uint64, err error) {
if len(bytes) > 9 || (len(bytes) > 8 && bytes[0] != 0x0) {
// We'll overflow a uint64 in this case.
err = errors.New("integer too large")
return
}
for bytesRead := 0; bytesRead < len(bytes); bytesRead++ {
ret <<= 8
ret |= uint64(bytes[bytesRead])
}
return
}
// parseUint32 treats the given bytes as a big-endian, signed integer and returns
// the result.
func parseUint32(bytes []byte) (uint32, error) {
ret, err := parseUint(bytes)
if err != nil {
return 0, err
}
return uint32(ret), nil
}
// parseUint treats the given bytes as a big-endian, signed integer and returns
// the result.
func parseUint(bytes []byte) (uint, error) {
ret64, err := parseUint64(bytes)
if err != nil {
return 0, err
}
if ret64 != uint64(uint(ret64)) {
return 0, errors.New("integer too large")
}
return uint(ret64), nil
}
func parseFloat32(bytes []byte) (ret float32, err error) {
if len(bytes) > 4 {
// We'll overflow a uint64 in this case.
err = errors.New("float too large")
return
}
ret = math.Float32frombits(binary.BigEndian.Uint32(bytes))
return
}
func parseFloat64(bytes []byte) (ret float64, err error) {
if len(bytes) > 8 {
// We'll overflow a uint64 in this case.
err = errors.New("float too large")
return
}
ret = math.Float64frombits(binary.BigEndian.Uint64(bytes))
return
}
// Issue 4389: math/big: add SetUint64 and Uint64 functions to *Int
//
// uint64ToBigInt copied from: http://github.com/cznic/mathutil/blob/master/mathutil.go#L341
//
// replace with Uint64ToBigInt or equivalent when using Go 1.1
//nolint:gochecknoglobals
var uint64ToBigIntDelta big.Int
func init() {
uint64ToBigIntDelta.SetBit(&uint64ToBigIntDelta, 63, 1)
}
func uint64ToBigInt(n uint64) *big.Int {
if n <= math.MaxInt64 {
return big.NewInt(int64(n))
}
y := big.NewInt(int64(n - uint64(math.MaxInt64) - 1))
return y.Add(y, &uint64ToBigIntDelta)
}
// -- Bit String ---------------------------------------------------------------
// BitStringValue is the structure to use when you want an ASN.1 BIT STRING type. A
// bit string is padded up to the nearest byte in memory and the number of
// valid bits is recorded. Padding bits will be zero.
type BitStringValue struct {
Bytes []byte // bits packed into bytes.
BitLength int // length in bits.
}
// At returns the bit at the given index. If the index is out of range it
// returns false.
func (b BitStringValue) At(i int) int {
if i < 0 || i >= b.BitLength {
return 0
}
x := i / 8
y := 7 - uint(i%8)
return int(b.Bytes[x]>>y) & 1
}
// RightAlign returns a slice where the padding bits are at the beginning. The
// slice may share memory with the BitString.
func (b BitStringValue) RightAlign() []byte {
shift := uint(8 - (b.BitLength % 8))
if shift == 8 || len(b.Bytes) == 0 {
return b.Bytes
}
a := make([]byte, len(b.Bytes))
a[0] = b.Bytes[0] >> shift
for i := 1; i < len(b.Bytes); i++ {
a[i] = b.Bytes[i-1] << (8 - shift)
a[i] |= b.Bytes[i] >> shift
}
return a
}
// -- SnmpVersion --------------------------------------------------------------
func (s SnmpVersion) String() string {
if s == Version1 {
return "1"
} else if s == Version2c {
return "2c"
}
return "3"
}