Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
f3466e3
refactor: name receivers and locals after the current types
ilyam8 Nov 11, 2026
c7e2ae7
refactor: one file per responsibility for the client and the message
ilyam8 Nov 11, 2026
bd0fb73
refactor: split the SNMPv3 header, scoped PDU, PDU fields and reply c…
ilyam8 Nov 11, 2026
6fa4bc1
test: pin the USM parameters' container and the clock a reply gives
ilyam8 Nov 11, 2026
d68f871
fix: name the PDU, not a function, in the PDU decode errors
ilyam8 Nov 11, 2026
a2e0937
docs: order the package documentation from the API to the protocol
ilyam8 Nov 11, 2026
ebed9cf
docs: correct the UnknownType, MaxOids and ReadEnvelope docs; a guide…
ilyam8 Nov 11, 2026
b485895
docs: examples beside the API; the README on the client and the receiver
ilyam8 Nov 11, 2026
242aea2
chore: drop a setting for a linter that does not run and a test that …
ilyam8 Nov 11, 2026
a702f59
refactor: the client and request names the first rename missed
ilyam8 Nov 11, 2026
5b2b2fd
test: pin the msgID a failed header keeps and a discovery's time-wind…
ilyam8 Nov 11, 2026
036f334
docs: correct what the closing review found; safer examples
ilyam8 Nov 11, 2026
05963f2
fix: name the PDU in the PDU length error
ilyam8 Nov 11, 2026
6ab1d7d
docs: the receiver snippet's rate limit and the end-to-end tests' needs
ilyam8 Nov 11, 2026
b9b216e
fix: the split USM reader returns the engine ID size error alone
ilyam8 Nov 11, 2026
f9e5aac
docs: readSecurityParameters names the engine ID size it takes
ilyam8 Nov 11, 2026
757c073
docs: Close and Concurrency say which request ends with net.ErrClosed
ilyam8 Nov 12, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,6 @@ linters:
gocritic:
disabled-checks:
- exitAfterDefer
gocyclo:
min-complexity: 20
gosec:
excludes:
- G501 # Allowed for handling old SNMP security methods.
Expand All @@ -61,10 +59,10 @@ linters:
- gosec
- nolintlint
path: _test.go
# Tests, examples and the net-snmp oracle may print, log and exit.
# Tests, the examples among them, and the net-snmp oracle may print, log and exit.
- linters:
- forbidigo
path: (_test\.go$|^examples/|^netsnmp/)
path: (_test\.go$|^netsnmp/)
# Explicit declaration types are what the public API tests assert.
- linters:
- staticcheck
Expand Down
120 changes: 60 additions & 60 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,25 +26,38 @@ For support and help with this fork, open an [issue](https://github.com/netdata/

# Overview

GoSNMP has the following SNMP functions:
A client (`NewClient`) talks to one agent:

* **NewClient** - makes a client of a `Config`, which it checks, with defaults for a zero port (161), timeout (1 s) and `MaxOids` (60).
* **Get** - one or more OIDs, up to `MaxOids` (60 by default); an answer with an error-status fails it with a `*StatusError`.
* **NewClient** - makes a client of a `Config`, which it checks, with defaults for a zero port (161), timeout (1 s) and
`MaxOids` (60).
* **Connect** and **Close** - open and close the client's UDP socket; Close may end a running request.
* **Get** - one or more OIDs, up to `MaxOids`; an answer with an error-status fails it with a `*StatusError`.
* **WalkAll** - retrieve a subtree of values using GETNEXT, and how the walk ended (`WalkEnd`).
* **BulkWalkAll** - retrieve a subtree of values using GETBULK (SNMPv2c and SNMPv3 only), with the walk's max-repetitions, and how the walk ended.
* **Receiver** - decodes received traps and informs with its SNMPv3 users, by engine ID, and returns the answers the RFCs give: the Response to an inform, as its authoritative engine, and the Reports a sender discovers its engine ID and time by; the library does not listen for notifications or send answers.
* **BulkWalkAll** - retrieve a subtree of values using GETBULK (SNMPv2c and SNMPv3), with the walk's max-repetitions,
and how the walk ended.
* **ForgetEngine** - makes an SNMPv3 client discover the agent's engine again, after a request fails with
`ErrUnknownEngineID`.
* **EncodeMessage** and **DecodeMessage** - encode and decode messages for other transports and for tests.

The library writes no log or other output and never exits the process: every function reports through its results and
errors. A call that fails returns no result with its error, but a walk, which also returns the values it collected
before the error.
A receiver (`NewReceiver`) decodes the notifications a manager receives:

* **Receive** - decodes a received trap or inform with the receiver's SNMPv3 users, by engine ID, and returns the answer
the RFCs give, for the caller to send: the Response to an inform, as its authoritative engine, and the Reports a
sender discovers its engine ID and time by. The library does not listen for notifications or send answers.

Connect and the requests take a context, which bounds that call. The library writes no log or other output and never
exits the process: every function reports through its results and errors. A call that fails returns no result with
its error, but a walk, which also returns the values it collected before the error. Each error of an incoming message
matches one exported category (`errors.Is`), named after the RFC counter that counts it but for `ErrUnmatchedReply`, a
reply that does not answer the request.

Each varbind holds a `Value` of one Go type per SMI type (an Integer is an `int32`, a Counter32 a `uint32`, an IpAddress
a `netip.Addr`, ...), read through its accessor (`Int32`, `Uint32`, `IP`, ...) and built by its constructor
(`IntegerValue`, `Counter32Value`, ...); `String` prints it as `%v` printed the untyped value.

The [package documentation](https://pkg.go.dev/github.com/netdata/gosnmp) describes request attempts and timeouts,
SNMPv3 engine discovery and Reports, the Go type of each value type, and how messages are decoded.
The [package documentation](https://pkg.go.dev/github.com/netdata/gosnmp) describes the client, walks, values, errors
and the receiver, then the protocol rules: request attempts and timeouts, SNMPv3 engine discovery and Reports, keys,
and how messages are encoded and decoded.

# Installation

Expand All @@ -58,69 +71,55 @@ https://pkg.go.dev/github.com/netdata/gosnmp

# Usage

Here is the body of `examples/example/main.go`, which imports the package as `g`:
A client of an SNMPv2c agent gets two objects (`ExampleNewClient`):

```go
// NewClient makes the client of a configuration, which it checks: SNMPv2c
// to port 161 with the community "public"; MaxOids takes its default (60).
client, err := g.NewClient(g.Config{
Target: "192.168.1.10",
Port: 161,
Community: "public",
Version: g.Version2c,
Timeout: 2 * time.Second,
Retries: 3,
client, err := gosnmp.NewClient(gosnmp.Config{
Target: "192.0.2.1",
Community: "public",
Version: gosnmp.Version2c,
Timeout: 2 * time.Second,
Retries: 2,
})
if err != nil {
log.Fatalf("NewClient() err: %v", err)
log.Fatal(err) // the error names the field NewClient rejects
}
// Connect and each request take a context that bounds that call only:
// here both end within 30 seconds.
// The context bounds each call it is given: here Connect and the Get.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil {
log.Fatalf("Connect() err: %v", err)
if err = client.Connect(ctx); err != nil {
log.Fatal(err)
}
defer client.Close()

oids := []string{"1.3.6.1.2.1.1.4.0", "1.3.6.1.2.1.1.7.0"}
result, err2 := client.Get(ctx, oids) // Get accepts up to MaxOids OIDs (60 by default)
if err2 != nil {
log.Fatalf("Get() err: %v", err2)
result, err := client.Get(ctx, []string{"1.3.6.1.2.1.1.4.0", "1.3.6.1.2.1.1.7.0"}) // sysContact, sysServices
if err != nil {
log.Fatal(err)
}

for i, variable := range result.VarBinds {
fmt.Printf("%d: oid: %s ", i, variable.Name)

// Each value type has its accessor (see Value): text for an
// OctetString, a number for the integer types (Uint64 for Counter64), ...
if b, ok := variable.Value.Bytes(); ok {
fmt.Printf("string: %s\n", string(b))
} else if n, ok := variable.Value.Int64(); ok {
fmt.Printf("number: %d\n", n)
} else if n, ok := variable.Value.Uint64(); ok {
fmt.Printf("number: %d\n", n)
} else {
fmt.Printf("type: %v\n", variable.Value.Type())
}
for _, vb := range result.VarBinds {
fmt.Printf("%s = %v: %v\n", vb.Name, vb.Value.Type(), vb.Value)
}
```

Run against an agent, it prints, for example:
A receiver decodes each datagram the caller reads; the caller checks the PDU type and the community and sends the
answer, if any, Reports at a rate it limits (`reportAllowed`; all of it in `ExampleReceiver_Receive`):

```shell
% go run ./examples/example
0: oid: .1.3.6.1.2.1.1.4.0 string: Administrator
1: oid: .1.3.6.1.2.1.1.7.0 number: 104
```go
notification, response, err := receiver.Receive(buf[:n])
if err != nil {
// A rejected SNMPv3 message may get a Report that lets its sender
// discover the engine or its time: the caller decides whether to
// send it, and how often.
if response != nil && reportAllowed() {
_, _ = conn.WriteToUDP(response, from)
}
log.Printf("rejected a datagram from %v: %v", from, err)
continue
}
```

More examples, each a program under `examples/`:

* `example2` - the target from the environment, and the time a request takes
* `example3` - SNMPv3 at authPriv
* `walkexample` - BulkWalkAll
* `Hex-String` - OctetString values that are not text, printed octet by octet in decimal
`example_test.go` holds the examples, shown with the API on [pkg.go.dev](https://pkg.go.dev/github.com/netdata/gosnmp):
a Get and the errors of a failed one, an SNMPv3 client, a walk and how it ended, values, and a receiver.

# MIB Parser

Expand Down Expand Up @@ -193,9 +192,10 @@ go test -v -tags end2end ./...
```

`go test ./...` runs all unit tests, including the public API consistency tests in
`gosnmp_api_test.go`. The end-to-end integration tests in `generic_e2e_test.go` need a
running SNMP agent and the environment variables above, so they only build with the
`end2end` build tag.
`gosnmp_api_test.go`. The end-to-end tests only build with the `end2end` build tag and run when
`GOSNMP_TARGET` is set: those in `generic_e2e_test.go` against the SNMP agent the environment
variables above name, those in `receiver_e2e_test.go` with net-snmp's `snmpinform` on the `PATH`,
which the Docker image and CI install.

The generic end-to-end integration test `generic_e2e_test.go` should
work against any SNMP MIB-2 compliant host (e.g. a router, NAS box, printer).
Expand Down Expand Up @@ -235,7 +235,7 @@ go test -coverprofile cover.out ./...
go tool cover -html cover.out
```

To measure the password-to-key cache, compare the cached and uncached key derivation benchmarks:
To measure key localization with the password-to-key cache filled:

```shell
go test -run '^$' -bench 'BenchmarkUSMKeys'
Expand Down
169 changes: 169 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
// Copyright 2012 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 (
"cmp"
"fmt"
"sync"
"time"
)

const (
// MaxOids is the default of Config.MaxOids, the maximum number of OIDs in a
// Get request. MaxOids too high can cause remote devices to fail strangely. 60
// seems to be a common value that works; set Config.MaxOids to change it.
MaxOids = 60

// defaultPort and defaultTimeout are the defaults of Config.Port and
// Config.Timeout (net-snmp's timeout).
defaultPort = 161
defaultTimeout = time.Second

// defaultMaxRepetitions is the max-repetitions BulkWalkAll sends for a
// zero argument; Java SNMP uses 50, net-snmp 10.
defaultMaxRepetitions = 50
)

// Config configures a Client. NewClient checks it and fills in its
// defaults; the client keeps it as it is.
type Config struct {
// Target is the agent's host name or IP address, which Connect dials; an
// empty Target fails Connect. A client that only encodes and decodes
// messages needs none.
Target string

// Port is the agent's port; zero means 161.
Port uint16

// Version is the SNMP version: Version1, Version2c or Version3; another
// value fails NewClient. The zero value is Version1, as the version is
// encoded.
Version Version

// Community is the community of SNMPv1 and SNMPv2c messages.
Community string

// Timeout is how long each attempt of a request waits for its answer, and
// how long Connect may take to look up Target and dial; zero means 1 s.
Timeout time.Duration

// Retries is the number of attempts after the first; zero makes one
// attempt.
Retries int

// MaxOids is the maximum number of OIDs in a Get request; zero means the
// MaxOids constant.
MaxOids int

// SecurityLevel is the SNMPv3 security level: NoAuthNoPriv, AuthNoPriv or
// AuthPriv. The encoder sets the reportable flag of each message by its
// PDU type (RFC 3412 section 6.4: set for requests and informs, clear for
// the others).
SecurityLevel SecurityLevel

// User is the SNMPv3 user. What the client learns of the agent's engine
// it keeps to itself (see the package documentation, SNMPv3, and
// ForgetEngine).
User User

// ContextName is the SNMPv3 context name of requests; their context
// engine ID is the agent's engine ID.
ContextName string
}

// Client is an SNMP client: NewClient makes it from a Config, Connect opens
// its connection, and its methods send requests. A zero Client, which
// NewClient did not make, has a zero configuration without its defaults: it
// can only encode SNMPv1 messages and decode messages. A Client is not safe for
// concurrent use, Close excepted: requests share its connection, receive
// buffer and deadline, so run one request at a time, or give each goroutine
// its own Client.
type Client struct {
// config is the configuration NewClient checked, with its defaults.
config Config

// requestID and msgID count the request IDs and the SNMPv3 msgIDs from
// the random values NewClient drew.
requestID, msgID uint32

// rx is the receive buffer, allocated by the first successful Connect.
rx *receiveBuffer // has to be pointer due to https://github.com/golang/go/issues/11728

// engine is the SNMPv3 engine state requests read and commit, and
// forgetEngine reports that ForgetEngine ran since the last request
// started (startEngine).
engine engineState
forgetEngine bool

// mu guards conn and closed against Close, which may run on any
// goroutine, and attempt against the request's context, whose interrupt
// runs on a goroutine of its own: Connect and Close change conn and closed
// under it, each attempt reads them and registers itself under it.
mu sync.Mutex
// conn is the client's connection, the UDP socket Connect opened, nil
// before the first Connect and after Close. The client owns it: Close and
// a later Connect close it.
conn transport
// closed reports that Close ran since the last successful Connect.
closed bool
// attempt is the running attempt, which the request's context
// interrupts.
attempt runningAttempt
}

// NewClient returns a client of config with its defaults filled in: Port
// 161, Timeout 1 s and MaxOids the MaxOids constant for zero values. A
// Version other than the three, and a negative Timeout, Retries or MaxOids
// fail it; so do, for SNMPv3, a security level other than the three, a user
// the level does not fit (a name outside 1..32 octets, a protocol out of its
// set, a protocol the level needs missing, a protocol without a passphrase)
// and keys that do not derive (FIPS 140-only mode refuses MD5 and SHA-1). The
// SNMPv3 fields of an SNMPv1 or SNMPv2c client are not checked. Its errors
// name the field. The client keeps the configuration: nothing changes it.
func NewClient(config Config) (*Client, error) {
if err := config.check(); err != nil {
return nil, err
}
config.Port = cmp.Or(config.Port, defaultPort)
config.Timeout = cmp.Or(config.Timeout, defaultTimeout)
config.MaxOids = cmp.Or(config.MaxOids, MaxOids)
return &Client{
config: config,
requestID: randomID(),
msgID: randomID(),
engine: newEngineState(&config.User),
}, nil
}

// check checks the configuration as NewClient does.
func (c *Config) check() error {
switch {
case c.Version != Version1 && c.Version != Version2c && c.Version != Version3:
return fmt.Errorf("Config.Version is %v, not Version1, Version2c or Version3", c.Version)
case c.Timeout < 0:
return fmt.Errorf("Config.Timeout %v is negative", c.Timeout)
case c.Retries < 0:
return fmt.Errorf("Config.Retries %d is negative", c.Retries)
case c.MaxOids < 0:
return fmt.Errorf("Config.MaxOids %d is negative", c.MaxOids)
case c.Version != Version3:
return nil
}
// validate names the user's fields and the level as fields of Config.
if err := c.User.validate(c.SecurityLevel); err != nil {
return fmt.Errorf("Config.%w", err)
}
// The keys derive for the engine ID discovery finds; before it, they must
// derive all the same: FIPS 140-only mode, for one, refuses MD5 and SHA-1.
if _, err := c.User.localize(nil); err != nil {
return fmt.Errorf("Config.User: %w", err)
}
return nil
}
File renamed without changes.
Loading
Loading