From f3466e3c09acefddaa6b8123d229c86564988eb3 Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Wed, 11 Nov 2026 21:29:18 +0200 Subject: [PATCH 01/17] refactor: name receivers and locals after the current types The receivers and locals still carried the names of the types they held before the API's renames: the client's methods took `x`, the message's `packet`, and requests, decoded messages and varbinds were `packetOut`, `response` and `pdu`. They now read `c *Client`, `m *Message` and the short receivers of SecurityLevel, AuthProtocol and PrivProtocol; the request is `req` (also the exchange's field), the reply an attempt ends with `reply`, a message being decoded `m` and a varbind `vb`. Identifiers only: renamed with gopls, and a comparison of the token streams of every Go file, comments skipped, finds no difference but the renamed identifiers. The goldens are unchanged. --- engine.go | 90 ++++++++++++------------- engine_fuzz_test.go | 10 +-- engine_requests_test.go | 8 +-- engine_state.go | 22 +++--- engine_state_test.go | 4 +- engine_v3.go | 52 +++++++------- gosnmp.go | 24 +++---- ids.go | 12 ++-- message.go | 8 +-- pdu.go | 146 ++++++++++++++++++++-------------------- request.go | 30 ++++----- transport.go | 92 ++++++++++++------------- v3.go | 96 +++++++++++++------------- v3_parse_test.go | 8 +-- v3_usm.go | 16 ++--- v3_usm_test.go | 2 +- walk.go | 42 ++++++------ 17 files changed, 331 insertions(+), 331 deletions(-) diff --git a/engine.go b/engine.go index a6c5531..4479f00 100644 --- a/engine.go +++ b/engine.go @@ -15,7 +15,7 @@ import ( "time" ) -// send runs the request packetOut (request) within ctx and returns its +// send runs the request req within ctx and returns its // answer, a Response whose error-status is NoError, or no message with the // error of a request that fails: marked with ErrAnswered when an answer ended // it (the message request returns beside its error), requestPanicked's error @@ -28,11 +28,11 @@ import ( // request panicked: under GODEBUG=panicnil=1, recover returns nil for // panic(nil). // -// packetOut is a request of the Read Class (RFC 3411 section 2.8.1), a Get, +// req is a request of the Read Class (RFC 3411 section 2.8.1), a Get, // GetNext or GetBulk, as every request the client sends: the SNMPv3 engine // clock signs it whatever the clock's source (sourcedClock.timeFor, mayLend), // which a request that changes the agent must not take. -func (x *Client) send(ctx context.Context, packetOut *Message) (result *Message, err error) { +func (c *Client) send(ctx context.Context, req *Message) (result *Message, err error) { if ctx == nil { return nil, errNilContext } @@ -42,7 +42,7 @@ func (x *Client) send(ctx context.Context, packetOut *Message) (result *Message, err = requestPanicked(recover()) } }() - result, err = x.request(ctx, packetOut) + result, err = c.request(ctx, req) completed = true if err != nil { if result != nil { @@ -63,22 +63,22 @@ func (x *Client) send(ctx context.Context, packetOut *Message) (result *Message, // client with the agent's engine. With an error it returns // the answer that ended the request, a Report or the discovery's answer, and // no message when none did: send marks the error by it. -func (x *Client) request(ctx context.Context, packetOut *Message) (result *Message, err error) { - if _, err = x.connection(); err != nil { +func (c *Client) request(ctx context.Context, req *Message) (result *Message, err error) { + if _, err = c.connection(); err != nil { return nil, err } // sec is the engine clock and the keys the attempts carry. var sec attemptSecurity - if packetOut.Version == Version3 { - x.startEngine() - if result, err = x.negotiateInitialSecurityParameters(ctx, packetOut); err != nil { + if req.Version == Version3 { + c.startEngine() + if result, err = c.negotiateInitialSecurityParameters(ctx, req); err != nil { return result, err } - sec = attemptSecurity{clock: x.engine.clock, keys: x.engine.keys} + sec = attemptSecurity{clock: c.engine.clock, keys: c.engine.keys} } var stored bool - result, stored, err = x.sendOneRequest(ctx, packetOut, false, sec) + result, stored, err = c.sendOneRequest(ctx, req, false, sec) kind := resyncKindOf(result) if !kind.resync { return result, err @@ -93,13 +93,13 @@ func (x *Client) request(ctx context.Context, packetOut *Message) (result *Messa // ends it with its error, and so does a resync Report answering the // retransmission. if stored { - sec.clock = x.engine.clock - } else if !mayLend(packetOut, result, kind) { + sec.clock = c.engine.clock + } else if !mayLend(req, result, kind) { return result, kind.err - } else if sec, err = x.lendEngineParameters(packetOut, result, kind, sec); err != nil { + } else if sec, err = c.lendEngineParameters(req, result, kind, sec); err != nil { return result, err } - result, _, err = x.sendOneRequest(ctx, packetOut, false, sec) + result, _, err = c.sendOneRequest(ctx, req, false, sec) if kind = resyncKindOf(result); kind.resync { return result, kind.err } @@ -130,8 +130,8 @@ func resyncKindOf(result *Message) reportKind { // exchange is one request on its way through the attempts sendOneRequest // makes. type exchange struct { - x *Client - packet *Message + c *Client + req *Message // ctx is the request's context. ctx context.Context @@ -208,13 +208,13 @@ func (k attemptKind) retryable() bool { // attemptOutcome is how an attempt ended, and with what: the reply and its // error, or the reason the attempt failed. type attemptOutcome struct { - packet *Message - err error - kind attemptKind - // verified reports that packet's digest checked against the request + reply *Message + err error + kind attemptKind + // verified reports that reply's digest checked against the request // (exchange.decode). verified bool - // committed reports that packet's engine parameters were committed into + // committed reports that reply's engine parameters were committed into // the engine state (exchange.settle). committed bool } @@ -265,7 +265,7 @@ type sentIDs struct { requestID, msgID uint32 } -// sendOneRequest sends packetOut, the engine discovery's request when +// sendOneRequest sends req, the engine discovery's request when // discovery is set, an SNMPv3 one with the engine boots and time of sec's clock // and its keys, and returns the reply that answers it, and whether the reply's // engine parameters were committed into the engine state, retrying up to @@ -273,8 +273,8 @@ type sentIDs struct { // reply ends with net.ErrClosed, whatever else ended it: an attempt's outcome // or the decision not to retry. An exchange that ends without an answer goes // through unanswered. -func (x *Client) sendOneRequest(ctx context.Context, packetOut *Message, discovery bool, sec attemptSecurity) (*Message, bool, error) { - e := exchange{x: x, packet: packetOut, ctx: ctx, discovery: discovery, sec: sec} +func (c *Client) sendOneRequest(ctx context.Context, req *Message, discovery bool, sec attemptSecurity) (*Message, bool, error) { + e := exchange{c: c, req: req, ctx: ctx, discovery: discovery, sec: sec} // The IDs of the attempts before the current one, in a local array, not a // field of exchange, so that eight of them stay on the stack: a field // would always escape to the heap, and a slice made for Retries+1 of @@ -283,19 +283,19 @@ func (x *Client) sendOneRequest(ctx context.Context, packetOut *Message, discove earlier := sent[:0] for n := 0; ; n++ { out := e.attempt(earlier) - if out.kind != attemptReply && x.isClosed() { + if out.kind != attemptReply && c.isClosed() { out = attemptOutcome{kind: attemptClosed, err: errClosed} } if !out.kind.retryable() { if out.kind != attemptReply { out.err = e.unanswered(out.err) } - return out.packet, out.committed, out.err + return out.reply, out.committed, out.err } - // A retryable attempt has stamped the packet with its IDs. - earlier = append(earlier, sentIDs{packetOut.RequestID, packetOut.MsgID}) + // A retryable attempt has stamped req with its IDs. + earlier = append(earlier, sentIDs{req.RequestID, req.MsgID}) if err := e.endErr(n, out); err != nil { - if x.isClosed() { + if c.isClosed() { err = errClosed } return nil, false, e.unanswered(err) @@ -316,7 +316,7 @@ func (e *exchange) endErr(n int, out attemptOutcome) error { if out.kind == attemptTimeout && e.contextDeadline { return context.DeadlineExceeded } - if n < e.x.config.Retries { + if n < e.c.config.Retries { return nil } if out.kind == attemptTimeout { @@ -342,7 +342,7 @@ func (e *exchange) attemptsError(text string, reason error) *attemptsError { // send recovers, does not get here. func (e *exchange) unanswered(err error) error { if e.outOfWindow { - e.x.forgetEngineTime() + e.c.forgetEngineTime() } if _, ended := err.(*attemptsError); e.discarded != nil && !ended && errors.Is(err, context.DeadlineExceeded) { return e.attemptsError(err.Error(), err) @@ -354,7 +354,7 @@ func (e *exchange) unanswered(err error) error { // a reply answers it, the attempt's deadline passes or the context is done. A // reply to an earlier attempt, one of earlier, answers it too. func (e *exchange) attempt(earlier []sentIDs) attemptOutcome { - x := e.x + x := e.c if err := e.ctx.Err(); err != nil { return attemptOutcome{kind: attemptContextDone, err: err} } @@ -372,7 +372,7 @@ func (e *exchange) attempt(earlier []sentIDs) attemptOutcome { // the attempt's connection, on which the attempt fails. defer x.interruptible(e.ctx, conn).end() - e.packet.RequestID = x.nextRequestID() + e.req.RequestID = x.nextRequestID() // An encoding failure is not retried: another attempt would fail the same // way. outBuf, err := e.encode() @@ -404,7 +404,7 @@ func attemptDeadline(ctx context.Context, timeout time.Duration) (deadline time. // An authenticated request is signed with the exchange's key, which must fit // its protocol (usm.Auth.CheckKey). func (e *exchange) encode() ([]byte, error) { - x, p := e.x, e.packet + x, p := e.c, e.req if p.Version == Version3 { p.MsgID = x.nextMsgID() h := &p.SecurityParameters @@ -422,7 +422,7 @@ func (e *exchange) encode() ([]byte, error) { // or that the commit rejects is discarded, its reason recorded (discard), and // the read goes on until the attempt's deadline (RFC 3412 section 7.2). func (e *exchange) await(conn transport, earlier []sentIDs) attemptOutcome { - x := e.x + x := e.c for { resp, err := receive(conn, x.rx) if err != nil { @@ -438,7 +438,7 @@ func (e *exchange) await(conn transport, earlier []sentIDs) attemptOutcome { e.discard(err, e.rankOf(reply, verified, earlier)) continue } - out, rejected := e.settle(attemptOutcome{kind: attemptReply, packet: reply, err: err, verified: verified}) + out, rejected := e.settle(attemptOutcome{kind: attemptReply, reply: reply, err: err, verified: verified}) if rejected == nil { return out } @@ -469,7 +469,7 @@ func (e *exchange) rankOf(read *Message, verified bool, earlier []sentIDs) disca if read == nil { return rankUnread } - if !e.named(read, earlier) || e.packet.Version != Version3 && read.PDUType != Response { + if !e.named(read, earlier) || e.req.Version != Version3 && read.PDUType != Response { return 0 } if verified && !read.PDUType.confirmed() { @@ -483,7 +483,7 @@ func (e *exchange) rankOf(read *Message, verified bool, earlier []sentIDs) disca // SNMPv3 request (RFC 3412 section 7.2 step 10 a), else by the request ID; // false when reply names none. func (e *exchange) attemptOf(reply *Message, earlier []sentIDs) (sentIDs, bool) { - if current := (sentIDs{e.packet.RequestID, e.packet.MsgID}); e.names(reply, current) { + if current := (sentIDs{e.req.RequestID, e.req.MsgID}); e.names(reply, current) { return current, true } for _, ids := range earlier { @@ -497,7 +497,7 @@ func (e *exchange) attemptOf(reply *Message, earlier []sentIDs) (sentIDs, bool) // names reports whether reply names the attempt that sent the request with // ids: by the msgID for an SNMPv3 request, else by the request ID. func (e *exchange) names(reply *Message, ids sentIDs) bool { - if e.packet.Version == Version3 { + if e.req.Version == Version3 { return reply.MsgID == ids.msgID } return reply.RequestID == ids.requestID @@ -523,17 +523,17 @@ func (e *exchange) named(reply *Message, earlier []sentIDs) bool { // the request's attempts (rankOf), else nil. func (e *exchange) decode(resp []byte, earlier []sentIDs) (_ *Message, verified bool, _ error) { reply := &Message{} - v3 := e.packet.Version == Version3 + v3 := e.req.Version == Version3 cursor, w, err := unmarshalHeader(resp, reply) switch { case err != nil: - case reply.Version != e.packet.Version: + case reply.Version != e.req.Version: err = errOtherVersion case !v3: case !e.named(reply, earlier): err = errOtherMessage default: - err = receiveReply(reply.SecurityLevel, &reply.SecurityParameters, &e.packet.SecurityParameters, &e.sec.keys) + err = receiveReply(reply.SecurityLevel, &reply.SecurityParameters, &e.req.SecurityParameters, &e.sec.keys) } // read is reply, as far as it was read, when an error ends the decode: for // an SNMPv3 request when the SNMPv3 header's msgID decoded, for another @@ -638,10 +638,10 @@ func (e *exchange) answers(reply *Message, earlier []sentIDs) (bool, error) { if ids, ok := e.attemptOf(reply, earlier); !ok || ids.requestID != reply.RequestID { return false, errOtherRequestID } - if e.packet.Version != Version3 { + if e.req.Version != Version3 { return true, nil } - p := e.packet + p := e.req got, want := &reply.SecurityParameters, &p.SecurityParameters switch { case reply.SecurityLevel != p.SecurityLevel: diff --git a/engine_fuzz_test.go b/engine_fuzz_test.go index 7e53c81..fd58f7f 100644 --- a/engine_fuzz_test.go +++ b/engine_fuzz_test.go @@ -79,8 +79,8 @@ func TestEngineReplySeeds(t *testing.T) { } for i, reply := range seeds { e := engineReplyExchange(t, r) - e.x.conn = &replyConn{reads: []scriptedRead{{data: reply}, {err: os.ErrDeadlineExceeded}}} - if out := e.attempt(nil); out.kind != attemptReply || out.packet == nil { + e.c.conn = &replyConn{reads: []scriptedRead{{data: reply}, {err: os.ErrDeadlineExceeded}}} + if out := e.attempt(nil); out.kind != attemptReply || out.reply == nil { t.Errorf("%+v seed %d: the attempt ended as %d, %v, not with an answer", r, i, out.kind, out.err) } } @@ -130,7 +130,7 @@ func engineReplyExchange(tb testing.TB, r engineReplyRequest) *exchange { sec = attemptSecurity{clock: x.engine.clock, keys: x.engine.keys} } } - return &exchange{x: x, packet: packet, ctx: context.Background(), discovery: r.discover, sec: sec} + return &exchange{c: x, req: packet, ctx: context.Background(), discovery: r.discover, sec: sec} } // engineReplySeeds returns replies to the first exchange of r's request @@ -141,7 +141,7 @@ func engineReplyExchange(tb testing.TB, r engineReplyRequest) *exchange { func engineReplySeeds(tb testing.TB, r engineReplyRequest) [][]byte { tb.Helper() e := engineReplyExchange(tb, r) - e.packet.RequestID = e.x.nextRequestID() + e.req.RequestID = e.c.nextRequestID() req, err := e.encode() if err != nil { tb.Fatal(err) @@ -152,7 +152,7 @@ func engineReplySeeds(tb testing.TB, r engineReplyRequest) [][]byte { } scripts := []func(int, agentRequest) (agentAnswer, bool){ nil, - onRequest(1, agentAnswer{report: usmStatsNotInTimeWindows, level: e.packet.SecurityLevel & AuthNoPriv}), + onRequest(1, agentAnswer{report: usmStatsNotInTimeWindows, level: e.req.SecurityLevel & AuthNoPriv}), onRequest(1, agentAnswer{report: usmStatsUnknownEngineIDs, level: NoAuthNoPriv}), } if r.discover { diff --git a/engine_requests_test.go b/engine_requests_test.go index 6e6cc64..69937a2 100644 --- a/engine_requests_test.go +++ b/engine_requests_test.go @@ -1108,7 +1108,7 @@ func TestExchangeRankOf(t *testing.T) { } for name, tc := range tests { t.Run(name, func(t *testing.T) { - e := exchange{packet: &Message{Version: tc.version, RequestID: 2, MsgID: 7}} + e := exchange{req: &Message{Version: tc.version, RequestID: 2, MsgID: 7}} assert.Equal(t, tc.want, e.rankOf(tc.read, tc.verified, earlier)) }) } @@ -1141,7 +1141,7 @@ func TestExchangeDecodeRequestID(t *testing.T) { } for name, tc := range tests { t.Run(name, func(t *testing.T) { - e := &exchange{x: mustClient(Config{Version: Version2c}), packet: &Message{Version: Version2c, PDUType: GetRequest}} + e := &exchange{c: mustClient(Config{Version: Version2c}), req: &Message{Version: Version2c, PDUType: GetRequest}} reply, _, err := e.decode(tc.msg, nil) require.Error(t, err) if tc.want == nil { @@ -1233,7 +1233,7 @@ func TestExchangeAnswers(t *testing.T) { if tc.reply != nil { tc.reply(rsp) } - e := exchange{packet: req} + e := exchange{req: req} answers, err := e.answers(rsp, earlier) assert.Equal(t, tc.answers, answers) assert.Equal(t, tc.err, err) @@ -1345,7 +1345,7 @@ func TestExchangeEndErrors(t *testing.T) { } for name, tc := range tests { t.Run(name, func(t *testing.T) { - e := exchange{x: mustClient(Config{})} + e := exchange{c: mustClient(Config{})} if tc.discarded != nil { e.discard(tc.discarded, rankAuthentic) } diff --git a/engine_state.go b/engine_state.go index 553723b..07ee270 100644 --- a/engine_state.go +++ b/engine_state.go @@ -116,9 +116,9 @@ func (s *engineState) withEngine(user *User, engineID []byte) (engineState, erro // startEngine starts the engine state of an SNMPv3 request (and of // EncodeMessage): after ForgetEngine the state starts over, with no engine ID, // so the request discovers the engine again. -func (x *Client) startEngine() { - if x.forgetEngine { - x.engine, x.forgetEngine = newEngineState(&x.config.User), false +func (c *Client) startEngine() { + if c.forgetEngine { + c.engine, c.forgetEngine = newEngineState(&c.config.User), false } } @@ -131,20 +131,20 @@ func (x *Client) startEngine() { // the agent's engine ID changed (a replaced device), or a forged answer to the // discovery gave the client another engine's. It is not safe to call while a // request runs on another goroutine. -func (x *Client) ForgetEngine() { - x.forgetEngine = true +func (c *Client) ForgetEngine() { + c.forgetEngine = true } // commitEngine replaces the engine state with next, a state validated by its // caller. -func (x *Client) commitEngine(next engineState) { - x.engine = next +func (c *Client) commitEngine(next engineState) { + c.engine = next } -// stamp gives packet, a request, the engine state's engine ID and context +// stamp gives m, a request, the engine state's engine ID and context // engine ID; its attempts sign and encrypt it with the state's keys and give // it the engine boots and time (exchange.encode). -func (s *engineState) stamp(packet *Message) { - packet.SecurityParameters.AuthoritativeEngineID = s.engineID - packet.ContextEngineID = s.contextEngineID() +func (s *engineState) stamp(m *Message) { + m.SecurityParameters.AuthoritativeEngineID = s.engineID + m.ContextEngineID = s.contextEngineID() } diff --git a/engine_state_test.go b/engine_state_test.go index d5271f2..9eb1e29 100644 --- a/engine_state_test.go +++ b/engine_state_test.go @@ -132,8 +132,8 @@ func TestEngineSettleKeepsEngine(t *testing.T) { VarBinds: []VarBind{{Name: usmStatsNotInTimeWindows}}, SecurityParameters: SecurityParameters{AuthoritativeEngineID: []byte(usmCharEngineID), AuthoritativeEngineBoots: 9, AuthoritativeEngineTime: 99}, } - e := exchange{x: x, packet: packet, sec: attemptSecurity{keys: known.keys}} - out, err := e.settle(attemptOutcome{kind: attemptReply, packet: report, verified: true}) + e := exchange{c: x, req: packet, sec: attemptSecurity{keys: known.keys}} + out, err := e.settle(attemptOutcome{kind: attemptReply, reply: report, verified: true}) require.NoError(t, err) require.True(t, out.committed) assert.Equal(t, [2]any{known.engineID, known.keys}, [2]any{x.engine.engineID, x.engine.keys}) diff --git a/engine_v3.go b/engine_v3.go index 8c4215f..14a6c5a 100644 --- a/engine_v3.go +++ b/engine_v3.go @@ -11,30 +11,30 @@ import ( "time" ) -// negotiateInitialSecurityParameters prepares packetOut's security parameters +// negotiateInitialSecurityParameters prepares req's security parameters // before an SNMPv3 request: it discovers the agent's engine while the engine -// state has no engine ID, and gives packetOut the engine state. A failed +// state has no engine ID, and gives req the engine state. A failed // discovery returns its error with the answer that ended it, if any. -func (x *Client) negotiateInitialSecurityParameters(ctx context.Context, packetOut *Message) (*Message, error) { - if len(x.engine.engineID) == 0 { - return x.discoverEngine(ctx, packetOut) +func (c *Client) negotiateInitialSecurityParameters(ctx context.Context, req *Message) (*Message, error) { + if len(c.engine.engineID) == 0 { + return c.discoverEngine(ctx, req) } - x.engine.stamp(packetOut) + c.engine.stamp(req) return nil, nil } // discoverEngine runs engine discovery (RFC 3414 section 4): it sends the // discovery request, whose answer the attempt commits into the engine state -// (exchange.settle), and gives packetOut the engine state. A discovery whose +// (exchange.settle), and gives req the engine state. A discovery whose // answer was not committed returns its error with the answer, if any. -func (x *Client) discoverEngine(ctx context.Context, packetOut *Message) (*Message, error) { +func (c *Client) discoverEngine(ctx context.Context, req *Message) (*Message, error) { discoveryPacket := newDiscoveryPacket() - discoveryPacket.ContextName = packetOut.ContextName - answer, committed, err := x.sendOneRequest(ctx, discoveryPacket, true, attemptSecurity{}) + discoveryPacket.ContextName = req.ContextName + answer, committed, err := c.sendOneRequest(ctx, discoveryPacket, true, attemptSecurity{}) if !committed { return answer, err } - x.engine.stamp(packetOut) + c.engine.stamp(req) return nil, nil } @@ -79,7 +79,7 @@ var errReplyNotInTime = inCategory(ErrNotInTimeWindow, errors.New("the reply is // (net-snmp's set_enginetime). A reply whose engine ID gives no valid state // answers without a commit. func (e *exchange) settle(out attemptOutcome) (attemptOutcome, error) { - x, reply := e.x, out.packet + c, reply := e.c, out.reply if reply.Version != Version3 { return out, nil } @@ -98,7 +98,7 @@ func (e *exchange) settle(out attemptOutcome) (attemptOutcome, error) { if out.verified && boots == maxEngineValue { return attemptOutcome{}, errReplyNotInTime } - next, err := x.engine.withEngine(&x.config.User, from.AuthoritativeEngineID) + next, err := c.engine.withEngine(&c.config.User, from.AuthoritativeEngineID) if err != nil { if e.discovery { out.err = err @@ -127,7 +127,7 @@ func (e *exchange) settle(out attemptOutcome) (attemptOutcome, error) { } next.clock = sourcedClock{clock, fromAuthenticated} } - x.commitEngine(next) + c.commitEngine(next) out.committed = true return out, nil } @@ -143,10 +143,10 @@ func (e *exchange) settle(out attemptOutcome) (attemptOutcome, error) { // authentic answer of one that does not is its first (the reset of RFC 3414 // section 2.3). A deviation from section 3.2 step 7 b and net-snmp, which // reject such a device until the client forgets its time by other means. -func (x *Client) forgetEngineTime() { - next := x.engine +func (c *Client) forgetEngineTime() { + next := c.engine next.clock = sourcedClock{} - x.commitEngine(next) + c.commitEngine(next) } // resetsClock reports whether a verified reply with engine boots and time @@ -168,7 +168,7 @@ func (e *exchange) resetsClock(boots, engineTime uint32, now time.Time) bool { } // mayLend reports whether report, a resync Report of kind the client did not -// store, may lend its engine parameters to the resend of packetOut. A request +// store, may lend its engine parameters to the resend of req. A request // without authentication carries no signature to misuse. An authenticated // request is signed with what the Report names, so it takes only the engine // boots and time of a Report that names the request's engine ID (RFC 3414 @@ -178,32 +178,32 @@ func (e *exchange) resetsClock(boots, engineTime uint32, now time.Time) bool { // every unauthenticated clock (sourcedClock.timeFor). It never takes an engine // ID: the request would be signed for another engine with the same // credentials (section 1.5.2). -func mayLend(packetOut, report *Message, kind reportKind) bool { - if !packetOut.SecurityLevel.authFlag() { +func mayLend(req, report *Message, kind reportKind) bool { + if !req.SecurityLevel.authFlag() { return true } if kind.namesEngine { return false } - return bytes.Equal(report.SecurityParameters.AuthoritativeEngineID, packetOut.SecurityParameters.AuthoritativeEngineID) + return bytes.Equal(report.SecurityParameters.AuthoritativeEngineID, req.SecurityParameters.AuthoritativeEngineID) } // lendEngineParameters lends the engine parameters of report, a resync Report -// the client does not store, to the resend of packetOut only, which the -// request's attempts so far made with sec: it gives packetOut the engine ID of +// the client does not store, to the resend of req only, which the +// request's attempts so far made with sec: it gives req the engine ID of // a Report that names the engine and its context engine ID, and the resend the // keys localized to it (by the rule of a commit, withEngine: an error for an // empty one), and the clock of the Report's boots and time, received now (RFC // 3414 section 3.2 checks the engine ID before the time window). The client // takes the agent's from the authenticated answer. -func (x *Client) lendEngineParameters(packetOut, report *Message, kind reportKind, sec attemptSecurity) (attemptSecurity, error) { +func (c *Client) lendEngineParameters(req, report *Message, kind reportKind, sec attemptSecurity) (attemptSecurity, error) { from := &report.SecurityParameters if kind.namesEngine { - lent, err := x.engine.withEngine(&x.config.User, from.AuthoritativeEngineID) + lent, err := c.engine.withEngine(&c.config.User, from.AuthoritativeEngineID) if err != nil { return attemptSecurity{}, err } - lent.stamp(packetOut) + lent.stamp(req) sec.keys = lent.keys } source := fromUnauthenticated diff --git a/gosnmp.go b/gosnmp.go index 141fc91..d6f8b5e 100644 --- a/gosnmp.go +++ b/gosnmp.go @@ -249,17 +249,17 @@ const ( // them. It runs no discovery: before the client knows the agent's engine the // message has no engine ID and no keys, so an authenticated or private one // fails. On an error it returns no message. -func (x *Client) EncodeMessage(pduType PDUType, varBinds []VarBind, nonRepeaters uint8, maxRepetitions uint32) ([]byte, error) { - pkt := x.NewMessage(pduType, varBinds, nonRepeaters, maxRepetitions) - pkt.RequestID = x.nextRequestID() +func (c *Client) EncodeMessage(pduType PDUType, varBinds []VarBind, nonRepeaters uint8, maxRepetitions uint32) ([]byte, error) { + pkt := c.NewMessage(pduType, varBinds, nonRepeaters, maxRepetitions) + pkt.RequestID = c.nextRequestID() var keys usmKeys - if x.config.Version == Version3 { - x.startEngine() - x.engine.stamp(pkt) - pkt.SecurityParameters.AuthoritativeEngineBoots = x.engine.clock.boots - pkt.SecurityParameters.AuthoritativeEngineTime = x.engine.clock.latest - keys = x.engine.keys - pkt.MsgID = x.nextMsgID() + if c.config.Version == Version3 { + c.startEngine() + c.engine.stamp(pkt) + pkt.SecurityParameters.AuthoritativeEngineBoots = c.engine.clock.boots + pkt.SecurityParameters.AuthoritativeEngineTime = c.engine.clock.latest + keys = c.engine.keys + pkt.MsgID = c.nextMsgID() } return pkt.marshalMsg(&keys) } @@ -274,7 +274,7 @@ func (x *Client) EncodeMessage(pduType PDUType, varBinds []VarBind, nonRepeaters // time window, nor any minimum level. It does not write data (see the package // documentation for the values that alias it). On an error it returns no // message. -func (x *Client) DecodeMessage(data []byte) (*Message, error) { +func (c *Client) DecodeMessage(data []byte) (*Message, error) { result := new(Message) cursor, w, err := unmarshalHeader(data, result) if err != nil { @@ -282,7 +282,7 @@ func (x *Client) DecodeMessage(data []byte) (*Message, error) { } if result.Version == Version3 { var in inbound - if in, err = receiveV3(data, w, result, &x.config.User, nil); err != nil { + if in, err = receiveV3(data, w, result, &c.config.User, nil); err != nil { return nil, fmt.Errorf("unable to decode packet header: %w", err) } if data, cursor, err = in.scopedPDU(result); err != nil { diff --git a/ids.go b/ids.go index 3d3e55e..c31e6fc 100644 --- a/ids.go +++ b/ids.go @@ -24,14 +24,14 @@ func randomID() uint32 { // nextRequestID advances the request ID counter, which NewClient seeds with a // random value, and returns it without its top bit, so request IDs wrap to 0 // after 2147483647. -func (x *Client) nextRequestID() uint32 { - x.requestID++ - return x.requestID & math.MaxInt32 +func (c *Client) nextRequestID() uint32 { + c.requestID++ + return c.requestID & math.MaxInt32 } // nextMsgID advances the msgID counter, which NewClient seeds with a random // value, and returns it without its top bit. -func (x *Client) nextMsgID() uint32 { - x.msgID++ - return x.msgID & math.MaxInt32 +func (c *Client) nextMsgID() uint32 { + c.msgID++ + return c.msgID & math.MaxInt32 } diff --git a/message.go b/message.go index 5f869e3..c4e6988 100644 --- a/message.go +++ b/message.go @@ -124,13 +124,13 @@ func (t PDUType) confirmed() bool { // (SecurityParameters' UserName). SNMPv1 and SNMPv2c messages take no user // (nil), and an SNMPv3 message at NoAuthNoPriv takes nil or any user with valid // protocols. Encode draws no new msgID (Client.EncodeMessage does). -func (packet *Message) Encode(user *User) ([]byte, error) { +func (m *Message) Encode(user *User) ([]byte, error) { var keys usmKeys - if packet.Version == Version3 && user != nil { + if m.Version == Version3 && user != nil { var err error - if keys, err = user.keysAt(packet.SecurityLevel, packet.SecurityParameters.AuthoritativeEngineID); err != nil { + if keys, err = user.keysAt(m.SecurityLevel, m.SecurityParameters.AuthoritativeEngineID); err != nil { return nil, err } } - return packet.marshalMsg(&keys) + return m.marshalMsg(&keys) } diff --git a/pdu.go b/pdu.go index e3dacaf..f70c05c 100644 --- a/pdu.go +++ b/pdu.go @@ -221,22 +221,22 @@ func readVersionField(packet []byte) (ber.Reader, int32, int, error) { return r, version, whole.Len(), nil } -// unmarshalHeader reads the message header into response: the version and, +// unmarshalHeader reads the message header into m: the version and, // for SNMPv1 and SNMPv2c, the community, or for SNMPv3 the header (parseV3), // whose USM fields it returns for security processing, also those that // decoded before an error. It returns the offset of the PDU, or of the scoped // PDU. Its errors have their categories: the version's (readVersion), an // SNMPv3 header's (v3ParseError), ErrASNParse for the community. -func unmarshalHeader(packet []byte, response *Message) (int, v3Wire, error) { +func unmarshalHeader(packet []byte, m *Message) (int, v3Wire, error) { version, cursor, err := readVersion(packet) if err != nil { return 0, v3Wire{}, err } - response.Version = version + m.Version = version - if response.Version == Version3 { + if m.Version == Version3 { var w v3Wire - if w, err = parseV3(packet, cursor, response); err != nil { + if w, err = parseV3(packet, cursor, m); err != nil { return 0, w, v3ParseError(err) } return w.scoped, w, nil @@ -247,15 +247,15 @@ func unmarshalHeader(packet []byte, response *Message) (int, v3Wire, error) { if err != nil { return 0, v3Wire{}, inCategory(ErrASNParse, fmt.Errorf("error parsing community string: %w", err)) } - response.Community = string(community) + m.Community = string(community) return len(packet) - r.Len(), v3Wire{}, nil } // unmarshalPayload reads the PDU at packet[cursor:], which must span the rest // of the packet (readPayload); its errors are ErrASNParse (RFC 3412 section // 7.2 step 7, an unknown PDU type included, as net-snmp v5.9.4 treats it). -func unmarshalPayload(packet []byte, cursor int, response *Message) error { - if err := readPayload(packet, cursor, response); err != nil { +func unmarshalPayload(packet []byte, cursor int, m *Message) error { + if err := readPayload(packet, cursor, m); err != nil { return inCategory(ErrASNParse, err) } return nil @@ -263,7 +263,7 @@ func unmarshalPayload(packet []byte, cursor int, response *Message) error { // readPayload reads the PDU at packet[cursor:], which must span the rest of // the packet. -func readPayload(packet []byte, cursor int, response *Message) error { +func readPayload(packet []byte, cursor int, m *Message) error { if len(packet) == 0 { return errors.New("cannot unmarshal nil or empty payload packet") } @@ -275,14 +275,14 @@ func readPayload(packet []byte, cursor int, response *Message) error { if !requestType.known() { return fmt.Errorf("unknown PDUType %#x", byte(requestType)) } - response.PDUType = requestType + m.PDUType = requestType if requestType == Trap { - if err := unmarshalTrapV1(packet[cursor:], response); err != nil { + if err := unmarshalTrapV1(packet[cursor:], m); err != nil { return fmt.Errorf("error in unmarshalTrapV1: %w", err) } return nil } - if err := unmarshalResponse(packet[cursor:], requestType, response); err != nil { + if err := unmarshalResponse(packet[cursor:], requestType, m); err != nil { return fmt.Errorf("error in unmarshalResponse: %w", err) } return nil @@ -323,14 +323,14 @@ func requestIDRead(packet []byte, cursor int) bool { // a GetBulkRequest, or the error status, 0..255, and the error index // (readCount) of any other PDU; and the varbinds. Fields read before an error // stay set. -func unmarshalResponse(packet []byte, pduType PDUType, response *Message) error { +func unmarshalResponse(packet []byte, pduType PDUType, m *Message) error { r, requestID, err := readRequestID(packet) if err != nil { return err } - response.RequestID = requestID + m.RequestID = requestID if pduType == GetBulkRequest { - if response.NonRepeaters, err = readCount(&r); err != nil { + if m.NonRepeaters, err = readCount(&r); err != nil { return fmt.Errorf("error parsing SNMP packet non repeaters: %w", err) } maxRepetitions, err := readInt32(&r) @@ -340,7 +340,7 @@ func unmarshalResponse(packet []byte, pduType PDUType, response *Message) error if err != nil { return fmt.Errorf("error parsing SNMP packet max repetitions: %w", err) } - response.MaxRepetitions = uint32(maxRepetitions) //nolint:gosec // not negative + m.MaxRepetitions = uint32(maxRepetitions) //nolint:gosec // not negative } else { errorStatus, err := readInt32(&r) if err == nil && (errorStatus < 0 || errorStatus > math.MaxUint8) { @@ -349,47 +349,47 @@ func unmarshalResponse(packet []byte, pduType PDUType, response *Message) error if err != nil { return fmt.Errorf("error parsing SNMP packet error: %w", err) } - response.ErrorStatus = ErrorStatus(errorStatus) //nolint:gosec // 0..255 - if response.ErrorIndex, err = readCount(&r); err != nil { + m.ErrorStatus = ErrorStatus(errorStatus) //nolint:gosec // 0..255 + if m.ErrorIndex, err = readCount(&r); err != nil { return fmt.Errorf("error parsing SNMP packet error index: %w", err) } } - return unmarshalVBL(r.Rest(), response) + return unmarshalVBL(r.Rest(), m) } // unmarshalTrapV1 reads an SNMPv1 trap PDU: the enterprise, an OBJECT // IDENTIFIER; the agent address (readAgentAddress); the generic and specific // trap, INTEGERs cut to 32 bits; the timestamp (readTimestamp); and the // varbinds. Fields read before an error stay set. -func unmarshalTrapV1(packet []byte, response *Message) error { +func unmarshalTrapV1(packet []byte, m *Message) error { pdu, err := readWhole(packet) if err != nil { return fmt.Errorf("error verifying Response sanity: %w", err) } r := ber.NewReader(pdu) - if response.Enterprise, err = readOID(&r); err != nil { + if m.Enterprise, err = readOID(&r); err != nil { return fmt.Errorf("error parsing SNMPv1 trap enterprise: %w", err) } - if response.AgentAddress, err = readAgentAddress(&r); err != nil { + if m.AgentAddress, err = readAgentAddress(&r); err != nil { return fmt.Errorf("error parsing SNMPv1 trap agent address: %w", err) } - if response.GenericTrap, err = readInt32(&r); err != nil { + if m.GenericTrap, err = readInt32(&r); err != nil { return fmt.Errorf("error parsing SNMPv1 trap generic trap: %w", err) } - if response.SpecificTrap, err = readInt32(&r); err != nil { + if m.SpecificTrap, err = readInt32(&r); err != nil { return fmt.Errorf("error parsing SNMPv1 trap specific trap: %w", err) } - if response.Timestamp, err = readTimestamp(&r); err != nil { + if m.Timestamp, err = readTimestamp(&r); err != nil { return fmt.Errorf("error parsing SNMPv1 trap timestamp: %w", err) } - return unmarshalVBL(r.Rest(), response) + return unmarshalVBL(r.Rest(), m) } // unmarshalVBL reads a varbind list, which must span all of packet, into -// response.VarBinds, an empty list when it has no varbinds; on an error the +// m.VarBinds, an empty list when it has no varbinds; on an error the // ones before it stay set. -func unmarshalVBL(packet []byte, response *Message) error { +func unmarshalVBL(packet []byte, m *Message) error { if len(packet) == 0 { return errors.New("truncated packet when unmarshalling a VBL") } @@ -401,14 +401,14 @@ func unmarshalVBL(packet []byte, response *Message) error { return fmt.Errorf("error verifying VBL length: %w", err) } - response.VarBinds = make([]VarBind, 0, 5) + m.VarBinds = make([]VarBind, 0, 5) r := ber.NewReader(vbl) for r.Len() > 0 { vb, err := readVarbind(&r) if err != nil { return err } - response.VarBinds = append(response.VarBinds, vb) + m.VarBinds = append(m.VarBinds, vb) } return nil } @@ -465,47 +465,47 @@ func readVarbind(r *ber.Reader) (VarBind, error) { // SNMPv3 message is then signed with keys when its level asks for // authentication. The version, which takes one octet, must be SNMPv1, SNMPv2c // or SNMPv3. -func (packet *Message) marshalMsg(keys *usmKeys) ([]byte, error) { - return packet.marshalWith(keys, nil) +func (m *Message) marshalMsg(keys *usmKeys) ([]byte, error) { + return m.marshalWith(keys, nil) } // marshalWith is marshalMsg with varBinds, when not nil, a varbind list // encoded already, which it writes as it is instead of VarBinds: a received // inform's, which a receiver's Response repeats (respond). -func (packet *Message) marshalWith(keys *usmKeys, varBinds []byte) ([]byte, error) { - switch packet.Version { +func (m *Message) marshalWith(keys *usmKeys, varBinds []byte) ([]byte, error) { + switch m.Version { case Version1, Version2c, Version3: default: - return nil, fmt.Errorf("unable to marshal SNMP version %d: not 1, 2c or 3", packet.Version) + return nil, fmt.Errorf("unable to marshal SNMP version %d: not 1, 2c or 3", m.Version) } - dst, start := ber.Begin(make([]byte, 0, packet.sizeHint()+len(varBinds)), ber.Sequence) - dst = append(dst, byte(Integer), 1, byte(packet.Version)) - if packet.Version != Version3 { - msg, err := packet.appendPDU(appendOctets(dst, OctetString, packet.Community), varBinds) + dst, start := ber.Begin(make([]byte, 0, m.sizeHint()+len(varBinds)), ber.Sequence) + dst = append(dst, byte(Integer), 1, byte(m.Version)) + if m.Version != Version3 { + msg, err := m.appendPDU(appendOctets(dst, OctetString, m.Community), varBinds) if err != nil { return nil, err } return ber.End(msg, start), nil } - dst, auth, err := packet.appendV3(dst, keys, varBinds) + dst, auth, err := m.appendV3(dst, keys, varBinds) if err != nil { return nil, err } dst, auth = ber.EndMoving(dst, start, auth) - return packet.sign(dst, auth, keys) + return m.sign(dst, auth, keys) } // sizeHint estimates the encoded size of the message so that marshalMsg // usually allocates once: room for the headers and the security parameters, // the text fields, and per varbind its name in dotted form (no shorter than // its encoding), its headers and an OCTET STRING or Opaque value. -func (packet *Message) sizeHint() int { - n := 64 + len(packet.Community) + len(packet.ContextEngineID) + len(packet.ContextName) - if packet.Version == Version3 { +func (m *Message) sizeHint() int { + n := 64 + len(m.Community) + len(m.ContextEngineID) + len(m.ContextName) + if m.Version == Version3 { n += 128 } - for i := range packet.VarBinds { - vb := &packet.VarBinds[i] + for i := range m.VarBinds { + vb := &m.VarBinds[i] n += 16 + len(vb.Name) + len(vb.Value.data) + len(vb.Value.oid) } return n @@ -517,31 +517,31 @@ func (packet *Message) sizeHint() int { // an SNMPv1 trap, then the varbind list (appendVBL). The request ID is an // Integer32 (RFC 3416) whose two's complement RequestID holds, so IDs of 2^31 // and up encode as negative INTEGERs on every platform. -func (packet *Message) appendPDU(dst, varBinds []byte) ([]byte, error) { - if !packet.PDUType.known() { - return nil, fmt.Errorf("unable to marshal PDU type %#x: not a PDU type", byte(packet.PDUType)) +func (m *Message) appendPDU(dst, varBinds []byte) ([]byte, error) { + if !m.PDUType.known() { + return nil, fmt.Errorf("unable to marshal PDU type %#x: not a PDU type", byte(m.PDUType)) } - if packet.PDUType == GetBulkRequest && packet.MaxRepetitions > math.MaxInt32 { - return nil, fmt.Errorf("unable to marshal max-repetitions %d: more than %d", packet.MaxRepetitions, math.MaxInt32) + if m.PDUType == GetBulkRequest && m.MaxRepetitions > math.MaxInt32 { + return nil, fmt.Errorf("unable to marshal max-repetitions %d: more than %d", m.MaxRepetitions, math.MaxInt32) } - dst, start := ber.Begin(dst, byte(packet.PDUType)) - requestID := int64(int32(packet.RequestID)) //nolint:gosec // the Integer32's two's complement - switch packet.PDUType { + dst, start := ber.Begin(dst, byte(m.PDUType)) + requestID := int64(int32(m.RequestID)) //nolint:gosec // the Integer32's two's complement + switch m.PDUType { case GetBulkRequest: dst = appendInt(dst, requestID) - dst = appendUint(dst, Integer, uint64(packet.NonRepeaters)) - dst = appendUint(dst, Integer, uint64(packet.MaxRepetitions)) + dst = appendUint(dst, Integer, uint64(m.NonRepeaters)) + dst = appendUint(dst, Integer, uint64(m.MaxRepetitions)) case Trap: var err error - if dst, err = packet.appendTrapV1Header(dst); err != nil { + if dst, err = m.appendTrapV1Header(dst); err != nil { return nil, err } default: dst = appendInt(dst, requestID) - dst = appendUint(dst, Integer, uint64(packet.ErrorStatus)) - dst = appendUint(dst, Integer, uint64(packet.ErrorIndex)) + dst = appendUint(dst, Integer, uint64(m.ErrorStatus)) + dst = appendUint(dst, Integer, uint64(m.ErrorIndex)) } - dst, err := packet.appendVBL(dst, varBinds) + dst, err := m.appendVBL(dst, varBinds) if err != nil { return nil, fmt.Errorf("unable to marshal varbind list: %w", err) } @@ -551,33 +551,33 @@ func (packet *Message) appendPDU(dst, varBinds []byte) ([]byte, error) { // appendTrapV1Header appends the SNMPv1 trap fields before the varbind list: // enterprise, the agent address (an IPv4 address, an IPv4-mapped one included: // RFC 1157's NetworkAddress), generic and specific trap and the timestamp. -func (packet *Message) appendTrapV1Header(dst []byte) ([]byte, error) { - dst, err := appendObjectIdentifier(dst, packet.Enterprise) +func (m *Message) appendTrapV1Header(dst []byte) ([]byte, error) { + dst, err := appendObjectIdentifier(dst, m.Enterprise) if err != nil { return nil, err } - agentAddress := packet.AgentAddress.Unmap() + agentAddress := m.AgentAddress.Unmap() if !agentAddress.Is4() { - return nil, fmt.Errorf("unable to marshal SNMPv1 AgentAddress: %v is not an IPv4 address", packet.AgentAddress) + return nil, fmt.Errorf("unable to marshal SNMPv1 AgentAddress: %v is not an IPv4 address", m.AgentAddress) } octets := agentAddress.As4() dst = appendOctets(dst, IPAddress, octets[:]) - dst = appendInt(dst, int64(packet.GenericTrap)) - dst = appendInt(dst, int64(packet.SpecificTrap)) - return appendUint(dst, TimeTicks, uint64(packet.Timestamp)), nil + dst = appendInt(dst, int64(m.GenericTrap)) + dst = appendInt(dst, int64(m.SpecificTrap)) + return appendUint(dst, TimeTicks, uint64(m.Timestamp)), nil } // appendVBL appends the varbind list: varBinds, a list encoded already, when // not nil, else a SEQUENCE of VarBinds, each a SEQUENCE of the name's OBJECT // IDENTIFIER and the value (see appendValue). -func (packet *Message) appendVBL(dst, varBinds []byte) ([]byte, error) { +func (m *Message) appendVBL(dst, varBinds []byte) ([]byte, error) { if varBinds != nil { return append(dst, varBinds...), nil } dst, start := ber.Begin(dst, ber.Sequence) - for i := range packet.VarBinds { + for i := range m.VarBinds { var err error - if dst, err = appendVarbind(dst, &packet.VarBinds[i]); err != nil { + if dst, err = appendVarbind(dst, &m.VarBinds[i]); err != nil { return nil, err } } @@ -585,13 +585,13 @@ func (packet *Message) appendVBL(dst, varBinds []byte) ([]byte, error) { } // appendVarbind appends one varbind. -func appendVarbind(dst []byte, pdu *VarBind) ([]byte, error) { +func appendVarbind(dst []byte, vb *VarBind) ([]byte, error) { dst, start := ber.Begin(dst, ber.Sequence) - dst, err := appendObjectIdentifier(dst, pdu.Name) + dst, err := appendObjectIdentifier(dst, vb.Name) if err != nil { return nil, err } - if dst, err = appendValue(dst, pdu.Value); err != nil { + if dst, err = appendValue(dst, vb.Value); err != nil { return nil, err } return ber.End(dst, start), nil diff --git a/request.go b/request.go index 5094708..1b42dfe 100644 --- a/request.go +++ b/request.go @@ -16,13 +16,13 @@ import ( // SNMPv3 message's engine fields and context engine ID are left empty: a // request takes them from the client's engine state, and the caller sets them // for a message it encodes itself. -func (x *Client) NewMessage(pduType PDUType, varBinds []VarBind, nonRepeaters uint8, maxRepetitions uint32) *Message { +func (c *Client) NewMessage(pduType PDUType, varBinds []VarBind, nonRepeaters uint8, maxRepetitions uint32) *Message { return &Message{ - Version: x.config.Version, - Community: x.config.Community, - SecurityLevel: x.config.SecurityLevel, - SecurityParameters: SecurityParameters{UserName: x.config.User.Name}, - ContextName: x.config.ContextName, + Version: c.config.Version, + Community: c.config.Community, + SecurityLevel: c.config.SecurityLevel, + SecurityParameters: SecurityParameters{UserName: c.config.User.Name}, + ContextName: c.config.ContextName, ErrorStatus: 0, ErrorIndex: 0, PDUType: pduType, @@ -40,24 +40,24 @@ func (x *Client) NewMessage(pduType PDUType, varBinds []VarBind, nonRepeaters ui // documentation, Errors). A done ctx ends the request with its error (see // the package documentation, Attempts and timeouts); a nil ctx fails it // before it is sent. -func (x *Client) Get(ctx context.Context, oids []string) (result *Message, err error) { - packetOut, err := x.oidRequest(GetRequest, oids, 0) +func (c *Client) Get(ctx context.Context, oids []string) (result *Message, err error) { + req, err := c.oidRequest(GetRequest, oids, 0) if err != nil { return nil, err } - return x.send(ctx, packetOut) + return c.send(ctx, req) } // oidRequest builds the request packet of pdutype for oids, each as a Null // varbind, with maxRepetitions for a GetBulk, after checking their count // against MaxOids: Get's, and each of a walk's GetNext and GetBulk requests. -func (x *Client) oidRequest(pdutype PDUType, oids []string, maxRepetitions uint32) (*Message, error) { - if len(oids) > x.config.MaxOids { - return nil, fmt.Errorf("oid count (%d) is greater than MaxOids (%d)", len(oids), x.config.MaxOids) +func (c *Client) oidRequest(pduType PDUType, oids []string, maxRepetitions uint32) (*Message, error) { + if len(oids) > c.config.MaxOids { + return nil, fmt.Errorf("oid count (%d) is greater than MaxOids (%d)", len(oids), c.config.MaxOids) } - pdus := make([]VarBind, 0, len(oids)) + varBinds := make([]VarBind, 0, len(oids)) for _, oid := range oids { - pdus = append(pdus, VarBind{Name: oid, Value: NullValue()}) + varBinds = append(varBinds, VarBind{Name: oid, Value: NullValue()}) } - return x.NewMessage(pdutype, pdus, 0, maxRepetitions), nil + return c.NewMessage(pduType, varBinds, 0, maxRepetitions), nil } diff --git a/transport.go b/transport.go index bdeb895..0dfb570 100644 --- a/transport.go +++ b/transport.go @@ -21,24 +21,24 @@ import ( // answers. The new connection replaces the client's, which Connect closes; // when Connect fails, the client keeps the connection it had. A nil ctx, and // then an empty Target, fail Connect before it changes the client. -func (x *Client) Connect(ctx context.Context) error { +func (c *Client) Connect(ctx context.Context) error { if ctx == nil { return errNilContext } - if x.config.Target == "" { + if c.config.Target == "" { return errNoTarget } - conn, err := dial(ctx, x.config.Timeout, net.JoinHostPort(x.config.Target, strconv.Itoa(int(x.config.Port)))) + conn, err := dial(ctx, c.config.Timeout, net.JoinHostPort(c.config.Target, strconv.Itoa(int(c.config.Port)))) if err != nil { return fmt.Errorf("error establishing connection to host: %w", err) } - if x.rx == nil { - x.rx = new(receiveBuffer) + if c.rx == nil { + c.rx = new(receiveBuffer) } - x.mu.Lock() - old := x.conn - x.conn, x.closed = conn, false - x.mu.Unlock() + c.mu.Lock() + old := c.conn + c.conn, c.closed = conn, false + c.mu.Unlock() if old != nil { _ = old.Close() } @@ -51,8 +51,8 @@ func (x *Client) Connect(ctx context.Context) error { // an error wrapping net.ErrClosed, as do later requests until Connect opens a // connection (see the package documentation). Only the first call closes the // connection; later calls, and calls on a client never connected, return nil. -func (x *Client) Close() error { - conn := x.markClosed() +func (c *Client) Close() error { + conn := c.markClosed() if conn == nil { return nil } @@ -61,11 +61,11 @@ func (x *Client) Close() error { // markClosed marks the client closed and returns its connection, which it // removes. -func (x *Client) markClosed() transport { - x.mu.Lock() - defer x.mu.Unlock() - conn := x.conn - x.conn, x.closed = nil, true +func (c *Client) markClosed() transport { + c.mu.Lock() + defer c.mu.Unlock() + conn := c.conn + c.conn, c.closed = nil, true return conn } @@ -82,13 +82,13 @@ type runningAttempt struct { // interruptible makes the attempt that uses conn the client's running attempt, // which ctx interrupts once it is done. The attempt calls it after setting its // deadline, which would otherwise undo an interrupt, and ends it with end. -func (x *Client) interruptible(ctx context.Context, conn transport) attemptInterrupts { - x.mu.Lock() - x.attempt.seq++ - x.attempt.conn = conn - seq := x.attempt.seq - x.mu.Unlock() - a := attemptInterrupts{x: x, seq: seq} +func (c *Client) interruptible(ctx context.Context, conn transport) attemptInterrupts { + c.mu.Lock() + c.attempt.seq++ + c.attempt.conn = conn + seq := c.attempt.seq + c.mu.Unlock() + a := attemptInterrupts{x: c, seq: seq} // Until this returns, the caller cannot defer end. Roll back setup if // a context's method panics, including while AfterFunc registers it. completed := false @@ -98,7 +98,7 @@ func (x *Client) interruptible(ctx context.Context, conn transport) attemptInter } }() if ctx.Done() != nil { - a.stopContext = context.AfterFunc(ctx, func() { x.interrupt(seq) }) + a.stopContext = context.AfterFunc(ctx, func() { c.interrupt(seq) }) } completed = true return a @@ -125,11 +125,11 @@ func (a attemptInterrupts) end() { // that has started is waited for, so that its deadline cannot land after a // later attempt's. func (a attemptInterrupts) clear() { - x := a.x - x.mu.Lock() - interrupted := x.attempt.interrupted - x.attempt.conn, x.attempt.interrupted = nil, nil - x.mu.Unlock() + c := a.x + c.mu.Lock() + interrupted := c.attempt.interrupted + c.attempt.conn, c.attempt.interrupted = nil, nil + c.mu.Unlock() if interrupted != nil { <-interrupted } @@ -139,16 +139,16 @@ func (a attemptInterrupts) clear() { // at once, with a deadline in the past on its connection, while the attempt // runs; once one interrupt has started, others do nothing. It sets the // deadline without mu, which a slow SetDeadline then cannot hold. -func (x *Client) interrupt(seq uint64) { - x.mu.Lock() - conn := x.attempt.conn - if conn == nil || x.attempt.seq != seq || x.attempt.interrupted != nil { - x.mu.Unlock() +func (c *Client) interrupt(seq uint64) { + c.mu.Lock() + conn := c.attempt.conn + if conn == nil || c.attempt.seq != seq || c.attempt.interrupted != nil { + c.mu.Unlock() return } interrupted := make(chan struct{}) - x.attempt.interrupted = interrupted - x.mu.Unlock() + c.attempt.interrupted = interrupted + c.mu.Unlock() defer close(interrupted) _ = conn.SetDeadline(time.Unix(1, 0)) } @@ -165,24 +165,24 @@ var ( // isClosed reports whether Close closed the client's connection, which no // Connect has replaced since. -func (x *Client) isClosed() bool { - x.mu.Lock() - defer x.mu.Unlock() - return x.conn == nil && x.closed +func (c *Client) isClosed() bool { + c.mu.Lock() + defer c.mu.Unlock() + return c.conn == nil && c.closed } // connection returns the client's connection, which an attempt of a request // uses. It fails without a connection, with net.ErrClosed after Close. -func (x *Client) connection() (transport, error) { - x.mu.Lock() - defer x.mu.Unlock() +func (c *Client) connection() (transport, error) { + c.mu.Lock() + defer c.mu.Unlock() switch { - case x.conn == nil && x.closed: + case c.conn == nil && c.closed: return nil, errClosed - case x.conn == nil: + case c.conn == nil: return nil, errNoConn } - return x.conn, nil + return c.conn, nil } // transport is the client's connection as a request uses it: the UDP socket diff --git a/v3.go b/v3.go index 12ceb46..3acc353 100644 --- a/v3.go +++ b/v3.go @@ -38,15 +38,15 @@ const reportableFlag = 0x4 // authFlag reports whether f has the authFlag (bit 0x1, RFC 3412 section 6.4) // set: the message asks for authentication. A set flag is a request, not // proof that the message was authenticated. -func (f SecurityLevel) authFlag() bool { return f&0x1 != 0 } +func (sl SecurityLevel) authFlag() bool { return sl&0x1 != 0 } // privFlag reports whether f has the privFlag (bit 0x2) set: the message asks // for privacy. Without the authFlag the combination is invalid (RFC 3412 // section 7.2 step 5 d). -func (f SecurityLevel) privFlag() bool { return f&0x2 != 0 } +func (sl SecurityLevel) privFlag() bool { return sl&0x2 != 0 } // valid reports whether f is one of the three security levels. -func (f SecurityLevel) valid() bool { return f == NoAuthNoPriv || f == AuthNoPriv || f == AuthPriv } +func (sl SecurityLevel) valid() bool { return sl == NoAuthNoPriv || sl == AuthNoPriv || sl == AuthPriv } //go:generate go tool -modfile=tools/go.mod stringer -type=SecurityLevel @@ -59,8 +59,8 @@ const usmSecurityModel = 3 // content of its msgAuthenticationParameters, at offset auth, with keys when // the level asks for authentication; a key that does not fit the protocol is // an error (usm.Auth.CheckKey). -func (packet *Message) sign(msg []byte, auth int, keys *usmKeys) ([]byte, error) { - if packet.SecurityLevel.authFlag() { +func (m *Message) sign(msg []byte, auth int, keys *usmKeys) ([]byte, error) { + if m.SecurityLevel.authFlag() { if err := keys.sign(msg, auth); err != nil { return nil, err } @@ -102,28 +102,28 @@ var errScopedPDUType = inCategory(ErrASNParse, errors.New("error parsing SNMPV3 // offset of the msgAuthenticationParameters content in dst, where sign writes // the digest. A // message the level encrypts gets the next salt of usm.Salts, never the -// packet's PrivacyParameters, so that no two messages share one, whatever the -// caller copied into the packet. -func (packet *Message) appendV3(dst []byte, keys *usmKeys, varBinds []byte) ([]byte, int, error) { - if err := packet.checkV3Header(); err != nil { +// message's PrivacyParameters, so that no two messages share one, whatever the +// caller copied into them. +func (m *Message) appendV3(dst []byte, keys *usmKeys, varBinds []byte) ([]byte, int, error) { + if err := m.checkV3Header(); err != nil { return nil, 0, err } - if err := checkLevel(keys.authProtocol, keys.privProtocol, packet.SecurityLevel); err != nil { + if err := checkLevel(keys.authProtocol, keys.privProtocol, m.SecurityLevel); err != nil { return nil, 0, err } - if err := packet.SecurityParameters.checkWireFields(); err != nil { + if err := m.SecurityParameters.checkWireFields(); err != nil { return nil, 0, err } var salt []byte - if packet.SecurityLevel.privFlag() { + if m.SecurityLevel.privFlag() { next := usm.Salts.Next() salt = next[:] } - dst = packet.appendV3Header(dst) + dst = m.appendV3Header(dst) dst, start := ber.Begin(dst, byte(OctetString)) - dst, auth := packet.SecurityParameters.marshal(dst, packet.SecurityLevel, keys.authProtocol, salt) + dst, auth := m.SecurityParameters.marshal(dst, m.SecurityLevel, keys.authProtocol, salt) dst, auth = ber.EndMoving(dst, start, auth) - dst, err := packet.appendV3ScopedPDU(dst, keys, salt, varBinds) + dst, err := m.appendV3ScopedPDU(dst, keys, salt, varBinds) return dst, auth, err } @@ -144,16 +144,16 @@ const ( // msgID of at most 2147483647, a MsgMaxSize of 0 (the receive buffer's size) or // 484..2147483647, and one of the three security levels (privacy without // authentication has its own error). -func (packet *Message) checkV3Header() error { +func (m *Message) checkV3Header() error { switch { - case packet.MsgID > maxMsgID: - return fmt.Errorf("unable to marshal SNMPv3 msgID %d: more than %d", packet.MsgID, maxMsgID) - case packet.MsgMaxSize != 0 && (packet.MsgMaxSize < minMsgMaxSize || packet.MsgMaxSize > maxMsgMaxSize): - return fmt.Errorf("unable to marshal SNMPv3 msgMaxSize %d: outside %d..%d", packet.MsgMaxSize, minMsgMaxSize, maxMsgMaxSize) - case packet.SecurityLevel.privFlag() && !packet.SecurityLevel.authFlag(): + case m.MsgID > maxMsgID: + return fmt.Errorf("unable to marshal SNMPv3 msgID %d: more than %d", m.MsgID, maxMsgID) + case m.MsgMaxSize != 0 && (m.MsgMaxSize < minMsgMaxSize || m.MsgMaxSize > maxMsgMaxSize): + return fmt.Errorf("unable to marshal SNMPv3 msgMaxSize %d: outside %d..%d", m.MsgMaxSize, minMsgMaxSize, maxMsgMaxSize) + case m.SecurityLevel.privFlag() && !m.SecurityLevel.authFlag(): return errors.New("unable to marshal SNMPv3 msgFlags: privacy without authentication") - case !packet.SecurityLevel.valid(): - return fmt.Errorf("unable to marshal SNMPv3 security level %d: not NoAuthNoPriv, AuthNoPriv or AuthPriv", packet.SecurityLevel) + case !m.SecurityLevel.valid(): + return fmt.Errorf("unable to marshal SNMPv3 security level %d: not NoAuthNoPriv, AuthNoPriv or AuthPriv", m.SecurityLevel) } return nil } @@ -163,16 +163,16 @@ func (packet *Message) checkV3Header() error { // ranges checkV3Header checked. The flags octet holds the security level and // the reportableFlag, set for a PDU of the Confirmed Class and clear for the // others (RFC 3412 section 6.4). -func (packet *Message) appendV3Header(dst []byte) []byte { +func (m *Message) appendV3Header(dst []byte) []byte { dst, start := ber.Begin(dst, ber.Sequence) - dst = appendUint(dst, Integer, uint64(packet.MsgID)) + dst = appendUint(dst, Integer, uint64(m.MsgID)) maxSize := uint32(rxBufSize) - if packet.MsgMaxSize != 0 { - maxSize = packet.MsgMaxSize + if m.MsgMaxSize != 0 { + maxSize = m.MsgMaxSize } dst = appendUint(dst, Integer, uint64(maxSize)) - flags := byte(packet.SecurityLevel) - if packet.PDUType.confirmed() { + flags := byte(m.SecurityLevel) + if m.PDUType.confirmed() { flags |= reportableFlag } dst = append(dst, byte(OctetString), 1, flags) @@ -184,18 +184,18 @@ func (packet *Message) appendV3Header(dst []byte) []byte { // ID, the context name and the PDU, encrypted with keys and salt into an OCTET // STRING when there is a salt (appendV3 draws it when the level asks for // privacy); the PDU with varBinds as appendPDU takes them. -func (packet *Message) appendV3ScopedPDU(dst []byte, keys *usmKeys, salt, varBinds []byte) ([]byte, error) { +func (m *Message) appendV3ScopedPDU(dst []byte, keys *usmKeys, salt, varBinds []byte) ([]byte, error) { scoped := len(dst) dst, start := ber.Begin(dst, ber.Sequence) - dst = appendOctets(dst, OctetString, packet.ContextEngineID) - dst = appendOctets(dst, OctetString, packet.ContextName) - dst, err := packet.appendPDU(dst, varBinds) + dst = appendOctets(dst, OctetString, m.ContextEngineID) + dst = appendOctets(dst, OctetString, m.ContextName) + dst, err := m.appendPDU(dst, varBinds) if err != nil { return nil, err } dst = ber.End(dst, start) if salt != nil { - ciphertext, err := keys.encrypt(&packet.SecurityParameters, dst[scoped:], salt) + ciphertext, err := keys.encrypt(&m.SecurityParameters, dst[scoped:], salt) if err != nil { return nil, err } @@ -248,7 +248,7 @@ func v3ParseError(err error) error { // parseV3 reads the SNMPv3 header at packet[cursor:]: the message ID, maximum // size, the security level of msgFlags and the USM fields (copies) into -// response, each as it decodes, and the offsets security processing needs into +// m, each as it decodes, and the offsets security processing needs into // the v3Wire it returns. It takes // net-snmp v5.9.4's extents: every declared length must fit what remains; the // fields of msgGlobalData are read against the rest of the message, whatever @@ -264,7 +264,7 @@ func v3ParseError(err error) error { // types, the engine boots and time within 0..2147483647 (RFC 3414 section 3.2 // step 1) and the user name at most 32 octets. It writes nothing into packet // and derives no key. -func parseV3(packet []byte, cursor int, response *Message) (v3Wire, error) { +func parseV3(packet []byte, cursor int, m *Message) (v3Wire, error) { w := v3Wire{authOff: -1} if packet[cursor] != ber.Sequence { return w, errors.New("invalid SNMPV3 Header") @@ -282,7 +282,7 @@ func parseV3(packet []byte, cursor int, response *Message) (v3Wire, error) { if err != nil { return w, fmt.Errorf("error parsing SNMPV3 message ID: %w", err) } - response.MsgID = uint32(msgID) //nolint:gosec // not negative + m.MsgID = uint32(msgID) //nolint:gosec // not negative w.msgIDRead = true maxSize, err := readInt32(&r) if err == nil && maxSize < minMsgMaxSize { @@ -291,7 +291,7 @@ func parseV3(packet []byte, cursor int, response *Message) (v3Wire, error) { if err != nil { return w, fmt.Errorf("error parsing SNMPV3 msgMaxSize: %w", err) } - response.MsgMaxSize = uint32(maxSize) //nolint:gosec // at least minMsgMaxSize + m.MsgMaxSize = uint32(maxSize) //nolint:gosec // at least minMsgMaxSize flags, err := readOctets(&r) switch { case errors.Is(err, errNotOctets): @@ -302,7 +302,7 @@ func parseV3(packet []byte, cursor int, response *Message) (v3Wire, error) { return w, errMsgFlags } // The level: the reportableFlag and the reserved bits stay on the wire. - response.SecurityLevel = SecurityLevel(flags[0]) & AuthPriv + m.SecurityLevel = SecurityLevel(flags[0]) & AuthPriv w.reportable = flags[0]&reportableFlag != 0 model, err := readInt32(&r) if err == nil && model < 1 { @@ -314,7 +314,7 @@ func parseV3(packet []byte, cursor int, response *Message) (v3Wire, error) { if model != usmSecurityModel { return w, errNotUSM } - if response.SecurityLevel.privFlag() && !response.SecurityLevel.authFlag() { + if m.SecurityLevel.privFlag() && !m.SecurityLevel.authFlag() { return w, errPrivWithoutAuth } if r.Len() == 0 { @@ -340,7 +340,7 @@ func parseV3(packet []byte, cursor int, response *Message) (v3Wire, error) { } ur := ber.NewReader(packet[usmStart:usmEnd]) - h := &response.SecurityParameters + h := &m.SecurityParameters engineID, err := usmOctets(&ur, "msgAuthoritativeEngineID") if err != nil { return w, err @@ -432,7 +432,7 @@ func tlvAt(packet []byte, off, end int) (start, stop int, err error) { // decryption failure, or a decrypted plaintext that does not parse, as with a // wrong key, ErrDecryption (net-snmp counts the latter as a parse error); a key // the process cannot decrypt with (usm.Priv.CheckUse) neither. -func unmarshalScopedPDU(packet []byte, cursor int, response *Message, encrypted bool, keys *usmKeys) ([]byte, int, error) { +func unmarshalScopedPDU(packet []byte, cursor int, m *Message, encrypted bool, keys *usmKeys) ([]byte, int, error) { if cursor >= len(packet) { return nil, 0, inCategory(ErrASNParse, errors.New("error parsing SNMPV3: truncated packet")) } @@ -453,7 +453,7 @@ func unmarshalScopedPDU(packet []byte, cursor int, response *Message, encrypted if err := keys.privProtocol.spec().CheckUse(keys.priv); err != nil { return nil, 0, fmt.Errorf("usm: decrypting: %w", err) } - plaintext, err := keys.decrypt(&response.SecurityParameters, packet[start:stop]) + plaintext, err := keys.decrypt(&m.SecurityParameters, packet[start:stop]) if err != nil { return nil, 0, inCategory(ErrDecryption, err) } @@ -471,7 +471,7 @@ func unmarshalScopedPDU(packet []byte, cursor int, response *Message, encrypted r = ber.NewReader(packet[start:]) } - if err := readContext(&r, response); err != nil { + if err := readContext(&r, m); err != nil { if encrypted { return nil, 0, inCategory(ErrDecryption, err) } @@ -481,17 +481,17 @@ func unmarshalScopedPDU(packet []byte, cursor int, response *Message, encrypted } // readContext reads the scoped PDU's contextEngineID (a copy) and contextName, -// OCTET STRINGs, into response; a field read before an error stays set. -func readContext(r *ber.Reader, response *Message) error { +// OCTET STRINGs, into m; a field read before an error stays set. +func readContext(r *ber.Reader, m *Message) error { engineID, err := readOctets(r) if err != nil { return fmt.Errorf("error parsing SNMPV3 contextEngineID: %w", err) } - response.ContextEngineID = bytes.Clone(engineID) + m.ContextEngineID = bytes.Clone(engineID) name, err := readOctets(r) if err != nil { return fmt.Errorf("error parsing SNMPV3 contextName: %w", err) } - response.ContextName = string(name) + m.ContextName = string(name) return nil } diff --git a/v3_parse_test.go b/v3_parse_test.go index b565a7b..a219046 100644 --- a/v3_parse_test.go +++ b/v3_parse_test.go @@ -331,7 +331,7 @@ func TestV3DecodeKeyDerivation(t *testing.T) { craftedUSM(octets(engineID), intTLV(1), intTLV(2), octets("codec-user"), octets(""), octets("")), tlv(0x30, octets(engineID), octets(""), craftedPDU(Report, craftedVBL(craftedVB(intTLV(5)))))) before := passwordCache.Len() - _, _, _ = (&exchange{x: x, packet: req, sec: attemptSecurity{keys: keys}}).decode(report, nil) + _, _, _ = (&exchange{c: x, req: req, sec: attemptSecurity{keys: keys}}).decode(report, nil) assert.Zero(t, passwordCache.Len()-before) }) } @@ -352,7 +352,7 @@ func TestV3ReplyDecode(t *testing.T) { Version: Version3, SecurityLevel: flags, SecurityParameters: signedTestHeader(usmCharEngineID, "codec-user"), MsgID: 7, PDUType: GetRequest, } - return &exchange{x: x, packet: req, sec: attemptSecurity{keys: keys}}, user + return &exchange{c: x, req: req, sec: attemptSecurity{keys: keys}}, user } // reply encodes a message from codec-user at usmCharEngineID, for user's // keys unless user is nil. @@ -434,7 +434,7 @@ func TestV3ReplyDecode(t *testing.T) { // A msgID means nothing to an SNMPv2c request. t.Run("SNMPv3 message to an SNMPv2c request", func(t *testing.T) { - e := &exchange{x: mustClient(Config{Version: Version2c}), packet: &Message{Version: Version2c, PDUType: GetRequest}} + e := &exchange{c: mustClient(Config{Version: Version2c}), req: &Message{Version: Version2c, PDUType: GetRequest}} msg := craftedV3(intTLV(7), intTLV(65507), octets("\x00"), intTLV(3), craftedUSM(octets(usmCharEngineID), intTLV(3), intTLV(77), octets("codec-user"), octets(""), octets("")), tlv(0x30, octets(usmCharEngineID), octets(""), craftedPDU(Response, craftedVBL(craftedVB(intTLV(5)))))) @@ -504,7 +504,7 @@ func TestV3ReplyDecode(t *testing.T) { SecurityLevel: AuthNoPriv, SecurityParameters: signedTestHeader(usmCharEngineID, "codec-user"), PDUType: Response, RequestID: 1, VarBinds: usmPlainVars, }, &sender) - got, _, err := (&exchange{x: x, packet: req}).decode(data, nil) + got, _, err := (&exchange{c: x, req: req}).decode(data, nil) require.NotNil(t, got, "the message as far as decode read it") assert.Equal(t, uint32(7), got.MsgID) require.ErrorIs(t, err, ErrUnknownSecurityLevel) diff --git a/v3_usm.go b/v3_usm.go index 5251c6f..8d30cbe 100644 --- a/v3_usm.go +++ b/v3_usm.go @@ -37,8 +37,8 @@ const ( // hash returns the hash of the protocol's HMAC and key derivation: MD5 for // NoAuth, unset and unknown values. -func (authProtocol AuthProtocol) hash() crypto.Hash { - if h := authProtocol.spec().Hash; h != 0 { +func (a AuthProtocol) hash() crypto.Hash { + if h := a.spec().Hash; h != 0 { return h } return crypto.MD5 @@ -56,9 +56,9 @@ var authSpecs = [...]usm.Auth{ //nolint:gochecknoglobals // a read-only table // spec describes the protocol; NoAuth, unset and unknown values have no // description. -func (authProtocol AuthProtocol) spec() usm.Auth { - if int(authProtocol) < len(authSpecs) { - return authSpecs[authProtocol] +func (a AuthProtocol) spec() usm.Auth { + if int(a) < len(authSpecs) { + return authSpecs[a] } return usm.Auth{} } @@ -101,9 +101,9 @@ var privSpecs = [...]usm.Priv{ //nolint:gochecknoglobals // a read-only table // spec describes the protocol; NoPriv, unset and unknown values have no // description. -func (privProtocol PrivProtocol) spec() usm.Priv { - if int(privProtocol) < len(privSpecs) { - return privSpecs[privProtocol] +func (p PrivProtocol) spec() usm.Priv { + if int(p) < len(privSpecs) { + return privSpecs[p] } return usm.Priv{} } diff --git a/v3_usm_test.go b/v3_usm_test.go index c2ae09c..d3bf976 100644 --- a/v3_usm_test.go +++ b/v3_usm_test.go @@ -632,7 +632,7 @@ func TestUSMFIPS140OnlyDecrypt(t *testing.T) { "raw": func() error { _, err := client().DecodeMessage(bytes.Clone(trap)); return err }, "reply": func() error { req := &Message{Version: Version3, SecurityLevel: AuthPriv, SecurityParameters: header, MsgID: 7} - e := exchange{x: client(), packet: req, sec: attemptSecurity{keys: keys}} + e := exchange{c: client(), req: req, sec: attemptSecurity{keys: keys}} _, _, err := e.decode(reply, nil) return err }, diff --git a/walk.go b/walk.go index 818df94..f105cbe 100644 --- a/walk.go +++ b/walk.go @@ -53,8 +53,8 @@ import ( // 2147483647, the most RFC 3416 allows, fails the walk before its first // request is sent. Some devices fail with large values; see // https://github.com/gosnmp/gosnmp/issues/100. -func (x *Client) BulkWalkAll(ctx context.Context, rootOid string, maxRepetitions uint32) (results []VarBind, end WalkEnd, err error) { - return x.walk(ctx, GetBulkRequest, rootOid, maxRepetitions) +func (c *Client) BulkWalkAll(ctx context.Context, rootOid string, maxRepetitions uint32) (results []VarBind, end WalkEnd, err error) { + return c.walk(ctx, GetBulkRequest, rootOid, maxRepetitions) } // WalkAll walks the subtree under rootOid with GETNEXT requests, one per @@ -63,8 +63,8 @@ func (x *Client) BulkWalkAll(ctx context.Context, rootOid string, maxRepetitions // and fails as BulkWalkAll does; net-snmp's snmpwalk differs only for a name // before rootOid, which fails its increasing check where WalkAll ends (or, as // the first answer, gets rootOid). -func (x *Client) WalkAll(ctx context.Context, rootOid string) (results []VarBind, end WalkEnd, err error) { - return x.walk(ctx, GetNextRequest, rootOid, 0) +func (c *Client) WalkAll(ctx context.Context, rootOid string) (results []VarBind, end WalkEnd, err error) { + return c.walk(ctx, GetNextRequest, rootOid, 0) } // WalkEnd is how a walk ended without an error: what ended it, and the @@ -115,7 +115,7 @@ const ( // default; it is checked after the root, before the first request. Each // request runs within ctx. An error ends the walk with the values collected // before it. -func (x *Client) walk(ctx context.Context, requestType PDUType, rootOid string, maxRepetitions uint32) (results []VarBind, end WalkEnd, err error) { +func (c *Client) walk(ctx context.Context, requestType PDUType, rootOid string, maxRepetitions uint32) (results []VarBind, end WalkEnd, err error) { root, err := walkRoot(rootOid) if err != nil { return nil, WalkEnd{}, err @@ -126,7 +126,7 @@ func (x *Client) walk(ctx context.Context, requestType PDUType, rootOid string, return nil, WalkEnd{}, fmt.Errorf("max-repetitions %d is more than %d", maxRepetitions, math.MaxInt32) } w := walker{ - x: x, + c: c, requestType: requestType, root: root, maxReps: cmp.Or(maxRepetitions, defaultMaxRepetitions), @@ -166,7 +166,7 @@ func (x *Client) walk(ctx context.Context, requestType PDUType, rootOid string, // walker holds what a walk fixes at its start. type walker struct { - x *Client + c *Client // requestType is GetNextRequest or GetBulkRequest. requestType PDUType root string @@ -212,16 +212,16 @@ func walkRoot(rootOid string) (string, error) { func (w *walker) request(ctx context.Context, oid string) (*Message, error) { var maxReps uint32 if w.requestType == GetBulkRequest { - if w.x.config.Version == Version1 { + if w.c.config.Version == Version1 { return nil, errors.New("GETBULK not supported in SNMPv1") } maxReps = w.maxReps } - packetOut, err := w.x.oidRequest(w.requestType, []string{oid}, maxReps) + req, err := w.c.oidRequest(w.requestType, []string{oid}, maxReps) if err != nil { return nil, err } - return w.x.send(ctx, packetOut) + return w.c.send(ctx, req) } // visit applies the walk's end rule, net-snmp's (apps/snmpwalk.c and @@ -238,28 +238,28 @@ func (w *walker) visit(response *Message, oid string, firstAnswer bool, results return results, WalkEnd{Reason: WalkEmpty}, walkDone, nil } - for i, pdu := range response.VarBinds { + for i, vb := range response.VarBinds { // A name outside the subtree ends the walk; as the walk's first value, // it shows the root to be a leaf (gosnmp/gosnmp#78). - if !inSubtree(pdu.Name, w.root) { + if !inSubtree(vb.Name, w.root) { if firstAnswer && i == 0 { return results, WalkEnd{}, walkGetRoot, nil } - return results, WalkEnd{Reason: WalkOutside, VarBind: pdu}, walkDone, nil + return results, WalkEnd{Reason: WalkOutside, VarBind: vb}, walkDone, nil } // An exception value (RFC 3416 section 4.2) ends the walk, also as its // first value, without the leaf Get, as in net-snmp's snmpwalk: a leaf // root that is the MIB's last object answers endOfMibView and is not // fetched. - if isException(pdu.Value.Type()) { - return results, WalkEnd{Reason: WalkException, VarBind: pdu}, walkDone, nil + if isException(vb.Value.Type()) { + return results, WalkEnd{Reason: WalkException, VarBind: vb}, walkDone, nil } // Each name is compared with the request's, as net-snmp's // snmpbulkwalk does: a name equal to the root fails too. - if oidCompare(oid, pdu.Name) >= 0 { - return results, WalkEnd{}, walkDone, fmt.Errorf("OID not increasing: %s >= %s", oid, pdu.Name) + if oidCompare(oid, vb.Name) >= 0 { + return results, WalkEnd{}, walkDone, fmt.Errorf("OID not increasing: %s >= %s", oid, vb.Name) } - results = append(results, pdu) + results = append(results, vb) } return results, WalkEnd{}, walkContinue, nil } @@ -273,7 +273,7 @@ func (w *walker) visit(response *Message, oid string, firstAnswer bool, results // Get fails the walk. func (w *walker) getRoot(ctx context.Context, results []VarBind) ([]VarBind, WalkEnd, error) { end := WalkEnd{Reason: WalkLeaf} - response, err := w.x.Get(ctx, []string{w.root}) + response, err := w.c.Get(ctx, []string{w.root}) switch { case err == nil: case errors.As(err, new(*StatusError)): @@ -285,8 +285,8 @@ func (w *walker) getRoot(ctx context.Context, results []VarBind) ([]VarBind, Wal return results, end, nil } end.VarBind = response.VarBinds[0] - if pdu := end.VarBind; pdu.Name == w.root && !isException(pdu.Value.Type()) { - results = append(results, pdu) + if vb := end.VarBind; vb.Name == w.root && !isException(vb.Value.Type()) { + results = append(results, vb) } return results, end, nil } From c7e2ae78d5a578005c152d7445c46abd2508678d Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Wed, 11 Nov 2026 21:31:07 +0200 Subject: [PATCH 02/17] refactor: one file per responsibility for the client and the message gosnmp.go held the client's configuration and constructor beside the value model's VarBind and ValueType, the PDU's ErrorStatus and the codec entry points. Each now lives with its kind: client.go holds Config, Client and NewClient; value.go VarBind and ValueType beside Value; message.go ErrorStatus and the codec entry points (NewMessage, EncodeMessage, DecodeMessage) beside Message and Encode. The client's test file follows its file. EncodeMessage's message is m, as the message's methods name it. Declarations moved only: each keeps its text and doc comment (EncodeMessage but for that local), and the //go:generate directives move with their types. --- client.go | 170 ++++++++++++++++++ gosnmp_test.go => client_test.go | 0 gosnmp.go | 296 ------------------------------- message.go | 112 +++++++++++- request.go | 23 --- value.go | 42 +++++ 6 files changed, 323 insertions(+), 320 deletions(-) create mode 100644 client.go rename gosnmp_test.go => client_test.go (100%) delete mode 100644 gosnmp.go diff --git a/client.go b/client.go new file mode 100644 index 0000000..41d232a --- /dev/null +++ b/client.go @@ -0,0 +1,170 @@ +// 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 and in each request of a walk. 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, and in each + // request of a walk, which carries one; 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 +} diff --git a/gosnmp_test.go b/client_test.go similarity index 100% rename from gosnmp_test.go rename to client_test.go diff --git a/gosnmp.go b/gosnmp.go deleted file mode 100644 index d6f8b5e..0000000 --- a/gosnmp.go +++ /dev/null @@ -1,296 +0,0 @@ -// 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 and in each request of a walk. 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, and in each - // request of a walk, which carries one; 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 -} - -// VarBind is a variable binding (varbind): the name of an object and its -// value. Requests, answers and traps carry them in Message.VarBinds. -type VarBind struct { - // Name is the object's OID in dotted form, such as ".1.3.6.1.2.1.1.1.0": - // with the leading dot when decoded from an OBJECT IDENTIFIER, with or - // without it when sent. A name a device sent as an OCTET STRING or an - // IpAddress is kept as text. - Name string - - // Value is the value; the requests of Get and the walks send Null. - Value Value -} - -//go:generate go tool -modfile=tools/go.mod stringer -type ValueType - -// ValueType is the BER tag of a varbind value, which names its type. -type ValueType byte - -// The value types: the SMI's (RFC 2578), ASN.1's Null, net-snmp's OpaqueFloat -// and OpaqueDouble, which it wraps in an Opaque, and the exceptions of RFC 3416 -// (NoSuchObject, NoSuchInstance, EndOfMibView). UnknownType is a value of a -// type the decoder does not decode, such as ASN.1's BOOLEAN or BIT STRING. -const ( - UnknownType ValueType = 0x00 - Integer ValueType = 0x02 - OctetString ValueType = 0x04 - Null ValueType = 0x05 - ObjectIdentifier ValueType = 0x06 - IPAddress ValueType = 0x40 - Counter32 ValueType = 0x41 - Gauge32 ValueType = 0x42 - TimeTicks ValueType = 0x43 - Opaque ValueType = 0x44 - Counter64 ValueType = 0x46 - Uinteger32 ValueType = 0x47 - OpaqueFloat ValueType = 0x78 - OpaqueDouble ValueType = 0x79 - NoSuchObject ValueType = 0x80 - NoSuchInstance ValueType = 0x81 - EndOfMibView ValueType = 0x82 -) - -//go:generate go tool -modfile=tools/go.mod stringer -type ErrorStatus - -// ErrorStatus is the error-status of a PDU (RFC 3416 section 3): NoError, or -// why the agent did not process a request as asked. -type ErrorStatus uint8 - -// The error statuses (RFC 3416; SNMPv1 has the first six). -const ( - NoError ErrorStatus = iota // No error occurred. This code is also used in all request PDUs, since they have no error status to report. - TooBig // The size of the Response-PDU would be too large to transport. - NoSuchName // The name of a requested object was not found. - BadValue // A value in the request didn't match the structure that the recipient of the request had for the object. For example, an object in the request was specified with an incorrect length or type. - ReadOnly // An attempt was made to set a variable that has an Access value indicating that it is read-only. - GenErr // An error occurred other than one indicated by a more specific error code in this table. - NoAccess // Access was denied to the object for security reasons. - WrongType // The object type in a variable binding is incorrect for the object. - WrongLength // A variable binding specifies a length incorrect for the object. - WrongEncoding // A variable binding specifies an encoding incorrect for the object. - WrongValue // The value given in a variable binding is not possible for the object. - NoCreation // A specified variable does not exist and cannot be created. - InconsistentValue // A variable binding specifies a value that could be held by the variable but cannot be assigned to it at this time. - ResourceUnavailable // An attempt to set a variable required a resource that is not available. - CommitFailed // An attempt to set a particular variable failed. - UndoFailed // An attempt to set a particular variable as part of a group of variables failed, and the attempt to then undo the setting of other variables was not successful. - AuthorizationError // A problem occurred in authorization. - NotWritable // The variable cannot be written or created. - InconsistentName // The name in a variable binding specifies a variable that does not exist. -) - -// EncodeMessage encodes a request or trap, for another transport or for tests: -// it builds the message with NewMessage and numbers it with the next request ID -// and, for SNMPv3, the next msgID, as a request's attempt does. An SNMPv3 -// message takes the client's engine state as a request starts it (startEngine): -// its engine ID and context engine ID, the keys localized to it, and the latest -// engine boots and time received, not advanced as a request's attempt advances -// them. It runs no discovery: before the client knows the agent's engine the -// message has no engine ID and no keys, so an authenticated or private one -// fails. On an error it returns no message. -func (c *Client) EncodeMessage(pduType PDUType, varBinds []VarBind, nonRepeaters uint8, maxRepetitions uint32) ([]byte, error) { - pkt := c.NewMessage(pduType, varBinds, nonRepeaters, maxRepetitions) - pkt.RequestID = c.nextRequestID() - var keys usmKeys - if c.config.Version == Version3 { - c.startEngine() - c.engine.stamp(pkt) - pkt.SecurityParameters.AuthoritativeEngineBoots = c.engine.clock.boots - pkt.SecurityParameters.AuthoritativeEngineTime = c.engine.clock.latest - keys = c.engine.keys - pkt.MsgID = c.nextMsgID() - } - return pkt.marshalMsg(&keys) -} - -// DecodeMessage decodes a message, from another transport or for tests; an -// SNMPv3 message with the configuration's User, whose keys it derives for the -// message's engine ID: the authentication key when the message asks for -// authentication, the privacy key to decrypt. Of the security processing (RFC -// 3414 section 3.2) it makes only the checks that need no digest: the user must -// have the protocols the message asks for, and the message is decrypted exactly -// when it asks for privacy; it checks neither the user name, the digest nor the -// time window, nor any minimum level. It does not write data (see the package -// documentation for the values that alias it). On an error it returns no -// message. -func (c *Client) DecodeMessage(data []byte) (*Message, error) { - result := new(Message) - cursor, w, err := unmarshalHeader(data, result) - if err != nil { - return nil, fmt.Errorf("unable to decode packet header: %w", err) - } - if result.Version == Version3 { - var in inbound - if in, err = receiveV3(data, w, result, &c.config.User, nil); err != nil { - return nil, fmt.Errorf("unable to decode packet header: %w", err) - } - if data, cursor, err = in.scopedPDU(result); err != nil { - return nil, err - } - } - if err = unmarshalPayload(data, cursor, result); err != nil { - return nil, fmt.Errorf("unable to decode packet body: %w", err) - } - return result, nil -} diff --git a/message.go b/message.go index c4e6988..1b38e0c 100644 --- a/message.go +++ b/message.go @@ -4,7 +4,11 @@ package gosnmp -import "net/netip" +import ( + "fmt" + "math" + "net/netip" +) // Version is the SNMP version of a message, as it is encoded. Its String // is "1", "2c" or "3", and "Version(N)" for another value. @@ -115,6 +119,57 @@ func (t PDUType) confirmed() bool { return false } +//go:generate go tool -modfile=tools/go.mod stringer -type ErrorStatus + +// ErrorStatus is the error-status of a PDU (RFC 3416 section 3): NoError, or +// why the agent did not process a request as asked. +type ErrorStatus uint8 + +// The error statuses (RFC 3416; SNMPv1 has the first six). +const ( + NoError ErrorStatus = iota // No error occurred. This code is also used in all request PDUs, since they have no error status to report. + TooBig // The size of the Response-PDU would be too large to transport. + NoSuchName // The name of a requested object was not found. + BadValue // A value in the request didn't match the structure that the recipient of the request had for the object. For example, an object in the request was specified with an incorrect length or type. + ReadOnly // An attempt was made to set a variable that has an Access value indicating that it is read-only. + GenErr // An error occurred other than one indicated by a more specific error code in this table. + NoAccess // Access was denied to the object for security reasons. + WrongType // The object type in a variable binding is incorrect for the object. + WrongLength // A variable binding specifies a length incorrect for the object. + WrongEncoding // A variable binding specifies an encoding incorrect for the object. + WrongValue // The value given in a variable binding is not possible for the object. + NoCreation // A specified variable does not exist and cannot be created. + InconsistentValue // A variable binding specifies a value that could be held by the variable but cannot be assigned to it at this time. + ResourceUnavailable // An attempt to set a variable required a resource that is not available. + CommitFailed // An attempt to set a particular variable failed. + UndoFailed // An attempt to set a particular variable as part of a group of variables failed, and the attempt to then undo the setting of other variables was not successful. + AuthorizationError // A problem occurred in authorization. + NotWritable // The variable cannot be written or created. + InconsistentName // The name in a variable binding specifies a variable that does not exist. +) + +// NewMessage builds a request or trap message of pduType with the varbinds +// varBinds from the client's version, community, SNMPv3 security level, user +// name and context name; maxRepetitions is kept with its top bit cleared. An +// SNMPv3 message's engine fields and context engine ID are left empty: a +// request takes them from the client's engine state, and the caller sets them +// for a message it encodes itself. +func (c *Client) NewMessage(pduType PDUType, varBinds []VarBind, nonRepeaters uint8, maxRepetitions uint32) *Message { + return &Message{ + Version: c.config.Version, + Community: c.config.Community, + SecurityLevel: c.config.SecurityLevel, + SecurityParameters: SecurityParameters{UserName: c.config.User.Name}, + ContextName: c.config.ContextName, + ErrorStatus: 0, + ErrorIndex: 0, + PDUType: pduType, + NonRepeaters: nonRepeaters, + MaxRepetitions: maxRepetitions & math.MaxInt32, + VarBinds: varBinds, + } +} + // Encode encodes the message as it is, ready for the wire. An SNMPv3 // message is encrypted and signed when its security level asks for it, with // user's keys localized to its engine ID (SecurityParameters' @@ -134,3 +189,58 @@ func (m *Message) Encode(user *User) ([]byte, error) { } return m.marshalMsg(&keys) } + +// EncodeMessage encodes a request or trap, for another transport or for tests: +// it builds the message with NewMessage and numbers it with the next request ID +// and, for SNMPv3, the next msgID, as a request's attempt does. An SNMPv3 +// message takes the client's engine state as a request starts it (startEngine): +// its engine ID and context engine ID, the keys localized to it, and the latest +// engine boots and time received, not advanced as a request's attempt advances +// them. It runs no discovery: before the client knows the agent's engine the +// message has no engine ID and no keys, so an authenticated or private one +// fails. On an error it returns no message. +func (c *Client) EncodeMessage(pduType PDUType, varBinds []VarBind, nonRepeaters uint8, maxRepetitions uint32) ([]byte, error) { + m := c.NewMessage(pduType, varBinds, nonRepeaters, maxRepetitions) + m.RequestID = c.nextRequestID() + var keys usmKeys + if c.config.Version == Version3 { + c.startEngine() + c.engine.stamp(m) + m.SecurityParameters.AuthoritativeEngineBoots = c.engine.clock.boots + m.SecurityParameters.AuthoritativeEngineTime = c.engine.clock.latest + keys = c.engine.keys + m.MsgID = c.nextMsgID() + } + return m.marshalMsg(&keys) +} + +// DecodeMessage decodes a message, from another transport or for tests; an +// SNMPv3 message with the configuration's User, whose keys it derives for the +// message's engine ID: the authentication key when the message asks for +// authentication, the privacy key to decrypt. Of the security processing (RFC +// 3414 section 3.2) it makes only the checks that need no digest: the user must +// have the protocols the message asks for, and the message is decrypted exactly +// when it asks for privacy; it checks neither the user name, the digest nor the +// time window, nor any minimum level. It does not write data (see the package +// documentation for the values that alias it). On an error it returns no +// message. +func (c *Client) DecodeMessage(data []byte) (*Message, error) { + result := new(Message) + cursor, w, err := unmarshalHeader(data, result) + if err != nil { + return nil, fmt.Errorf("unable to decode packet header: %w", err) + } + if result.Version == Version3 { + var in inbound + if in, err = receiveV3(data, w, result, &c.config.User, nil); err != nil { + return nil, fmt.Errorf("unable to decode packet header: %w", err) + } + if data, cursor, err = in.scopedPDU(result); err != nil { + return nil, err + } + } + if err = unmarshalPayload(data, cursor, result); err != nil { + return nil, fmt.Errorf("unable to decode packet body: %w", err) + } + return result, nil +} diff --git a/request.go b/request.go index 1b42dfe..860110f 100644 --- a/request.go +++ b/request.go @@ -7,31 +7,8 @@ package gosnmp import ( "context" "fmt" - "math" ) -// NewMessage builds a request or trap message of pduType with the varbinds -// varBinds from the client's version, community, SNMPv3 security level, user -// name and context name; maxRepetitions is kept with its top bit cleared. An -// SNMPv3 message's engine fields and context engine ID are left empty: a -// request takes them from the client's engine state, and the caller sets them -// for a message it encodes itself. -func (c *Client) NewMessage(pduType PDUType, varBinds []VarBind, nonRepeaters uint8, maxRepetitions uint32) *Message { - return &Message{ - Version: c.config.Version, - Community: c.config.Community, - SecurityLevel: c.config.SecurityLevel, - SecurityParameters: SecurityParameters{UserName: c.config.User.Name}, - ContextName: c.config.ContextName, - ErrorStatus: 0, - ErrorIndex: 0, - PDUType: pduType, - NonRepeaters: nonRepeaters, - MaxRepetitions: maxRepetitions & math.MaxInt32, - VarBinds: varBinds, - } -} - // Get sends a GET request for oids, at most MaxOids of them, within ctx, and // returns the answer, a Response whose error-status is NoError; on an error it // returns no message, also when the agent's answer ended the request (an diff --git a/value.go b/value.go index 3d209d3..5a842cb 100644 --- a/value.go +++ b/value.go @@ -13,6 +13,48 @@ import ( "github.com/netdata/gosnmp/internal/ber" ) +// VarBind is a variable binding (varbind): the name of an object and its +// value. Requests, answers and traps carry them in Message.VarBinds. +type VarBind struct { + // Name is the object's OID in dotted form, such as ".1.3.6.1.2.1.1.1.0": + // with the leading dot when decoded from an OBJECT IDENTIFIER, with or + // without it when sent. A name a device sent as an OCTET STRING or an + // IpAddress is kept as text. + Name string + + // Value is the value; the requests of Get and the walks send Null. + Value Value +} + +//go:generate go tool -modfile=tools/go.mod stringer -type ValueType + +// ValueType is the BER tag of a varbind value, which names its type. +type ValueType byte + +// The value types: the SMI's (RFC 2578), ASN.1's Null, net-snmp's OpaqueFloat +// and OpaqueDouble, which it wraps in an Opaque, and the exceptions of RFC 3416 +// (NoSuchObject, NoSuchInstance, EndOfMibView). UnknownType is a value of a +// type the decoder does not decode, such as ASN.1's BOOLEAN or BIT STRING. +const ( + UnknownType ValueType = 0x00 + Integer ValueType = 0x02 + OctetString ValueType = 0x04 + Null ValueType = 0x05 + ObjectIdentifier ValueType = 0x06 + IPAddress ValueType = 0x40 + Counter32 ValueType = 0x41 + Gauge32 ValueType = 0x42 + TimeTicks ValueType = 0x43 + Opaque ValueType = 0x44 + Counter64 ValueType = 0x46 + Uinteger32 ValueType = 0x47 + OpaqueFloat ValueType = 0x78 + OpaqueDouble ValueType = 0x79 + NoSuchObject ValueType = 0x80 + NoSuchInstance ValueType = 0x81 + EndOfMibView ValueType = 0x82 +) + // Value is a varbind's value: its type and the number, octets or OID it // holds. Each type holds one Go type, read through its accessor: // From bd0fb73dfad37b452dec3a912091b9220af06db0 Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Wed, 11 Nov 2026 21:34:39 +0200 Subject: [PATCH 03/17] refactor: split the SNMPv3 header, scoped PDU, PDU fields and reply clock reads Four functions each did two things the RFCs name apart: - parseV3 read msgGlobalData and then msgSecurityParameters (RFC 3412 section 6, RFC 3414 section 2.4): readGlobalData and readSecurityParameters, each with the field rules it applies. - unmarshalScopedPDU's encrypted branch is the decryption of RFC 3414 section 3.2 step 8: decryptScopedPDU. - unmarshalResponse read every PDU but the SNMPv1 trap, and either the GetBulk fields or the error fields (RFC 3416 section 3): unmarshalPDU, with readBulkFields and readErrorFields. - settle decided whether a reply commits the engine state and then the clock it gives (RFC 3414 section 3.2 step 7 b): replyClock, which carries the clock rules from settle's doc. The code moves as it was; the goldens are unchanged. --- engine_v3.go | 86 ++++++++++++++++------------ pdu.go | 76 +++++++++++++++---------- v3.go | 157 +++++++++++++++++++++++++++++---------------------- 3 files changed, 186 insertions(+), 133 deletions(-) diff --git a/engine_v3.go b/engine_v3.go index 14a6c5a..62e9f58 100644 --- a/engine_v3.go +++ b/engine_v3.go @@ -61,23 +61,13 @@ var errReplyNotInTime = inCategory(ErrNotInTimeWindow, errors.New("the reply is // carrying an engine ID) gives the engine ID, its keys and an unauthenticated // clock, or ends the request when it names no engine ID or the keys do not // derive. A reply whose digest checked against the request (verified) gives -// its engine ID (another one takes keys derived for it, and no clock) and, by -// RFC 3414 section 3.2 step 7 b against the authenticated clock (none: the -// first authenticated message), its boots and time; an equal time updates the -// clock as a newer one does (net-snmp; a reply answers an outstanding request, -// so it replays nothing), and a reply outside the time window is discarded -// (resetsClock names the exception; an exchange that ends without an answer -// after one drops the clock, forgetEngineTime). -// Maximum boots are rejected before either recovery exception. An -// authenticated notInTimeWindow Report gives its boots and time whatever their -// order: the agent's own, matched to the request (a deviation from section 3.2 -// step 7 b, for devices whose boots do not go up when they restart). -// Unverified, a Response, which answers only a request without -// authentication and names its engine ID (exchange.answers: the engine state's, -// a lent one, or none for discovery), gives that engine ID and an -// unauthenticated clock, which does not replace an authenticated one -// (net-snmp's set_enginetime). A reply whose engine ID gives no valid state -// answers without a commit. +// its engine ID (another one takes keys derived for it, and no clock) and the +// clock replyClock gives; maximum boots are rejected before either recovery +// exception. Unverified, a Response, which answers only a request without +// authentication and names its engine ID (exchange.answers: the engine +// state's, a lent one, or none for discovery), gives that engine ID and the +// clock replyClock gives. A reply whose engine ID gives no valid state answers +// without a commit. func (e *exchange) settle(out attemptOutcome) (attemptOutcome, error) { c, reply := e.c, out.reply if reply.Version != Version3 { @@ -105,31 +95,53 @@ func (e *exchange) settle(out attemptOutcome) (attemptOutcome, error) { } return out, nil } - now := time.Now() + clock, ok := e.replyClock(next.clock, out.verified, kind, boots, engineTime, time.Now()) + if !ok { + return attemptOutcome{}, errReplyNotInTime + } + next.clock = clock + c.commitEngine(next) + out.committed = true + return out, nil +} + +// replyClock returns the clock the engine state takes from a reply that +// settles (settle), with engine boots and time received at now, given the +// clock the state has for the reply's engine ID (current); false for an +// authenticated reply outside the time window, which is discarded. An +// unverified reply gives an unauthenticated clock, which does not replace an +// authenticated one (net-snmp's set_enginetime). A verified reply's boots and +// time go by RFC 3414 section 3.2 step 7 b against the authenticated clock +// (none: the first authenticated message); an equal time updates the clock as +// a newer one does (net-snmp; a reply answers an outstanding request, so it +// replays nothing), and a reply outside the time window is discarded +// (resetsClock names the exception; an exchange that ends without an answer +// after one drops the clock, forgetEngineTime). An authenticated +// notInTimeWindow Report gives its boots and time whatever their order: the +// agent's own, matched to the request (a deviation from section 3.2 step 7 b, +// for devices whose boots do not go up when they restart). +func (e *exchange) replyClock(current sourcedClock, verified bool, kind reportKind, boots, engineTime uint32, now time.Time) (sourcedClock, bool) { switch { - case !out.verified: - if next.clock.source != fromAuthenticated { - next.clock = clockOf(boots, engineTime, now, fromUnauthenticated) + case !verified: + if current.source == fromAuthenticated { + return current, true } + return clockOf(boots, engineTime, now, fromUnauthenticated), true case kind.timeWindow: - next.clock = clockOf(boots, engineTime, now, fromAuthenticated) - default: - var clock engineClock - if next.clock.source == fromAuthenticated { - clock = next.clock.engineClock - } - clock, _ = clock.update(boots, engineTime, now, true) - if !clock.inWindow(boots, engineTime, now) { - if !e.resetsClock(boots, engineTime, now) { - return attemptOutcome{}, errReplyNotInTime - } - clock = engineClock{boots: boots, latest: engineTime, received: now} + return clockOf(boots, engineTime, now, fromAuthenticated), true + } + var clock engineClock + if current.source == fromAuthenticated { + clock = current.engineClock + } + clock, _ = clock.update(boots, engineTime, now, true) + if !clock.inWindow(boots, engineTime, now) { + if !e.resetsClock(boots, engineTime, now) { + return sourcedClock{}, false } - next.clock = sourcedClock{clock, fromAuthenticated} + clock = engineClock{boots: boots, latest: engineTime, received: now} } - c.commitEngine(next) - out.committed = true - return out, nil + return sourcedClock{clock, fromAuthenticated}, true } // forgetEngineTime drops the engine state's clock after an exchange that diff --git a/pdu.go b/pdu.go index f70c05c..eeee07c 100644 --- a/pdu.go +++ b/pdu.go @@ -282,7 +282,7 @@ func readPayload(packet []byte, cursor int, m *Message) error { } return nil } - if err := unmarshalResponse(packet[cursor:], requestType, m); err != nil { + if err := unmarshalPDU(packet[cursor:], requestType, m); err != nil { return fmt.Errorf("error in unmarshalResponse: %w", err) } return nil @@ -317,46 +317,62 @@ func requestIDRead(packet []byte, cursor int) bool { return err == nil } -// unmarshalResponse reads a PDU of pduType other than the SNMPv1 trap: the -// request ID, an Integer32 whose two's complement RequestID holds; the -// non-repeaters (readCount) and the max-repetitions, not negative (RFC 3416), of -// a GetBulkRequest, or the error status, 0..255, and the error index -// (readCount) of any other PDU; and the varbinds. Fields read before an error -// stay set. -func unmarshalResponse(packet []byte, pduType PDUType, m *Message) error { +// unmarshalPDU reads a PDU of pduType other than the SNMPv1 trap: the request +// ID, an Integer32 whose two's complement RequestID holds; the fields after it +// (readBulkFields of a GetBulkRequest, readErrorFields of any other PDU); and +// the varbinds. Fields read before an error stay set. +func unmarshalPDU(packet []byte, pduType PDUType, m *Message) error { r, requestID, err := readRequestID(packet) if err != nil { return err } m.RequestID = requestID if pduType == GetBulkRequest { - if m.NonRepeaters, err = readCount(&r); err != nil { - return fmt.Errorf("error parsing SNMP packet non repeaters: %w", err) - } - maxRepetitions, err := readInt32(&r) - if err == nil && maxRepetitions < 0 { - err = fmt.Errorf("%d is negative", maxRepetitions) - } - if err != nil { - return fmt.Errorf("error parsing SNMP packet max repetitions: %w", err) - } - m.MaxRepetitions = uint32(maxRepetitions) //nolint:gosec // not negative + err = readBulkFields(&r, m) } else { - errorStatus, err := readInt32(&r) - if err == nil && (errorStatus < 0 || errorStatus > math.MaxUint8) { - err = fmt.Errorf("%d is outside 0..255", errorStatus) - } - if err != nil { - return fmt.Errorf("error parsing SNMP packet error: %w", err) - } - m.ErrorStatus = ErrorStatus(errorStatus) //nolint:gosec // 0..255 - if m.ErrorIndex, err = readCount(&r); err != nil { - return fmt.Errorf("error parsing SNMP packet error index: %w", err) - } + err = readErrorFields(&r, m) + } + if err != nil { + return err } return unmarshalVBL(r.Rest(), m) } +// readBulkFields reads a GetBulkRequest's non-repeaters (readCount) and +// max-repetitions, not negative (RFC 3416 section 3). +func readBulkFields(r *ber.Reader, m *Message) error { + var err error + if m.NonRepeaters, err = readCount(r); err != nil { + return fmt.Errorf("error parsing SNMP packet non repeaters: %w", err) + } + maxRepetitions, err := readInt32(r) + if err == nil && maxRepetitions < 0 { + err = fmt.Errorf("%d is negative", maxRepetitions) + } + if err != nil { + return fmt.Errorf("error parsing SNMP packet max repetitions: %w", err) + } + m.MaxRepetitions = uint32(maxRepetitions) //nolint:gosec // not negative + return nil +} + +// readErrorFields reads a PDU's error status, 0..255, and error index +// (readCount) (RFC 3416 section 3). +func readErrorFields(r *ber.Reader, m *Message) error { + errorStatus, err := readInt32(r) + if err == nil && (errorStatus < 0 || errorStatus > math.MaxUint8) { + err = fmt.Errorf("%d is outside 0..255", errorStatus) + } + if err != nil { + return fmt.Errorf("error parsing SNMP packet error: %w", err) + } + m.ErrorStatus = ErrorStatus(errorStatus) //nolint:gosec // 0..255 + if m.ErrorIndex, err = readCount(r); err != nil { + return fmt.Errorf("error parsing SNMP packet error index: %w", err) + } + return nil +} + // unmarshalTrapV1 reads an SNMPv1 trap PDU: the enterprise, an OBJECT // IDENTIFIER; the agent address (readAgentAddress); the generic and specific // trap, INTEGERs cut to 32 bits; the timestamp (readTimestamp); and the diff --git a/v3.go b/v3.go index 3acc353..4dcc435 100644 --- a/v3.go +++ b/v3.go @@ -246,24 +246,13 @@ func v3ParseError(err error) error { return inCategory(ErrASNParse, err) } -// parseV3 reads the SNMPv3 header at packet[cursor:]: the message ID, maximum -// size, the security level of msgFlags and the USM fields (copies) into -// m, each as it decodes, and the offsets security processing needs into -// the v3Wire it returns. It takes -// net-snmp v5.9.4's extents: every declared length must fit what remains; the -// fields of msgGlobalData are read against the rest of the message, whatever -// its declared length; the USM fields are bounded by their SEQUENCE and the -// SEQUENCE by the security parameters' OCTET STRING; msgData starts right -// after msgPrivacyParameters. It takes net-snmp's field rules (RFC 3412 -// section 6, RFC 3414 section 2.4), each range applying once the INTEGER is -// cut to 32 bits: msgID an INTEGER of 0..2147483647, msgMaxSize one of -// 484..2147483647, msgFlags an OCTET STRING of one octet, the security model -// an INTEGER of 1..2147483647, the User-based Security Model's 3 (another -// value is another model), and then the flags may not ask for privacy without -// authentication; the USM fields of their -// types, the engine boots and time within 0..2147483647 (RFC 3414 section 3.2 -// step 1) and the user name at most 32 octets. It writes nothing into packet -// and derives no key. +// parseV3 reads the SNMPv3 header at packet[cursor:], msgGlobalData +// (readGlobalData) and then msgSecurityParameters (readSecurityParameters), +// into m, each field as it decodes, and the offsets security processing needs +// into the v3Wire it returns, also with an error. It takes net-snmp v5.9.4's +// extents: every declared length must fit what remains; the fields of +// msgGlobalData are read against the rest of the message, whatever its +// declared length. It writes nothing into packet and derives no key. func parseV3(packet []byte, cursor int, m *Message) (v3Wire, error) { w := v3Wire{authOff: -1} if packet[cursor] != ber.Sequence { @@ -273,111 +262,135 @@ func parseV3(packet []byte, cursor int, m *Message) (v3Wire, error) { if err != nil { return w, fmt.Errorf("error parsing SNMPV3 header: %w", err) } - r := ber.NewReader(packet[start:]) - msgID, err := readInt32(&r) + if err = readGlobalData(&r, m, &w); err != nil { + return w, err + } + if r.Len() == 0 { + return w, errors.New("error parsing SNMPV3: nothing after the security model") + } + err = readSecurityParameters(packet, len(packet)-r.Len(), m, &w) + return w, err +} + +// readGlobalData reads msgGlobalData from r into m and w (RFC 3412 section 6) +// by net-snmp's field rules, each range applying once the INTEGER is cut to +// 32 bits: msgID an INTEGER of 0..2147483647, msgMaxSize one of +// 484..2147483647, msgFlags an OCTET STRING of one octet, the security model +// an INTEGER of 1..2147483647, the User-based Security Model's 3 (another +// value is another model), and then the flags may not ask for privacy without +// authentication. +func readGlobalData(r *ber.Reader, m *Message, w *v3Wire) error { + msgID, err := readInt32(r) if err == nil && msgID < 0 { err = fmt.Errorf("%d is outside 0..%d", msgID, maxMsgID) } if err != nil { - return w, fmt.Errorf("error parsing SNMPV3 message ID: %w", err) + return fmt.Errorf("error parsing SNMPV3 message ID: %w", err) } m.MsgID = uint32(msgID) //nolint:gosec // not negative w.msgIDRead = true - maxSize, err := readInt32(&r) + maxSize, err := readInt32(r) if err == nil && maxSize < minMsgMaxSize { err = fmt.Errorf("%d is outside %d..%d", maxSize, minMsgMaxSize, maxMsgMaxSize) } if err != nil { - return w, fmt.Errorf("error parsing SNMPV3 msgMaxSize: %w", err) + return fmt.Errorf("error parsing SNMPV3 msgMaxSize: %w", err) } m.MsgMaxSize = uint32(maxSize) //nolint:gosec // at least minMsgMaxSize - flags, err := readOctets(&r) + flags, err := readOctets(r) switch { case errors.Is(err, errNotOctets): - return w, errMsgFlags + return errMsgFlags case err != nil: - return w, fmt.Errorf("error parsing SNMPV3 msgFlags: %w", err) + return fmt.Errorf("error parsing SNMPV3 msgFlags: %w", err) case len(flags) != 1: - return w, errMsgFlags + return errMsgFlags } // The level: the reportableFlag and the reserved bits stay on the wire. m.SecurityLevel = SecurityLevel(flags[0]) & AuthPriv w.reportable = flags[0]&reportableFlag != 0 - model, err := readInt32(&r) + model, err := readInt32(r) if err == nil && model < 1 { err = fmt.Errorf("%d is outside 1..2147483647", model) } if err != nil { - return w, fmt.Errorf("error parsing SNMPV3 msgSecModel: %w", err) + return fmt.Errorf("error parsing SNMPV3 msgSecModel: %w", err) } if model != usmSecurityModel { - return w, errNotUSM + return errNotUSM } if m.SecurityLevel.privFlag() && !m.SecurityLevel.authFlag() { - return w, errPrivWithoutAuth - } - if r.Len() == 0 { - return w, errors.New("error parsing SNMPV3: nothing after the security model") + return errPrivWithoutAuth } + return nil +} - if PDUType(packet[len(packet)-r.Len()]) != PDUType(OctetString) { - return w, errors.New("invalid SNMPV3 Security Parameters") - } - params, paramsEnd, err := tlvAt(packet, len(packet)-r.Len(), len(packet)) +// readSecurityParameters reads msgSecurityParameters, the OCTET STRING at +// packet[off:] that holds the User-based Security Model's parameters (RFC 3414 +// section 2.4), into m's SecurityParameters (copies) and w: the USM fields +// bounded by their SEQUENCE and the SEQUENCE by the OCTET STRING, each of its +// type, the engine boots and time within 0..2147483647 (RFC 3414 section 3.2 +// step 1) once cut to 32 bits, and the user name at most 32 octets; msgData +// starts right after msgPrivacyParameters. +func readSecurityParameters(packet []byte, off int, m *Message, w *v3Wire) error { + if PDUType(packet[off]) != PDUType(OctetString) { + return errors.New("invalid SNMPV3 Security Parameters") + } + params, paramsEnd, err := tlvAt(packet, off, len(packet)) if err != nil { - return w, fmt.Errorf("error parsing SNMPV3 security parameters: %w", err) + return fmt.Errorf("error parsing SNMPV3 security parameters: %w", err) } if params == paramsEnd { - return w, errors.New("error parsing SNMPV3 User Security Model parameters: end of packet") + return errors.New("error parsing SNMPV3 User Security Model parameters: end of packet") } if packet[params] != ber.Sequence { - return w, errors.New("error parsing SNMPV3 User Security Model parameters") + return errors.New("error parsing SNMPV3 User Security Model parameters") } usmStart, usmEnd, err := tlvAt(packet, params, paramsEnd) if err != nil { - return w, fmt.Errorf("error parsing SNMPV3 User Security Model parameters: %w", err) + return fmt.Errorf("error parsing SNMPV3 User Security Model parameters: %w", err) } ur := ber.NewReader(packet[usmStart:usmEnd]) h := &m.SecurityParameters engineID, err := usmOctets(&ur, "msgAuthoritativeEngineID") if err != nil { - return w, err + return err } if len(engineID) > maxDecodedEngineIDLen { return w, fmt.Errorf("error parsing %smsgAuthoritativeEngineID: %d octets, more than %d", usmField, len(engineID), maxDecodedEngineIDLen) } h.AuthoritativeEngineID = bytes.Clone(engineID) if h.AuthoritativeEngineBoots, err = usmEngineValue(&ur, "msgAuthoritativeEngineBoots"); err != nil { - return w, err + return err } if h.AuthoritativeEngineTime, err = usmEngineValue(&ur, "msgAuthoritativeEngineTime"); err != nil { - return w, err + return err } userName, err := usmOctets(&ur, "msgUserName") if err != nil { - return w, err + return err } if len(userName) > maxUserNameLen { - return w, fmt.Errorf("error parsing %smsgUserName: %d octets, more than %d", usmField, len(userName), maxUserNameLen) + return fmt.Errorf("error parsing %smsgUserName: %d octets, more than %d", usmField, len(userName), maxUserNameLen) } h.UserName = string(userName) authAt := usmEnd - ur.Len() authParams, err := usmOctets(&ur, "msgAuthenticationParameters") if err != nil { - return w, err + return err } h.AuthenticationParameters = bytes.Clone(authParams) authStart, authEnd, _ := tlvAt(packet, authAt, usmEnd) // read above w.authOff, w.authLen = authStart, authEnd-authStart privParams, err := usmOctets(&ur, "msgPrivacyParameters") if err != nil { - return w, err + return err } h.PrivacyParameters = bytes.Clone(privParams) w.scoped = usmEnd - ur.Len() - return w, nil + return nil } // usmOctets reads the next USM field, which must be an OCTET STRING (RFC 3414 @@ -450,23 +463,9 @@ func unmarshalScopedPDU(packet []byte, cursor int, m *Message, encrypted bool, k return nil, 0, inCategory(ErrASNParse, fmt.Errorf("error parsing SNMPV3 scoped PDU: %w", err)) } if encrypted { - if err := keys.privProtocol.spec().CheckUse(keys.priv); err != nil { - return nil, 0, fmt.Errorf("usm: decrypting: %w", err) - } - plaintext, err := keys.decrypt(&m.SecurityParameters, packet[start:stop]) - if err != nil { - return nil, 0, inCategory(ErrDecryption, err) + if packet, r, err = decryptScopedPDU(packet[start:stop], &m.SecurityParameters, keys); err != nil { + return nil, 0, err } - pr := ber.NewReader(plaintext) - tag, content, err := pr.Next() - if err == nil && tag != ber.Sequence { - err = fmt.Errorf("tag %#x, not a SEQUENCE", tag) - } - if err != nil { - return nil, 0, inCategory(ErrDecryption, fmt.Errorf("error parsing SNMPV3 decrypted scoped PDU: %w", err)) - } - packet = plaintext[:len(plaintext)-pr.Len()] - r = ber.NewReader(content) } else { r = ber.NewReader(packet[start:]) } @@ -480,6 +479,32 @@ func unmarshalScopedPDU(packet []byte, cursor int, m *Message, encrypted bool, k return packet, len(packet) - r.Len(), nil } +// decryptScopedPDU decrypts ciphertext, an encrypted scoped PDU's content, with +// keys and h's privacy parameters, engine boots and time (RFC 3414 section 3.2 +// step 8) and returns the plaintext SEQUENCE, which cuts off the padding, and a +// reader of its content. +// A key the process cannot decrypt with (usm.Priv.CheckUse) fails in no +// category; a decryption failure, or a plaintext that is not a SEQUENCE, is +// ErrDecryption. +func decryptScopedPDU(ciphertext []byte, h *SecurityParameters, keys *usmKeys) ([]byte, ber.Reader, error) { + if err := keys.privProtocol.spec().CheckUse(keys.priv); err != nil { + return nil, ber.Reader{}, fmt.Errorf("usm: decrypting: %w", err) + } + plaintext, err := keys.decrypt(h, ciphertext) + if err != nil { + return nil, ber.Reader{}, inCategory(ErrDecryption, err) + } + pr := ber.NewReader(plaintext) + tag, content, err := pr.Next() + if err == nil && tag != ber.Sequence { + err = fmt.Errorf("tag %#x, not a SEQUENCE", tag) + } + if err != nil { + return nil, ber.Reader{}, inCategory(ErrDecryption, fmt.Errorf("error parsing SNMPV3 decrypted scoped PDU: %w", err)) + } + return plaintext[:len(plaintext)-pr.Len()], ber.NewReader(content), nil +} + // readContext reads the scoped PDU's contextEngineID (a copy) and contextName, // OCTET STRINGs, into m; a field read before an error stays set. func readContext(r *ber.Reader, m *Message) error { From 6fa4bc136b0cd1960119aee2acb7546d6ffdaf6c Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Wed, 11 Nov 2026 21:50:24 +0200 Subject: [PATCH 04/17] test: pin the USM parameters' container and the clock a reply gives The USM parameters of a decoded SNMPv3 message must be a SEQUENCE: an OCTET STRING or a SET holding valid fields now fails the decode in a test, as it does in the code. replyClock gets a table test of its rules: an unverified reply's clock does not replace an authenticated one, a notInTimeWindow Report gives its boots and time whatever their order, a verified reply goes by the time window, an equal time updating the clock, and one outside it gives none unless it answers the resend a Report lent its clock to. --- codec_failure_test.go | 11 +++++-- engine_state_test.go | 69 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 2 deletions(-) diff --git a/codec_failure_test.go b/codec_failure_test.go index 61c7ca4..0018506 100644 --- a/codec_failure_test.go +++ b/codec_failure_test.go @@ -128,11 +128,15 @@ func TestDecodeFailureNoMessage(t *testing.T) { // parse with ErrASNParse, on the raw path too. func TestDecodeUSMFields(t *testing.T) { const engineID = "\x80\x00\x1f\x88\x04codec-engine" - fields := func(edit func(f [][]byte)) []byte { + // usm builds a message whose USM parameters are the fields, edited, in a + // container of tag, a SEQUENCE as sent. + usm := func(tag byte, edit func(f [][]byte)) []byte { f := [][]byte{octets(engineID), intTLV(7), intTLV(1234), octets("codec-user"), octets(""), octets("")} edit(f) - return craftedV3(intTLV(42), intTLV(65507), octets("\x00"), intTLV(3), tlv(0x30, f...), craftedScopedResp) + return craftedV3(intTLV(42), intTLV(65507), octets("\x00"), intTLV(3), tlv(tag, f...), craftedScopedResp) } + fields := func(edit func(f [][]byte)) []byte { return usm(0x30, edit) } + in := func(tag byte) []byte { return usm(tag, func([][]byte) {}) } tests := map[string]struct { in []byte invalid bool @@ -150,6 +154,9 @@ func TestDecodeUSMFields(t *testing.T) { "boots 4294967301": {in: fields(func(f [][]byte) { f[1] = intTLV(4294967301) })}, "boots -1": {in: fields(func(f [][]byte) { f[1] = intTLV(-1) }), invalid: true}, "time -2147483648": {in: fields(func(f [][]byte) { f[2] = intTLV(-2147483648) }), invalid: true}, + // The fields in another container than a SEQUENCE (RFC 3414 section 2.4). + "fields in an OCTET STRING": {in: in(byte(OctetString)), invalid: true}, + "fields in a SET": {in: in(0x31), invalid: true}, } for name, tc := range tests { t.Run(name, func(t *testing.T) { diff --git a/engine_state_test.go b/engine_state_test.go index 9eb1e29..99c77ea 100644 --- a/engine_state_test.go +++ b/engine_state_test.go @@ -264,6 +264,75 @@ func TestEngineTimeFor(t *testing.T) { } } +// TestEngineReplyClock pins the clock a settling reply gives +// (exchange.replyClock): an unverified reply's unauthenticated clock does not +// replace an authenticated one (net-snmp's set_enginetime); an authenticated +// notInTimeWindow Report gives its boots and time whatever their order; a +// verified reply goes by RFC 3414 section 3.2 step 7 b against the +// authenticated clock (boots 7, time 1000, 10 s ago), an equal time updating +// it, and one outside the time window gives none unless it answers the resend +// a notInTimeWindow Report lent its clock to (resetsClock). +func TestEngineReplyClock(t *testing.T) { + now := time.Unix(1_000_000_000, 0) + auth := clockOf(7, 1000, now.Add(-10*time.Second), fromAuthenticated) + unauth := clockOf(7, 1000, now.Add(-10*time.Second), fromUnauthenticated) + type result struct { + clock sourcedClock + ok bool + } + tests := map[string]struct { + current sourcedClock + verified bool + kind reportKind + lent sourcedClock + boots, engineTime uint32 + want result + }{ + "unverified, an authenticated clock kept": { + current: auth, boots: 3, engineTime: 5, want: result{auth, true}, + }, + "unverified, an unauthenticated clock replaced": { + current: unauth, boots: 3, engineTime: 5, want: result{clockOf(3, 5, now, fromUnauthenticated), true}, + }, + "unverified, no clock": { + boots: 3, engineTime: 5, want: result{clockOf(3, 5, now, fromUnauthenticated), true}, + }, + "notInTimeWindow Report, lower boots": { + current: auth, verified: true, kind: reportKind{timeWindow: true}, boots: 3, engineTime: 5, + want: result{clockOf(3, 5, now, fromAuthenticated), true}, + }, + "verified, first authenticated": { + current: unauth, verified: true, boots: 3, engineTime: 5, want: result{clockOf(3, 5, now, fromAuthenticated), true}, + }, + "verified, newer time": { + current: auth, verified: true, boots: 7, engineTime: 1020, want: result{clockOf(7, 1020, now, fromAuthenticated), true}, + }, + "verified, equal time": { + current: auth, verified: true, boots: 7, engineTime: 1000, want: result{clockOf(7, 1000, now, fromAuthenticated), true}, + }, + "verified, older within the window": { + current: auth, verified: true, boots: 7, engineTime: 900, want: result{auth, true}, + }, + "verified, lower boots": { + current: auth, verified: true, boots: 6, engineTime: 1000, + }, + "verified, 220 s behind": { + current: auth, verified: true, boots: 7, engineTime: 790, + }, + "verified, 220 s behind, answering a lent clock": { + current: auth, verified: true, lent: clockOf(7, 790, now, fromTimeWindowReport), boots: 7, engineTime: 790, + want: result{clockOf(7, 790, now, fromAuthenticated), true}, + }, + } + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + e := &exchange{sec: attemptSecurity{clock: tc.lent}} + clock, ok := e.replyClock(tc.current, tc.verified, tc.kind, tc.boots, tc.engineTime, now) + assert.Equal(t, tc.want, result{clock, ok}) + }) + } +} + // TestEngineResetsClock pins when a verified answer outside the time window // sets the clock (exchange.resetsClock): when it answers a resend an // unauthenticated notInTimeWindow Report lent its clock (boots 7, time 3, 10 s From d68f8712d7bfb4b2cda711c00a9d79718cd31a8b Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Wed, 11 Nov 2026 21:55:54 +0200 Subject: [PATCH 05/17] fix: name the PDU, not a function, in the PDU decode errors The errors of a PDU that does not decode began with the name of the function that read it: "error in unmarshalResponse: ", which the PDU's reader no longer has, and "error in unmarshalTrapV1: ". They now say what failed to decode: "error in the PDU: " and "error in the SNMPv1 trap PDU: ". Their categories are unchanged (ErrASNParse); the request golden's seven lines that record the first text change with it. --- codec_failure_test.go | 4 ++-- pdu.go | 4 ++-- testdata/engine/requests.golden | 14 +++++++------- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/codec_failure_test.go b/codec_failure_test.go index 0018506..940aee6 100644 --- a/codec_failure_test.go +++ b/codec_failure_test.go @@ -27,8 +27,8 @@ func TestDecodeFailureNoMessage(t *testing.T) { } const ( header = "unable to decode packet header: " - body = "unable to decode packet body: error in unmarshalResponse: " - trapV1 = "unable to decode packet body: error in unmarshalTrapV1: error parsing SNMPv1 trap " + body = "unable to decode packet body: error in the PDU: " + trapV1 = "unable to decode packet body: error in the SNMPv1 trap PDU: error parsing SNMPv1 trap " usm = header + "error parsing SNMPV3 User Security Model " notInt = ": not an INTEGER" notStr = ": not an OCTET STRING" diff --git a/pdu.go b/pdu.go index eeee07c..a858257 100644 --- a/pdu.go +++ b/pdu.go @@ -278,12 +278,12 @@ func readPayload(packet []byte, cursor int, m *Message) error { m.PDUType = requestType if requestType == Trap { if err := unmarshalTrapV1(packet[cursor:], m); err != nil { - return fmt.Errorf("error in unmarshalTrapV1: %w", err) + return fmt.Errorf("error in the SNMPv1 trap PDU: %w", err) } return nil } if err := unmarshalPDU(packet[cursor:], requestType, m); err != nil { - return fmt.Errorf("error in unmarshalResponse: %w", err) + return fmt.Errorf("error in the PDU: %w", err) } return nil } diff --git a/testdata/engine/requests.golden b/testdata/engine/requests.golden index 27cd840..bd82aac 100644 --- a/testdata/engine/requests.golden +++ b/testdata/engine/requests.golden @@ -458,17 +458,17 @@ 0s deadline +1s 0s write #1: 2c "public" GetRequest id=1001 [.1.3.6.1.2.1.1.1.0] 0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 52 octets, not decodable (error in unmarshalResponse: error parsing SNMP packet error: -1 is outside 0..255) +0s read from 127.0.0.2:161: 52 octets, not decodable (error in the PDU: error parsing SNMP packet error: -1 is outside 0..255) 1s read from 127.0.0.2:161: deadline 1s deadline +1s 1s write #2: 2c "public" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] 1s agent answers #2 after 0s -1s read from 127.0.0.2:161: 52 octets, not decodable (error in unmarshalResponse: error parsing SNMP packet error: -1 is outside 0..255) +1s read from 127.0.0.2:161: 52 octets, not decodable (error in the PDU: error parsing SNMP packet error: -1 is outside 0..255) 2s read from 127.0.0.2:161: deadline 2s deadline +1s 2s write #3: 2c "public" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] 2s agent answers #3 after 0s -2s read from 127.0.0.2:161: 52 octets, not decodable (error in unmarshalResponse: error parsing SNMP packet error: -1 is outside 0..255) +2s read from 127.0.0.2:161: 52 octets, not decodable (error in the PDU: error parsing SNMP packet error: -1 is outside 0..255) 3s read from 127.0.0.2:161: deadline 3s result: packet nil, error "request timeout (after 2 retries)" *gosnmp.attemptsError (is os.ErrDeadlineExceeded, net.Error timeout) 3s client after: next request id=1004 @@ -479,24 +479,24 @@ 0s write #1: 2c "public" GetRequest id=1001 [.1.3.6.1.2.1.1.1.0] 0s agent answers #1 after 0s 0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 52 octets, not decodable (error in unmarshalResponse: error parsing SNMP packet error: -1 is outside 0..255) +0s read from 127.0.0.2:161: 52 octets, not decodable (error in the PDU: error parsing SNMP packet error: -1 is outside 0..255) 0s read from 127.0.0.2:161: 4 octets, not decodable (error verifying packet sanity: invalid packet length: TLV length exceeds the remaining input) 1s read from 127.0.0.2:161: deadline 1s deadline +1s 1s write #2: 2c "public" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] 1s agent answers #2 after 0s 1s agent answers #2 after 0s -1s read from 127.0.0.2:161: 52 octets, not decodable (error in unmarshalResponse: error parsing SNMP packet error: -1 is outside 0..255) +1s read from 127.0.0.2:161: 52 octets, not decodable (error in the PDU: error parsing SNMP packet error: -1 is outside 0..255) 1s read from 127.0.0.2:161: 4 octets, not decodable (error verifying packet sanity: invalid packet length: TLV length exceeds the remaining input) 2s read from 127.0.0.2:161: deadline 2s deadline +1s 2s write #3: 2c "public" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] 2s agent answers #3 after 0s 2s agent answers #3 after 0s -2s read from 127.0.0.2:161: 52 octets, not decodable (error in unmarshalResponse: error parsing SNMP packet error: -1 is outside 0..255) +2s read from 127.0.0.2:161: 52 octets, not decodable (error in the PDU: error parsing SNMP packet error: -1 is outside 0..255) 2s read from 127.0.0.2:161: 4 octets, not decodable (error verifying packet sanity: invalid packet length: TLV length exceeds the remaining input) 3s read from 127.0.0.2:161: deadline -3s result: packet nil, error "request timeout (after 2 retries): last discarded reply: error in unmarshalResponse: error parsing SNMP packet error: -1 is outside 0..255" *gosnmp.attemptsError (is os.ErrDeadlineExceeded, ErrASNParse, net.Error timeout) +3s result: packet nil, error "request timeout (after 2 retries): last discarded reply: error in the PDU: error parsing SNMP packet error: -1 is outside 0..255" *gosnmp.attemptsError (is os.ErrDeadlineExceeded, ErrASNParse, net.Error timeout) 3s client after: next request id=1004 == requests/answer/unknown-pdu-type From a2e09371b9842e9519957a0bb6d889c8f0361948 Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Wed, 11 Nov 2026 21:56:37 +0200 Subject: [PATCH 06/17] docs: order the package documentation from the API to the protocol The package documentation grew a section at a time with the API. Its sections now run from what a caller uses first to the protocol rules underneath: Lifecycle, Concurrency, Walks, Values, Errors and Notifications, then Attempts and timeouts, SNMPv3, Keys, Encoding and decoding (Decoding with the encoder's checks of the message's fields, which were under Values) and Panics. Every paragraph is reflowed to whole lines. Order and line breaks only: a sentence-by-sentence comparison finds the same 149 sentences before and after. --- doc.go | 656 ++++++++++++++++++++++++++++----------------------------- 1 file changed, 326 insertions(+), 330 deletions(-) diff --git a/doc.go b/doc.go index 40f118c..974920f 100644 --- a/doc.go +++ b/doc.go @@ -8,8 +8,8 @@ // makes their answers. It writes no log or other output and never exits the // process: its functions report through their 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, and Receive, whose Report to a -// rejected message comes with the error (see Notifications). +// values it collected before the error, and Receive, whose Report to a rejected +// message comes with the error (see Notifications). // // # Lifecycle // @@ -23,21 +23,21 @@ // client's connection, a UDP socket connected to Target and Port, which // replaces the one it had (a failed Connect keeps it); an empty Target fails // it, and a client that only encodes and decodes messages needs neither. The -// client has no other connection: a request before its first successful -// Connect fails before it sends anything, with an error that says so. The -// client owns its connection: [Client.Close] closes it, and so does a Connect -// that replaces it. Connect may be called again after Close. A request -// resolves no name: Connect looks up Target, and a request writes to the peer -// of the socket Connect opened. The request IDs and msgIDs start at random -// values NewClient draws, and Connect does not reset them. -// -// Connect, Get and the walks take a context first, which bounds that call -// only: Connect's lookup of Target and its dial, not the connection; each -// attempt of a request (see Attempts and timeouts); a walk's every request, -// the Get of a leaf root included. A request that its context ends returns no -// message and an error that matches the context's error, [context.Canceled], -// or [context.DeadlineExceeded] at its deadline (see Attempts and timeouts), -// and does not match [ErrAnswered], also after an answered discovery or resync +// client has no other connection: a request before its first successful Connect +// fails before it sends anything, with an error that says so. The client owns +// its connection: [Client.Close] closes it, and so does a Connect that replaces +// it. Connect may be called again after Close. A request resolves no name: +// Connect looks up Target, and a request writes to the peer of the socket +// Connect opened. The request IDs and msgIDs start at random values NewClient +// draws, and Connect does not reset them. +// +// Connect, Get and the walks take a context first, which bounds that call only: +// Connect's lookup of Target and its dial, not the connection; each attempt of +// a request (see Attempts and timeouts); a walk's every request, the Get of a +// leaf root included. A request that its context ends returns no message and an +// error that matches the context's error, [context.Canceled], or +// [context.DeadlineExceeded] at its deadline (see Attempts and timeouts), and +// does not match [ErrAnswered], also after an answered discovery or resync // Report (see SNMPv3); a walk returns the values before it with that error. // Once Close has run, the error wraps [net.ErrClosed] instead (see // Concurrency). A nil context fails the call with an error before it sends or @@ -55,12 +55,223 @@ // context included, and so do later requests until Connect opens a connection. // A [Receiver] and the package's key cache are safe for concurrent use. // +// # Walks +// +// [Client.WalkAll] and [Client.BulkWalkAll] return the values of a subtree, in +// order, and how the walk ended ([WalkEnd]): the reason, and the varbind that +// ended it, such as the first name outside the subtree, an EndOfMibView, or the +// answer to the Get of a root that is a leaf, whose NoSuchObject or +// NoSuchInstance tells an object the agent does not have from an instance it +// does not have. A walk that fails returns the values before its error. +// BulkWalkAll takes the max-repetitions of its GETBULK requests as an argument. +// Their docs say how a walk starts and ends. +// +// # Values +// +// A varbind ([VarBind]) holds a [Value]: its type and one Go type per type, the +// same on every platform, read through the type's accessor (each returns false +// for a value of another type): +// +// - Integer: int32 ([Value.Int32]) +// - Counter32, Gauge32, TimeTicks, Uinteger32: uint32 ([Value.Uint32]) +// - Counter64: uint64 ([Value.Uint64]) +// - OctetString, Opaque: []byte, empty included ([Value.Bytes]) +// - ObjectIdentifier: a dotted string, with a leading dot when decoded +// ([Value.OID]) +// - IPAddress: a netip.Addr ([Value.IP]): an IPv4 address, or what some +// devices send instead: the zero Addr for an empty one, an IPv6 address for +// 16 octets (an IPv4-mapped one reads as the IPv4 address) +// - OpaqueFloat: float32 ([Value.Float32]); OpaqueDouble: float64 +// ([Value.Float64]); net-snmp's floats, wrapped in an Opaque +// - Null, NoSuchObject, NoSuchInstance, EndOfMibView: no value +// - UnknownType, the zero Value: no value; the decoder gives it for a type it +// does not decode (ASN.1's BOOLEAN or BIT STRING: SMIv2 sends BITS as an +// OctetString) and for a Uinteger32, Counter32, Gauge32, TimeTicks or +// Counter64 that is empty or too long +// +// [Value.Int64] and [Value.Uint64] read every integer type that fits them, +// [Value.Float64] both floats. A Value is built by its type's constructor +// ([IntegerValue], [Counter32Value], and so on), so it holds its Go type; the +// encoder refuses UnknownType, an IPAddress that is not 4 or 16 octets (the +// zero Addr) and an ObjectIdentifier that does not encode. [Value.String] +// prints a value as fmt's %v printed it before values were typed: numbers in +// decimal, octets as a byte list ("[1 2]"), an ObjectIdentifier dotted, an +// address as text, and "" for an empty IpAddress and the types without a +// value. +// +// # Errors +// +// Every error of an incoming message unwraps ([errors.Is]) to exactly one +// category, an exported error named after the counter RFC 3412, RFC 3414 or RFC +// 3418 counts the message in, as net-snmp v5.9.4 counts it, with a text of its +// own: an error of DecodeMessage, of Receive, of ReadEnvelope, and the reason a +// request discards a reply for. The categories: +// +// - [ErrASNParse] (snmpInASNParseErrs): the message does not parse, of any +// version: its encoding, a header field of another type or outside its +// range, the USM parameters (RFC 3414 section 3.2 step 1; net-snmp counts +// msgPrivacyParameters that do not parse in usmStatsDecryptionErrors), a +// scoped PDU of the other type than the privFlag asks for or one that does +// not parse in plaintext, the PDU, an unknown PDU type and a varbind (RFC +// 3412 section 7.2 steps 2 and 7); +// - [ErrBadVersion] (snmpInBadVersions): a version other than SNMPv1, SNMPv2c +// and SNMPv3 (RFC 3412 section 4.2.1; net-snmp counts a negative one in +// snmpInASNParseErrs too); +// - [ErrUnknownSecurityModels]: another security model (step 4); +// - [ErrInvalidMsgs]: privacy without authentication (step 5 d); +// - [ErrUnknownEngineID] through [ErrDecryption]: the security processing +// (RFC 3414 section 3.2 steps 3 to 8), [ErrUnknownEngineID] for a request +// or an inform a receiver decodes for another engine too (RFC 3412 section +// 7.2 step 13 a, which counts it nowhere), [ErrUnknownSecurityLevel] for a +// receiver's minimum level, and [ErrDecryption] for a decrypted plaintext +// that is not a SEQUENCE of a contextEngineID and a contextName, as a wrong +// privacy key yields (net-snmp counts it in snmpInASNParseErrs; a PDU that +// does not parse after them is [ErrASNParse]); +// - [ErrUnmatchedReply]: a reply that does not answer the request: of another +// version, naming none of its attempts, neither a Response nor a Report, or +// with another request ID, security level, user name, engine ID or context +// (RFC 3412 section 7.2 steps 10 a and 12 b). +// +// A request answered by an SNMPv3 Report fails with an error that matches the +// Report's counter, the same errors ([ErrUnknownPDUHandlers] too), or +// [ErrUnknownReportPDU] for a counter the library does not know. A request that +// times out or ends at the context's deadline after discarded replies fails +// with an error that also matches the category of the one that came closest to +// answering it (see Attempts and timeouts). So a category says why a message +// was rejected, by the agent or by the library, not who rejected it. A local +// failure, such as a configuration error, a key that does not derive or fit its +// protocol, or a protocol FIPS 140-only mode refuses, matches none of them, nor +// does a transport error or a timeout without a discarded reply. +// +// A request answered by a Response whose error-status is not NoError fails with +// a [*StatusError], whose fields give the status and the error-index +// ([errors.As]); it matches no category, since the answer is a valid message. +// So does a walk, but for the statuses its end rule takes for an end (see +// [Client.BulkWalkAll]). +// +// [ErrAnswered] says whether the agent's answer ended a request: the error of a +// request (a walk's included) that a Report, a discovery answer without an +// engine ID or a Response with an error-status (a [*StatusError]) ended also +// matches it, besides the answer's category when it has one, while the library +// marks no error of a request that ended without an answer, a timeout after +// discarded replies included; errors of the caller's own code (a context it +// gave, and a panic in one) pass through unchanged. A failed request returns no +// message, so this is how a caller tells an agent that answered from one that +// did not. +// +// The categories are variables only so that errors.Is can match them; do not +// assign to them. The library makes some of its errors with their values when +// the package is initialized and others when the error occurs, so after an +// assignment its errors match the old value or the new one. +// +// # Notifications +// +// A [Receiver] decodes received traps and informs and makes the answers the +// RFCs give them: built once from its users and its own engine ([NewReceiver]), +// it is safe for concurrent use, and [Receiver.Receive] takes each datagram the +// caller read and returns the notification, or an error, and the datagram to +// send back to its sender, if any. The library does not listen for +// notifications or send answers. [ReadEnvelope] reads a datagram's header, +// unauthenticated, for a caller's checks before it receives one, or to describe +// one it rejected. +// +// A receiver holds the SNMPv3 users of each engine ID, as the usmUserTable of +// RFC 3414 does: a message is decoded with the users registered for its user +// name and engine ID only, in the order they were added, so a user's keys are +// never localized to another engine ID than its own. An agent's traps name its +// own engine ID; an inform names its receiver's, so the users that send informs +// are registered for the receiver's engine ID. A receiver may also learn the +// users of a new engine (RFC 3414 section 3.2 step 3): the LearnUsers of a +// message's user name decode an unreportable message whose name and engine ID +// it has no user for, and the first message one of them accepts, at the user's +// own level, registers them all for its engine ID, up to MaxLearned names. An +// inform is never learned, nor the receiver's own engine, nor an engine ID of +// another size than 5..32 octets (RFC 3411's snmpEngineID), which step 3 makes +// unknown unless the caller registered users for it; one over 64 octets does +// not decode. Receive gives the security processing and the minimum level a +// receiver requires. +// +// A receiver is the authoritative engine (RFC 3414 section 1.5.1) of the +// messages that name its own engine ID (ReceiverConfig.EngineID): informs. The +// caller keeps the engine ID and the engine boots across restarts and raises +// the boots at each; the receiver counts its engine time from its construction. +// Such a message is decoded with the users registered for the local engine ID, +// and an authenticated one must be in the local engine's time window (RFC 3414 +// section 3.2 step 7 a), or it is rejected with [ErrNotInTimeWindow]: its boots +// must be the local boots, which must not be 2147483647, and its time within +// 150 seconds of the local engine time; a trap naming the local engine ID too. +// A request or an inform naming another engine ID is rejected with +// [ErrUnknownEngineID] once decoded (RFC 3412 section 7.2 step 13 a); a +// reportable message naming an engine ID the receiver has no user for (a +// discovery request names none) is rejected with it before any key is used. +// +// The answers. An accepted inform, SNMPv2c or SNMPv3, gets its Response (RFC +// 3416 section 4.2.7): its request ID and its varbind list as received (a value +// the decoder takes and the encoder refuses goes back as it came); for SNMPv3 +// from the local engine (its engine ID, boots and time), by the user that +// accepted the inform, at its level, with its msgID and context; with tooBig +// instead of the varbinds when it would exceed the inform's msgMaxSize, and +// none when it would exceed it even so (RFC 3418's snmpSilentDrops). A rejected +// SNMPv3 message whose reportableFlag is set gets a Report (RFC 3412 section +// 7.1 step 3) for two errors: an unknown engine ID (step 3, +// usmStatsUnknownEngineIDs, unauthenticated), which answers discovery and gives +// a sender that holds another engine ID the local one; and the local engine's +// time window (step 7 a, usmStatsNotInTimeWindows, at authNoPriv, signed by the +// user whose digest checked), which gives a sender with stale boots, or one +// synchronizing with boots and time zero (RFC 3414 section 4), the local +// engine's. A Report comes from the local engine with the message's msgID and +// user name, the request ID of a plaintext PDU (0 for an encrypted one) and the +// receiver's count of the error. A message is answered only when its msgData is +// what its flags say: a plaintext scoped PDU whose PDU decodes and is of the +// Confirmed Class, or an encrypted one, an OCTET STRING that ends the datagram. +// +// Where a receiver answers less than RFC 3412 and net-snmp: it reports no +// unknown user name, unsupported security level, wrong digest or decryption +// error (section 7.2 step 6 a), since such Reports would tell any sender which +// user names it has and at which levels, and none lets a sender recover by +// itself; and it takes a plaintext request or inform without the +// reportableFlag, which section 6.4 forbids its sender, as the flag says rather +// than as section 6.4 asks of its receiver: it gets no Report (section 7.1 step +// 3 b would send one), and at an engine without users the LearnUsers of its +// name decode it, then reject it as a message for another engine, learning +// nothing. What its answers tell: the unknownEngineIDs Report tells any sender, +// as net-snmp's does, whether the receiver has users for an engine ID the +// sender names. A Report answers a datagram whose source anyone can forge and +// can be larger than it (the local engine ID appears twice: about 140 octets to +// a 58-octet discovery request, with a local engine ID of 32 octets), so the +// caller decides whether to send it, and how often. Without a local engine, a +// receiver takes no SNMPv3 inform and sends no Report. +// +// An authenticated SNMPv3 message naming another engine ID, an agent's trap, +// whatever its PDU and reportable flag, must be in the time window of its +// engine (RFC 3414 section 3.2 step 7 b), or it is rejected with +// [ErrNotInTimeWindow]. For each engine and authentication credential that +// authenticated a message, a receiver keeps the latest engine boots and time +// received and when: a message newer than the latest updates them and is +// accepted; one with lower boots, an older one more than 150 seconds behind the +// latest advanced by the time since, and any of an engine whose boots reached +// 2147483647 are rejected, so an exact copy of a trap is rejected after 150 +// seconds. Like snmptrapd, a receiver then loses the traps of a device whose +// engine time does not advance in real time, whose boots do not increase when +// it restarts, or that shares its engine ID with another, for as long as the +// receiver lives; a new receiver starts with no records, and accepts a copy of +// each engine's latest trap once more. A trap of a user the receiver is +// learning is decided on the record of its engine and credential when another +// user's traps made one; without one, it makes none unless the user is learned, +// so a trap at the maximum boots is rejected and leaves none, and the next +// authentic trap is a first contact. Step 7 comes before decryption, as the RFC +// orders it: a message outside its window is rejected without being decrypted. +// Unauthenticated messages are neither checked nor recorded, and the local +// engine keeps no record. The records are at most one per user and engine ID, +// since only a receiver's users authenticate a message, each for its own engine +// ID. +// // # Attempts and timeouts // // A request makes up to Retries+1 attempts. Each sends the request with a new // request ID (and SNMPv3 msgID) and waits up to Timeout for an answer, or until -// the context's deadline when that comes first. An answer is a Response of -// the request's SNMP version with the request ID of one of its attempts, or an +// the context's deadline when that comes first. An answer is a Response of the +// request's SNMP version with the request ID of one of its attempts, or an // SNMPv3 Report (see SNMPv3 below): an answer to any earlier attempt of the // same request answers it too. A message read that does not decode or // authenticate, or that is no answer, is discarded, and the attempt goes on @@ -85,42 +296,30 @@ // closest to answering it (the last authentic reply naming the request, by its // SNMPv3 msgID, else the last naming it, by that msgID or as an SNMPv1 or // SNMPv2c Response with one of its request IDs, else the last one whose ID -// could not be read, as one of another SNMP version; messages to other -// requests do not count), and its text ends with ": last discarded reply: " -// and that reason's text. A Response whose error-status is not NoError ends -// the request with a [*StatusError] (see Errors). Connect uses Timeout and its -// context too, for its lookup of Target and its dial together. -// -// # Panics -// -// A panic in the code a request runs on its own goroutine ends the request: in -// a method of the context the caller gave that the request calls. The request -// returns no message and an error whose text starts with "request panicked: " -// and that wraps the panic's value when it is an error, so that [errors.Is] and -// [errors.As] reach it (a [runtime.Error] included); the client stays usable. -// Other panics are not recovered: they reach the caller, or end the process -// when they run on a goroutine of their own. That is a panic in a context's -// methods that Connect calls, or that the context package calls on goroutines -// of its own. +// could not be read, as one of another SNMP version; messages to other requests +// do not count), and its text ends with ": last discarded reply: " and that +// reason's text. A Response whose error-status is not NoError ends the request +// with a [*StatusError] (see Errors). Connect uses Timeout and its context too, +// for its lookup of Target and its dial together. // // # SNMPv3 // // The client's configuration holds the user ([User]: name, protocols and -// passphrases), the security level and the context name. What the client -// learns of the agent's engine is its engine state (RFC 3414 section 2.3), -// internal to it: the engine ID, the user's keys localized to it and the engine -// boots and time; requests take the engine ID as their context engine ID. Every -// request reads it; only an answer that matched a request changes it, whole, -// once the new state is valid. A request without an engine ID first discovers -// it (RFC 3414 section 4): it sends an unauthenticated, empty Get and takes the -// engine ID, boots and time of the answer, with keys derived for that engine -// ID. The answer is usually a usmStatsUnknownEngineIDs Report; a +// passphrases), the security level and the context name. What the client learns +// of the agent's engine is its engine state (RFC 3414 section 2.3), internal to +// it: the engine ID, the user's keys localized to it and the engine boots and +// time; requests take the engine ID as their context engine ID. Every request +// reads it; only an answer that matched a request changes it, whole, once the +// new state is valid. A request without an engine ID first discovers it (RFC +// 3414 section 4): it sends an unauthenticated, empty Get and takes the engine +// ID, boots and time of the answer, with keys derived for that engine ID. The +// answer is usually a usmStatsUnknownEngineIDs Report; a // usmStatsUnknownUserNames Report that carries an engine ID, as some devices -// send, serves too (a Response answers discovery only with neither an engine -// ID nor a context engine ID: see below). An answer without an engine ID ends -// the request with an error that matches [ErrUnknownEngineID]: the client -// learns nothing, and the next request discovers again. Keys that do not derive -// (FIPS 140-only mode refuses MD5 and SHA-1) fail NewClient. +// send, serves too (a Response answers discovery only with neither an engine ID +// nor a context engine ID: see below). An answer without an engine ID ends the +// request with an error that matches [ErrUnknownEngineID]: the client learns +// nothing, and the next request discovers again. Keys that do not derive (FIPS +// 140-only mode refuses MD5 and SHA-1) fail NewClient. // // The engine boots and time are a clock: the latest values received and when, // advancing with the local clock (RFC 3414 section 2.3); each attempt of a @@ -145,15 +344,15 @@ // 7 b, below); a reply is decrypted exactly when it asks for privacy. A Report // then answers whatever its request ID, level and context, by the counter its // first varbind names, with one instance sub-identifier of any value (as -// net-snmp). A Response answers -// only with the request ID of the attempt whose msgID it carries and the -// request's security level (its authentication and privacy flags), user name, -// engine ID, context engine ID and context name (RFC 3412 section 7.2 step 12 -// b; one that differs leaves the request outstanding, as in net-snmp). A reply -// that fails is discarded like one that does not decode; the error of a request -// that then times out or ends at the context's deadline also matches the -// step's, [ErrNotInTimeWindow] for the time window, and [ErrUnmatchedReply] -// for a reply that does not answer (see Attempts and timeouts). +// net-snmp). A Response answers only with the request ID of the attempt whose +// msgID it carries and the request's security level (its authentication and +// privacy flags), user name, engine ID, context engine ID and context name (RFC +// 3412 section 7.2 step 12 b; one that differs leaves the request outstanding, +// as in net-snmp). A reply that fails is discarded like one that does not +// decode; the error of a request that then times out or ends at the context's +// deadline also matches the step's, [ErrNotInTimeWindow] for the time window, +// and [ErrUnmatchedReply] for a reply that does not answer (see Attempts and +// timeouts). // // The client takes the engine ID of each answer whose digest it checked and of // each Response, which name the request's (security processing, the rule @@ -191,17 +390,16 @@ // an engine ID with an error that matches [ErrUnknownEngineID]; each such error // also matches [ErrAnswered]. // -// A request that discarded an authentic answer outside the time window and -// ends without an answer (its attempts ran out, its context ended it, Close, -// or a failure; not a panic) drops the clock: the next request carries boots -// and time zero, which -// an agent that checks the time window answers with an authenticated -// usmStatsNotInTimeWindows Report carrying its own, and the next authenticated -// answer of one that does not sets the clock. So a device that does not check -// the time of requests and whose engine time went back without its boots going -// up (a restart, a stepped wall clock), or whose boots went down (a failover -// pair sharing an engine ID), costs one request that fails with -// [ErrNotInTimeWindow] (a deviation from RFC 3414 section 3.2 step 7 b and +// A request that discarded an authentic answer outside the time window and ends +// without an answer (its attempts ran out, its context ended it, Close, or a +// failure; not a panic) drops the clock: the next request carries boots and +// time zero, which an agent that checks the time window answers with an +// authenticated usmStatsNotInTimeWindows Report carrying its own, and the next +// authenticated answer of one that does not sets the clock. So a device that +// does not check the time of requests and whose engine time went back without +// its boots going up (a restart, a stepped wall clock), or whose boots went +// down (a failover pair sharing an engine ID), costs one request that fails +// with [ErrNotInTimeWindow] (a deviation from RFC 3414 section 3.2 step 7 b and // net-snmp, which reject it until their cached time is cleared). // // So a client whose requests are authenticated never leaves an engine ID by @@ -212,78 +410,66 @@ // authenticated request with a usmStatsUnknownEngineIDs Report, as net-snmp's // does for every engine ID the decoder takes. // -// # Walks -// -// [Client.WalkAll] and [Client.BulkWalkAll] return the values of a subtree, in -// order, and how the walk ended ([WalkEnd]): the reason, and the varbind that -// ended it, such as the first name outside the subtree, an EndOfMibView, or -// the answer to the Get of a root that is a leaf, whose NoSuchObject or -// NoSuchInstance tells an object the agent does not have from an instance it -// does not have. A walk that fails returns the values before its error. -// BulkWalkAll takes the max-repetitions of its GETBULK requests as an -// argument. Their docs say how a walk starts and ends. -// -// # Values -// -// A varbind ([VarBind]) holds a [Value]: its type and one Go type per type, -// the same on every platform, read through the type's accessor (each returns -// false for a value of another type): +// # Keys // -// - Integer: int32 ([Value.Int32]) -// - Counter32, Gauge32, TimeTicks, Uinteger32: uint32 ([Value.Uint32]) -// - Counter64: uint64 ([Value.Uint64]) -// - OctetString, Opaque: []byte, empty included ([Value.Bytes]) -// - ObjectIdentifier: a dotted string, with a leading dot when decoded -// ([Value.OID]) -// - IPAddress: a netip.Addr ([Value.IP]): an IPv4 address, or what some -// devices send instead: the zero Addr for an empty one, an IPv6 address -// for 16 octets (an IPv4-mapped one reads as the IPv4 address) -// - OpaqueFloat: float32 ([Value.Float32]); OpaqueDouble: float64 -// ([Value.Float64]); net-snmp's floats, wrapped in an Opaque -// - Null, NoSuchObject, NoSuchInstance, EndOfMibView: no value -// - UnknownType, the zero Value: no value; the decoder gives it for a type -// it does not decode (ASN.1's BOOLEAN or BIT STRING: SMIv2 sends BITS as an -// OctetString) and for a Uinteger32, Counter32, Gauge32, TimeTicks or -// Counter64 that is empty or too long +// An SNMPv3 key fits its protocol: an authentication key is the size of the +// protocol's hash (RFC 3414, RFC 7860), a privacy key the cipher's key (AES's, +// or DES's 16 octets of key and pre-IV); the salt of an encrypted message is 8 +// octets. Signing, verifying, encrypting and decrypting refuse anything else, +// and AES-CFB in FIPS 140-only mode, with an error. A [User] holds passphrases, +// not keys: the keys derive from non-empty passphrases of any length (RFC 3414 +// section 11.2 asks for at least 8 octets), localized to the engine ID at hand +// (RFC 3414 section 2.6). A client derives them once when it is made, for no +// engine ID, to check that they derive, and when its engine state takes an +// engine ID (discovery, an answer it takes, a Report lent to a resend); +// decoding a reply derives none. [Client.DecodeMessage] derives them for the +// engine ID a message names, the authentication key when the message asks for +// authentication, the privacy key only to decrypt it. A [Receiver] derives its +// users' keys for their engine IDs when it is made (and a LearnUser's once, to +// check they derive), and a user it learns the authentication key for the +// message's engine ID to check the digest, the privacy key only once the digest +// checked, and every learned user's keys once it registers them. +// [Message.Encode] derives them for the message's engine ID. No message carries +// keys or passphrases. Deriving a key starts with hashing a megabyte of the +// passphrase (RFC 3414 appendix A.2.1). The package caches that result for +// every client and receiver, by passphrase and hash, for the life of the +// process; it holds the passphrases in memory meanwhile. The Reeder key +// extension (AES192C, AES256C) hashes the localized key the same way, so it +// adds a result per user and engine ID, and DecodeMessage, which decrypts +// without checking the digest, one per engine ID its messages name; a +// receiver's, one per user it has, learns or may learn, and one per engine ID +// an authentic message of a LearnUser names when the receiver does not learn it +// (an unreportable inform or request, a message that does not decrypt or whose +// PDU does not parse; one outside the time window is not decrypted). // -// [Value.Int64] and [Value.Uint64] read every integer type that fits them, -// [Value.Float64] both floats. A Value is built by its type's constructor -// ([IntegerValue], [Counter32Value], and so on), so it holds its Go type; the -// encoder refuses UnknownType, an IPAddress that is not 4 or 16 octets (the -// zero Addr) and an ObjectIdentifier that does not encode. -// [Value.String] prints a value as fmt's %v printed it before values were -// typed: numbers in decimal, octets as a byte list ("[1 2]"), an -// ObjectIdentifier dotted, an address as text, and "" for an empty -// IpAddress and the types without a value. +// # Encoding and decoding // // The encoder also checks the message's fields: SNMPv1, SNMPv2c or SNMPv3; a // PDU type the package knows; max-repetitions up to 2147483647; an SNMPv1 // trap's agent address an IPv4 address (an IPv4-mapped one included); for // SNMPv3, a msgID up to 2147483647, a MsgMaxSize of 0 or 484..2147483647, one // of the three security levels, engine boots and time up to 2147483647 and a -// user name of at most 32 octets (RFC 3412 section 6, RFC 3414 section 2.4). -// It writes the request ID as the Integer32 whose two's complement RequestID +// user name of at most 32 octets (RFC 3412 section 6, RFC 3414 section 2.4). It +// writes the request ID as the Integer32 whose two's complement RequestID // holds, the security model of an SNMPv3 message as the User-based Security // Model's (3), and its reportable flag by its PDU type (RFC 3412 section 6.4): // set for requests and informs, clear for responses, reports and traps. // -// # Decoding -// // The decoder applies one rule per value type and header field, with the same // results on every platform. An INTEGER, value or header field, has one to // eight octets and is cut to 32 bits by two's complement (an Integer32, RFC // 2578 section 7.1.1); Uinteger32, Counter32, Gauge32 and TimeTicks values are // unsigned, of one to eight octets or nine with a leading zero, and keep their // low 32 bits; an OBJECT IDENTIFIER has at most 128 arcs. A header field must -// be of its type and, once cut, within its range, or it fails the message, as -// a missing one does: the version SNMPv1, SNMPv2c or SNMPv3; the community, +// be of its type and, once cut, within its range, or it fails the message, as a +// missing one does: the version SNMPv1, SNMPv2c or SNMPv3; the community, // contextEngineID and contextName OCTET STRINGs; the error status 0..255; the // error index and non-repeaters not negative, read as 255 above it (the most -// their fields hold); max-repetitions not negative; an SNMPv1 trap's -// enterprise an OBJECT IDENTIFIER, its agent address four octets, an IpAddress -// or an OCTET STRING, and its timestamp TimeTicks or another unsigned type, as -// net-snmp v5.9.4 takes it. The SNMPv3 header takes net-snmp's field rules -// (RFC 3412 section 6, RFC 3414 section 2.4): msgID 0..2147483647, msgMaxSize +// their fields hold); max-repetitions not negative; an SNMPv1 trap's enterprise +// an OBJECT IDENTIFIER, its agent address four octets, an IpAddress or an OCTET +// STRING, and its timestamp TimeTicks or another unsigned type, as net-snmp +// v5.9.4 takes it. The SNMPv3 header takes net-snmp's field rules (RFC 3412 +// section 6, RFC 3414 section 2.4): msgID 0..2147483647, msgMaxSize // 484..2147483647, msgFlags an OCTET STRING of one octet, the User-based // Security Model's number, flags that do not ask for privacy without // authentication, the USM fields of their types, an engine ID of at most 64 @@ -303,18 +489,18 @@ // devices), an IPAddress value may be empty or of 16 octets, an SNMPv1 agent // address an empty IpAddress, a varbind name an OCTET STRING or an IpAddress, // kept as text, and an unsigned value that is empty or too long decodes as -// UnknownType, with no value, instead of failing its message. Other -// differences from net-snmp v5.9.4: +// UnknownType, with no value, instead of failing its message. Other differences +// from net-snmp v5.9.4: // // - an empty OBJECT IDENTIFIER reads as .0.0, not .0 // - an INTEGER outside the int32 range keeps its low 32 bits as an int32 -// (3000000000 reads -1294967296), where net-snmp keeps them unsigned -// above it and negates them below it +// (3000000000 reads -1294967296), where net-snmp keeps them unsigned above +// it and negates them below it // - the community and context fields take OCTET STRINGs only, and an SNMPv1 // agent address four octets or an empty IpAddress, where net-snmp takes // other string types (of up to four octets for the agent address) -// - the error status, the error index, non-repeaters and max-repetitions -// are checked against their ranges +// - the error status, the error index, non-repeaters and max-repetitions are +// checked against their ranges // - a length takes at most eight long-form octets, where net-snmp takes as // many as its long holds // - bytes after a TLV inside its container fail the message (see above), @@ -325,212 +511,22 @@ // message // // The decoders never write their input. [Client.DecodeMessage] and -// [Receiver.Receive] return OctetString, Opaque and IPAddress values that -// alias the input, or, in an encrypted message, the buffer the scoped PDU is +// [Receiver.Receive] return OctetString, Opaque and IPAddress values that alias +// the input, or, in an encrypted message, the buffer the scoped PDU is // decrypted into: copy the octets ([Value.Bytes]) and read the addresses // ([Value.IP]) before reusing the input. A decoded message's SecurityParameters // and ContextEngineID are copies. The answers to requests are copied from the // receive buffer, so their values stay valid. // -// # Keys -// -// An SNMPv3 key fits its protocol: an authentication key is the size of the -// protocol's hash (RFC 3414, RFC 7860), a privacy key the cipher's key (AES's, -// or DES's 16 octets of key and pre-IV); the salt of an encrypted message is 8 -// octets. Signing, verifying, encrypting and decrypting refuse anything else, -// and AES-CFB in FIPS 140-only mode, with an error. A [User] holds -// passphrases, not keys: the keys derive from non-empty passphrases of any -// length (RFC 3414 section 11.2 asks for at least 8 octets), localized to the -// engine ID at hand (RFC 3414 section 2.6). A client derives them once when it -// is made, for no engine ID, to check that they derive, and when its engine -// state takes an engine ID (discovery, an answer it takes, a Report lent to a -// resend); decoding a reply derives none. -// [Client.DecodeMessage] derives them for the engine ID a message names, the -// authentication key when the message asks for authentication, the privacy key -// only to decrypt it. A [Receiver] derives its users' keys for their engine IDs -// when it is made (and a LearnUser's once, to check they derive), and a user it -// learns the authentication key for the -// message's engine ID to check the digest, the privacy key only once the -// digest checked, and every learned user's keys once it registers them. -// [Message.Encode] derives them for the message's engine ID. No -// message carries keys or passphrases. Deriving a key starts with hashing a -// megabyte of the passphrase (RFC 3414 appendix A.2.1). The package caches that -// result for every client and receiver, by passphrase and hash, for the life of -// the process; it holds the passphrases in memory meanwhile. The Reeder key -// extension (AES192C, AES256C) hashes the localized key the same way, so it -// adds a result per user and engine ID, and DecodeMessage, which decrypts -// without checking the digest, one per engine ID its messages name; a -// receiver's, one per user it has, learns or may learn, and one per engine ID -// an authentic message of a LearnUser names when the receiver does not learn -// it (an unreportable inform or request, a message that does not decrypt or -// whose PDU does not parse; one outside the time window is not decrypted). -// -// # Notifications -// -// A [Receiver] decodes received traps and informs and makes the answers the -// RFCs give them: built once from its users and its own engine -// ([NewReceiver]), it is safe for concurrent use, and [Receiver.Receive] takes -// each datagram the caller read and returns the notification, or an error, and -// the datagram to send back to its sender, if any. The library does not listen -// for notifications or send answers. [ReadEnvelope] reads a datagram's header, -// unauthenticated, for a caller's checks before it receives one, or to -// describe one it rejected. -// -// A receiver holds the SNMPv3 users of each engine ID, as the usmUserTable of -// RFC 3414 does: a message is decoded with the users registered for its user -// name and engine ID only, in the order they were added, so a user's keys are -// never localized to another engine ID than its own. An agent's traps name its -// own engine ID; an inform names its receiver's, so the users that send informs -// are registered for the receiver's engine ID. A receiver may also learn the -// users of a new engine (RFC 3414 section 3.2 step 3): the LearnUsers of a -// message's user name decode an unreportable message whose name and engine ID -// it has no user for, and the first message one of them accepts, at the user's -// own level, registers them all for its engine ID, up to MaxLearned names. An -// inform is never learned, nor the receiver's own engine, nor an engine ID of -// another size than 5..32 octets (RFC 3411's snmpEngineID), which step 3 makes -// unknown unless the caller registered users for it; one over 64 octets does -// not decode. Receive gives the security processing and the minimum level a -// receiver requires. -// -// A receiver is the authoritative engine (RFC 3414 section 1.5.1) of the -// messages that name its own engine ID (ReceiverConfig.EngineID): informs. The -// caller keeps the engine ID and the engine boots across restarts and raises -// the boots at each; the receiver counts its engine time from its -// construction. Such a message is decoded with the users registered for the -// local engine ID, and an authenticated one must be in the local engine's time -// window (RFC 3414 section 3.2 step 7 a), or it is rejected with -// [ErrNotInTimeWindow]: its boots must be the local boots, which must not be -// 2147483647, and its time within 150 seconds of the local engine time; a -// trap naming the local engine ID too. A request or an inform naming another -// engine ID is rejected with [ErrUnknownEngineID] once decoded (RFC 3412 -// section 7.2 step 13 a); a reportable message naming an engine ID the -// receiver has no user for (a discovery request names none) is rejected with -// it before any key is used. -// -// The answers. An accepted inform, SNMPv2c or SNMPv3, gets its Response (RFC -// 3416 section 4.2.7): its request ID and its varbind list as received (a value -// the decoder takes and the encoder refuses goes back as it came); for SNMPv3 -// from the local engine (its engine ID, boots and time), by the user that -// accepted the inform, at its level, with its msgID and context; with tooBig -// instead of the varbinds when it would exceed the inform's msgMaxSize, and -// none when it would exceed it even so (RFC 3418's snmpSilentDrops). A rejected -// SNMPv3 message whose reportableFlag is set gets a Report (RFC 3412 section -// 7.1 step 3) for two errors: an unknown engine ID (step 3, -// usmStatsUnknownEngineIDs, unauthenticated), which answers discovery and gives -// a sender that holds another engine ID the local one; and the local engine's -// time window (step 7 a, usmStatsNotInTimeWindows, at authNoPriv, signed by the -// user whose digest checked), which gives a sender with stale boots, or one -// synchronizing with boots and time zero (RFC 3414 section 4), the local -// engine's. A Report comes from the local engine with the message's msgID and -// user name, the request ID of a plaintext PDU (0 for an encrypted one) and the -// receiver's count of the error. A message is answered only when its msgData is -// what its flags say: a plaintext scoped PDU whose PDU decodes and is of the -// Confirmed Class, or an encrypted one, an OCTET STRING that ends the datagram. -// -// Where a receiver answers less than RFC 3412 and net-snmp: it reports no -// unknown user name, unsupported security level, wrong digest or decryption -// error (section 7.2 step 6 a), since such Reports would tell any sender which -// user names it has and at which levels, and none lets a sender recover by -// itself; and it takes a plaintext request or inform without the -// reportableFlag, which section 6.4 forbids its sender, as the flag says rather -// than as section 6.4 asks of its receiver: it gets no Report (section 7.1 step -// 3 b would send one), and at an engine without users the LearnUsers of its -// name decode it, then reject it as a message for another engine, learning -// nothing. What its answers tell: the unknownEngineIDs Report tells any sender, -// as net-snmp's does, whether the receiver has users for an engine ID the -// sender names. A Report answers a datagram whose source anyone can forge and -// can be larger than it (the local engine ID appears twice: about 140 octets to -// a 58-octet discovery request, with a local engine ID of 32 octets), so the -// caller decides whether to send it, and how often. Without a local engine, a -// receiver takes no SNMPv3 inform and sends no Report. -// -// An authenticated SNMPv3 message naming another engine ID, an agent's trap, -// whatever its PDU and reportable flag, must be in the time window of its -// engine (RFC 3414 section 3.2 step 7 b), or it is rejected with -// [ErrNotInTimeWindow]. For each engine and authentication credential that -// authenticated a message, a receiver keeps the latest engine boots and time -// received and when: a message newer than the latest updates them and is -// accepted; one with lower boots, an older one more than 150 seconds behind -// the latest advanced by the time since, and any of an engine whose boots -// reached 2147483647 are rejected, so an exact copy of a trap is rejected after -// 150 seconds. Like snmptrapd, a receiver then loses the traps of a device -// whose engine time does not advance in real time, whose boots do not increase -// when it restarts, or that shares its engine ID with another, for as long as -// the receiver lives; a new receiver starts with no records, and accepts a copy -// of each engine's latest trap once more. A trap of a user the receiver is -// learning is decided on the record of its engine and credential when another -// user's traps made one; without one, it makes none unless the user is -// learned, so a trap at the maximum boots is rejected and leaves none, and the -// next authentic trap is a first contact. Step 7 comes before decryption, as -// the RFC orders it: a message outside its window is rejected without being -// decrypted. Unauthenticated messages are neither checked nor recorded, and the -// local engine keeps no record. The records are at most one per user and -// engine ID, since only a receiver's users authenticate a message, each for its -// own engine ID. -// -// # Errors -// -// Every error of an incoming message unwraps ([errors.Is]) to exactly one -// category, an exported error named after the counter RFC 3412, RFC 3414 or -// RFC 3418 counts the message in, as net-snmp v5.9.4 counts it, with a text of -// its own: an error of DecodeMessage, of Receive, of ReadEnvelope, and the reason a -// request discards a reply for. The categories: -// -// - [ErrASNParse] (snmpInASNParseErrs): the message does not parse, of any -// version: its encoding, a header field of another type or outside its -// range, the USM parameters (RFC 3414 section 3.2 step 1; net-snmp counts -// msgPrivacyParameters that do not parse in usmStatsDecryptionErrors), a -// scoped PDU of the other type than the privFlag asks for or one that does -// not parse in plaintext, the PDU, an unknown PDU type and a varbind (RFC -// 3412 section 7.2 steps 2 and 7); -// - [ErrBadVersion] (snmpInBadVersions): a version other than SNMPv1, SNMPv2c -// and SNMPv3 (RFC 3412 section 4.2.1; net-snmp counts a negative one in -// snmpInASNParseErrs too); -// - [ErrUnknownSecurityModels]: another security model (step 4); -// - [ErrInvalidMsgs]: privacy without authentication (step 5 d); -// - [ErrUnknownEngineID] through [ErrDecryption]: the security processing -// (RFC 3414 section 3.2 steps 3 to 8), [ErrUnknownEngineID] for a request -// or an inform a receiver decodes for another engine too (RFC 3412 section -// 7.2 step 13 a, which counts it nowhere), [ErrUnknownSecurityLevel] for a -// receiver's minimum level, and [ErrDecryption] for a decrypted -// plaintext that is not a SEQUENCE of a contextEngineID and a contextName, -// as a wrong privacy key yields (net-snmp counts it in snmpInASNParseErrs; -// a PDU that does not parse after them is [ErrASNParse]); -// - [ErrUnmatchedReply]: a reply that does not answer the request: of another -// version, naming none of its attempts, neither a Response nor a Report, -// or with another request ID, security level, user name, engine ID or -// context (RFC 3412 section 7.2 steps 10 a and 12 b). -// -// A request answered by an SNMPv3 Report fails with an error that matches the -// Report's counter, the same errors ([ErrUnknownPDUHandlers] too), or -// [ErrUnknownReportPDU] for a counter the library does not know. A request -// that times out or ends at the context's deadline after discarded replies -// fails with an error that also matches the category of the one that came -// closest to answering it (see Attempts and timeouts). So a category says why -// a message was rejected, by the agent or by the library, not who rejected -// it. A local failure, such as a configuration error, a key that does not -// derive or fit its protocol, or a protocol FIPS 140-only mode refuses, -// matches none of them, nor does a transport error or a timeout without a -// discarded reply. -// -// A request answered by a Response whose error-status is not NoError fails -// with a [*StatusError], whose fields give the status and the error-index -// ([errors.As]); it matches no category, since the answer is a valid message. -// So does a walk, but for the statuses its end rule takes for an end (see -// [Client.BulkWalkAll]). -// -// [ErrAnswered] says whether the agent's answer ended a request: the error of -// a request (a walk's included) that a Report, a discovery answer without an -// engine ID or a Response with an error-status (a [*StatusError]) ended also -// matches it, besides the answer's category when it has one, while the library -// marks no error of a request that ended without an answer, a timeout after -// discarded replies included; errors of the caller's own code (a context it -// gave, and a panic in one) pass through unchanged. A failed request returns no -// message, so this is how a caller tells an agent that answered from one that -// did not. +// # Panics // -// The categories are variables only so that errors.Is can match them; do not -// assign to them. The library makes some of its errors with their values when -// the package is initialized and others when the error occurs, so after an -// assignment its errors match the old value or the new one. +// A panic in the code a request runs on its own goroutine ends the request: in +// a method of the context the caller gave that the request calls. The request +// returns no message and an error whose text starts with "request panicked: " +// and that wraps the panic's value when it is an error, so that [errors.Is] and +// [errors.As] reach it (a [runtime.Error] included); the client stays usable. +// Other panics are not recovered: they reach the caller, or end the process +// when they run on a goroutine of their own. That is a panic in a context's +// methods that Connect calls, or that the context package calls on goroutines +// of its own. package gosnmp From ebed9cf4ac40c82b295144b131edbd906064e027 Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Wed, 11 Nov 2026 21:57:06 +0200 Subject: [PATCH 07/17] docs: correct the UnknownType, MaxOids and ReadEnvelope docs; a guide to the sections - UnknownType is also what the decoder gives an unsigned value that is empty or too long, as the package documentation says; the Value and ValueType docs now say so too. - MaxOids limits the OIDs of a Get: each request of a walk carries one, so the "each request of a walk" clause of the constant and of Config.MaxOids said nothing. - ReadEnvelope's error case reads plainly: the zero Envelope, also when the version was read. - The package documentation opens with the order of its sections and the examples; "The encoder also checks" loses its "also", the paragraph having moved out of Values. --- client.go | 11 +++++------ doc.go | 8 +++++++- receiver.go | 6 +++--- value.go | 10 ++++++---- 4 files changed, 21 insertions(+), 14 deletions(-) diff --git a/client.go b/client.go index 41d232a..938d000 100644 --- a/client.go +++ b/client.go @@ -16,10 +16,9 @@ import ( ) const ( - // MaxOids is the default of Config.MaxOids, the maximum number of OIDs in - // a Get request and in each request of a walk. 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 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 @@ -59,8 +58,8 @@ type Config struct { // attempt. Retries int - // MaxOids is the maximum number of OIDs in a Get request, and in each - // request of a walk, which carries one; zero means the MaxOids constant. + // 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 diff --git a/doc.go b/doc.go index 974920f..d8acc39 100644 --- a/doc.go +++ b/doc.go @@ -11,6 +11,12 @@ // values it collected before the error, and Receive, whose Report to a rejected // message comes with the error (see Notifications). // +// The sections below describe the client first (Lifecycle, Concurrency, Walks, +// Values, Errors), then the receiver (Notifications), then the protocol rules +// they follow: how a request is attempted, the SNMPv3 engine and its keys, +// encoding and decoding, and panics. The examples show a Get and its errors, an +// SNMPv3 client, a walk, values and a receiver. +// // # Lifecycle // // [NewClient] makes a [Client] from a [Config]: it checks the configuration, @@ -444,7 +450,7 @@ // // # Encoding and decoding // -// The encoder also checks the message's fields: SNMPv1, SNMPv2c or SNMPv3; a +// The encoder checks the message's fields: SNMPv1, SNMPv2c or SNMPv3; a // PDU type the package knows; max-repetitions up to 2147483647; an SNMPv1 // trap's agent address an IPv4 address (an IPv4-mapped one included); for // SNMPv3, a msgID up to 2147483647, a MsgMaxSize of 0 or 484..2147483647, one diff --git a/receiver.go b/receiver.go index 0d35a44..f5fb710 100644 --- a/receiver.go +++ b/receiver.go @@ -562,9 +562,9 @@ type Envelope struct { // rules a decode reads it with and with the errors of their categories: the // message's SEQUENCE, which must span datagram, the version and, for SNMPv1 // and SNMPv2c, the community (not returned), or, for SNMPv3, every header -// field up to the USM parameters. It returns no envelope with an error, also -// when the version read. It decodes no PDU, derives no key and checks no -// digest. +// field up to the USM parameters. With an error it returns the zero Envelope, +// also when the version was read. It decodes no PDU, derives no key and checks +// no digest. func ReadEnvelope(datagram []byte) (Envelope, error) { var m Message _, w, err := unmarshalHeader(datagram, &m) diff --git a/value.go b/value.go index 5a842cb..864e8d5 100644 --- a/value.go +++ b/value.go @@ -34,7 +34,8 @@ type ValueType byte // The value types: the SMI's (RFC 2578), ASN.1's Null, net-snmp's OpaqueFloat // and OpaqueDouble, which it wraps in an Opaque, and the exceptions of RFC 3416 // (NoSuchObject, NoSuchInstance, EndOfMibView). UnknownType is a value of a -// type the decoder does not decode, such as ASN.1's BOOLEAN or BIT STRING. +// type the decoder does not decode, such as ASN.1's BOOLEAN or BIT STRING, or +// an unsigned value that is empty or too long. const ( UnknownType ValueType = 0x00 Integer ValueType = 0x02 @@ -69,9 +70,10 @@ const ( // - Null, NoSuchObject, NoSuchInstance, EndOfMibView, UnknownType: none // // Int64, Uint64 and Float64 also read the narrower types they hold exactly. -// The zero Value is UnknownType, a value of a type the decoder does not decode, -// which the encoder refuses. Values are built by the constructor of their type, -// such as Counter32Value, and every decoded value is one a constructor builds; +// The zero Value is UnknownType, which the decoder gives a value of a type it +// does not decode and an unsigned value that is empty or too long, and which +// the encoder refuses. Values are built by the constructor of their type, such +// as Counter32Value, and every decoded value is one a constructor builds; // octets are held as given, not copied. A Value holds a slice, so it is not // comparable with ==: compare the types and the accessors' results. type Value struct { From b485895f6b7a95de0d8e5ffd6018c251fdd3f581 Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Wed, 11 Nov 2026 21:58:08 +0200 Subject: [PATCH 08/17] docs: examples beside the API; the README on the client and the receiver The five programs under examples/ become Example functions in example_test.go, which pkg.go.dev shows with the API and every go test compiles: NewClient (an SNMPv2c Get), NewClient_snmpv3 (authPriv, and ForgetEngine after ErrUnknownEngineID), Client.Get (the errors of a failed request: *StatusError, ErrAnswered, none), Client.BulkWalkAll (the values and WalkEnd), Value (the accessors) and Receiver (a trap a client encodes, received), both of which run with their output, and Receiver.Receive (a UDP read loop that checks the PDU type and the community and sends the answers). Four of the programs repeated the same Get; none showed the receiver. The README's overview lists the client's and the receiver's functions and its usage shows a Get and a receiver's read loop, pointing at the examples. The lint exclusion for examples/ goes with the directory. --- .golangci.yml | 4 +- README.md | 110 +++++++------- example_test.go | 270 +++++++++++++++++++++++++++++++++++ examples/Hex-String/main.go | 69 --------- examples/example/main.go | 61 -------- examples/example2/main.go | 81 ----------- examples/example3/main.go | 62 -------- examples/walkexample/main.go | 91 ------------ 8 files changed, 326 insertions(+), 422 deletions(-) create mode 100644 example_test.go delete mode 100644 examples/Hex-String/main.go delete mode 100644 examples/example/main.go delete mode 100644 examples/example2/main.go delete mode 100644 examples/example3/main.go delete mode 100644 examples/walkexample/main.go diff --git a/.golangci.yml b/.golangci.yml index 3fc6783..b31efb5 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -61,10 +61,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 diff --git a/README.md b/README.md index f4550c7..3834c35 100644 --- a/README.md +++ b/README.md @@ -26,25 +26,37 @@ 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 named after the RFC counter that counts it (`errors.Is`). 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 @@ -58,69 +70,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 (`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 { + _, _ = 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 diff --git a/example_test.go b/example_test.go new file mode 100644 index 0000000..3c98564 --- /dev/null +++ b/example_test.go @@ -0,0 +1,270 @@ +// Copyright 2026 Netdata Inc. 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_test + +import ( + "context" + "errors" + "fmt" + "log" + "net" + "time" + + "github.com/netdata/gosnmp" +) + +// A client of an SNMPv2c agent gets two objects. The examples that need an +// agent use the documentation address 192.0.2.1. +func ExampleNewClient() { + 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.Fatal(err) // the error names the field NewClient rejects + } + // The context bounds each call it is given: here Connect and the Get. + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + if err = client.Connect(ctx); err != nil { + log.Fatal(err) + } + defer client.Close() + + 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 _, vb := range result.VarBinds { + fmt.Printf("%s = %v: %v\n", vb.Name, vb.Value.Type(), vb.Value) + } +} + +// An SNMPv3 client at authPriv: the configuration holds the user's +// passphrases; the client discovers the agent's engine at its first request +// and localizes the keys to it. +func ExampleNewClient_snmpv3() { + client, err := gosnmp.NewClient(gosnmp.Config{ + Target: "192.0.2.1", + Version: gosnmp.Version3, + SecurityLevel: gosnmp.AuthPriv, + User: gosnmp.User{ + Name: "monitor", + AuthProtocol: gosnmp.SHA256, + AuthPassphrase: "authentication passphrase", + PrivProtocol: gosnmp.AES, + PrivPassphrase: "privacy passphrase", + }, + }) + if err != nil { + log.Fatal(err) + } + ctx := context.Background() + if err = client.Connect(ctx); err != nil { + log.Fatal(err) + } + defer client.Close() + + result, err := client.Get(ctx, []string{"1.3.6.1.2.1.1.5.0"}) // sysName + if errors.Is(err, gosnmp.ErrUnknownEngineID) { + // The agent's engine ID changed: forget the engine and ask again. + client.ForgetEngine() + result, err = client.Get(ctx, []string{"1.3.6.1.2.1.1.5.0"}) + } + if err != nil { + log.Fatal(err) + } + fmt.Println(result.VarBinds[0].Value) +} + +// A failed request returns no message: its error tells whether the agent +// answered, and how. +func ExampleClient_Get() { + client, err := gosnmp.NewClient(gosnmp.Config{Target: "192.0.2.1", Community: "public", Version: gosnmp.Version2c}) + if err != nil { + log.Fatal(err) + } + ctx := context.Background() + if err = client.Connect(ctx); err != nil { + log.Fatal(err) + } + defer client.Close() + + result, err := client.Get(ctx, []string{"1.3.6.1.2.1.1.3.0"}) // sysUpTime + var status *gosnmp.StatusError + switch { + case err == nil: + uptime, _ := result.VarBinds[0].Value.Uint32() + fmt.Println("uptime:", time.Duration(uptime)*10*time.Millisecond) + case errors.As(err, &status): + // A Response with an error-status: the agent answered. + fmt.Printf("the agent answered %v for varbind %d\n", status.Status, status.Index) + case errors.Is(err, gosnmp.ErrAnswered): + // An SNMPv3 Report, whose counter's category the error matches. + fmt.Println("the agent answered:", err) + default: + // No answer: a timeout, the context, a transport error. + fmt.Println("no answer:", err) + } +} + +// A walk returns the subtree's values and how it ended; a walk that fails +// returns the values before its error. +func ExampleClient_BulkWalkAll() { + client, err := gosnmp.NewClient(gosnmp.Config{Target: "192.0.2.1", Community: "public", Version: gosnmp.Version2c}) + if err != nil { + log.Fatal(err) + } + ctx := context.Background() + if err = client.Connect(ctx); err != nil { + log.Fatal(err) + } + defer client.Close() + + // The interfaces table, 10 objects per GETBULK request (0 sends 50). + values, end, err := client.BulkWalkAll(ctx, "1.3.6.1.2.1.2.2", 10) + for _, vb := range values { + fmt.Printf("%s = %v\n", vb.Name, vb.Value) + } + if err != nil { + log.Fatal(err) + } + // The end: past the subtree, an exception value such as EndOfMibView, or + // the Get of a root that is a leaf, whose NoSuchObject or NoSuchInstance + // tells an object the agent lacks from an instance it lacks. + fmt.Printf("ended by %v at %s\n", end.Reason, end.VarBind.Name) +} + +// Each SMI type has one Go type, read through its accessor. +func ExampleValue() { + values := []gosnmp.Value{ + gosnmp.Counter32Value(4294967295), + gosnmp.Counter64Value(18446744073709551615), + gosnmp.OctetStringValue([]byte{0x00, 0x1b, 0x21}), + gosnmp.NoSuchInstanceValue(), + } + for _, v := range values { + if n, ok := v.Uint64(); ok { + fmt.Printf("%v: %d\n", v.Type(), n) + } else if b, ok := v.Bytes(); ok { + fmt.Printf("%v: %x\n", v.Type(), b) + } else { + fmt.Printf("%v: no value (%v)\n", v.Type(), v) + } + } + // Output: + // Counter32: 4294967295 + // Counter64: 18446744073709551615 + // OctetString: 001b21 + // NoSuchInstance: no value () +} + +// A receiver decodes a datagram the caller read: here an SNMPv2c trap that a +// client encodes. +func ExampleReceiver() { + sender, err := gosnmp.NewClient(gosnmp.Config{Version: gosnmp.Version2c, Community: "public"}) + if err != nil { + log.Fatal(err) + } + datagram, err := sender.EncodeMessage(gosnmp.SNMPv2Trap, []gosnmp.VarBind{ + // sysUpTime.0, then snmpTrapOID.0: linkDown. + {Name: ".1.3.6.1.2.1.1.3.0", Value: gosnmp.TimeTicksValue(12345)}, + {Name: ".1.3.6.1.6.3.1.1.4.1.0", Value: gosnmp.ObjectIdentifierValue(".1.3.6.1.6.3.1.1.5.3")}, + }, 0, 0) + if err != nil { + log.Fatal(err) + } + + receiver, err := gosnmp.NewReceiver(gosnmp.ReceiverConfig{}) + if err != nil { + log.Fatal(err) + } + notification, response, err := receiver.Receive(datagram) + if err != nil { + log.Fatal(err) + } + m := notification.Message + fmt.Println(m.Version, m.PDUType, m.Community) + for _, vb := range m.VarBinds { + fmt.Printf("%s = %v: %v\n", vb.Name, vb.Value.Type(), vb.Value) + } + fmt.Println("response to send:", response != nil) + // Output: + // 2c SNMPv2Trap public + // .1.3.6.1.2.1.1.3.0 = TimeTicks: 12345 + // .1.3.6.1.6.3.1.1.4.1.0 = ObjectIdentifier: .1.3.6.1.6.3.1.1.5.3 + // response to send: false +} + +// A receiver's read loop: the caller owns the socket, checks what the library +// does not (the PDU type and the community) and sends the answers. +func ExampleReceiver_Receive() { + // The receiver's own engine, the authoritative engine of the informs it + // receives: the caller keeps the engine ID and the boots across restarts + // and raises the boots at each. + localEngineID := []byte{0x80, 0x00, 0x1f, 0x88, 0x04, 't', 'r', 'a', 'p', 's'} + user := gosnmp.User{ + Name: "monitor", + AuthProtocol: gosnmp.SHA256, + AuthPassphrase: "authentication passphrase", + PrivProtocol: gosnmp.AES, + PrivPassphrase: "privacy passphrase", + } + receiver, err := gosnmp.NewReceiver(gosnmp.ReceiverConfig{ + EngineID: localEngineID, + EngineBoots: 1, + // Informs name the receiver's engine; an agent's traps name its own. + Users: []gosnmp.EngineUser{ + {EngineID: localEngineID, User: user}, + {EngineID: []byte{0x80, 0x00, 0x1f, 0x88, 0x04, 'a', 'g', 'e', 'n', 't'}, User: user}, + }, + }) + if err != nil { + log.Fatal(err) + } + + conn, err := net.ListenUDP("udp", &net.UDPAddr{Port: 162}) + if err != nil { + log.Fatal(err) + } + defer conn.Close() + buf := make([]byte, 65535) + for { + n, from, err := conn.ReadFromUDP(buf) + if err != nil { + log.Fatal(err) + } + 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 { + _, _ = conn.WriteToUDP(response, from) + } + log.Printf("rejected a datagram from %v: %v", from, err) + continue + } + m := ¬ification.Message + switch m.PDUType { + case gosnmp.Trap, gosnmp.SNMPv2Trap, gosnmp.InformRequest: + default: + continue + } + if m.Version != gosnmp.Version3 && m.Community != "public" { + continue + } + if response != nil { + _, _ = conn.WriteToUDP(response, from) // an inform's Response + } + // The values alias buf: use or copy them before the next read. + for _, vb := range m.VarBinds { + fmt.Printf("%v %s = %v\n", from, vb.Name, vb.Value) + } + } +} diff --git a/examples/Hex-String/main.go b/examples/Hex-String/main.go deleted file mode 100644 index f9675df..0000000 --- a/examples/Hex-String/main.go +++ /dev/null @@ -1,69 +0,0 @@ -// 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. - -package main - -import ( - "context" - "fmt" - "log" - "strconv" - "strings" - "time" - - g "github.com/netdata/gosnmp" -) - -func main() { - // 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, - }) - if err != nil { - log.Fatalf("NewClient() err: %v", err) - } - ctx := context.Background() - err = client.Connect(ctx) - if err != nil { - log.Fatalf("Connect() err: %v", 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) - } - - for i, variable := range result.VarBinds { - fmt.Printf("%d: oid: %s ", i, variable.Name) - if value, ok := variable.Value.Bytes(); ok { - if strings.Contains(strconv.Quote(string(value)), "\\x") { - var tmp strings.Builder - for i := range value { - fmt.Fprintf(&tmp, "%v", value[i]) - if i != (len(value) - 1) { - tmp.WriteString(" ") - } - } - fmt.Printf("Hex-String: %s\n", tmp.String()) - } else { - fmt.Printf("string: %s\n", string(value)) - } - } else if n, ok := variable.Value.Int64(); ok { - // ... or often you're just interested in numeric values. - 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()) - } - } -} diff --git a/examples/example/main.go b/examples/example/main.go deleted file mode 100644 index 55e3e02..0000000 --- a/examples/example/main.go +++ /dev/null @@ -1,61 +0,0 @@ -// 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. - -package main - -import ( - "context" - "fmt" - "log" - "time" - - g "github.com/netdata/gosnmp" -) - -func main() { - // 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, - }) - if err != nil { - log.Fatalf("NewClient() err: %v", err) - } - // Connect and each request take a context that bounds that call only: - // here both end within 30 seconds. - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - defer cancel() - err = client.Connect(ctx) - if err != nil { - log.Fatalf("Connect() err: %v", 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) - } - - 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()) - } - } -} diff --git a/examples/example2/main.go b/examples/example2/main.go deleted file mode 100644 index 5728ab0..0000000 --- a/examples/example2/main.go +++ /dev/null @@ -1,81 +0,0 @@ -// 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. - -/* -Example usage and output: - -$ GOSNMP_TARGET=10.12.0.1 GOSNMP_PORT=161 go run main.go -2021/01/03 13:31:15 Query latency in seconds: 0.000625777 -0: oid: .1.3.6.1.2.1.1.4.0 string: contact -1: oid: .1.3.6.1.2.1.1.7.0 number: 78 - -*/ - -package main - -import ( - "context" - "fmt" - "log" - "os" - "strconv" - "time" - - g "github.com/netdata/gosnmp" -) - -func main() { - // get Target and Port from environment - envTarget := os.Getenv("GOSNMP_TARGET") - envPort := os.Getenv("GOSNMP_PORT") - if len(envTarget) == 0 { - log.Fatalf("environment variable not set: GOSNMP_TARGET") - } - if len(envPort) == 0 { - log.Fatalf("environment variable not set: GOSNMP_PORT") - } - port, _ := strconv.ParseUint(envPort, 10, 16) - - params, err := g.NewClient(g.Config{ - Target: envTarget, - Port: uint16(port), - Community: "public", - Version: g.Version2c, - Timeout: time.Duration(2) * time.Second, - }) - if err != nil { - log.Fatalf("NewClient() err: %v", err) - } - ctx := context.Background() - err = params.Connect(ctx) - if err != nil { - log.Fatalf("Connect() err: %v", err) - } - defer params.Close() - - // The time a request takes, its retries included. - oids := []string{"1.3.6.1.2.1.1.4.0", "1.3.6.1.2.1.1.7.0"} - start := time.Now() - result, err2 := params.Get(ctx, oids) // Get accepts up to MaxOids OIDs (60 by default) - if err2 != nil { - log.Fatalf("Get() err: %v", err2) - } - log.Println("Query latency in seconds:", time.Since(start).Seconds()) - - 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()) - } - } -} diff --git a/examples/example3/main.go b/examples/example3/main.go deleted file mode 100644 index d4cc204..0000000 --- a/examples/example3/main.go +++ /dev/null @@ -1,62 +0,0 @@ -// 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. - -package main - -import ( - "context" - "fmt" - "log" - "time" - - g "github.com/netdata/gosnmp" -) - -func main() { - params, err := g.NewClient(g.Config{ - Target: "192.168.91.20", - Port: 161, - Version: g.Version3, - SecurityLevel: g.AuthPriv, - Timeout: time.Duration(30) * time.Second, - User: g.User{ - Name: "user", - AuthProtocol: g.SHA, - AuthPassphrase: "password", - PrivProtocol: g.DES, - PrivPassphrase: "password", - }, - }) - if err != nil { - log.Fatalf("NewClient() err: %v", err) - } - ctx := context.Background() - err = params.Connect(ctx) - if err != nil { - log.Fatalf("Connect() err: %v", err) - } - defer params.Close() - - oids := []string{"1.3.6.1.2.1.1.4.0", "1.3.6.1.2.1.1.7.0"} - result, err2 := params.Get(ctx, oids) // Get accepts up to MaxOids OIDs (60 by default) - if err2 != nil { - log.Fatalf("Get() err: %v", err2) - } - - 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()) - } - } -} diff --git a/examples/walkexample/main.go b/examples/walkexample/main.go deleted file mode 100644 index 5fbb258..0000000 --- a/examples/walkexample/main.go +++ /dev/null @@ -1,91 +0,0 @@ -// 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. - -// This program demonstrates BulkWalkAll. -package main - -import ( - "context" - "flag" - "fmt" - "os" - "path/filepath" - "time" - - "github.com/netdata/gosnmp" -) - -func main() { - flag.Usage = func() { - fmt.Printf("Usage:\n") - fmt.Printf(" %s [-community=] host [oid]\n", filepath.Base(os.Args[0])) - fmt.Printf(" host - the host to walk/scan\n") - fmt.Printf(" oid - the MIB/Oid defining a subtree of values\n\n") - flag.PrintDefaults() - } - - var community string - flag.StringVar(&community, "community", "public", "the community string for device") - - flag.Parse() - - if len(flag.Args()) < 1 { - flag.Usage() - os.Exit(1) - } - target := flag.Args()[0] - var oid string - if len(flag.Args()) > 1 { - oid = flag.Args()[1] - } - - client, err := gosnmp.NewClient(gosnmp.Config{ - Target: target, - Port: 161, - Community: community, - Version: gosnmp.Version2c, - Timeout: 10 * time.Second, // Timeout better suited to walking - Retries: 3, - }) - if err != nil { - fmt.Printf("NewClient err: %v\n", err) - os.Exit(1) - } - ctx := context.Background() - err = client.Connect(ctx) - if err != nil { - fmt.Printf("Connect err: %v\n", err) - os.Exit(1) - } - defer client.Close() - - // maxRepetitions is how many objects each GETBULK request asks for: net-snmp - // snmpbulkwalk's default; 0 asks for the library's, 50. - const maxRepetitions = 10 - values, end, err := client.BulkWalkAll(ctx, oid, maxRepetitions) - for _, vb := range values { - printValue(vb) - } - if err != nil { - fmt.Printf("Walk Error: %v\n", err) - os.Exit(1) - } - // end says how the walk ended: past the subtree, at an exception value - // such as EndOfMibView, or with the Get of a leaf root, whose - // NoSuchObject or NoSuchInstance tells a missing object from a missing - // instance. - fmt.Printf("End of walk: %v %s\n", end.Reason, end.VarBind.Name) -} - -func printValue(vb gosnmp.VarBind) { - fmt.Printf("%s = ", vb.Name) - - if b, ok := vb.Value.Bytes(); ok { - fmt.Printf("STRING: %s\n", string(b)) - } else if n, ok := vb.Value.Int64(); ok { - fmt.Printf("%v: %d\n", vb.Value.Type(), n) - } else { - fmt.Printf("%v\n", vb.Value.Type()) - } -} From 242aea25d8545275dc845ac16295d347689cc1f8 Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Wed, 11 Nov 2026 21:58:28 +0200 Subject: [PATCH 09/17] chore: drop a setting for a linter that does not run and a test that never ran .golangci.yml set gocyclo's minimum complexity, but enables no gocyclo: the project reviews complexity and runs no complexity linter. TestGenericFailureConnectionTimeout skipped itself unconditionally (a TODO from upstream); the engine tests cover a request that times out. --- .golangci.yml | 2 -- generic_e2e_test.go | 23 ----------------------- 2 files changed, 25 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index b31efb5..8a5194f 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -37,8 +37,6 @@ linters: gocritic: disabled-checks: - exitAfterDefer - gocyclo: - min-complexity: 20 gosec: excludes: - G501 # Allowed for handling old SNMP security methods. diff --git a/generic_e2e_test.go b/generic_e2e_test.go index c5686d8..3fe4322 100644 --- a/generic_e2e_test.go +++ b/generic_e2e_test.go @@ -355,29 +355,6 @@ func TestGenericFailureUnknownHost(t *testing.T) { } } -func TestGenericFailureConnectionTimeout(t *testing.T) { - t.Skip("local testing - skipping this slow one") // TODO test tag, or something - envTarget := os.Getenv("GOSNMP_TARGET") - if envTarget == "" { - t.Skip("local testing - skipping this slow one") - } - - config := testConfig() - config.Target = "198.51.100.1" // Black hole - gs := mustClient(config) - err := gs.Connect(context.Background()) - if err != nil { - t.Fatalf("Did not expect connection error with IP address") - } - _, err = gs.Get(context.Background(), []string{".1.3.6.1.2.1.1.1.0"}) // SNMP MIB-2 sysDescr - if err == nil { - t.Fatalf("Expected Get() to fail due to invalid IP") - } - if !strings.Contains(err.Error(), "timeout") { - t.Fatalf("Expected timeout error. Got => %v", err) - } -} - func TestGenericFailureConnectionRefused(t *testing.T) { config := testConfig() config.Target = "127.0.0.1" From a702f59116e1223f047700e9e7b7bd20b855dc7e Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Wed, 11 Nov 2026 22:21:28 +0200 Subject: [PATCH 10/17] refactor: the client and request names the first rename missed The receiver and local renames left five sites that took their values from fields renamed in the same pass: the exchange's attempt, encode and await named the client x, encode and answers named the request p, and reportKindOf its message p; attemptInterrupts kept a field x for the client. They read c, req and m now. The discovery request is newDiscoveryRequest, beside discoverEngine, which alone uses it: it was newDiscoveryPacket, in the USM model's file. Identifiers and one declaration's place only: the token streams of every Go file, comments skipped, differ only by the renamed identifiers, and every declaration keeps its text but the one moved. --- engine.go | 42 +++++++++++++++++++++--------------------- engine_fuzz_test.go | 2 +- engine_v3.go | 18 +++++++++++++++--- marshal_test.go | 2 +- transport.go | 6 +++--- v3_discovery_test.go | 2 +- v3_usm.go | 12 ------------ 7 files changed, 42 insertions(+), 42 deletions(-) diff --git a/engine.go b/engine.go index 4479f00..f1f62f3 100644 --- a/engine.go +++ b/engine.go @@ -354,25 +354,25 @@ func (e *exchange) unanswered(err error) error { // a reply answers it, the attempt's deadline passes or the context is done. A // reply to an earlier attempt, one of earlier, answers it too. func (e *exchange) attempt(earlier []sentIDs) attemptOutcome { - x := e.c + c := e.c if err := e.ctx.Err(); err != nil { return attemptOutcome{kind: attemptContextDone, err: err} } - conn, err := x.connection() + conn, err := c.connection() if err != nil { return attemptOutcome{kind: attemptFailed, err: err} } var deadline time.Time - deadline, e.contextDeadline = attemptDeadline(e.ctx, x.config.Timeout) + deadline, e.contextDeadline = attemptDeadline(e.ctx, c.config.Timeout) if err = conn.SetDeadline(deadline); err != nil { return attemptOutcome{kind: attemptFailed, err: err} } // The context interrupts the attempt from here on, after its deadline: an // interrupt before it would be undone by it. Close, at any time, closes // the attempt's connection, on which the attempt fails. - defer x.interruptible(e.ctx, conn).end() + defer c.interruptible(e.ctx, conn).end() - e.req.RequestID = x.nextRequestID() + e.req.RequestID = c.nextRequestID() // An encoding failure is not retried: another attempt would fail the same // way. outBuf, err := e.encode() @@ -404,13 +404,13 @@ func attemptDeadline(ctx context.Context, timeout time.Duration) (deadline time. // An authenticated request is signed with the exchange's key, which must fit // its protocol (usm.Auth.CheckKey). func (e *exchange) encode() ([]byte, error) { - x, p := e.c, e.req - if p.Version == Version3 { - p.MsgID = x.nextMsgID() - h := &p.SecurityParameters + c, req := e.c, e.req + if req.Version == Version3 { + req.MsgID = c.nextMsgID() + h := &req.SecurityParameters h.AuthoritativeEngineBoots, h.AuthoritativeEngineTime = e.sec.clock.timeFor(time.Now()) } - out, err := p.marshalMsg(&e.sec.keys) + out, err := req.marshalMsg(&e.sec.keys) if err != nil { return nil, fmt.Errorf("marshal: %w", err) } @@ -422,9 +422,9 @@ func (e *exchange) encode() ([]byte, error) { // or that the commit rejects is discarded, its reason recorded (discard), and // the read goes on until the attempt's deadline (RFC 3412 section 7.2). func (e *exchange) await(conn transport, earlier []sentIDs) attemptOutcome { - x := e.c + c := e.c for { - resp, err := receive(conn, x.rx) + resp, err := receive(conn, c.rx) if err != nil { return ioFailure(err) } @@ -641,16 +641,16 @@ func (e *exchange) answers(reply *Message, earlier []sentIDs) (bool, error) { if e.req.Version != Version3 { return true, nil } - p := e.req - got, want := &reply.SecurityParameters, &p.SecurityParameters + req := e.req + got, want := &reply.SecurityParameters, &req.SecurityParameters switch { - case reply.SecurityLevel != p.SecurityLevel: + case reply.SecurityLevel != req.SecurityLevel: return false, errOtherLevel case got.UserName != want.UserName: return false, errOtherUser case !bytes.Equal(got.AuthoritativeEngineID, want.AuthoritativeEngineID): return false, errOtherEngine - case !bytes.Equal(reply.ContextEngineID, p.ContextEngineID) || reply.ContextName != p.ContextName: + case !bytes.Equal(reply.ContextEngineID, req.ContextEngineID) || reply.ContextName != req.ContextName: return false, errOtherContext } return true, nil @@ -702,18 +702,18 @@ var reportKinds = map[string]reportKind{ //nolint:gochecknoglobals // a read-onl reportCounter(snmpUnknownPDUHandlers): {err: ErrUnknownPDUHandlers}, } -// reportKindOf returns the kind of p as a Report, and false when p is not an +// reportKindOf returns the kind of m as a Report, and false when m is not an // SNMPv3 Report. The agent puts the counter of the error it detected in the // Report's varbinds; the Report's request ID is the request's, or 0 when the // agent could not read it. As in net-snmp's snmpv3_get_report_type, the first // varbind names the counter, with one instance sub-identifier of any value; // none, or another name, gives ErrUnknownReportPDU. -func reportKindOf(p *Message) (reportKind, bool) { - if p.Version != Version3 || p.PDUType != Report { +func reportKindOf(m *Message) (reportKind, bool) { + if m.Version != Version3 || m.PDUType != Report { return reportKind{}, false } - if len(p.VarBinds) > 0 { - if kind, ok := reportKinds[reportCounter(p.VarBinds[0].Name)]; ok { + if len(m.VarBinds) > 0 { + if kind, ok := reportKinds[reportCounter(m.VarBinds[0].Name)]; ok { return kind, true } } diff --git a/engine_fuzz_test.go b/engine_fuzz_test.go index fd58f7f..0eb9e13 100644 --- a/engine_fuzz_test.go +++ b/engine_fuzz_test.go @@ -124,7 +124,7 @@ func engineReplyExchange(tb testing.TB, r engineReplyRequest) *exchange { if x.config.Version == Version3 { x.startEngine() if r.discover { - packet = newDiscoveryPacket() + packet = newDiscoveryRequest() } else { x.engine.stamp(packet) sec = attemptSecurity{clock: x.engine.clock, keys: x.engine.keys} diff --git a/engine_v3.go b/engine_v3.go index 62e9f58..0add53a 100644 --- a/engine_v3.go +++ b/engine_v3.go @@ -28,9 +28,9 @@ func (c *Client) negotiateInitialSecurityParameters(ctx context.Context, req *Me // (exchange.settle), and gives req the engine state. A discovery whose // answer was not committed returns its error with the answer, if any. func (c *Client) discoverEngine(ctx context.Context, req *Message) (*Message, error) { - discoveryPacket := newDiscoveryPacket() - discoveryPacket.ContextName = req.ContextName - answer, committed, err := c.sendOneRequest(ctx, discoveryPacket, true, attemptSecurity{}) + discovery := newDiscoveryRequest() + discovery.ContextName = req.ContextName + answer, committed, err := c.sendOneRequest(ctx, discovery, true, attemptSecurity{}) if !committed { return answer, err } @@ -38,6 +38,18 @@ func (c *Client) discoverEngine(ctx context.Context, req *Message) (*Message, er return nil, nil } +// newDiscoveryRequest returns the request that discovers the authoritative +// engine's ID, boots and time (RFC 3414 section 4): an unauthenticated Get +// without variable bindings and with empty security parameters, which the +// encoder sends reportable as every request. +func newDiscoveryRequest() *Message { + return &Message{ + Version: Version3, + SecurityLevel: NoAuthNoPriv, + PDUType: GetRequest, + } +} + // engineFoundDespiteUnknownUser reports whether a discovery that failed with // ErrUnknownUsername still found the engine: some devices (e.g. Dell EMC // switches) answer discovery with usmStatsUnknownUserNames instead of diff --git a/marshal_test.go b/marshal_test.go index 5222183..6c38c33 100644 --- a/marshal_test.go +++ b/marshal_test.go @@ -1486,7 +1486,7 @@ func TestUnmarshalEmptyPanic(t *testing.T) { } func TestV3USMInitialPacket(t *testing.T) { - blankPacket := newDiscoveryPacket() + blankPacket := newDiscoveryRequest() iBytes, err := blankPacket.Encode(nil) if err != nil { t.Errorf("#TestV3USMInitialPacket: Encode() err returned: %v", err) diff --git a/transport.go b/transport.go index 0dfb570..eac28f1 100644 --- a/transport.go +++ b/transport.go @@ -88,7 +88,7 @@ func (c *Client) interruptible(ctx context.Context, conn transport) attemptInter c.attempt.conn = conn seq := c.attempt.seq c.mu.Unlock() - a := attemptInterrupts{x: c, seq: seq} + a := attemptInterrupts{c: c, seq: seq} // Until this returns, the caller cannot defer end. Roll back setup if // a context's method panics, including while AfterFunc registers it. completed := false @@ -106,7 +106,7 @@ func (c *Client) interruptible(ctx context.Context, conn transport) attemptInter // attemptInterrupts are the interrupts of attempt seq. type attemptInterrupts struct { - x *Client + c *Client seq uint64 stopContext func() bool } @@ -125,7 +125,7 @@ func (a attemptInterrupts) end() { // that has started is waited for, so that its deadline cannot land after a // later attempt's. func (a attemptInterrupts) clear() { - c := a.x + c := a.c c.mu.Lock() interrupted := c.attempt.interrupted c.attempt.conn, c.attempt.interrupted = nil, nil diff --git a/v3_discovery_test.go b/v3_discovery_test.go index 85645fa..710e89e 100644 --- a/v3_discovery_test.go +++ b/v3_discovery_test.go @@ -213,7 +213,7 @@ func (m *mockAgentUnknownUserNames) marshalResponse(req *Message) ([]byte, error // newV3NoAuthClientForDiscoveryTest returns a client configured for // NoAuthNoPriv SNMPv3, which knows no engine yet, so that the first request -// starts with engine-ID discovery (discoveryPacket). +// starts with engine-ID discovery (newDiscoveryRequest). func newV3NoAuthClientForDiscoveryTest(port uint16) *Client { config := testConfigV3(NoAuthNoPriv, User{Name: "testUser"}) config.Target, config.Port, config.Retries = "127.0.0.1", port, 0 diff --git a/v3_usm.go b/v3_usm.go index 8d30cbe..467532b 100644 --- a/v3_usm.go +++ b/v3_usm.go @@ -338,18 +338,6 @@ func (h *SecurityParameters) checkWireFields() error { // passwordCache derives the keys of every user. var passwordCache = usm.NewCache() //nolint:gochecknoglobals // one cache for every client and receiver -// newDiscoveryPacket returns the request that discovers the authoritative -// engine's ID, boots and time (RFC 3414 section 4): an unauthenticated Get -// without variable bindings and with empty security parameters, which the -// encoder sends reportable as every request. -func newDiscoveryPacket() *Message { - return &Message{ - Version: Version3, - SecurityLevel: NoAuthNoPriv, - PDUType: GetRequest, - } -} - // sign writes the digest of packet, an outgoing message whose // msgAuthenticationParameters content at offset auth still holds the zeros of // appendMACPlaceholder, into that content. From 5b2b2fdc11aac586cc815075b2896306365b7d6c Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Wed, 11 Nov 2026 22:22:18 +0200 Subject: [PATCH 11/17] test: pin the msgID a failed header keeps and a discovery's time-window Report - A msgMaxSize below 484, or negative engine boots, fails a reply's header after its msgID: the reply keeps the msgID it read, by which the request ranks the replies it discards. - An unauthenticated notInTimeWindow Report answering the engine discovery serves as its answer: its engine ID commits with an unauthenticated clock; replyClock's table gains the unverified notInTimeWindow Report. - Stale test code goes: a commented-out test of a function that no longer exists, and comments and a test error text that named removed functions. --- engine_state_test.go | 26 ++++++++++++++++++++++++++ marshal_test.go | 4 ++-- misc_test.go | 23 ----------------------- v3_discovery_test.go | 2 +- v3_parse_test.go | 20 ++++++++++++++++++++ 5 files changed, 49 insertions(+), 26 deletions(-) diff --git a/engine_state_test.go b/engine_state_test.go index 99c77ea..579ce98 100644 --- a/engine_state_test.go +++ b/engine_state_test.go @@ -264,6 +264,28 @@ func TestEngineTimeFor(t *testing.T) { } } +// TestEngineSettleDiscoveryTimeWindowReport pins that an unauthenticated +// notInTimeWindow Report answering the engine discovery serves as its answer: +// it answers without an error (a resync Report) and its engine ID commits +// with an unauthenticated clock. +func TestEngineSettleDiscoveryTimeWindowReport(t *testing.T) { + x := stateClient(undiscovered(stateUser)) + report := &Message{ + Version: Version3, SecurityLevel: NoAuthNoPriv, PDUType: Report, + VarBinds: []VarBind{{Name: usmStatsNotInTimeWindows}}, + SecurityParameters: SecurityParameters{AuthoritativeEngineID: []byte(usmCharEngineID), AuthoritativeEngineBoots: 9, AuthoritativeEngineTime: 99}, + } + e := exchange{c: x, req: newDiscoveryRequest(), discovery: true} + answered, err := e.answers(report, nil) + require.True(t, answered) + require.NoError(t, err) + out, err := e.settle(attemptOutcome{kind: attemptReply, reply: report}) + require.NoError(t, err) + require.True(t, out.committed) + assert.Equal(t, [4]any{[]byte(usmCharEngineID), uint32(9), uint32(99), fromUnauthenticated}, + [4]any{x.engine.engineID, x.engine.clock.boots, x.engine.clock.latest, x.engine.clock.source}) +} + // TestEngineReplyClock pins the clock a settling reply gives // (exchange.replyClock): an unverified reply's unauthenticated clock does not // replace an authenticated one (net-snmp's set_enginetime); an authenticated @@ -297,6 +319,10 @@ func TestEngineReplyClock(t *testing.T) { "unverified, no clock": { boots: 3, engineTime: 5, want: result{clockOf(3, 5, now, fromUnauthenticated), true}, }, + "unverified notInTimeWindow Report, an unauthenticated clock": { + current: unauth, kind: reportKind{timeWindow: true}, boots: 3, engineTime: 5, + want: result{clockOf(3, 5, now, fromUnauthenticated), true}, + }, "notInTimeWindow Report, lower boots": { current: auth, verified: true, kind: reportKind{timeWindow: true}, boots: 3, engineTime: 5, want: result{clockOf(3, 5, now, fromAuthenticated), true}, diff --git a/marshal_test.go b/marshal_test.go index 6c38c33..18c06ff 100644 --- a/marshal_test.go +++ b/marshal_test.go @@ -916,7 +916,7 @@ func panicUnmarshalParseRawFieldTimeTicks() []byte { /* panicUnmarshalDecryptPacketIndex() tests a boundary condition that results in a panic -in decryptPacket when handling malformed data. +in the decryption of the scoped PDU when handling malformed data. */ func panicUnmarshalDecryptPacketIndex() []byte { return []byte{ @@ -930,7 +930,7 @@ func panicUnmarshalDecryptPacketIndex() []byte { } /* -panicUnmarshalDecryptPacketIndex() tests a boundary condition that results in a panic +panicUnmarshalDecryptNoPriv() tests a boundary condition that results in a panic in the decryption of the scoped PDU when handling malformed data. */ func panicUnmarshalDecryptNoPriv() []byte { diff --git a/misc_test.go b/misc_test.go index 25c681a..9c0b835 100644 --- a/misc_test.go +++ b/misc_test.go @@ -27,26 +27,3 @@ func TestVersionString(t *testing.T) { } } } - -// --------------------------------------------------------------------- - -/* -var testMarshalTimeticks = []struct { - timeticks uint32 - out []byte -}{ - {1034156, []byte{0x0f, 0xc7, 0xac}}, -} - -func TestMarshalTimeticks(t *testing.T) { - for i, test := range testMarshalTimeticks { - result, err := marshalTimeticks(test.timeticks) - if err != nil { - t.Errorf("%d: expected %v got err %v", i, result, err) - } - if !bytes.Equal(result, test.out) { - t.Errorf("#%d, got %v expected %v", i, result, test.out) - } - } -} -*/ diff --git a/v3_discovery_test.go b/v3_discovery_test.go index 710e89e..611588c 100644 --- a/v3_discovery_test.go +++ b/v3_discovery_test.go @@ -126,7 +126,7 @@ func (m *mockAgentUnknownUserNames) serve() { // sends noAuthNoPriv requests, which take no keys. pkt, cursor, err := unmarshalScopedPDU(buf[:n], cursor, req, req.SecurityLevel.privFlag(), &usmKeys{}) if err != nil { - m.sendErr(fmt.Errorf("decryptPacket: %w", err)) + m.sendErr(fmt.Errorf("unmarshalScopedPDU: %w", err)) continue } diff --git a/v3_parse_test.go b/v3_parse_test.go index a219046..f1d4aaa 100644 --- a/v3_parse_test.go +++ b/v3_parse_test.go @@ -376,6 +376,26 @@ func TestV3ReplyDecode(t *testing.T) { require.ErrorIs(t, err, errMsgFlags) }) + // A header field after the msgID that fails leaves the message as far as + // decode read it, its msgID included, so that rankOf can rank it. + for name, report := range map[string][]byte{ + "msgMaxSize below 484": craftedV3(intTLV(7), intTLV(100), octets("\x00"), intTLV(3), + craftedUSM(octets(usmCharEngineID), intTLV(3), intTLV(77), octets("codec-user"), octets(""), octets("")), + tlv(0x30, octets(usmCharEngineID), octets(""), craftedPDU(Report, craftedVBL(craftedVB(intTLV(5)))))), + "negative engine boots": craftedV3(intTLV(7), intTLV(65507), octets("\x00"), intTLV(3), + craftedUSM(octets(usmCharEngineID), intTLV(-1), intTLV(77), octets("codec-user"), octets(""), octets("")), + tlv(0x30, octets(usmCharEngineID), octets(""), craftedPDU(Report, craftedVBL(craftedVB(intTLV(5)))))), + } { + t.Run(name+" after the msgID", func(t *testing.T) { + e, _ := request(AuthNoPriv, NoPriv) + reply, verified, err := e.decode(report, nil) + require.NotNil(t, reply, "the message as far as decode read it") + assert.Equal(t, uint32(7), reply.MsgID) + assert.False(t, verified) + require.ErrorIs(t, err, ErrASNParse) + }) + } + t.Run("header that fails before its msgID", func(t *testing.T) { e, _ := request(AuthNoPriv, NoPriv) report := craftedV3(intTLV(-1), intTLV(65507), octets("\x00"), intTLV(3), From 036f334c82e0a456e4be90f7d21b6cbfc6eb0547 Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Wed, 11 Nov 2026 22:24:18 +0200 Subject: [PATCH 12/17] docs: correct what the closing review found; safer examples - Message's ErrorStatus and ErrorIndex are not cut to their low byte: an error status outside 0..255 fails the decode, and an error index or non-repeaters above 255 reads as 255. - The engine state changes on a matched answer, and otherwise only by ForgetEngine and the drop of its clock, which the docs describe below. - ErrUnmatchedReply is a category not named after an RFC counter (the package documentation and the README said every category is). - A notInTimeWindow Report that carries an engine ID answers a discovery too (the package documentation and settle's doc). - The Reeder key extension adds a cache entry only when the localized key is shorter than the cipher's (MD5 or SHA-1, or SHA-224 for AES256C). - EncodeMessage's doc names no unexported function; comments name the renamed receivers and parameters; the resend is request's; three paragraphs left with broken lines are reflowed. - The examples range over a Get's varbinds and check each value's type (an agent without the object answers NoSuchObject without an error); the receiver's loop limits the Reports it sends and takes its engine boots from a placeholder of the caller's store. The README's receiver snippet follows. - README "Running the Tests": the receiver's end-to-end tests need snmpinform; the key benchmark measures the filled cache only. The end-to-end tests' header names the environment they read. Comments and docs only, but for the examples: the token streams of every other Go file are unchanged. --- README.md | 14 +++++++----- doc.go | 27 ++++++++++++++--------- engine.go | 54 ++++++++++++++++++++++----------------------- engine_v3.go | 26 +++++++++++----------- example_test.go | 39 ++++++++++++++++++++++++++------ generic_e2e_test.go | 4 ++-- message.go | 19 ++++++++-------- request.go | 6 ++--- v3.go | 13 +++++------ 9 files changed, 116 insertions(+), 86 deletions(-) diff --git a/README.md b/README.md index 3834c35..6ce6b6e 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,8 @@ A receiver (`NewReceiver`) decodes the notifications a manager receives: 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 named after the RFC counter that counts it (`errors.Is`). +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 @@ -109,7 +110,7 @@ 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 { + if response != nil && reportAllowed() { _, _ = conn.WriteToUDP(response, from) } log.Printf("rejected a datagram from %v: %v", from, err) @@ -191,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 in `generic_e2e_test.go` and `receiver_e2e_test.go` +need a running SNMP agent and the environment variables above, so they only build with the +`end2end` build tag; the receiver's also need 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). @@ -233,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' diff --git a/doc.go b/doc.go index d8acc39..e5c3b36 100644 --- a/doc.go +++ b/doc.go @@ -108,10 +108,12 @@ // # Errors // // Every error of an incoming message unwraps ([errors.Is]) to exactly one -// category, an exported error named after the counter RFC 3412, RFC 3414 or RFC -// 3418 counts the message in, as net-snmp v5.9.4 counts it, with a text of its -// own: an error of DecodeMessage, of Receive, of ReadEnvelope, and the reason a -// request discards a reply for. The categories: +// category: an error of DecodeMessage, of Receive, of ReadEnvelope, and the +// reason a request discards a reply for. A category is an exported error with a +// text of its own, named after the counter RFC 3412, RFC 3414 or RFC 3418 +// counts the message in, as net-snmp v5.9.4 counts it, but for +// [ErrUnmatchedReply], a reply that does not answer the request. The +// categories: // // - [ErrASNParse] (snmpInASNParseErrs): the message does not parse, of any // version: its encoding, a header field of another type or outside its @@ -315,14 +317,16 @@ // of the agent's engine is its engine state (RFC 3414 section 2.3), internal to // it: the engine ID, the user's keys localized to it and the engine boots and // time; requests take the engine ID as their context engine ID. Every request -// reads it; only an answer that matched a request changes it, whole, once the -// new state is valid. A request without an engine ID first discovers it (RFC +// reads it; an answer that matched a request changes it, whole, once the new +// state is valid, and otherwise only [Client.ForgetEngine] and the drop of its +// clock (both below) do. A request without an engine ID first discovers it (RFC // 3414 section 4): it sends an unauthenticated, empty Get and takes the engine // ID, boots and time of the answer, with keys derived for that engine ID. The // answer is usually a usmStatsUnknownEngineIDs Report; a // usmStatsUnknownUserNames Report that carries an engine ID, as some devices -// send, serves too (a Response answers discovery only with neither an engine ID -// nor a context engine ID: see below). An answer without an engine ID ends the +// send, serves too, and so does a usmStatsNotInTimeWindows Report that carries +// one (a Response answers discovery only with neither an engine ID nor a +// context engine ID: see below). An answer without an engine ID ends the // request with an error that matches [ErrUnknownEngineID]: the client learns // nothing, and the next request discovers again. Keys that do not derive (FIPS // 140-only mode refuses MD5 and SHA-1) fail NewClient. @@ -440,9 +444,10 @@ // passphrase (RFC 3414 appendix A.2.1). The package caches that result for // every client and receiver, by passphrase and hash, for the life of the // process; it holds the passphrases in memory meanwhile. The Reeder key -// extension (AES192C, AES256C) hashes the localized key the same way, so it -// adds a result per user and engine ID, and DecodeMessage, which decrypts -// without checking the digest, one per engine ID its messages name; a +// extension (AES192C, AES256C) hashes the localized key the same way when it is +// shorter than the cipher's key (from MD5 or SHA-1, or SHA-224 for AES256C), so +// it adds a result per such user and engine ID, and DecodeMessage, which +// decrypts without checking the digest, one per engine ID its messages name; a // receiver's, one per user it has, learns or may learn, and one per engine ID // an authentic message of a LearnUser names when the receiver does not learn it // (an unreportable inform or request, a message that does not decrypt or whose diff --git a/engine.go b/engine.go index f1f62f3..3be9371 100644 --- a/engine.go +++ b/engine.go @@ -15,18 +15,17 @@ import ( "time" ) -// send runs the request req within ctx and returns its -// answer, a Response whose error-status is NoError, or no message with the -// error of a request that fails: marked with ErrAnswered when an answer ended -// it (the message request returns beside its error), requestPanicked's error -// for one that panics, and a *StatusError for a Response with another -// error-status. A nil ctx fails the request before it starts. The library -// prevents panics of its own: the recover is for the caller's code the request -// runs on its goroutine (the methods of the context it calls) and for bugs, -// which would otherwise end the process of a caller that runs requests on a -// goroutine without a recover. A flag, not recover's value, tells that the -// request panicked: under GODEBUG=panicnil=1, recover returns nil for -// panic(nil). +// send runs the request req within ctx and returns its answer, a Response whose +// error-status is NoError, or no message with the error of a request that +// fails: marked with ErrAnswered when an answer ended it (the message request +// returns beside its error), requestPanicked's error for one that panics, and a +// *StatusError for a Response with another error-status. A nil ctx fails the +// request before it starts. The library prevents panics of its own: the recover +// is for the caller's code the request runs on its goroutine (the methods of +// the context it calls) and for bugs, which would otherwise end the process of +// a caller that runs requests on a goroutine without a recover. A flag, not +// recover's value, tells that the request panicked: under GODEBUG=panicnil=1, +// recover returns nil for panic(nil). // // req is a request of the Read Class (RFC 3411 section 2.8.1), a Get, // GetNext or GetBulk, as every request the client sends: the SNMPv3 engine @@ -611,20 +610,19 @@ var ( // unmatched returns the error with text, of ErrUnmatchedReply. func unmatched(text string) error { return inCategory(ErrUnmatchedReply, errors.New(text)) } -// answers reports whether reply, a message decode read for the request, -// answers it, with the error of a Report that does, or else the reason it does -// not (RFC 3412 section 7.2 steps 11 and 12; net-snmp's snmpv3_verify_msg). An -// SNMPv3 Report answers, whatever its request ID, level and context (security +// answers reports whether reply, a message decode read for the request, answers +// it, with the error of a Report that does, or else the reason it does not (RFC +// 3412 section 7.2 steps 11 and 12; net-snmp's snmpv3_verify_msg). An SNMPv3 +// Report answers, whatever its request ID, level and context (security // processing bound its user, and with authentication its engine ID), with its -// counter's error -// (reportKindOf), none for a resync Report. A Response answers with the -// request ID of the attempt it names (attemptOf: an SNMPv3 one by its msgID, -// so with that attempt's pair of IDs) and, for SNMPv3, the request's security -// level (the auth and priv flags), user name, engine ID, context engine ID and -// context name (step 12 b). Nothing else answers: a request sent back -// unchanged, SNMPv1 and SNMPv2c Reports. A message that does not answer leaves -// the request outstanding, as net-snmp does (step 12 b discards the request -// unless the model or level differs): a forged one cannot end it. +// counter's error (reportKindOf), none for a resync Report. A Response answers +// with the request ID of the attempt it names (attemptOf: an SNMPv3 one by its +// msgID, so with that attempt's pair of IDs) and, for SNMPv3, the request's +// security level (the auth and priv flags), user name, engine ID, context +// engine ID and context name (step 12 b). Nothing else answers: a request sent +// back unchanged, SNMPv1 and SNMPv2c Reports. A message that does not answer +// leaves the request outstanding, as net-snmp does (step 12 b discards the +// request unless the model or level differs): a forged one cannot end it. func (e *exchange) answers(reply *Message, earlier []sentIDs) (bool, error) { if kind, ok := reportKindOf(reply); ok { if kind.resync { @@ -674,9 +672,9 @@ const ( type reportKind struct { // err is the request's error. err error - // resync marks the Reports that say the request's engine ID or time is - // out of date: they answer without err. discoverEngine takes the engine - // parameters of one; send sends the request again with them, or returns + // resync marks the Reports that say the request's engine ID or time is out + // of date: they answer without err. discoverEngine takes the engine + // parameters of one; request sends the request again with them, or returns // err when it may not or when a resync Report answers that too. resync bool // namesEngine marks the Report that names the engine ID the request diff --git a/engine_v3.go b/engine_v3.go index 0add53a..e3d180d 100644 --- a/engine_v3.go +++ b/engine_v3.go @@ -67,19 +67,19 @@ var errReplyNotInTime = inCategory(ErrNotInTimeWindow, errors.New("the reply is // settle commits the engine state an SNMPv3 reply that answers the exchange's // request carries, after the match, and returns out, the attempt's outcome, -// with the commit or its error, or, for an authenticated reply outside the -// time window, the error that discards it. A discovery answer (an -// unknownEngineIDs Report, or the unknownUserNames Report some devices send, -// carrying an engine ID) gives the engine ID, its keys and an unauthenticated -// clock, or ends the request when it names no engine ID or the keys do not -// derive. A reply whose digest checked against the request (verified) gives -// its engine ID (another one takes keys derived for it, and no clock) and the -// clock replyClock gives; maximum boots are rejected before either recovery -// exception. Unverified, a Response, which answers only a request without -// authentication and names its engine ID (exchange.answers: the engine -// state's, a lent one, or none for discovery), gives that engine ID and the -// clock replyClock gives. A reply whose engine ID gives no valid state answers -// without a commit. +// with the commit or its error, or, for an authenticated reply outside the time +// window, the error that discards it. A discovery answer (an unknownEngineIDs +// Report, the unknownUserNames Report some devices send, or a notInTimeWindows +// Report, carrying an engine ID) gives the engine ID, its keys and an +// unauthenticated clock, or ends the request when it names no engine ID or the +// keys do not derive. A reply whose digest checked against the request +// (verified) gives its engine ID (another one takes keys derived for it, and no +// clock) and the clock replyClock gives; maximum boots are rejected before +// either recovery exception. Unverified, a Response, which answers only a +// request without authentication and names its engine ID (exchange.answers: the +// engine state's, a lent one, or none for discovery), gives that engine ID and +// the clock replyClock gives. A reply whose engine ID gives no valid state +// answers without a commit. func (e *exchange) settle(out attemptOutcome) (attemptOutcome, error) { c, reply := e.c, out.reply if reply.Version != Version3 { diff --git a/example_test.go b/example_test.go index 3c98564..a52578c 100644 --- a/example_test.go +++ b/example_test.go @@ -79,7 +79,9 @@ func ExampleNewClient_snmpv3() { if err != nil { log.Fatal(err) } - fmt.Println(result.VarBinds[0].Value) + for _, vb := range result.VarBinds { + fmt.Printf("%s = %v\n", vb.Name, vb.Value) + } } // A failed request returns no message: its error tells whether the agent @@ -99,13 +101,21 @@ func ExampleClient_Get() { var status *gosnmp.StatusError switch { case err == nil: - uptime, _ := result.VarBinds[0].Value.Uint32() - fmt.Println("uptime:", time.Duration(uptime)*10*time.Millisecond) + // An agent without the object answers NoSuchObject or NoSuchInstance + // in its place, without an error: check each value's type. + for _, vb := range result.VarBinds { + if ticks, ok := vb.Value.Uint32(); ok && vb.Value.Type() == gosnmp.TimeTicks { + fmt.Println("uptime:", time.Duration(ticks)*10*time.Millisecond) + } else { + fmt.Printf("%s: %v\n", vb.Name, vb.Value.Type()) + } + } case errors.As(err, &status): // A Response with an error-status: the agent answered. fmt.Printf("the agent answered %v for varbind %d\n", status.Status, status.Index) case errors.Is(err, gosnmp.ErrAnswered): - // An SNMPv3 Report, whose counter's category the error matches. + // An SNMPv3 Report (of an SNMPv3 client), whose counter's category + // the error matches. fmt.Println("the agent answered:", err) default: // No answer: a timeout, the context, a transport error. @@ -206,8 +216,11 @@ func ExampleReceiver() { func ExampleReceiver_Receive() { // The receiver's own engine, the authoritative engine of the informs it // receives: the caller keeps the engine ID and the boots across restarts - // and raises the boots at each. + // and raises the boots at each (RFC 3414 section 2.2.2). localEngineID := []byte{0x80, 0x00, 0x1f, 0x88, 0x04, 't', 'r', 'a', 'p', 's'} + // raiseBoots stands for the caller's store: it loads the boots of the + // last start, adds one, stores and returns them. + raiseBoots := func() uint32 { return 1 } user := gosnmp.User{ Name: "monitor", AuthProtocol: gosnmp.SHA256, @@ -217,7 +230,7 @@ func ExampleReceiver_Receive() { } receiver, err := gosnmp.NewReceiver(gosnmp.ReceiverConfig{ EngineID: localEngineID, - EngineBoots: 1, + EngineBoots: raiseBoots(), // Informs name the receiver's engine; an agent's traps name its own. Users: []gosnmp.EngineUser{ {EngineID: localEngineID, User: user}, @@ -233,6 +246,18 @@ func ExampleReceiver_Receive() { log.Fatal(err) } defer conn.Close() + // A Report goes to a source anyone can forge and can be larger than the + // datagram it answers: send at most reportsPerSecond of them. + const reportsPerSecond = 10 + var reportWindow time.Time + var reportsSent int + reportAllowed := func() bool { + if now := time.Now(); now.Sub(reportWindow) >= time.Second { + reportWindow, reportsSent = now, 0 + } + reportsSent++ + return reportsSent <= reportsPerSecond + } buf := make([]byte, 65535) for { n, from, err := conn.ReadFromUDP(buf) @@ -244,7 +269,7 @@ func ExampleReceiver_Receive() { // 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 { + if response != nil && reportAllowed() { _, _ = conn.WriteToUDP(response, from) } log.Printf("rejected a datagram from %v: %v", from, err) diff --git a/generic_e2e_test.go b/generic_e2e_test.go index 3fe4322..9bd97a6 100644 --- a/generic_e2e_test.go +++ b/generic_e2e_test.go @@ -6,8 +6,8 @@ // SNMP MIB-2 host. Potential test systems could include a router, NAS box, printer, // or a linux box running snmpd, snmpsimd.py, etc. // -// Ensure "gosnmp-test-host" is defined in your hosts file, and points to your -// generic test system. +// Set GOSNMP_TARGET and GOSNMP_PORT to the test system (see README.md, +// "Running the Tests"). //go:build end2end diff --git a/message.go b/message.go index 1b38e0c..29fa07d 100644 --- a/message.go +++ b/message.go @@ -54,9 +54,10 @@ type Message struct { // encoder sends 65535 for zero. MsgMaxSize uint32 - // ErrorStatus and ErrorIndex are the PDU's error status and index, each - // decoded to its low byte; a GetBulkRequest has NonRepeaters and - // MaxRepetitions in their place. + // ErrorStatus and ErrorIndex are the PDU's error status and index; a + // GetBulkRequest has NonRepeaters and MaxRepetitions in their place. + // Decoded, an error status outside 0..255 fails the message, and an error + // index or non-repeaters above 255 reads as 255. ErrorStatus ErrorStatus ErrorIndex uint8 NonRepeaters uint8 @@ -193,12 +194,12 @@ func (m *Message) Encode(user *User) ([]byte, error) { // EncodeMessage encodes a request or trap, for another transport or for tests: // it builds the message with NewMessage and numbers it with the next request ID // and, for SNMPv3, the next msgID, as a request's attempt does. An SNMPv3 -// message takes the client's engine state as a request starts it (startEngine): -// its engine ID and context engine ID, the keys localized to it, and the latest -// engine boots and time received, not advanced as a request's attempt advances -// them. It runs no discovery: before the client knows the agent's engine the -// message has no engine ID and no keys, so an authenticated or private one -// fails. On an error it returns no message. +// message takes the client's engine state as a request starts it: its engine ID +// and context engine ID, the keys localized to it, and the latest engine boots +// and time received, not advanced as a request's attempt advances them. It runs +// no discovery: before the client knows the agent's engine the message has no +// engine ID and no keys, so an authenticated or private one fails. On an error +// it returns no message. func (c *Client) EncodeMessage(pduType PDUType, varBinds []VarBind, nonRepeaters uint8, maxRepetitions uint32) ([]byte, error) { m := c.NewMessage(pduType, varBinds, nonRepeaters, maxRepetitions) m.RequestID = c.nextRequestID() diff --git a/request.go b/request.go index 860110f..1da87b4 100644 --- a/request.go +++ b/request.go @@ -25,9 +25,9 @@ func (c *Client) Get(ctx context.Context, oids []string) (result *Message, err e return c.send(ctx, req) } -// oidRequest builds the request packet of pdutype for oids, each as a Null -// varbind, with maxRepetitions for a GetBulk, after checking their count -// against MaxOids: Get's, and each of a walk's GetNext and GetBulk requests. +// oidRequest builds the request of pduType for oids, each as a Null varbind, +// with maxRepetitions for a GetBulk, after checking their count against +// MaxOids: Get's, and each of a walk's GetNext and GetBulk requests. func (c *Client) oidRequest(pduType PDUType, oids []string, maxRepetitions uint32) (*Message, error) { if len(oids) > c.config.MaxOids { return nil, fmt.Errorf("oid count (%d) is greater than MaxOids (%d)", len(oids), c.config.MaxOids) diff --git a/v3.go b/v3.go index 4dcc435..a811b0c 100644 --- a/v3.go +++ b/v3.go @@ -35,17 +35,17 @@ const ( // (appendV3Header). const reportableFlag = 0x4 -// authFlag reports whether f has the authFlag (bit 0x1, RFC 3412 section 6.4) +// authFlag reports whether sl has the authFlag (bit 0x1, RFC 3412 section 6.4) // set: the message asks for authentication. A set flag is a request, not // proof that the message was authenticated. func (sl SecurityLevel) authFlag() bool { return sl&0x1 != 0 } -// privFlag reports whether f has the privFlag (bit 0x2) set: the message asks +// privFlag reports whether sl has the privFlag (bit 0x2) set: the message asks // for privacy. Without the authFlag the combination is invalid (RFC 3412 // section 7.2 step 5 d). func (sl SecurityLevel) privFlag() bool { return sl&0x2 != 0 } -// valid reports whether f is one of the three security levels. +// valid reports whether sl is one of the three security levels. func (sl SecurityLevel) valid() bool { return sl == NoAuthNoPriv || sl == AuthNoPriv || sl == AuthPriv } //go:generate go tool -modfile=tools/go.mod stringer -type=SecurityLevel @@ -100,10 +100,9 @@ var errScopedPDUType = inCategory(ErrASNParse, errors.New("error parsing SNMPV3 // PDU, once the header fields (checkV3Header) fit and keys has the protocols // the level needs, with varBinds as appendPDU takes them. It also returns the // offset of the msgAuthenticationParameters content in dst, where sign writes -// the digest. A -// message the level encrypts gets the next salt of usm.Salts, never the -// message's PrivacyParameters, so that no two messages share one, whatever the -// caller copied into them. +// the digest. A message the level encrypts gets the next salt of usm.Salts, +// never the message's PrivacyParameters, so that no two messages share one, +// whatever the caller copied into them. func (m *Message) appendV3(dst []byte, keys *usmKeys, varBinds []byte) ([]byte, int, error) { if err := m.checkV3Header(); err != nil { return nil, 0, err From 05963f208a6868d06701115a95f3d69c0981ed3c Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Wed, 11 Nov 2026 22:24:46 +0200 Subject: [PATCH 13/17] fix: name the PDU in the PDU length error A PDU whose TLV does not span its bytes failed with "error verifying Response sanity: ", for every PDU type, the SNMPv1 trap included: it now reads "error verifying the PDU's length: ". The category is unchanged (ErrASNParse); no golden records the text. --- pdu.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pdu.go b/pdu.go index a858257..ec1ee5a 100644 --- a/pdu.go +++ b/pdu.go @@ -294,7 +294,7 @@ func readPayload(packet []byte, cursor int, m *Message) error { func readRequestID(packet []byte) (ber.Reader, uint32, error) { pdu, err := readWhole(packet) if err != nil { - return ber.Reader{}, 0, fmt.Errorf("error verifying Response sanity: %w", err) + return ber.Reader{}, 0, fmt.Errorf("error verifying the PDU's length: %w", err) } r := ber.NewReader(pdu) requestID, err := readInt32(&r) @@ -380,7 +380,7 @@ func readErrorFields(r *ber.Reader, m *Message) error { func unmarshalTrapV1(packet []byte, m *Message) error { pdu, err := readWhole(packet) if err != nil { - return fmt.Errorf("error verifying Response sanity: %w", err) + return fmt.Errorf("error verifying the PDU's length: %w", err) } r := ber.NewReader(pdu) From 6ab1d7d068881f64b8bf8ca9196e39f245fb8768 Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Wed, 11 Nov 2026 22:32:25 +0200 Subject: [PATCH 14/17] docs: the receiver snippet's rate limit and the end-to-end tests' needs The README's receiver snippet names reportAllowed, the example's limit on the Reports it sends, which counts per one-second window, as its comment now says. The end-to-end tests run when GOSNMP_TARGET is set: the generic ones against the agent it names, the receiver's with net-snmp's snmpinform, not an agent. --- README.md | 10 +++++----- example_test.go | 3 ++- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 6ce6b6e..55c2649 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,7 @@ for _, vb := range result.VarBinds { ``` A receiver decodes each datagram the caller reads; the caller checks the PDU type and the community and sends the -answer, if any (`ExampleReceiver_Receive`): +answer, if any, Reports at a rate it limits (`reportAllowed`; all of it in `ExampleReceiver_Receive`): ```go notification, response, err := receiver.Receive(buf[:n]) @@ -192,10 +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 tests in `generic_e2e_test.go` and `receiver_e2e_test.go` -need a running SNMP agent and the environment variables above, so they only build with the -`end2end` build tag; the receiver's also need net-snmp's `snmpinform` on the `PATH`, which the -Docker image and CI install. +`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). diff --git a/example_test.go b/example_test.go index a52578c..7937985 100644 --- a/example_test.go +++ b/example_test.go @@ -247,7 +247,8 @@ func ExampleReceiver_Receive() { } defer conn.Close() // A Report goes to a source anyone can forge and can be larger than the - // datagram it answers: send at most reportsPerSecond of them. + // datagram it answers: send at most reportsPerSecond of them in each + // one-second window. const reportsPerSecond = 10 var reportWindow time.Time var reportsSent int From b9b216ebb0f2a280cd51b7107bba508582209069 Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Thu, 12 Nov 2026 00:06:35 +0200 Subject: [PATCH 15/17] fix: the split USM reader returns the engine ID size error alone The engine ID size check, added below the split of the SNMPv3 header reader, returns the one value readSecurityParameters returns. --- v3.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/v3.go b/v3.go index a811b0c..ae70827 100644 --- a/v3.go +++ b/v3.go @@ -358,7 +358,7 @@ func readSecurityParameters(packet []byte, off int, m *Message, w *v3Wire) error return err } if len(engineID) > maxDecodedEngineIDLen { - return w, fmt.Errorf("error parsing %smsgAuthoritativeEngineID: %d octets, more than %d", usmField, len(engineID), maxDecodedEngineIDLen) + return fmt.Errorf("error parsing %smsgAuthoritativeEngineID: %d octets, more than %d", usmField, len(engineID), maxDecodedEngineIDLen) } h.AuthoritativeEngineID = bytes.Clone(engineID) if h.AuthoritativeEngineBoots, err = usmEngineValue(&ur, "msgAuthoritativeEngineBoots"); err != nil { From f9e5aaccc39e780db7316a0d361263cb619ece08 Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Thu, 12 Nov 2026 00:13:54 +0200 Subject: [PATCH 16/17] docs: readSecurityParameters names the engine ID size it takes --- v3.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/v3.go b/v3.go index ae70827..a5928cd 100644 --- a/v3.go +++ b/v3.go @@ -329,9 +329,10 @@ func readGlobalData(r *ber.Reader, m *Message, w *v3Wire) error { // packet[off:] that holds the User-based Security Model's parameters (RFC 3414 // section 2.4), into m's SecurityParameters (copies) and w: the USM fields // bounded by their SEQUENCE and the SEQUENCE by the OCTET STRING, each of its -// type, the engine boots and time within 0..2147483647 (RFC 3414 section 3.2 -// step 1) once cut to 32 bits, and the user name at most 32 octets; msgData -// starts right after msgPrivacyParameters. +// type, the engine ID at most 64 octets (net-snmp's), the engine boots and time +// within 0..2147483647 (RFC 3414 section 3.2 step 1) once cut to 32 bits, and +// the user name at most 32 octets; msgData starts right after +// msgPrivacyParameters. func readSecurityParameters(packet []byte, off int, m *Message, w *v3Wire) error { if PDUType(packet[off]) != PDUType(OctetString) { return errors.New("invalid SNMPV3 Security Parameters") From 757c07361a69ef3419298dbc163d57489a68ddbd Mon Sep 17 00:00:00 2001 From: ilyam8 Date: Thu, 12 Nov 2026 06:26:02 +0200 Subject: [PATCH 17/17] docs: Close and Concurrency say which request ends with net.ErrClosed Close's doc names every request that ends without a reply, as the package documentation does, and the package documentation says that a call's own argument checks come first. --- doc.go | 5 +++-- transport.go | 12 ++++++------ 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/doc.go b/doc.go index e5c3b36..fe7bb88 100644 --- a/doc.go +++ b/doc.go @@ -58,8 +58,9 @@ // request: it closes the connection, which ends the running attempt at once, as // a done context does. Once Close has run, a request that ends without a reply // fails with an error wrapping [net.ErrClosed], whatever else ended it, a done -// context included, and so do later requests until Connect opens a connection. -// A [Receiver] and the package's key cache are safe for concurrent use. +// context included, and so do later requests until Connect opens a connection +// (a call's own checks of its arguments, its context's included, come first). A +// [Receiver] and the package's key cache are safe for concurrent use. // // # Walks // diff --git a/transport.go b/transport.go index eac28f1..1379ca6 100644 --- a/transport.go +++ b/transport.go @@ -45,12 +45,12 @@ func (c *Client) Connect(ctx context.Context) error { return nil } -// Close closes the client's connection, which ends the running attempt at -// once. Any goroutine may call it, also while a request runs, which it ends: -// once Close has run, a request whose attempt ends without a reply fails with -// an error wrapping net.ErrClosed, as do later requests until Connect opens a -// connection (see the package documentation). Only the first call closes the -// connection; later calls, and calls on a client never connected, return nil. +// Close closes the client's connection, which ends the running attempt at once. +// Any goroutine may call it, also while a request runs, which it ends: once +// Close has run, a request that ends without a reply fails with an error +// wrapping net.ErrClosed, as do later requests until Connect opens a connection +// (see the package documentation). Only the first call closes the connection; +// later calls, and calls on a client never connected, return nil. func (c *Client) Close() error { conn := c.markClosed() if conn == nil {