diff --git a/README.md b/README.md index 58da761..4757026 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ For support and help with this fork, open an [issue](https://github.com/netdata/ GoSNMP has the following SNMP functions: +* **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). * **WalkAll** - retrieve a subtree of values using GETNEXT. * **BulkWalkAll** - retrieve a subtree of values using GETBULK (SNMPv2c and SNMPv3 only), with the walk's max-repetitions. @@ -60,21 +61,24 @@ https://pkg.go.dev/github.com/netdata/gosnmp Here is the body of `examples/example/main.go`, which imports the package as `g`: ```go -// A Client literal configures the client: SNMPv2c to port 161 with the -// community "public"; Connect fills in MaxOids (60). -client := &g.Client{ +// 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) +err = client.Connect(ctx) if err != nil { log.Fatalf("Connect() err: %v", err) } diff --git a/codec_bench_test.go b/codec_bench_test.go index 0dfbbff..891b802 100644 --- a/codec_bench_test.go +++ b/codec_bench_test.go @@ -29,7 +29,7 @@ func BenchmarkDecode(b *testing.B) { for _, in := range inputs { b.Run(in.name, func(b *testing.B) { data := in.in() - x := &Client{} + x := mustClient(Config{}) b.ReportAllocs() for b.Loop() { if _, err := x.DecodeMessage(data); err != nil { @@ -47,7 +47,7 @@ func BenchmarkEncode(b *testing.B) { for i := range oids { oids[i] = VarBind{Name: ".1.3.6.1.2.1.2.2.1.10." + strconv.Itoa(i+1), Value: NullValue()} } - response, err := (&Client{}).DecodeMessage(kyoceraResponseBytes()) + response, err := mustClient(Config{}).DecodeMessage(kyoceraResponseBytes()) if err != nil { b.Fatal(err) } diff --git a/codec_decode_test.go b/codec_decode_test.go index 4a56c27..922eddc 100644 --- a/codec_decode_test.go +++ b/codec_decode_test.go @@ -48,7 +48,7 @@ type decodeCase struct { // dumpDecode decodes c with DecodeMessage and, for a case with SNMPv3 // credentials, with a receiver of its own (dumpReceive). func dumpDecode(t *testing.T, c decodeCase) string { - x := &Client{} + x := mustClient(Config{}) if c.decoder != nil { x = c.decoder() } @@ -80,7 +80,7 @@ func dumpDecode(t *testing.T, c decodeCase) string { d.line("input: modified " + dumpBytes(in)) } dumpPacket(&d, p) - dumpReencode(&d, p, &x.User, c.in) + dumpReencode(&d, p, &x.config.User, c.in) dumpReceive(t, &d, c) return d.String() } @@ -97,7 +97,7 @@ func dumpReceive(t *testing.T, d *dumpWriter, c decodeCase) { } // A user NewReceiver refuses, such as one with a protocol and no // passphrase, is refused for every engine ID. - user := c.decoder().User + user := c.decoder().config.User if _, err := NewReceiver(ReceiverConfig{Users: []EngineUser{{EngineID: []byte(codecEngineID), User: user}}}); err != nil { d.line("receive: NewReceiver " + dumpError(err)) return @@ -448,7 +448,7 @@ func usmUser(auth AuthProtocol, authPass string, priv PrivProtocol, privPass str // usmDecoder returns a decoder configured for the synthetic codec-user credentials. func usmDecoder(auth AuthProtocol, authPass string, priv PrivProtocol, privPass string) func() *Client { return func() *Client { - return &Client{User: usmUser(auth, authPass, priv, privPass)} + return mustClient(Config{User: usmUser(auth, authPass, priv, privPass)}) } } diff --git a/codec_encode_test.go b/codec_encode_test.go index 1e23f1c..176a49e 100644 --- a/codec_encode_test.go +++ b/codec_encode_test.go @@ -74,7 +74,7 @@ func TestMarshalLongOctetStringFields(t *testing.T) { if len(want.engineID) > maxDecodedEngineIDLen { // Longer than the decoder takes: the fields as the encoder // laid them out. - _, err = (&Client{}).DecodeMessage(msg) + _, err = mustClient(Config{}).DecodeMessage(msg) require.ErrorIs(t, err, ErrASNParse) m := splitV3Message(t, msg) if got := (fields{engineID: string(m.usm[0]), userName: string(m.usm[3])}); got != want { @@ -83,7 +83,7 @@ func TestMarshalLongOctetStringFields(t *testing.T) { return } - decoded, err := (&Client{}).DecodeMessage(msg) + decoded, err := mustClient(Config{}).DecodeMessage(msg) if err != nil { t.Fatalf("decoding the encoded message: %v\nmessage: %x", err, msg) } @@ -262,7 +262,7 @@ func TestEncodeReportableFlag(t *testing.T) { continue // EncodeMessage has no SNMPv1 trap fields } t.Run(fmt.Sprintf("EncodeMessage/%v/%v", pdu, level), func(t *testing.T) { - x := &Client{Version: Version3, SecurityLevel: level, User: codecUser(levelAuth(level), NoPriv)} + x := mustClient(Config{Version: Version3, SecurityLevel: level, User: codecUser(levelAuth(level), NoPriv)}) seedEngine(codecEngineID, 7, 1234)(x) // EncodeMessage signs with the engine state's keys msg, err := x.EncodeMessage(pdu, vars, 0, 0) if err != nil { @@ -286,19 +286,18 @@ func classFlags(level SecurityLevel, pdu PDUType) SecurityLevel { } // TestInvalidSecurityLevel checks that a security level other than the three -// fails: the encoder's check (Message.Encode) and the client's (validate, as -// Connect, EncodeMessage and DecodeMessage run it); privacy without -// authentication has its own error in the encoder. +// fails: the encoder's check (Message.Encode) and the client's (NewClient); +// privacy without authentication has its own error in the encoder. func TestInvalidSecurityLevel(t *testing.T) { - const invalid = "validate: SecurityLevel must be populated with an appropriate security level" + const invalid = " is not NoAuthNoPriv, AuthNoPriv or AuthPriv" tests := map[string]struct { level SecurityLevel encodeErr, valid string }{ - "privacy without authentication": {level: AuthPriv &^ AuthNoPriv, encodeErr: "unable to marshal SNMPv3 msgFlags: privacy without authentication", valid: invalid}, - "the reportableFlag's bit": {level: reportableFlag, encodeErr: "unable to marshal SNMPv3 security level 4: not NoAuthNoPriv, AuthNoPriv or AuthPriv", valid: invalid}, - "authNoPriv and another bit": {level: AuthNoPriv | reportableFlag, encodeErr: "unable to marshal SNMPv3 security level 5: not NoAuthNoPriv, AuthNoPriv or AuthPriv", valid: invalid}, - "authPriv and another bit": {level: AuthPriv | 0x80, encodeErr: "unable to marshal SNMPv3 security level 131: not NoAuthNoPriv, AuthNoPriv or AuthPriv", valid: invalid}, + "privacy without authentication": {level: AuthPriv &^ AuthNoPriv, encodeErr: "unable to marshal SNMPv3 msgFlags: privacy without authentication", valid: "Config.SecurityLevel SecurityLevel(2)" + invalid}, + "the reportableFlag's bit": {level: reportableFlag, encodeErr: "unable to marshal SNMPv3 security level 4: not NoAuthNoPriv, AuthNoPriv or AuthPriv", valid: "Config.SecurityLevel SecurityLevel(4)" + invalid}, + "authNoPriv and another bit": {level: AuthNoPriv | reportableFlag, encodeErr: "unable to marshal SNMPv3 security level 5: not NoAuthNoPriv, AuthNoPriv or AuthPriv", valid: "Config.SecurityLevel SecurityLevel(5)" + invalid}, + "authPriv and another bit": {level: AuthPriv | 0x80, encodeErr: "unable to marshal SNMPv3 security level 131: not NoAuthNoPriv, AuthNoPriv or AuthPriv", valid: "Config.SecurityLevel SecurityLevel(131)" + invalid}, } for name, tc := range tests { t.Run(name, func(t *testing.T) { @@ -308,9 +307,9 @@ func TestInvalidSecurityLevel(t *testing.T) { PDUType: GetRequest, MsgID: 1, RequestID: 1, }).Encode(&user) require.EqualError(t, err, tc.encodeErr) - x := &Client{Version: Version3, SecurityLevel: tc.level, User: user} - _, err = x.EncodeMessage(GetRequest, nil, 0, 0) + x, err := NewClient(Config{Version: Version3, SecurityLevel: tc.level, User: user}) require.EqualError(t, err, tc.valid) + require.Nil(t, x) }) } } @@ -680,8 +679,7 @@ func encodeCases(t *testing.T) []encodeCase { // fixedIDs starts the client's ID counters at 0, so that its request ID // and msgID are 1 (a client draws random ones otherwise). fixedIDs := func(x *Client) *Client { - x.SetRequestID(0) - x.SetMsgID(0) + x.requestID, x.msgID = 0, 0 return x } marshal := func(p *Message) func() ([]byte, error) { return func() ([]byte, error) { return p.Encode(nil) } } @@ -844,36 +842,36 @@ func encodeCases(t *testing.T) []encodeCase { // EncodeMessage builds the message from the client's configuration. {"encode-packet/v1/get-request", func() ([]byte, error) { - x := fixedIDs(&Client{Version: Version1, Community: "public"}) + x := fixedIDs(mustClient(Config{Version: Version1, Community: "public"})) return x.EncodeMessage(GetRequest, nullVar, 0, 0) }}, {"encode-packet/v2c/getbulk-request", func() ([]byte, error) { - x := fixedIDs(&Client{Version: Version2c, Community: "public"}) + x := fixedIDs(mustClient(Config{Version: Version2c, Community: "public"})) return x.EncodeMessage(GetBulkRequest, nullVar, 1, 10) }}, {"encode-packet/v2c/getbulk-request/max-repetitions-max-uint32", func() ([]byte, error) { - x := fixedIDs(&Client{Version: Version2c, Community: "public"}) + x := fixedIDs(mustClient(Config{Version: Version2c, Community: "public"})) return x.EncodeMessage(GetBulkRequest, nullVar, 0, math.MaxUint32) }}, // An SNMPv3 one takes the engine state a request learned: the codec // engine with boots 7 and time 1234. {"encode-packet/v3/auth-no-priv/sha", func() ([]byte, error) { - x := fixedIDs(&Client{ + x := fixedIDs(mustClient(Config{ Version: Version3, SecurityLevel: AuthNoPriv, User: codecUser(SHA, NoPriv), ContextName: "codec-context", - }) + })) seedEngine(codecEngineID, 7, 1234)(x) return x.EncodeMessage(GetRequest, nullVar, 0, 0) }}, {"encode-packet/v3/auth-priv/sha-aes", func() ([]byte, error) { - x := fixedIDs(&Client{ + x := fixedIDs(mustClient(Config{ Version: Version3, SecurityLevel: AuthPriv, User: codecUser(SHA, AES), ContextName: "codec-context", - }) + })) seedEngine(codecEngineID, 7, 1234)(x) return x.EncodeMessage(GetRequest, nullVar, 0, 0) }}, diff --git a/codec_failure_test.go b/codec_failure_test.go index 1c3b767..61c7ca4 100644 --- a/codec_failure_test.go +++ b/codec_failure_test.go @@ -113,7 +113,7 @@ func TestDecodeFailureNoMessage(t *testing.T) { for name, tc := range tests { t.Run(name, func(t *testing.T) { - p, err := (&Client{}).DecodeMessage(tc.in) + p, err := mustClient(Config{}).DecodeMessage(tc.in) if assert.Error(t, err) { assert.Equal(t, tc.wantErr, err.Error()) } @@ -122,28 +122,6 @@ func TestDecodeFailureNoMessage(t *testing.T) { } } -// TestDecodeMessagePrepareFailure pins that DecodeMessage checks the client's -// configuration as Connect does and returns no message with its error. -func TestDecodeMessagePrepareFailure(t *testing.T) { - tests := map[string]struct { - x *Client - wantErr string - }{ - "negative MaxOids": {x: &Client{MaxOids: -1}, wantErr: "field MaxOids cannot be less than 0"}, - "SNMPv3 user without a name": { - x: &Client{Version: Version3, SecurityLevel: NoAuthNoPriv}, - wantErr: "User.Name is required", - }, - } - for name, tc := range tests { - t.Run(name, func(t *testing.T) { - p, err := tc.x.DecodeMessage(craftedMsg(1, craftedPDU(Response, craftedVBL(craftedVB(intTLV(5)))))) - assert.EqualError(t, err, tc.wantErr) - assert.Nil(t, p) - }) - } -} - // TestDecodeUSMFields pins RFC 3414 section 3.2 step 1: each USM field must // be of its type, and the engine boots and time within 0..2147483647 once cut // to 32 bits (as net-snmp v5.9.4 reads them); anything else fails the header @@ -175,7 +153,7 @@ func TestDecodeUSMFields(t *testing.T) { } for name, tc := range tests { t.Run(name, func(t *testing.T) { - _, err := (&Client{}).DecodeMessage(tc.in) + _, err := mustClient(Config{}).DecodeMessage(tc.in) if tc.invalid { assert.ErrorIs(t, err, ErrASNParse) } else { @@ -200,10 +178,10 @@ func TestUnknownPDUTypeError(t *testing.T) { } for name, tc := range tests { t.Run(name, func(t *testing.T) { - _, err := (&Client{Version: Version2c}).DecodeMessage(craftedMsg(1, pdu(tc.tag))) + _, err := mustClient(Config{Version: Version2c}).DecodeMessage(craftedMsg(1, pdu(tc.tag))) assert.EqualError(t, err, "unable to decode packet body: "+tc.want, "SNMPv2c") - v3 := &Client{Version: Version3, User: User{Name: "codec-user"}} + v3 := mustClient(Config{Version: Version3, User: User{Name: "codec-user"}}) _, err = v3.DecodeMessage(craftedV3NoAuth(tlv(0x30, craftedEngineID, octets("ctx"), pdu(tc.tag)))) assert.EqualError(t, err, "unable to decode packet body: "+tc.want, "SNMPv3") diff --git a/codec_fuzz_test.go b/codec_fuzz_test.go index b627ba4..3075286 100644 --- a/codec_fuzz_test.go +++ b/codec_fuzz_test.go @@ -94,7 +94,7 @@ func FuzzDecodeReencode(f *testing.F) { } f.Fuzz(func(t *testing.T, data []byte) { - first, err := (&Client{}).DecodeMessage(bytes.Clone(data)) + first, err := mustClient(Config{}).DecodeMessage(bytes.Clone(data)) if err != nil { return } @@ -107,7 +107,7 @@ func FuzzDecodeReencode(f *testing.F) { t.Fatalf("decoded packet does not encode: %v\ninput: %x", err, data) } - second, err := (&Client{}).DecodeMessage(bytes.Clone(encoded)) + second, err := mustClient(Config{}).DecodeMessage(bytes.Clone(encoded)) if err != nil { t.Fatalf("re-encoded packet does not decode: %v\ninput: %x\nre-encoded: %x", err, data, encoded) } diff --git a/doc.go b/doc.go index 864275c..f88080b 100644 --- a/doc.go +++ b/doc.go @@ -13,23 +13,23 @@ // // # Lifecycle // -// A client is a [Client] whose exported fields configure it. The package +// [NewClient] makes a [Client] from a [Config]: it checks the configuration, +// fills in its defaults (Port 161, Timeout 1 s, [MaxOids]) and fails with an +// error naming the field it rejects, such as a negative Retries or an SNMPv3 +// user the security level does not fit. The client keeps the configuration as +// it is: nothing changes it, and the client does not show it. The package // declares no interface of the client for tests to mock: code that mocks it -// declares one of its own with the methods it calls. [Client.Connect] fills in -// the default [MaxOids], checks the SNMPv3 configuration and opens the client's -// connection, a UDP socket connected to Target and Port, which replaces the one -// it had (a failed Connect keeps it). 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 reads the -// client's configuration when it starts and does not change it: a change the -// caller makes during a request applies from the next one, but the SNMPv3 -// engine state the client learns during a request serves the rest of it (see -// SNMPv3). 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 a random value on first use unless [Client.SetRequestID] and -// [Client.SetMsgID] set them, and Connect does not reset them. +// declares one of its own with the methods it calls. [Client.Connect] opens the +// 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 @@ -120,8 +120,7 @@ // 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 -// (a protocol without a passphrase; FIPS 140-only mode refuses MD5 and SHA-1) -// end the request with the derivation's error, before any discovery. +// (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 @@ -133,11 +132,8 @@ // authentication carries the clock's values (as net-snmp; RFC 3414 section 3.1 // step 6 c sends zeros). // -// A request takes the configuration into the engine state at its start: another -// User, set since the last request started, keeps the engine ID and clock and -// derives its keys for the engine ID. [Client.ForgetEngine] makes the next -// request start over and discover the engine again; a request that is running -// keeps the state it has. +// [Client.ForgetEngine] makes the next request start over and discover the +// engine again; a request that is running keeps the state it has. // // A reply whose msgID names none of the request's attempts is discarded before // security processing. A reply then goes through the security processing of RFC @@ -340,9 +336,10 @@ // 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 when its -// engine state takes an engine ID (discovery, an answer it takes, a Report lent -// to a resend) or another User; decoding a reply derives none. +// 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 diff --git a/engine.go b/engine.go index 61e31af..e297ba0 100644 --- a/engine.go +++ b/engine.go @@ -51,33 +51,29 @@ func (x *Client) send(ctx context.Context, packetOut *Message) (result *Message, return result, nil } -// request runs a request within ctx: for SNMPv3 it first takes the -// configuration into the engine state and discovers the agent's engine when it -// has none, then sends the request, whose answer commits the engine parameters -// it carries, and sends the request once more when the answer is a Report that -// resynchronizes the client with the agent's engine. With an error it returns +// request runs a request within ctx: for SNMPv3 it first starts the engine +// state and discovers the agent's engine when it has none, then sends the +// request, whose answer commits the engine parameters it carries, and sends +// the request once more when the answer is a Report that resynchronizes the +// 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) { - cfg := x.prepareRequest(ctx) if _, err = x.connection(); err != nil { return nil, err } // sec is the engine clock and the keys the attempts carry. var sec attemptSecurity if packetOut.Version == Version3 { - // The engine state takes the configuration at the request's start. - if err = x.startEngine(); err != nil { - return nil, err - } - if result, err = x.negotiateInitialSecurityParameters(&cfg, packetOut); err != nil { + x.startEngine() + if result, err = x.negotiateInitialSecurityParameters(ctx, packetOut); err != nil { return result, err } sec = attemptSecurity{clock: x.engine.clock, keys: x.engine.keys} } var stored bool - result, stored, err = x.sendOneRequest(&cfg, packetOut, false, sec) + result, stored, err = x.sendOneRequest(ctx, packetOut, false, sec) kind := resyncKindOf(result) if !kind.resync { return result, err @@ -98,7 +94,7 @@ func (x *Client) request(ctx context.Context, packetOut *Message) (result *Messa } else if sec, err = x.lendEngineParameters(packetOut, result, kind, sec); err != nil { return result, err } - result, _, err = x.sendOneRequest(&cfg, packetOut, false, sec) + result, _, err = x.sendOneRequest(ctx, packetOut, false, sec) if kind = resyncKindOf(result); kind.resync { return result, kind.err } @@ -126,40 +122,13 @@ func resyncKindOf(result *Message) reportKind { return kind } -// requestConfig is the client's configuration as a request reads it, once, at -// its start, with the request's context: a change the caller makes to the -// client during the request applies from the next one. The packet carries the -// rest (version, security level, user name, context name), and the SNMPv3 -// engine state takes the user at the same time (startEngine). Not part of it: -// the connection, which each attempt takes from the client (connection). -type requestConfig struct { - ctx context.Context - timeout time.Duration - retries int -} - -// prepareRequest reads the request configuration, with ctx and no negative -// retries, and allocates the receive buffer at the client's first request. -func (x *Client) prepareRequest(ctx context.Context) requestConfig { - if x.rx == nil { - x.rx = new(receiveBuffer) - } - return requestConfig{ - ctx: ctx, - timeout: x.Timeout, - retries: max(x.Retries, 0), - } -} - // exchange is one request on its way through the attempts sendOneRequest // makes. type exchange struct { x *Client packet *Message - // cfg is a copy of the request's configuration: escape analysis is - // field-insensitive, so a pointer beside packet would move the request's - // configuration to the heap. - cfg requestConfig + // ctx is the request's context. + ctx context.Context // contextDeadline is set when the context's deadline ends the current // attempt, at or before its timeout: endErr then reports @@ -295,15 +264,15 @@ type sentIDs struct { // 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 -// cfg.retries times. Once Close closed the client, a request that ends -// without a 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(cfg *requestConfig, packetOut *Message, discovery bool, sec attemptSecurity) (*Message, bool, error) { - e := exchange{x: x, packet: packetOut, cfg: *cfg, discovery: discovery, sec: sec} +// Retries times. Once Close closed the client, a request that ends without a +// 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} // 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 cfg.retries+1 of + // would always escape to the heap, and a slice made for Retries+1 of // them escapes beyond 32 bytes. var sent [8]sentIDs earlier := sent[:0] @@ -336,13 +305,13 @@ func (x *Client) sendOneRequest(cfg *requestConfig, packetOut *Message, discover // and the last attempt with its own error, or, after a timeout, with an // attemptsError. func (e *exchange) endErr(n int, out attemptOutcome) error { - if err := e.cfg.ctx.Err(); err != nil { + if err := e.ctx.Err(); err != nil { return err } if out.kind == attemptTimeout && e.contextDeadline { return context.DeadlineExceeded } - if n < e.cfg.retries { + if n < e.x.config.Retries { return nil } if out.kind == attemptTimeout { @@ -381,7 +350,7 @@ func (e *exchange) unanswered(err error) error { // reply to an earlier attempt, one of earlier, answers it too. func (e *exchange) attempt(earlier []sentIDs) attemptOutcome { x := e.x - if err := e.cfg.ctx.Err(); err != nil { + if err := e.ctx.Err(); err != nil { return attemptOutcome{kind: attemptContextDone, err: err} } conn, err := x.connection() @@ -389,14 +358,14 @@ func (e *exchange) attempt(earlier []sentIDs) attemptOutcome { return attemptOutcome{kind: attemptFailed, err: err} } var deadline time.Time - deadline, e.contextDeadline = attemptDeadline(e.cfg.ctx, e.cfg.timeout) + deadline, e.contextDeadline = attemptDeadline(e.ctx, x.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.cfg.ctx, conn).end() + defer x.interruptible(e.ctx, conn).end() e.packet.RequestID = x.nextRequestID() // An encoding failure is not retried: another attempt would fail the same diff --git a/engine_fuzz_test.go b/engine_fuzz_test.go index 12de568..7e53c81 100644 --- a/engine_fuzz_test.go +++ b/engine_fuzz_test.go @@ -90,23 +90,24 @@ func TestEngineReplySeeds(t *testing.T) { // engineReplyClient returns a client for r whose next request ID and msgID // are 1001 and 2001, without a connection. func engineReplyClient(r engineReplyRequest) *Client { - x := &Client{Version: Version2c, Community: "public", Timeout: time.Second, MaxOids: MaxOids} + config := Config{Version: Version2c, Community: "public", Timeout: time.Second} if r.user != "" { creds := agentCreds[r.user] - x.Version, x.SecurityLevel = Version3, NoAuthNoPriv + config.Version, config.SecurityLevel = Version3, NoAuthNoPriv switch { case creds.priv > NoPriv: - x.SecurityLevel = AuthPriv + config.SecurityLevel = AuthPriv case creds.auth > NoAuth: - x.SecurityLevel = AuthNoPriv - } - x.User = creds.user(r.user) - if !r.discover { - seedEngine(agentEngineID, agentBoots, agentTimeBase)(x) + config.SecurityLevel = AuthNoPriv } + config.User = creds.user(r.user) + } + x := mustClient(config) + if r.user != "" && !r.discover { + seedEngine(agentEngineID, agentBoots, agentTimeBase)(x) } - x.SetRequestID(1000) - x.SetMsgID(2000) + x.rx = new(receiveBuffer) + x.requestID, x.msgID = 1000, 2000 return x } @@ -120,10 +121,8 @@ func engineReplyExchange(tb testing.TB, r engineReplyRequest) *exchange { tb.Fatal(err) } var sec attemptSecurity - if x.Version == Version3 { - if err := x.startEngine(); err != nil { - tb.Fatal(err) - } + if x.config.Version == Version3 { + x.startEngine() if r.discover { packet = newDiscoveryPacket() } else { @@ -131,8 +130,7 @@ func engineReplyExchange(tb testing.TB, r engineReplyRequest) *exchange { sec = attemptSecurity{clock: x.engine.clock, keys: x.engine.keys} } } - cfg := x.prepareRequest(context.Background()) - return &exchange{x: x, packet: packet, cfg: cfg, discovery: r.discover, sec: sec} + return &exchange{x: x, packet: packet, ctx: context.Background(), discovery: r.discover, sec: sec} } // engineReplySeeds returns replies to the first exchange of r's request diff --git a/engine_harness_test.go b/engine_harness_test.go index c9ebec5..59bc3e9 100644 --- a/engine_harness_test.go +++ b/engine_harness_test.go @@ -10,10 +10,8 @@ import ( "errors" "fmt" "io" - "maps" "net" "os" - "reflect" "slices" "strconv" "strings" @@ -321,63 +319,35 @@ func transportOf(tb testing.TB, x *Client) *fakeTransport { return c } -// newEngineClient returns a v1/v2c client on conn with a 1 s timeout and 2 -// retries, completed by newEngineClientFrom. +// engineConfig returns the configuration of a v1/v2c client with a 1 s +// timeout and 2 retries. +func engineConfig(version Version) Config { + return Config{Version: version, Community: "public", Timeout: time.Second, Retries: 2} +} + +// newEngineClient returns a client of engineConfig on conn, completed by +// newEngineClientFrom. func newEngineClient(tb testing.TB, version Version, conn *fakeTransport) *Client { tb.Helper() - return newEngineClientFrom(tb, conn, &Client{ - Version: version, - Community: "public", - Timeout: time.Second, - Retries: 2, - }) + return newEngineClientFrom(tb, conn, engineConfig(version)) } -// newEngineClientFrom completes x on conn as Connect would leave it, with the -// receive buffer its first request allocates, request IDs starting after 1000, -// message IDs after 2000 and the next salt 0x101. -func newEngineClientFrom(tb testing.TB, conn *fakeTransport, x *Client) *Client { +// newEngineClientFrom returns the client NewClient makes of config on conn, +// as Connect would leave it, with request IDs starting after 1000, message IDs +// after 2000 and the next salt 0x101. +func newEngineClientFrom(tb testing.TB, conn *fakeTransport, config Config) *Client { tb.Helper() - if err := x.prepare(); err != nil { + x, err := NewClient(config) + if err != nil { tb.Fatal(err) } usm.Salts.Set(0x101) x.conn = conn x.rx = new(receiveBuffer) - x.SetRequestID(1000) - x.SetMsgID(2000) + x.requestID, x.msgID = 1000, 2000 return x } -// configOf returns the client's configuration a request must not write: its -// exported fields, the SNMPv3 User included. -func configOf(x *Client) map[string]any { - v := reflect.ValueOf(x).Elem() - cfg := make(map[string]any) - for i := range v.NumField() { - if f := v.Type().Field(i); f.IsExported() { - cfg[f.Name] = v.Field(i).Interface() - } - } - return cfg -} - -// addConfigChanges records the configuration fields whose values changed -// from before to the client's current ones: a test's code may change them, -// the library may not. -func (tr *engineTranscript) addConfigChanges(before map[string]any, x *Client) { - after := configOf(x) - var changed []string - for _, name := range slices.Sorted(maps.Keys(before)) { - if !reflect.DeepEqual(before[name], after[name]) { - changed = append(changed, name) - } - } - if len(changed) > 0 { - tr.addf("client configuration changed: %s", strings.Join(changed, ", ")) - } -} - // decodeMessage decodes a v1/v2c message, as an agent reads a request. func decodeMessage(b []byte) (*Message, error) { p := new(Message) diff --git a/engine_requests_test.go b/engine_requests_test.go index 12dde2b..7a08638 100644 --- a/engine_requests_test.go +++ b/engine_requests_test.go @@ -36,8 +36,10 @@ const engineOID = ".1.3.6.1.2.1.1.1.0" // engineScenario is one v1/v2c request run against a scripted agent. type engineScenario struct { - v1 bool // SNMPv1 instead of SNMPv2c - setup func(x *Client, c *fakeTransport) + v1 bool // SNMPv1 instead of SNMPv2c + // config, when set, changes the client's configuration before NewClient. + config func(c *Config) + setup func(x *Client, c *fakeTransport) // context, when set, gives the request's context, background unless // set; its cancel runs when the scenario ends. context func() (context.Context, context.CancelFunc) @@ -326,7 +328,7 @@ func engineScenarios() map[string]engineScenario { } return x.Get(ctx, []string{engineOID}) } - maxOIDs2 := func(x *Client, _ *fakeTransport) { x.MaxOids = 2 } + maxOIDs2 := func(c *Config) { c.MaxOids = 2 } twoOIDs := []string{engineOID, ".1.3.6.1.2.1.1.3.0"} threeOIDs := []string{engineOID, ".1.3.6.1.2.1.1.3.0", ".1.3.6.1.2.1.1.5.0"} @@ -340,28 +342,19 @@ func engineScenarios() map[string]engineScenario { "get/invalid-oid": {agent: answer(), run: getOIDs(".1.3.6.1.x")}, // The MaxOids limit, at 2. - "get/max-oids/at-limit": {agent: answer(sysDescr), setup: maxOIDs2, run: getOIDs(twoOIDs...)}, - "get/max-oids/over-limit": {agent: answer(sysDescr), setup: maxOIDs2, run: getOIDs(threeOIDs...)}, + "get/max-oids/at-limit": {agent: answer(sysDescr), config: maxOIDs2, run: getOIDs(twoOIDs...)}, + "get/max-oids/over-limit": {agent: answer(sysDescr), config: maxOIDs2, run: getOIDs(threeOIDs...)}, // A client Connect never connected. "get/no-conn": {agent: answer(sysDescr), setup: func(x *Client, _ *fakeTransport) { x.conn = nil }}, // Timeouts and retries. - "timeout": {}, - "timeout/no-retries": {setup: func(x *Client, _ *fakeTransport) { x.Retries = 0 }}, - "timeout/negative-retries": {setup: func(x *Client, _ *fakeTransport) { x.Retries = -3 }}, - - // The Conn's code changes the client during a request: the request - // keeps the configuration it started with. - "user-code/sets-retries": {setup: func(x *Client, c *fakeTransport) { - c.afterWrite = func(n int) { - if n == 1 { - c.tr.addf("the Conn's write #1 sets Retries to 0") - x.Retries = 0 - } - } - }}, - "timeout/zero": {agent: answer(sysDescr), setup: func(x *Client, _ *fakeTransport) { x.Timeout = 0 }}, + "timeout": {}, + "timeout/no-retries": {config: func(c *Config) { c.Retries = 0 }}, + // The configured Timeout bounds each attempt. + "timeout/configured": {config: func(c *Config) { c.Timeout = 3 * time.Second }}, + // A zero Timeout means 1 s. + "timeout/zero": {agent: answer(sysDescr), config: func(c *Config) { c.Timeout = 0 }}, "answer/second-attempt": {agent: answerFromSecond(sysDescr)}, // Reply matching. @@ -508,7 +501,7 @@ func engineScenarios() map[string]engineScenario { // A datagram that fills the receive buffer, which may have been cut // short: the attempt fails, and the retry uses the same socket. "answer/too-big-udp": { - setup: func(x *Client, _ *fakeTransport) { x.Retries = 1 }, + config: func(c *Config) { c.Retries = 1 }, agent: func(_ int, req []byte) []agentReply { return []agentReply{{data: replySized(req, rxBufSize)}} }, @@ -569,7 +562,7 @@ func engineScenarios() map[string]engineScenario { }}, "context/deadline-equal-to-timeout": { context: withEngineTimeout(time.Second), - setup: func(x *Client, _ *fakeTransport) { x.Retries = 0 }, + config: func(c *Config) { c.Retries = 0 }, }, "context/deadline-in-first-attempt": {context: withEngineTimeout(700 * time.Millisecond)}, "context/deadline-in-third-attempt": {context: withEngineTimeout(2500 * time.Millisecond)}, @@ -582,7 +575,7 @@ func engineScenarios() map[string]engineScenario { "context/deadline-unreported-in-first-attempt": {context: withUnreportedDeadline(700 * time.Millisecond)}, "context/deadline-unreported-equal-to-timeout": { context: withUnreportedDeadline(time.Second), - setup: func(x *Client, _ *fakeTransport) { x.Retries = 0 }, + config: func(c *Config) { c.Retries = 0 }, }, // A context whose deadline passed ends the request after an attempt // that failed otherwise, before the decision to retry. @@ -694,11 +687,11 @@ func engineScenarios() map[string]engineScenario { }}, // Request IDs. - "request-id/wraps": {agent: answer(sysDescr), setup: func(x *Client, _ *fakeTransport) { x.SetRequestID(0x7FFFFFFF) }}, + "request-id/wraps": {agent: answer(sysDescr), setup: func(x *Client, _ *fakeTransport) { x.requestID = 0x7FFFFFFF }}, "request-id/wraps-between-attempts": {agent: answerFromSecond(sysDescr), setup: func(x *Client, _ *fakeTransport) { - x.SetRequestID(0x7FFFFFFE) + x.requestID = 0x7FFFFFFE }}, - "request-id/set": {agent: answer(sysDescr), setup: func(x *Client, _ *fakeTransport) { x.SetRequestID(5) }}, + "request-id/set": {agent: answer(sysDescr), setup: func(x *Client, _ *fakeTransport) { x.requestID = 5 }}, // The Conn's code panics in a request, which ends. "panics/write": {agent: answer(sysDescr), setup: func(_ *Client, c *fakeTransport) { @@ -763,11 +756,14 @@ func TestEngineRequestCharacterization(t *testing.T) { func runEngineScenario(t *testing.T, sc engineScenario) string { tr := newEngineTranscript(t) c := newFakeTransport(tr, sc.agent) - version := Version2c + config := engineConfig(Version2c) if sc.v1 { - version = Version1 + config.Version = Version1 } - x := newEngineClient(t, version, c) + if sc.config != nil { + sc.config(&config) + } + x := newEngineClientFrom(t, c, config) ctx := context.Background() if sc.context != nil { var cancel context.CancelFunc @@ -782,17 +778,15 @@ func runEngineScenario(t *testing.T, sc engineScenario) string { run = getOIDs(engineOID) } - tr.addf("client: %v timeout=%s retries=%d", x.Version, x.Timeout, x.Retries) + tr.addf("client: %v timeout=%s retries=%d", x.config.Version, x.config.Timeout, x.config.Retries) var res *Message var err error - before := configOf(x) if v, _ := recoverPanic(func() { res, err = run(ctx, x) }); v != nil { tr.addf("panic: %v", v) } else { tr.addf("result: %s", describeEngineResult(res, err)) } - tr.addConfigChanges(before, x) - after := fmt.Sprintf("client after: retries=%d next request id=%d", x.Retries, (x.requestID.Load()+1)&0x7FFFFFFF) + after := fmt.Sprintf("client after: next request id=%d", (x.requestID+1)&0x7FFFFFFF) tr.addf("%s", after) // Let the scenario's own goroutines finish on the bubble's clock: when a // regression ends the request before them, what they record afterwards @@ -946,8 +940,9 @@ func TestRequestContextPanicCleanup(t *testing.T) { for _, interrupt := range []string{"cancel", "close"} { t.Run(stage+"/"+value.name+"/"+interrupt, func(t *testing.T) { synctest.Test(t, func(t *testing.T) { - x := newEngineClient(t, Version2c, newFakeTransport(nil, nil)) - x.Timeout, x.Retries = time.Hour, 0 + config := engineConfig(Version2c) + config.Timeout, config.Retries = time.Hour, 0 + x := newEngineClientFrom(t, newFakeTransport(nil, nil), config) panicking := &panicInterruptContext{ Context: context.Background(), done: make(chan struct{}), stage: stage, value: value.panic, @@ -997,14 +992,14 @@ func TestEngineRequestTimeoutError(t *testing.T) { require.NoError(t, err) defer agent.Close() - x := &Client{ + x := mustClient(Config{ Target: "127.0.0.1", Port: uint16(agent.LocalAddr().(*net.UDPAddr).Port), //nolint:gosec // a UDP port Community: "public", Version: Version2c, Timeout: 50 * time.Millisecond, Retries: 1, - } + }) require.NoError(t, x.Connect(context.Background())) defer x.Close() @@ -1030,11 +1025,11 @@ func BenchmarkSendOneRequest(b *testing.B) { }) x := newEngineClient(b, Version2c, c) pkt := x.NewMessage(GetRequest, []VarBind{{Name: oid, Value: NullValue()}}, 0, 0) - cfg := x.prepareRequest(context.Background()) + ctx := context.Background() b.ReportAllocs() for b.Loop() { - if _, _, err := x.sendOneRequest(&cfg, pkt, false, attemptSecurity{}); err != nil { + if _, _, err := x.sendOneRequest(ctx, pkt, false, attemptSecurity{}); err != nil { b.Fatal(err) } } @@ -1136,7 +1131,7 @@ func TestExchangeDecodeRequestID(t *testing.T) { } for name, tc := range tests { t.Run(name, func(t *testing.T) { - e := &exchange{x: &Client{Version: Version2c}, packet: &Message{Version: Version2c, PDUType: GetRequest}} + e := &exchange{x: mustClient(Config{Version: Version2c}), packet: &Message{Version: Version2c, PDUType: GetRequest}} reply, _, err := e.decode(tc.msg, nil) require.Error(t, err) if tc.want == nil { @@ -1304,7 +1299,7 @@ func TestExchangeEndErrors(t *testing.T) { "transport error after a discard": { discarded: reason, end: func(e *exchange) error { - e.cfg.ctx = context.Background() + e.ctx = context.Background() return e.endErr(0, attemptOutcome{kind: attemptTransportError, err: errEngineWrite}) }, wantText: errEngineWrite.Error(), same: errEngineWrite, wantNotIs: []error{ErrNotInTimeWindow}, @@ -1340,7 +1335,7 @@ func TestExchangeEndErrors(t *testing.T) { } for name, tc := range tests { t.Run(name, func(t *testing.T) { - e := exchange{x: &Client{}} + e := exchange{x: mustClient(Config{})} if tc.discarded != nil { e.discard(tc.discarded, rankAuthentic) } @@ -1443,8 +1438,9 @@ func TestCloseWinsOverAttemptOutcome(t *testing.T) { for name, tc := range tests { t.Run(name, func(t *testing.T) { conn := newFakeTransport(nil, nil) - x := newEngineClient(t, Version2c, conn) - x.Retries = tc.retries + config := engineConfig(Version2c) + config.Retries = tc.retries + x := newEngineClientFrom(t, conn, config) base, cancel := context.WithCancel(context.Background()) defer cancel() ctx := base diff --git a/engine_state.go b/engine_state.go index 0a9007a..553723b 100644 --- a/engine_state.go +++ b/engine_state.go @@ -15,13 +15,10 @@ import ( // 2.3): the engine ID, the user's keys localized to it and the engine boots // and time; the context engine ID of requests is the engine ID. Every decision // of a request reads it, and only a commit replaces it, whole, with a value -// validated first (commitEngine); startEngine takes the configuration into it -// when a request starts. It is internal: nothing exported shows it. +// validated first (commitEngine); NewClient starts it, and a request after +// ForgetEngine starts it over (startEngine). It is internal: nothing exported +// shows it. type engineState struct { - // user is the user the keys derive from, as the last request started - // with it; zero before the first SNMPv3 request. - user User - // engineID is the agent's engine ID, empty before discovery; a new value // is a new slice, never written. engineID []byte @@ -33,6 +30,13 @@ type engineState struct { keys usmKeys } +// newEngineState returns the engine state of user before discovery: no +// engine ID and no clock, and of the keys only their protocols, so that a +// message signed or encrypted then (EncodeMessage) fails the key check. +func newEngineState(user *User) engineState { + return engineState{keys: usmKeys{authProtocol: user.AuthProtocol, privProtocol: user.PrivProtocol}} +} + // clockSource is where an engine clock came from. type clockSource uint8 @@ -89,11 +93,11 @@ func (s *engineState) contextEngineID() []byte { } // withEngine returns the state for the engine engineID: the same state for its -// own engine ID, else one with the user's keys localized to engineID and no -// clock (RFC 3414 section 2.3: the next authentic message synchronizes it). An -// empty engine ID is an error, and so are keys that do not derive. The state -// keeps a copy of engineID: an answer's header, which the caller gets. -func (s *engineState) withEngine(engineID []byte) (engineState, error) { +// own engine ID, else one with user's keys localized to engineID and no clock +// (RFC 3414 section 2.3: the next authentic message synchronizes it). An empty +// engine ID is an error, and so are keys that do not derive. The state keeps a +// copy of engineID: an answer's header, which the caller gets. +func (s *engineState) withEngine(user *User, engineID []byte) (engineState, error) { next := *s switch { case len(engineID) == 0: @@ -101,7 +105,7 @@ func (s *engineState) withEngine(engineID []byte) (engineState, error) { case bytes.Equal(engineID, s.engineID): return next, nil } - keys, err := s.user.localize(engineID) + keys, err := user.localize(engineID) if err != nil { return next, err } @@ -109,33 +113,13 @@ func (s *engineState) withEngine(engineID []byte) (engineState, error) { return next, nil } -// startEngine takes the configuration into the engine state at the start of -// an SNMPv3 request (and of EncodeMessage): after ForgetEngine the state starts -// over, with no engine ID, so the request discovers the engine again; another -// User keeps the engine ID and clock and derives the keys again for the engine -// ID. Without an engine ID the keys must derive all the same, before -// discovery: FIPS 140-only mode, for one, refuses MD5 and SHA-1. An error ends -// the request and changes nothing. -func (x *Client) startEngine() error { - next := x.engine +// 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 { - next = engineState{} - } else if next.user == x.User { - return nil - } - next.user = x.User - keys, err := next.user.localize(next.engineID) - if err != nil { - return err - } - if len(next.engineID) == 0 { - // No keys before discovery, only their protocols: a message signed - // or encrypted then (EncodeMessage) fails the key check. - keys.auth, keys.priv = nil, nil + x.engine, x.forgetEngine = newEngineState(&x.config.User), false } - next.keys = keys - x.engine, x.forgetEngine = next, false - return nil } // ForgetEngine makes the client forget what it learned of the agent's SNMPv3 @@ -145,8 +129,8 @@ func (x *Client) startEngine() error { // that is running keeps the state it has. // Call it when a request fails with an error that matches ErrUnknownEngineID: // the agent's engine ID changed (a replaced device), or a forged answer to the -// discovery gave the client another engine's. Like the configuration, it is -// not safe to call while a request runs on another goroutine. +// 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 } diff --git a/engine_state_test.go b/engine_state_test.go index 77df5b6..d5271f2 100644 --- a/engine_state_test.go +++ b/engine_state_test.go @@ -21,7 +21,14 @@ var stateUser = User{ // undiscovered is the engine state of u before discovery: no engine ID, and // keys with u's protocols only. func undiscovered(u User) engineState { - return engineState{user: u, keys: usmKeys{authProtocol: u.AuthProtocol, privProtocol: u.PrivProtocol}} + return engineState{keys: usmKeys{authProtocol: u.AuthProtocol, privProtocol: u.PrivProtocol}} +} + +// stateClient returns an SNMPv3 client of stateUser whose engine state is s. +func stateClient(s engineState) *Client { + x := mustClient(Config{Version: Version3, SecurityLevel: AuthPriv, User: stateUser}) + x.engine = s + return x } // stateKeys returns u's keys localized to engineID. @@ -32,67 +39,30 @@ func stateKeys(t *testing.T, u User, engineID string) usmKeys { return keys } -// TestEngineStart pins how the start of a request takes the configuration -// into the engine state (startEngine): the first request takes the user, with -// no engine ID and keys with the user's protocols only; another user, a changed passphrase or name -// included, keeps the engine ID and clock and derives the keys again for the -// engine ID; keys that do not derive end the request and change nothing, also -// before discovery; after ForgetEngine the state starts over from the user, -// and a failed start keeps the request to forget for the next one. +// TestEngineStart pins the engine state NewClient starts, and a request's +// start (startEngine): after ForgetEngine the state starts over, with no engine +// ID and keys with the user's protocols only; otherwise it stays. func TestEngineStart(t *testing.T) { - otherPass := stateUser - otherPass.AuthPassphrase = "codec-other-pass" - otherName := stateUser - otherName.Name = "codec-other" - noPass := stateUser - noPass.AuthPassphrase = "" - clock := clockOf(7, 1000, time.Unix(1_000_000_000, 0), fromAuthenticated) + assert.Equal(t, undiscovered(stateUser), mustClient(Config{Version: Version3, SecurityLevel: AuthPriv, User: stateUser}).engine, + "NewClient's state") known := engineState{ - user: stateUser, engineID: []byte(usmCharEngineID), clock: clock, + engineID: []byte(usmCharEngineID), clock: clockOf(7, 1000, time.Unix(1_000_000_000, 0), fromAuthenticated), keys: stateKeys(t, stateUser, usmCharEngineID), } - withUser := func(s engineState, u User) engineState { - s.user = u - if len(s.engineID) != 0 { - s.keys = stateKeys(t, u, string(s.engineID)) - } - return s - } - tests := map[string]struct { - state engineState - user User - forget bool - want engineState - wantForget bool - wantErr string + forget bool + want engineState }{ - "the first request": {user: stateUser, want: undiscovered(stateUser)}, - "nothing changed": {state: known, user: stateUser, want: known}, - "a changed passphrase": {state: known, user: otherPass, want: withUser(known, otherPass)}, - "another name": {state: known, user: otherName, want: withUser(known, otherName)}, - "keys that do not derive": { - state: known, user: noPass, want: known, - wantErr: "usm: no authentication key, want 20 octets", - }, - "keys that do not derive, before discovery": { - user: noPass, want: engineState{}, wantErr: "usm: no authentication key, want 20 octets", - }, - "ForgetEngine": {state: known, user: stateUser, forget: true, want: undiscovered(stateUser)}, - "ForgetEngine and another user": {state: known, user: otherPass, forget: true, want: undiscovered(otherPass)}, - "ForgetEngine, keys that do not": {state: known, user: noPass, forget: true, want: known, wantForget: true, wantErr: "usm: no authentication key, want 20 octets"}, + "nothing to forget": {want: known}, + "ForgetEngine": {forget: true, want: undiscovered(stateUser)}, } for name, tc := range tests { t.Run(name, func(t *testing.T) { - x := &Client{Version: Version3, User: tc.user, engine: tc.state, forgetEngine: tc.forget} - err := x.startEngine() - if tc.wantErr != "" { - require.EqualError(t, err, tc.wantErr) - } else { - require.NoError(t, err) - } + x := stateClient(known) + x.forgetEngine = tc.forget + x.startEngine() assert.Equal(t, tc.want, x.engine, "the engine state") - assert.Equal(t, tc.wantForget, x.forgetEngine, "forget") + assert.False(t, x.forgetEngine, "forget") }) } } @@ -100,11 +70,11 @@ func TestEngineStart(t *testing.T) { // TestEngineForgetEngine pins that ForgetEngine changes no state by itself: // a running request keeps its engine state, and the next start drops it. func TestEngineForgetEngine(t *testing.T) { - known := engineState{user: stateUser, engineID: []byte(usmCharEngineID), keys: stateKeys(t, stateUser, usmCharEngineID)} - x := &Client{Version: Version3, User: stateUser, engine: known} + known := engineState{engineID: []byte(usmCharEngineID), keys: stateKeys(t, stateUser, usmCharEngineID)} + x := stateClient(known) x.ForgetEngine() assert.Equal(t, known, x.engine, "the state, before the next start") - require.NoError(t, x.startEngine()) + x.startEngine() assert.Equal(t, undiscovered(stateUser), x.engine, "the state after the next start") assert.False(t, x.forgetEngine) } @@ -117,29 +87,27 @@ func TestEngineWithEngine(t *testing.T) { noPass := stateUser noPass.PrivPassphrase = "" given := engineState{ - user: stateUser, engineID: []byte(usmCharEngineID), keys: stateKeys(t, stateUser, usmCharEngineID), + engineID: []byte(usmCharEngineID), keys: stateKeys(t, stateUser, usmCharEngineID), clock: clockOf(7, 1000, time.Unix(1_000_000_000, 0), fromAuthenticated), } - other := engineState{user: stateUser, engineID: []byte(usmOtherEngineID), keys: stateKeys(t, stateUser, usmOtherEngineID)} - noPassState := given - noPassState.user = noPass + other := engineState{engineID: []byte(usmOtherEngineID), keys: stateKeys(t, stateUser, usmOtherEngineID)} tests := map[string]struct { - state engineState + user User engineID string want engineState wantErr string }{ - "its own engine ID": {state: given, engineID: usmCharEngineID, want: given}, - "no engine ID": {state: given, engineID: "", wantErr: "the answer names no engine ID"}, - "another engine ID": {state: given, engineID: usmOtherEngineID, want: other}, - "keys that do not derive": {state: noPassState, engineID: usmOtherEngineID, wantErr: "usm: no privacy key, want 16 octets"}, + "its own engine ID": {user: stateUser, engineID: usmCharEngineID, want: given}, + "no engine ID": {user: stateUser, engineID: "", wantErr: "the answer names no engine ID"}, + "another engine ID": {user: stateUser, engineID: usmOtherEngineID, want: other}, + "keys that do not derive": {user: noPass, engineID: usmOtherEngineID, wantErr: "usm: no privacy key, want 16 octets"}, } for name, tc := range tests { t.Run(name, func(t *testing.T) { - before := tc.state - got, err := tc.state.withEngine([]byte(tc.engineID)) - assert.Equal(t, before, tc.state, "the state") + state := given + got, err := state.withEngine(&tc.user, []byte(tc.engineID)) + assert.Equal(t, given, state, "the state") if tc.wantErr != "" { require.EqualError(t, err, tc.wantErr) return @@ -155,8 +123,8 @@ func TestEngineWithEngine(t *testing.T) { // names the request's engine ID (receiveReply), so the commit takes its clock // and keeps the engine ID and keys. func TestEngineSettleKeepsEngine(t *testing.T) { - known := engineState{user: stateUser, engineID: []byte(usmCharEngineID), keys: stateKeys(t, stateUser, usmCharEngineID)} - x := &Client{Version: Version3, User: stateUser, engine: known} + known := engineState{engineID: []byte(usmCharEngineID), keys: stateKeys(t, stateUser, usmCharEngineID)} + x := stateClient(known) packet := x.NewMessage(GetRequest, nil, 0, 0) x.engine.stamp(packet) report := &Message{ @@ -330,12 +298,9 @@ func TestEngineResetsClock(t *testing.T) { // (lendEngineParameters): its boots and time, unauthenticated, marked for // resetsClock only when it is a notInTimeWindow Report; an unknownEngineIDs // Report also lends its engine ID, as the request's engine and context engine -// ID, with keys localized to it for the user the request started with, also -// when the caller has set another User since. +// ID, with the user's keys localized to it. func TestEngineLendClock(t *testing.T) { - known := engineState{user: stateUser, engineID: []byte(usmCharEngineID), keys: stateKeys(t, stateUser, usmCharEngineID)} - otherUser := stateUser - otherUser.AuthPassphrase = "codec-other-pass" + known := engineState{engineID: []byte(usmCharEngineID), keys: stateKeys(t, stateUser, usmCharEngineID)} tests := map[string]struct { counter string wantSource clockSource @@ -350,10 +315,9 @@ func TestEngineLendClock(t *testing.T) { } for name, tc := range tests { t.Run(name, func(t *testing.T) { - x := &Client{Version: Version3, User: stateUser, engine: known} + x := stateClient(known) packet := x.NewMessage(GetRequest, nil, 0, 0) x.engine.stamp(packet) - x.User = otherUser report := &Message{ Version: Version3, PDUType: Report, VarBinds: []VarBind{{Name: tc.counter}}, SecurityParameters: SecurityParameters{ diff --git a/engine_v3.go b/engine_v3.go index 8b34c42..8c4215f 100644 --- a/engine_v3.go +++ b/engine_v3.go @@ -6,6 +6,7 @@ package gosnmp import ( "bytes" + "context" "errors" "time" ) @@ -14,9 +15,9 @@ import ( // 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 // discovery returns its error with the answer that ended it, if any. -func (x *Client) negotiateInitialSecurityParameters(cfg *requestConfig, packetOut *Message) (*Message, error) { +func (x *Client) negotiateInitialSecurityParameters(ctx context.Context, packetOut *Message) (*Message, error) { if len(x.engine.engineID) == 0 { - return x.discoverEngine(cfg, packetOut) + return x.discoverEngine(ctx, packetOut) } x.engine.stamp(packetOut) return nil, nil @@ -26,10 +27,10 @@ func (x *Client) negotiateInitialSecurityParameters(cfg *requestConfig, packetOu // discovery request, whose answer the attempt commits into the engine state // (exchange.settle), and gives packetOut the engine state. A discovery whose // answer was not committed returns its error with the answer, if any. -func (x *Client) discoverEngine(cfg *requestConfig, packetOut *Message) (*Message, error) { +func (x *Client) discoverEngine(ctx context.Context, packetOut *Message) (*Message, error) { discoveryPacket := newDiscoveryPacket() discoveryPacket.ContextName = packetOut.ContextName - answer, committed, err := x.sendOneRequest(cfg, discoveryPacket, true, attemptSecurity{}) + answer, committed, err := x.sendOneRequest(ctx, discoveryPacket, true, attemptSecurity{}) if !committed { return answer, err } @@ -97,7 +98,7 @@ func (e *exchange) settle(out attemptOutcome) (attemptOutcome, error) { if out.verified && boots == maxEngineValue { return attemptOutcome{}, errReplyNotInTime } - next, err := x.engine.withEngine(from.AuthoritativeEngineID) + next, err := x.engine.withEngine(&x.config.User, from.AuthoritativeEngineID) if err != nil { if e.discovery { out.err = err @@ -198,7 +199,7 @@ func mayLend(packetOut, report *Message, kind reportKind) bool { func (x *Client) lendEngineParameters(packetOut, report *Message, kind reportKind, sec attemptSecurity) (attemptSecurity, error) { from := &report.SecurityParameters if kind.namesEngine { - lent, err := x.engine.withEngine(from.AuthoritativeEngineID) + lent, err := x.engine.withEngine(&x.config.User, from.AuthoritativeEngineID) if err != nil { return attemptSecurity{}, err } diff --git a/engine_v3_clock_test.go b/engine_v3_clock_test.go index 0baa101..8892873 100644 --- a/engine_v3_clock_test.go +++ b/engine_v3_clock_test.go @@ -33,7 +33,7 @@ func TestEngineV3MaximumBoots(t *testing.T) { tr := newEngineTranscript(t) a := newFakeV3Agent(tr, agentCreds, sysDescr) c := newFakeTransport(tr, a.handle) - x := newEngineClientFrom(t, c, &Client{ + x := newEngineClientFrom(t, c, Config{ Version: Version3, SecurityLevel: AuthNoPriv, User: agentUserOf("codec-md5"), Timeout: time.Second, Retries: 1, }) diff --git a/engine_v3_fips_test.go b/engine_v3_fips_test.go index 77acf97..4b2f7b8 100644 --- a/engine_v3_fips_test.go +++ b/engine_v3_fips_test.go @@ -5,34 +5,21 @@ package gosnmp import ( - "context" "crypto/fips140" - "io" "maps" "slices" "testing" "testing/synctest" - "time" "github.com/stretchr/testify/assert" ) -// getFirstOf2 runs two Gets, records the first one's result and returns the -// second's. -func getFirstOf2(x *Client, a *fakeV3Agent) (*Message, error) { - res, err := x.Get(context.Background(), []string{engineOID}) - a.tr.addf("first Get: %s", describeEngineResult(res, err)) - return x.Get(context.Background(), []string{engineOID}) -} - -// v3FIPSScenarios are the scenarios of TestEngineV3FIPS140Only. +// v3FIPSScenarios are the scenarios of TestEngineV3FIPS140Only. A user whose +// keys FIPS 140-only mode refuses to derive fails NewClient +// (TestEngineV3FIPS140OnlyNewClient). func v3FIPSScenarios() map[string]v3Scenario { return map[string]v3Scenario{ - "discovery/noauth": {user: "codec-noauth"}, - // A refused key derivation ends each request before discovery: no - // traffic, nothing learned. - "discovery/md5": {user: "codec-md5", run: getFirstOf2}, - "discovery/sha-aes": {user: "codec-sha-aes", run: getFirstOf2}, + "discovery/noauth": {user: "codec-noauth"}, "discovery/sha256-des": {user: "codec-sha256-des"}, "discovery/sha256-aes": {user: "codec-sha256-aes"}, "discovery/sha512-aes256c": {user: "codec-sha512-aes256c"}, @@ -62,11 +49,10 @@ func TestEngineV3FIPS140Only(t *testing.T) { engineGolden.check(t, "v3-fips", results) } -// TestEngineV3FIPS140OnlyDiscoveryPreflight checks that the user's keys must -// derive before discovery, and before EncodeMessage encodes a message. A -// refusal sends nothing, returns no message and leaves the configuration and -// state unchanged. -func TestEngineV3FIPS140OnlyDiscoveryPreflight(t *testing.T) { +// TestEngineV3FIPS140OnlyNewClient checks that the user's keys must derive +// when NewClient makes the client, before any discovery: a refusal fails +// NewClient with an error naming the user. +func TestEngineV3FIPS140OnlyNewClient(t *testing.T) { if !fips140.Enforced() { t.Skip("run with GODEBUG=fips140=only") } @@ -75,42 +61,20 @@ func TestEngineV3FIPS140OnlyDiscoveryPreflight(t *testing.T) { priv PrivProtocol wantErr string }{ - "MD5": {auth: MD5, priv: NoPriv, wantErr: "crypto/md5: use of MD5 is not allowed in FIPS 140-only mode"}, - "SHA": {auth: SHA, priv: NoPriv, wantErr: "crypto/sha1: use of SHA-1 is not allowed in FIPS 140-only mode"}, - "SHA-AES": {auth: SHA, priv: AES, wantErr: "crypto/sha1: use of SHA-1 is not allowed in FIPS 140-only mode"}, + "MD5": {auth: MD5, priv: NoPriv, wantErr: "Config.User: crypto/md5: use of MD5 is not allowed in FIPS 140-only mode"}, + "SHA": {auth: SHA, priv: NoPriv, wantErr: "Config.User: crypto/sha1: use of SHA-1 is not allowed in FIPS 140-only mode"}, + "SHA-AES": {auth: SHA, priv: AES, wantErr: "Config.User: crypto/sha1: use of SHA-1 is not allowed in FIPS 140-only mode"}, } for name, tc := range tests { t.Run(name, func(t *testing.T) { user := User{Name: "codec-user", AuthProtocol: tc.auth, AuthPassphrase: "codec-auth-pass", PrivProtocol: tc.priv} + level := AuthNoPriv if tc.priv > NoPriv { - user.PrivPassphrase = "codec-priv-pass" - } - - tr := newEngineTranscript(t) - c := newFakeTransport(tr, nil) - c.failRead = func(int) error { return io.EOF } - flags := AuthNoPriv - if tc.priv > NoPriv { - flags = AuthPriv - } - x := newEngineClientFrom(t, c, &Client{ - Version: Version3, SecurityLevel: flags, - User: user, ContextName: "codec-context", Timeout: time.Second, Retries: 2, - }) - for range 2 { - res, err := x.Get(context.Background(), []string{engineOID}) - assert.EqualError(t, err, tc.wantErr) - assert.Nil(t, res) - assert.Zero(t, c.writes, "discovery must not be sent") - assert.Zero(t, c.reads) - assert.Equal(t, user, x.User, "the configured user must be preserved") - assert.Equal(t, engineState{}, x.engine) - assert.Equal(t, "codec-context", x.ContextName) + user.PrivPassphrase, level = "codec-priv-pass", AuthPriv } - out, err := x.EncodeMessage(GetRequest, []VarBind{{Name: engineOID, Value: NullValue()}}, 0, 0) + x, err := NewClient(Config{Version: Version3, SecurityLevel: level, User: user, ContextName: "codec-context"}) assert.EqualError(t, err, tc.wantErr) - assert.Nil(t, out) - assert.Equal(t, engineState{}, x.engine) + assert.Nil(t, x) }) } } diff --git a/engine_v3_test.go b/engine_v3_test.go index 3c13f50..29f0d53 100644 --- a/engine_v3_test.go +++ b/engine_v3_test.go @@ -32,8 +32,10 @@ var agentCreds = map[string]agentUser{ // v3Scenario is one SNMPv3 request run against the fake agent. type v3Scenario struct { - user string // the client's user, with agentCreds credentials unless creds is set - creds *agentUser // the client's credentials + user string // the client's user, with agentCreds credentials unless creds is set + creds *agentUser // the client's credentials + // config, when set, changes the client's configuration before NewClient. + config func(c *Config) setup func(x *Client) script func(n int, req agentRequest) (agentAnswer, bool) run func(x *Client, a *fakeV3Agent) (*Message, error) // a Get of engineOID unless set @@ -137,7 +139,7 @@ func encodeThenGet(what string, change func(x *Client)) func(x *Client, a *fakeV func encodeMessage(x *Client, a *fakeV3Agent) { out, err := x.EncodeMessage(GetRequest, []VarBind{{Name: engineOID, Value: NullValue()}}, 0, 0) if err != nil { - a.tr.addf("EncodeMessage: error %v; client %s", err, describeEngineState(&x.engine)) + a.tr.addf("EncodeMessage: error %v; client %s", err, describeEngineState(x)) return } m, err := parseV3Message(out) @@ -158,7 +160,7 @@ func encodeMessage(x *Client, a *fakeV3Agent) { } digest = map[bool]string{true: "digest checks", false: "digest wrong"}[ok] } - a.tr.addf("EncodeMessage: %s, %s; client %s", describeAgentRequest(req), digest, describeEngineState(&x.engine)) + a.tr.addf("EncodeMessage: %s, %s; client %s", describeAgentRequest(req), digest, describeEngineState(x)) } // afterReadThenGet runs a Get after whose read n the fake connection runs @@ -176,7 +178,7 @@ func afterReadThenGet(n int, what string, change func(x *Client)) func(x *Client } // afterRead makes x's fake connection run change after its read n, which the -// transcript names as what: code that changes the client during a request. +// transcript names as what: code that acts on the client during a request. func afterRead(x *Client, a *fakeV3Agent, n int, what string, change func(x *Client)) { c := transportOf(a.tr.tb, x) c.afterRead = func(k int) { @@ -187,22 +189,6 @@ func afterRead(x *Client, a *fakeV3Agent, n int, what string, change func(x *Cli } } -// onFirstWrite runs a Get after whose first write, the engine discovery's, the -// fake connection runs change: code that changes the client during a request, -// before the discovery's answer commits the engine state. -func onFirstWrite(what string, change func(x *Client)) func(x *Client, a *fakeV3Agent) (*Message, error) { - return func(x *Client, a *fakeV3Agent) (*Message, error) { - c := transportOf(a.tr.tb, x) - c.afterWrite = func(n int) { - if n == 1 { - a.tr.addf("the Conn's write #1 %s", what) - change(x) - } - } - return x.Get(context.Background(), []string{engineOID}) - } -} - // agentUserOf returns the User of the agentCreds credentials of name. func agentUserOf(name string) User { return agentCreds[name].user(name) @@ -213,10 +199,8 @@ func agentUserOf(name string) User { // from a Report): the scenarios that start with the engine known. func seedEngine(engineID string, boots, engineTime uint32) func(*Client) { return func(x *Client) { - if err := x.startEngine(); err != nil { - panic(err) - } - next, err := x.engine.withEngine([]byte(engineID)) + x.startEngine() + next, err := x.engine.withEngine(&x.config.User, []byte(engineID)) if err != nil { panic(err) } @@ -250,25 +234,6 @@ func getThrice(between func(a *fakeV3Agent)) func(x *Client, a *fakeV3Agent) (*M } } -// getsAt runs one Get per level, 10 s apart, the client's SecurityLevel set to the -// level before each: a client whose requests change level. It records each -// Get's result but the last, which it returns. -func getsAt(levels ...SecurityLevel) func(x *Client, a *fakeV3Agent) (*Message, error) { - return func(x *Client, a *fakeV3Agent) (*Message, error) { - var res *Message - var err error - for i, level := range levels { - if i > 0 { - a.tr.addf("Get %d: %s", i, describeEngineResult(res, err)) - time.Sleep(10 * time.Second) - } - x.SecurityLevel = level - res, err = x.Get(context.Background(), []string{engineOID}) - } - return res, err - } -} - // otherKey encrypts an answer with a key the client does not have. func otherKey(p *agentOut) { p.keys.priv = bytes.Repeat([]byte{0x5a}, len(p.keys.priv)) @@ -534,8 +499,8 @@ func v3Scenarios() map[string]v3Scenario { "discovery/unknown-user-names-report": {user: "codec-md5", script: onRequest(1, agentAnswer{ report: usmStatsUnknownUserNames, why: "answers discovery like some devices", })}, - "discovery/context-name": {user: "codec-md5", setup: func(x *Client) { - x.ContextName = "codec-vrf" + "discovery/context-name": {user: "codec-md5", config: func(c *Config) { + c.ContextName = "codec-vrf" }}, "discovery/other-security-model": { user: "codec-md5", script: onRequest(1, agentAnswer{ @@ -709,22 +674,6 @@ func v3Scenarios() map[string]v3Scenario { } return agentAnswer{}, false }}, - "unauthenticated-report/security-level-changed-during-request": { - user: "codec-md5", - script: onRequest(2, agentAnswer{report: usmStatsNotInTimeWindows, why: "not in time window, unauthenticated"}), - run: func(x *Client, a *fakeV3Agent) (*Message, error) { - afterRead(x, a, 2, "sets the client's security level to noAuthNoPriv", func(x *Client) { x.SecurityLevel = NoAuthNoPriv }) - return x.Get(context.Background(), []string{engineOID}) - }, - }, - "unauthenticated-report/version-changed-during-request": { - user: "codec-md5", - script: onRequest(2, agentAnswer{report: usmStatsNotInTimeWindows, why: "not in time window, unauthenticated"}), - run: func(x *Client, a *fakeV3Agent) (*Message, error) { - afterRead(x, a, 2, "sets the client's version to 2c", func(x *Client) { x.Version = Version2c }) - return x.Get(context.Background(), []string{engineOID}) - }, - }, // A Report another agent with the same credentials sent, for another // message or with the request's msgID, followed by two Gets. "answer/other-agent-report/other-message": {user: "codec-md5", run: getThrice(nil), script: onRequest(2, agentAnswer{ @@ -763,7 +712,7 @@ func v3Scenarios() map[string]v3Scenario { // A client with authentication keys that sends at noAuthNoPriv does // not check the digest of an authNoPriv answer. "report-later/noauth-request-authenticated-report": { - user: "codec-md5", setup: func(x *Client) { x.SecurityLevel = NoAuthNoPriv }, + user: "codec-md5", config: func(c *Config) { c.SecurityLevel = NoAuthNoPriv }, run: getTwice(nil), script: onRequest(3, agentAnswer{ report: usmStatsUnknownUserNames, level: AuthNoPriv, why: "authNoPriv Report from another engine ID 10 s later", edit: fromOtherEngine, @@ -787,16 +736,6 @@ func v3Scenarios() map[string]v3Scenario { report: usmStatsUnknownEngineIDs, why: "discovery Report without an engine ID", edit: withoutEngineID, }), }, - // A protocol without a passphrase has no key, which Connect rejects; - // a user changed after Connect fails the request at its start, before - // discovery and without traffic, the engine state empty. - "empty-passphrase/auth-protocol-without-passphrase": { - user: "codec-md5", run: func(x *Client, a *fakeV3Agent) (*Message, error) { - a.tr.addf("caller clears the authentication passphrase") - x.User.AuthPassphrase = "" - return x.Get(context.Background(), []string{engineOID}) - }, - }, "discovery/report-without-engine-id/sha256-des": { user: "codec-sha256-des", script: onRequest(1, agentAnswer{ report: usmStatsUnknownEngineIDs, why: "discovery Report without an engine ID", edit: withoutEngineID, @@ -815,75 +754,6 @@ func v3Scenarios() map[string]v3Scenario { }), }, - // The Conn's code changes the client in the discovery's write, the - // first one of a request: the request keeps the values its packet - // took at its start. - "user-code/discovery-write-changes-version": { - user: "codec-md5", - run: onFirstWrite("sets the client's version to 2c", func(x *Client) { x.Version = Version2c }), - }, - "user-code/discovery-write-changes-security-level": { - user: "codec-md5", - run: onFirstWrite("sets the client's security level to noAuthNoPriv", func(x *Client) { x.SecurityLevel = NoAuthNoPriv }), - }, - // The Conn's code changes the client as it reads the discovery's - // answer: the request keeps its retries and timeout. - "user-code/discovery-answer-changes-client": { - user: "codec-md5", script: func(n int, _ agentRequest) (agentAnswer, bool) { - return agentAnswer{drop: true, why: "no answer"}, n == 2 || n == 3 - }, - run: func(x *Client, a *fakeV3Agent) (*Message, error) { - afterRead(x, a, 1, "sets Retries to 0 and Timeout to 5s", func(x *Client) { x.Retries, x.Timeout = 0, 5*time.Second }) - return x.Get(context.Background(), []string{engineOID}) - }, - }, - // The Conn's code changes the client as it reads the resync Report, - // before the resend. - "user-code/resync-report-changes-client": { - user: "codec-md5", script: func(n int, _ agentRequest) (agentAnswer, bool) { - switch n { - case 2: - return agentAnswer{report: usmStatsNotInTimeWindows, level: AuthNoPriv, why: "not in time window"}, true - case 3: - return agentAnswer{drop: true, why: "no answer"}, true - } - return agentAnswer{}, false - }, - run: func(x *Client, a *fakeV3Agent) (*Message, error) { - afterRead(x, a, 2, "sets Retries to 0", func(x *Client) { x.Retries = 0 }) - return x.Get(context.Background(), []string{engineOID}) - }, - }, - "user-code/discovery-write-changes-context-name": { - user: "codec-md5", - run: onFirstWrite("sets the client's context name", func(x *Client) { x.ContextName = "codec-other-name" }), - }, - // The request stays SNMPv3 when the Conn's code changes the client's - // version as it reads the discovery's answer, before the request. - "user-code/discovery-answer-changes-version": { - user: "codec-md5", - run: func(x *Client, a *fakeV3Agent) (*Message, error) { - afterRead(x, a, 1, "sets the client's version to 2c", func(x *Client) { x.Version = Version2c }) - return x.Get(context.Background(), []string{engineOID}) - }, - }, - "user-code/read-lowers-security-level": { - user: "codec-md5", script: onRequest(2, agentAnswer{ - report: usmStatsUnknownUserNames, level: AuthNoPriv, why: "Report signed with another key", edit: forgeReport, - }), - run: func(x *Client, a *fakeV3Agent) (*Message, error) { - afterRead(x, a, 2, "sets the client's security level to noAuthNoPriv", func(x *Client) { x.SecurityLevel = NoAuthNoPriv }) - return x.Get(context.Background(), []string{engineOID}) - }, - }, - "user-code/answer-changes-version": { - user: "codec-md5", - run: func(x *Client, a *fakeV3Agent) (*Message, error) { - afterRead(x, a, 2, "sets the client's version to 2c", func(x *Client) { x.Version = Version2c }) - return x.Get(context.Background(), []string{engineOID}) - }, - }, - // A panic after the discovery's commit, as the request's first attempt // sets its deadline, ends the request; the next request uses the // engine state the discovery committed. @@ -916,22 +786,6 @@ func v3Scenarios() map[string]v3Scenario { return x.Get(context.Background(), []string{engineOID}) }, }, - "resync/security-level-changed-during-request": { - user: "codec-md5", - script: onRequest(2, agentAnswer{report: usmStatsNotInTimeWindows, level: AuthNoPriv, why: "not in time window"}), - run: func(x *Client, a *fakeV3Agent) (*Message, error) { - afterRead(x, a, 2, "sets the client's security level to noAuthNoPriv", func(x *Client) { x.SecurityLevel = NoAuthNoPriv }) - return x.Get(context.Background(), []string{engineOID}) - }, - }, - "resync/version-changed-during-request": { - user: "codec-md5", - script: onRequest(2, agentAnswer{report: usmStatsNotInTimeWindows, level: AuthNoPriv, why: "not in time window"}), - run: func(x *Client, a *fakeV3Agent) (*Message, error) { - afterRead(x, a, 2, "sets the client's version to 2c", func(x *Client) { x.Version = Version2c }) - return x.Get(context.Background(), []string{engineOID}) - }, - }, "resync/retransmission-answered-by-report": { user: "codec-noauth", script: func(n int, _ agentRequest) (agentAnswer, bool) { switch n { @@ -1013,9 +867,9 @@ func v3Scenarios() map[string]v3Scenario { if err != nil { return nil, fmt.Errorf("second Get: %w", err) } - a.tr.addf("caller clears the second result's engine ID; client %s", describeEngineState(&x.engine)) + a.tr.addf("caller clears the second result's engine ID; client %s", describeEngineState(x)) clear(res.SecurityParameters.AuthoritativeEngineID) - a.tr.addf("client %s", describeEngineState(&x.engine)) + a.tr.addf("client %s", describeEngineState(x)) time.Sleep(10 * time.Second) return x.Get(context.Background(), []string{engineOID}) }, @@ -1077,20 +931,10 @@ func v3Scenarios() map[string]v3Scenario { return x.Get(context.Background(), []string{engineOID}) }, }, - // Another user keeps the engine ID and clock, and its keys derive for - // the engine ID. - "caller/other-user": {user: "codec-md5", run: changeThenGet( - "sets another user", func(x *Client) { x.User = agentUserOf("codec-sha-aes") })}, - "caller/changed-passphrase": { - user: "codec-md5", run: changeThenGet( - "changes the authentication passphrase", func(x *Client) { - x.User.AuthPassphrase = "codec-other-pass" - }), - }, // EncodeMessage takes the engine state as a request starts it: the // engine ID, the keys localized to it and the latest boots and time - // received, not advanced; a ForgetEngine or another User since the - // last request applies to it as to a request. + // received, not advanced; a ForgetEngine since the last request + // applies to it as to a request. "caller/encode-after-get/known-engine": { user: "codec-md5", setup: seedEngine(agentEngineID, 0, 0), run: func(x *Client, a *fakeV3Agent) (*Message, error) { @@ -1104,32 +948,12 @@ func v3Scenarios() map[string]v3Scenario { "calls ForgetEngine", func(x *Client) { x.ForgetEngine() })}, "caller/encode-after-forget-engine/noauth": {user: "codec-noauth", run: encodeThenGet( "calls ForgetEngine", func(x *Client) { x.ForgetEngine() })}, - "caller/encode-after-other-user": {user: "codec-md5", run: encodeThenGet( - "sets another user", func(x *Client) { x.User = agentUserOf("codec-sha-aes") })}, - // The Conn's code forgets the engine or changes the user during a - // request: the change applies from the next request. + // The fake connection's code forgets the engine during a request, + // which keeps its state: the next request discovers the engine again. "user-code/discovery-answer-forgets-engine": { user: "codec-md5", run: afterReadThenGet(1, "calls ForgetEngine", func(x *Client) { x.ForgetEngine() }), }, - // A user the Conn's code sets during the discovery serves from the - // next request: the discovery's commit derives the keys of the user - // the request started with. - "user-code/discovery-write-changes-user": { - user: "codec-md5", run: func(x *Client, a *fakeV3Agent) (*Message, error) { - res, err := onFirstWrite("sets another user", func(x *Client) { - x.User = agentUserOf("codec-sha-aes") - })(x, a) - a.tr.addf("first Get: %s", describeEngineResult(res, err)) - time.Sleep(10 * time.Second) - return x.Get(context.Background(), []string{engineOID}) - }, - }, - "user-code/request-answer-changes-user": { - user: "codec-md5", run: afterReadThenGet(2, "sets another user", func(x *Client) { - x.User = agentUserOf("codec-sha-aes") - }), - }, // A Response to a request without authentication naming another // engine ID than the request's answers nothing (RFC 3412 section 7.2 @@ -1150,7 +974,7 @@ func v3Scenarios() map[string]v3Scenario { // it, and answers nothing, at another level than the request's: the // resend times out with that reason. "noauth/lent-engine-authenticated-answer": { - user: "codec-md5", setup: func(x *Client) { x.SecurityLevel = NoAuthNoPriv }, + user: "codec-md5", config: func(c *Config) { c.SecurityLevel = NoAuthNoPriv }, script: func(n int, _ agentRequest) (agentAnswer, bool) { switch { case n == 2: @@ -1225,25 +1049,11 @@ func v3Scenarios() map[string]v3Scenario { edit: func(p *agentOut) { p.SecurityParameters.AuthoritativeEngineBoots = maxEngineValue }, }), }, - // A client whose parameters have an authentication protocol and whose - // requests change level: authenticated answers set the clock its - // requests without authentication carry. - "clock/noauth/verified-old-time": { - user: "codec-md5", run: getsAt(AuthNoPriv, AuthNoPriv, NoAuthNoPriv), script: onRequest(3, agentAnswer{ - level: AuthNoPriv, why: "authNoPriv answer with an engine time 200 s old", - edit: func(p *agentOut) { p.SecurityParameters.AuthoritativeEngineTime -= 200 }, - }), - }, - "clock/noauth/authenticated-then-unauthenticated": { - user: "codec-md5", run: getsAt(AuthNoPriv, NoAuthNoPriv, NoAuthNoPriv), script: onRequest(3, agentAnswer{ - why: "noAuthNoPriv answer with an engine time 500 s ahead", - edit: func(p *agentOut) { p.SecurityParameters.AuthoritativeEngineTime += 500 }, - }), - }, // Discovery's unauthenticated time is no notion step 7 checks the - // first authenticated answer against. - "clock/noauth/verified-after-discovery-time-ahead": { - user: "codec-md5", run: getsAt(AuthNoPriv, NoAuthNoPriv), + // first authenticated answer against, which sets the clock the next + // request carries. + "clock/verified-after-discovery-time-ahead": { + user: "codec-md5", run: getTwice(nil), script: func(n int, _ agentRequest) (agentAnswer, bool) { switch n { case 1: @@ -1417,19 +1227,6 @@ func v3Scenarios() map[string]v3Scenario { "answer/other-version/sha-aes": { user: "codec-sha-aes", script: onRequest(2, agentAnswer{level: AuthPriv, why: "SNMPv2c Response", edit: asV2c}), }, - "user-code/privacy-protocol-changed-in-request-write": { - user: "codec-sha-aes", script: onRequest(2, agentAnswer{drop: true, why: "no answer"}), - setup: func(x *Client) { x.Retries = 1 }, - run: func(x *Client, a *fakeV3Agent) (*Message, error) { - transportOf(a.tr.tb, x).afterWrite = func(n int) { - if n == 2 { - a.tr.addf("the Conn's write #2 sets the client's privacy protocol to DES") - x.User.PrivProtocol = DES - } - } - return x.Get(context.Background(), []string{engineOID}) - }, - }, "answer/other-security-model": { user: "codec-noauth", script: onRequest(2, agentAnswer{ why: "Response with security model 2", raw: securityModel2, @@ -1601,7 +1398,7 @@ func v3Scenarios() map[string]v3Scenario { level: AuthNoPriv, why: "Response without encryption", then: true, })}, "discard/authenticated-to-noauth-then-answer": { - user: "codec-md5", setup: func(x *Client) { x.SecurityLevel = NoAuthNoPriv }, + user: "codec-md5", config: func(c *Config) { c.SecurityLevel = NoAuthNoPriv }, script: onRequest(2, agentAnswer{level: AuthNoPriv, why: "authNoPriv Response", then: true}), }, "discard/other-engine-then-answer": {user: "codec-noauth", script: onRequest(2, agentAnswer{ @@ -1812,7 +1609,7 @@ func runV3Polls(t *testing.T, setup func(a *fakeV3Agent)) string { return replies }) creds := agentCreds["codec-md5"] - x := newEngineClientFrom(t, c, &Client{ + x := newEngineClientFrom(t, c, Config{ Version: Version3, SecurityLevel: AuthNoPriv, User: creds.user("codec-md5"), @@ -1878,17 +1675,20 @@ func runV3Scenario(t *testing.T, sc v3Scenario) string { case creds.auth > NoAuth: flags = AuthNoPriv } - x := &Client{ + config := Config{ Version: Version3, SecurityLevel: flags, User: creds.user(sc.user), Timeout: time.Second, Retries: 2, } + if sc.config != nil { + sc.config(&config) + } + x := newEngineClientFrom(t, c, config) if sc.setup != nil { sc.setup(x) } - x = newEngineClientFrom(t, c, x) run := sc.run if run == nil { run = func(x *Client, _ *fakeV3Agent) (*Message, error) { @@ -1896,38 +1696,37 @@ func runV3Scenario(t *testing.T, sc v3Scenario) string { } } - tr.addf("client: user=%q %s timeout=%s retries=%d", sc.user, describeFlags(x.SecurityLevel), x.Timeout, x.Retries) + tr.addf("client: user=%q %s timeout=%s retries=%d", sc.user, describeFlags(x.config.SecurityLevel), x.config.Timeout, x.config.Retries) var res *Message var err error - before := configOf(x) if v, _ := recoverPanic(func() { res, err = run(x, agent) }); v != nil { tr.addf("panic: %v", v) } else { tr.addf("result: %s", describeEngineResult(res, err)) } - tr.addConfigChanges(before, x) - tr.addf("client after: %s", describeEngineState(&x.engine)) + tr.addf("client after: %s", describeEngineState(x)) return tr.text() } // describeEngineState describes the client's engine state: its engine ID, // the latest engine boots and time it received, the engine ID its keys are // localized to and the context engine ID of its requests. -func describeEngineState(s *engineState) string { +func describeEngineState(x *Client) string { + s := &x.engine return fmt.Sprintf("engine=%q boots=%d time=%d keys=%s context engine=%q", s.engineID, s.clock.boots, - s.clock.latest, describeKeys(s), s.contextEngineID()) + s.clock.latest, describeKeys(s, &x.config.User), s.contextEngineID()) } -// describeKeys names the engine ID the keys of s are localized to: "current" -// for its own, "none" without keys. -func describeKeys(s *engineState) string { +// describeKeys names the engine ID the keys of s, user's, are localized to: +// "current" for its own, "none" without keys. +func describeKeys(s *engineState, user *User) string { if len(s.keys.auth) == 0 && len(s.keys.priv) == 0 { return "none" } for _, id := range []string{string(s.engineID), agentEngineID, agentOtherEngineID} { var want usmKeys var err error - fips140.WithoutEnforcement(func() { want, err = s.user.localize([]byte(id)) }) + fips140.WithoutEnforcement(func() { want, err = user.localize([]byte(id)) }) if err != nil || !bytes.Equal(want.auth, s.keys.auth) || !bytes.Equal(want.priv, s.keys.priv) { continue } @@ -1946,7 +1745,7 @@ func BenchmarkGetV3(b *testing.B) { agent := newFakeV3Agent(nil, agentCreds, sysDescr) c := newFakeTransport(nil, agent.handle) creds := agentCreds["codec-md5"] - x := newEngineClientFrom(b, c, &Client{ + x := newEngineClientFrom(b, c, Config{ Version: Version3, SecurityLevel: AuthNoPriv, User: creds.user("codec-md5"), diff --git a/engine_walk_test.go b/engine_walk_test.go index e255a39..a9f6391 100644 --- a/engine_walk_test.go +++ b/engine_walk_test.go @@ -166,9 +166,6 @@ type walkScenario struct { // maxRepetitions is BulkWalkAll's argument. maxRepetitions uint32 script func(n int, req, out *Message) bool - // afterReply, when set, runs after each reply the Conn reads: the Conn's - // code changing the client during the walk. - afterReply func(x *Client, tr *engineTranscript) // context, when set, gives the walk's context; its cancel runs when the // scenario ends. context func() (context.Context, context.CancelFunc) @@ -339,34 +336,6 @@ func walkScenarios() map[string]walkScenario { script: onWalkRequest(4, varbinds(VarBind{Name: walkIfDescr + "0.1", Value: OctetStringValue([]byte("sibling"))})), }, - // User code changing the client during a walk. A change of version - // applies from the walk's next request: GETBULK on SNMPv1 is refused, - // and the walk returns the values so far. - "user-code/sets-version-1": { - root: walkIfDescr, bulk: true, maxRepetitions: 1, - afterReply: func(x *Client, tr *engineTranscript) { - tr.addf("the Conn's read sets Version to 1") - x.Version = Version1 - }, - }, - // The walk's later GetNext requests are SNMPv1 requests. - "user-code/sets-version-1/getnext": { - root: walkIfDescr, - afterReply: func(x *Client, tr *engineTranscript) { - tr.addf("the Conn's read sets Version to 1") - x.Version = Version1 - }, - }, - // MaxOids applies to each of the walk's requests: zero refuses the - // next one, and the walk returns the values so far. - "user-code/sets-max-oids-0": { - root: walkIfDescr, - afterReply: func(x *Client, tr *engineTranscript) { - tr.addf("the Conn's read sets MaxOids to 0") - x.MaxOids = 0 - }, - }, - // The walk's context bounds each of its requests, the leaf's Get // included: once it is done, the walk ends with its error and the // values before it. @@ -543,9 +512,6 @@ func runWalkScenario(t *testing.T, sc walkScenario) string { } c := newFakeTransport(tr, agent.handle) x := newEngineClient(t, version, c) - if sc.afterReply != nil { - c.afterRead = func(int) { sc.afterReply(x, tr) } - } ctx := context.Background() if sc.context != nil { var cancel context.CancelFunc @@ -553,7 +519,7 @@ func runWalkScenario(t *testing.T, sc walkScenario) string { defer cancel() } - tr.addf("client: %v root=%q bulk=%t max-repetitions=%d", x.Version, sc.root, sc.bulk, sc.maxRepetitions) + tr.addf("client: %v root=%q bulk=%t max-repetitions=%d", x.config.Version, sc.root, sc.bulk, sc.maxRepetitions) walk := x.WalkAll if sc.bulk { walk = func(ctx context.Context, rootOid string) ([]VarBind, error) { @@ -630,7 +596,7 @@ func TestWalkEndedByReport(t *testing.T) { return agentAnswer{report: usmStatsUnknownUserNames, why: "rejects the walk's second request"}, true } c := newFakeTransport(nil, agent.handle) - x := newEngineClientFrom(t, c, &Client{ + x := newEngineClientFrom(t, c, Config{ Version: Version3, SecurityLevel: NoAuthNoPriv, User: agentCreds["codec-noauth"].user("codec-noauth"), diff --git a/errors_test.go b/errors_test.go index bf4e1be..1dc3866 100644 --- a/errors_test.go +++ b/errors_test.go @@ -94,7 +94,7 @@ func TestRejectionCategories(t *testing.T) { return err } decode := func(data []byte) error { - _, err := (&Client{User: usmUser(SHA, "codec-auth-pass", AES, "codec-priv-pass")}).DecodeMessage(data) + _, err := mustClient(Config{User: usmUser(SHA, "codec-auth-pass", AES, "codec-priv-pass")}).DecodeMessage(data) return err } // A PDU whose error status is missing. diff --git a/examples/Hex-String/main.go b/examples/Hex-String/main.go index b68317d..f9675df 100644 --- a/examples/Hex-String/main.go +++ b/examples/Hex-String/main.go @@ -16,18 +16,21 @@ import ( ) func main() { - // A Client literal configures the client: SNMPv2c to port 161 with the - // community "public"; Connect fills in MaxOids (60). - client := &g.Client{ + // 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) + err = client.Connect(ctx) if err != nil { log.Fatalf("Connect() err: %v", err) } diff --git a/examples/example/main.go b/examples/example/main.go index d381619..55e3e02 100644 --- a/examples/example/main.go +++ b/examples/example/main.go @@ -14,21 +14,24 @@ import ( ) func main() { - // A Client literal configures the client: SNMPv2c to port 161 with the - // community "public"; Connect fills in MaxOids (60). - client := &g.Client{ + // 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) + err = client.Connect(ctx) if err != nil { log.Fatalf("Connect() err: %v", err) } diff --git a/examples/example2/main.go b/examples/example2/main.go index 168bde7..5728ab0 100644 --- a/examples/example2/main.go +++ b/examples/example2/main.go @@ -37,15 +37,18 @@ func main() { } port, _ := strconv.ParseUint(envPort, 10, 16) - params := &g.Client{ + 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) + err = params.Connect(ctx) if err != nil { log.Fatalf("Connect() err: %v", err) } diff --git a/examples/example3/main.go b/examples/example3/main.go index 5f60a9c..d4cc204 100644 --- a/examples/example3/main.go +++ b/examples/example3/main.go @@ -14,7 +14,7 @@ import ( ) func main() { - params := &g.Client{ + params, err := g.NewClient(g.Config{ Target: "192.168.91.20", Port: 161, Version: g.Version3, @@ -27,9 +27,12 @@ func main() { PrivProtocol: g.DES, PrivPassphrase: "password", }, + }) + if err != nil { + log.Fatalf("NewClient() err: %v", err) } ctx := context.Background() - err := params.Connect(ctx) + err = params.Connect(ctx) if err != nil { log.Fatalf("Connect() err: %v", err) } diff --git a/examples/walkexample/main.go b/examples/walkexample/main.go index bdcf43f..e78fb72 100644 --- a/examples/walkexample/main.go +++ b/examples/walkexample/main.go @@ -40,16 +40,20 @@ func main() { oid = flag.Args()[1] } - client := &gosnmp.Client{ + 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) + err = client.Connect(ctx) if err != nil { fmt.Printf("Connect err: %v\n", err) os.Exit(1) diff --git a/generic_e2e_test.go b/generic_e2e_test.go index eafc8a2..8e48276 100644 --- a/generic_e2e_test.go +++ b/generic_e2e_test.go @@ -45,26 +45,32 @@ func getTarget(t *testing.T) (string, uint16) { return envTarget, uint16(port) } -func connectToTarget(t *testing.T, gs *Client) { +// connectToTarget returns the client of config, with the test agent's Target +// and Port, connected. +func connectToTarget(t *testing.T, config Config) *Client { target, port := getTarget(t) - gs.Target = target - gs.Port = port + config.Target = target + config.Port = port + gs, err := NewClient(config) + if err != nil { + t.Fatal(err) + } - err := gs.Connect(context.Background()) + err = gs.Connect(context.Background()) if err != nil { if len(target) > 0 { t.Fatalf("Connection failed. Is snmpd reachable on %s:%d?\n(err: %v)", target, port, err) } } + return gs } func TestClose(t *testing.T) { - gs := newTestClient() - gs.Retries = 1 - - connectToTarget(t, gs) + config := testConfig() + config.Retries = 1 + gs := connectToTarget(t, config) // Ensure connection is open if gs.conn == nil { @@ -85,7 +91,7 @@ func TestClose(t *testing.T) { } func TestClose_NilConnection(t *testing.T) { - gs := &Client{} + gs := mustClient(Config{}) err := gs.Close() if err != nil { @@ -94,11 +100,10 @@ func TestClose_NilConnection(t *testing.T) { } func TestClose_Concurrent(t *testing.T) { - gs := newTestClient() - gs.Timeout = time.Second - gs.Retries = 1 - - connectToTarget(t, gs) + config := testConfig() + config.Timeout = time.Second + config.Retries = 1 + gs := connectToTarget(t, config) var wg sync.WaitGroup for range 100 { // simulate 100 concurrent calls @@ -115,8 +120,7 @@ func TestClose_Concurrent(t *testing.T) { } func TestGenericBasicGet(t *testing.T) { - gs := newTestClient() - connectToTarget(t, gs) + gs := connectToTarget(t, testConfig()) defer gs.Close() result, err := gs.Get(context.Background(), []string{".1.3.6.1.2.1.1.1.0"}) // SNMP MIB-2 sysDescr @@ -136,8 +140,7 @@ func TestGenericBasicGet(t *testing.T) { } func TestGenericMultiGet(t *testing.T) { - gs := newTestClient() - connectToTarget(t, gs) + gs := connectToTarget(t, testConfig()) defer gs.Close() oids := []string{ @@ -159,8 +162,7 @@ func TestGenericMultiGet(t *testing.T) { } func TestGenericWalk(t *testing.T) { - gs := newTestClient() - connectToTarget(t, gs) + gs := connectToTarget(t, testConfig()) defer gs.Close() result, err := gs.WalkAll(context.Background(), "") @@ -173,8 +175,7 @@ func TestGenericWalk(t *testing.T) { } func TestGenericBulkWalk(t *testing.T) { - gs := newTestClient() - connectToTarget(t, gs) + gs := connectToTarget(t, testConfig()) defer gs.Close() result, err := gs.BulkWalkAll(context.Background(), "", 0) @@ -190,8 +191,7 @@ func TestGenericBulkWalk(t *testing.T) { // the smallest and the largest max-repetitions: the agent returns the same // objects for each. func TestGenericBulkWalkMaxRepetitions(t *testing.T) { - gs := newTestClient() - connectToTarget(t, gs) + gs := connectToTarget(t, testConfig()) defer gs.Close() walkNames := func(t *testing.T, maxRepetitions uint32) []string { @@ -220,9 +220,9 @@ func TestGenericBulkWalkMaxRepetitions(t *testing.T) { } func TestV1BulkWalkError(t *testing.T) { - g := newTestClient() - g.Version = Version1 - connectToTarget(t, g) + config := testConfig() + config.Version = Version1 + g := connectToTarget(t, config) g.Close() @@ -235,12 +235,11 @@ func TestV1BulkWalkError(t *testing.T) { // Standard exception/error tests func TestMaxOids(t *testing.T) { - gs := newTestClient() - connectToTarget(t, gs) + config := testConfig() + config.MaxOids = 1 + gs := connectToTarget(t, config) defer gs.Close() - gs.MaxOids = 1 - var err error oids := []string{ ".1.3.6.1.2.1.1.7.0", @@ -258,8 +257,9 @@ func TestMaxOids(t *testing.T) { func TestGenericFailureUnknownHost(t *testing.T) { unknownHost := "nonexistent.invalid" // .invalid is guaranteed by RFC 2606 to never resolve. - gs := newTestClient() - gs.Target = unknownHost + config := testConfig() + config.Target = unknownHost + gs := mustClient(config) err := gs.Connect(context.Background()) if err == nil { t.Fatalf("Expected connection failure due to unknown host") @@ -283,8 +283,9 @@ func TestGenericFailureConnectionTimeout(t *testing.T) { t.Skip("local testing - skipping this slow one") } - gs := newTestClient() - gs.Target = "198.51.100.1" // Black hole + 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") @@ -299,9 +300,10 @@ func TestGenericFailureConnectionTimeout(t *testing.T) { } func TestGenericFailureConnectionRefused(t *testing.T) { - gs := newTestClient() - gs.Target = "127.0.0.1" - gs.Port = 1 // Don't expect SNMP to be running here! + config := testConfig() + config.Target = "127.0.0.1" + config.Port = 1 // Don't expect SNMP to be running here! + gs := mustClient(config) err := gs.Connect(context.Background()) if err != nil { t.Fatalf("Did not expect connection error with IP address") @@ -321,8 +323,7 @@ func TestGenericFailureConnectionRefused(t *testing.T) { func TestSnmpV3Users(t *testing.T) { for _, u := range loadSnmpUsers(t) { t.Run(u.name, func(t *testing.T) { - gs := newTestClientV3(u.msgFlags(), u.securityParameters()) - connectToTarget(t, gs) + gs := connectToTarget(t, testConfigV3(u.msgFlags(), u.securityParameters())) defer gs.Close() result, err := gs.Get(context.Background(), []string{".1.3.6.1.2.1.1.1.0"}) // SNMP MIB-2 sysDescr diff --git a/gosnmp.go b/gosnmp.go index dd2088a..141fc91 100644 --- a/gosnmp.go +++ b/gosnmp.go @@ -9,61 +9,64 @@ package gosnmp import ( + "cmp" "fmt" "sync" - "sync/atomic" "time" ) const ( - // MaxOids is the default of Client.MaxOids, the maximum number of OIDs in + // 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 Client.MaxOids to change it. + // 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 ) -// Client is an SNMP client: its exported fields configure it, Connect opens -// its connection, and its methods send requests. 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 { - // Target is the agent's host name or IP address, which Connect dials. +// 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, usually 161; it has no default. + // 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 - // Version is the SNMP version: Version1, Version2c or Version3. - Version Version - // 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. It has no default: - // a zero Timeout times out every attempt at once, and leaves Connect - // without a time limit. + // 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; a negative value - // counts as 0. + // 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. Connect replaces zero with the - // MaxOids constant. + // request of a walk, which carries one; zero means the MaxOids constant. MaxOids int // SecurityLevel is the SNMPv3 security level: NoAuthNoPriv, AuthNoPriv or - // AuthPriv; another value fails Connect. 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). + // 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 @@ -74,16 +77,24 @@ type Client struct { // ContextName is the SNMPv3 context name of requests; their context // engine ID is the agent's engine ID. ContextName string +} - // requestID and msgID count the request IDs and the SNMPv3 msgIDs; - // requestIDSet and msgIDSet report that they were started, at a random - // value on first use or by SetRequestID and SetMsgID. - requestID atomic.Uint32 - msgID atomic.Uint32 - requestIDSet atomic.Bool - msgIDSet atomic.Bool +// 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 request. + // 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 @@ -108,6 +119,56 @@ type Client struct { 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 { @@ -179,46 +240,21 @@ const ( InconsistentName // The name in a variable binding specifies a variable that does not exist. ) -// prepare readies the client for Connect, EncodeMessage and -// DecodeMessage, which call it each time: it fills in the default MaxOids, -// rejects a negative MaxOids and, for SNMPv3, checks the security level and -// parameters. -func (x *Client) prepare() error { - if x.MaxOids == 0 { - x.MaxOids = MaxOids - } else if x.MaxOids < 0 { - return fmt.Errorf("field MaxOids cannot be less than 0") - } - - if x.Version == Version3 { - if err := x.validateParametersV3(); err != nil { - return err - } - } - return nil -} - -// EncodeMessage encodes a request or trap, for another transport or for -// tests: it prepares the client as Connect does, 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. +// 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 (x *Client) EncodeMessage(pduType PDUType, varBinds []VarBind, nonRepeaters uint8, maxRepetitions uint32) ([]byte, error) { - if err := x.prepare(); err != nil { - return nil, err - } pkt := x.NewMessage(pduType, varBinds, nonRepeaters, maxRepetitions) pkt.RequestID = x.nextRequestID() var keys usmKeys - if x.Version == Version3 { - if err := x.startEngine(); err != nil { - return nil, err - } + 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 @@ -228,21 +264,17 @@ func (x *Client) EncodeMessage(pduType PDUType, varBinds []VarBind, nonRepeaters return pkt.marshalMsg(&keys) } -// DecodeMessage decodes a message, from another transport or for tests, -// after preparing the client as Connect does; an SNMPv3 message with the -// client'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. +// 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 (x *Client) DecodeMessage(data []byte) (*Message, error) { - if err := x.prepare(); err != nil { - return nil, err - } - result := new(Message) cursor, w, err := unmarshalHeader(data, result) if err != nil { @@ -250,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.User, nil); err != nil { + if in, err = receiveV3(data, w, result, &x.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/gosnmp_api_test.go b/gosnmp_api_test.go index 06d0a41..a0df3c8 100644 --- a/gosnmp_api_test.go +++ b/gosnmp_api_test.go @@ -18,15 +18,20 @@ import ( ) func TestAPIConfigTypes(_ *testing.T) { - g := &gosnmp.Client{} - g.Target = "" - g.Port = 0 - g.Community = "" - g.Version = gosnmp.Version1 - g.Version = gosnmp.Version2c - g.Timeout = time.Duration(0) - g.Retries = 0 - g.MaxOids = 0 + var f func(gosnmp.Config) (*gosnmp.Client, error) = gosnmp.NewClient + _ = f + _ = gosnmp.Config{ + Target: "", + Port: 0, + Version: gosnmp.Version2c, + Community: "", + Timeout: time.Duration(0), + Retries: 0, + MaxOids: 0, + SecurityLevel: gosnmp.NoAuthNoPriv, + User: gosnmp.User{}, + ContextName: "", + } } func TestAPIConnectMethodSignature(_ *testing.T) { diff --git a/gosnmp_test.go b/gosnmp_test.go new file mode 100644 index 0000000..aadd740 --- /dev/null +++ b/gosnmp_test.go @@ -0,0 +1,107 @@ +// 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 + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +// TestNewClient pins what NewClient makes of a configuration: the client keeps +// it with the defaults of its zero Port, Timeout and MaxOids filled in, or it +// fails with an error naming the field and returns no client. The SNMPv3 fields +// are checked for SNMPv3 only. +func TestNewClient(t *testing.T) { + v3User := User{Name: "codec-user", AuthProtocol: SHA, AuthPassphrase: "codec-auth-pass", PrivProtocol: AES, PrivPassphrase: "codec-priv-pass"} + type result struct { + config Config // the client's configuration + err string + } + tests := map[string]struct { + config Config + want result + }{ + "defaults": { + want: result{config: Config{Port: 161, Timeout: time.Second, MaxOids: MaxOids}}, + }, + "values kept": { + config: Config{ + Target: "192.0.2.1", Port: 1161, Version: Version2c, Community: "codec-community", + Timeout: 5 * time.Second, Retries: 3, MaxOids: 10, + }, + want: result{config: Config{ + Target: "192.0.2.1", Port: 1161, Version: Version2c, Community: "codec-community", + Timeout: 5 * time.Second, Retries: 3, MaxOids: 10, + }}, + }, + "SNMPv3 fields unchecked for SNMPv2c": { + config: Config{Version: Version2c, SecurityLevel: 2, User: User{AuthProtocol: 99}}, + want: result{config: Config{ + Port: 161, Version: Version2c, Timeout: time.Second, MaxOids: MaxOids, + SecurityLevel: 2, User: User{AuthProtocol: 99}, + }}, + }, + "SNMPv3": { + config: Config{Version: Version3, SecurityLevel: AuthPriv, User: v3User, ContextName: "codec-context"}, + want: result{config: Config{ + Port: 161, Version: Version3, Timeout: time.Second, MaxOids: MaxOids, + SecurityLevel: AuthPriv, User: v3User, ContextName: "codec-context", + }}, + }, + "unknown version": { + config: Config{Version: 2}, + want: result{err: "Config.Version is Version(2), not Version1, Version2c or Version3"}, + }, + "negative timeout": { + config: Config{Version: Version2c, Timeout: -time.Nanosecond}, + want: result{err: "Config.Timeout -1ns is negative"}, + }, + "negative retries": { + config: Config{Version: Version2c, Retries: -1}, + want: result{err: "Config.Retries -1 is negative"}, + }, + "negative max OIDs": { + config: Config{Version: Version2c, MaxOids: -1}, + want: result{err: "Config.MaxOids -1 is negative"}, + }, + "SNMPv3 unknown security level": { + config: Config{Version: Version3, SecurityLevel: 2, User: User{Name: "codec-user"}}, + want: result{err: "Config.SecurityLevel SecurityLevel(2) is not NoAuthNoPriv, AuthNoPriv or AuthPriv"}, + }, + "SNMPv3 user without a name": { + config: Config{Version: Version3, SecurityLevel: NoAuthNoPriv}, + want: result{err: "Config.User.Name is required"}, + }, + "SNMPv3 unknown authentication protocol": { + config: Config{Version: Version3, SecurityLevel: NoAuthNoPriv, User: User{Name: "codec-user", AuthProtocol: 99}}, + want: result{err: "Config.User.AuthProtocol AuthProtocol(99) is not supported"}, + }, + "SNMPv3 level without its protocol": { + config: Config{Version: Version3, SecurityLevel: AuthNoPriv, User: User{Name: "codec-user"}}, + want: result{err: "Config.User.AuthProtocol is required"}, + }, + "SNMPv3 protocol without a passphrase": { + config: Config{Version: Version3, SecurityLevel: AuthPriv, User: User{ + Name: "codec-user", AuthProtocol: SHA, AuthPassphrase: "codec-auth-pass", PrivProtocol: AES, + }}, + want: result{err: "Config.User.PrivPassphrase is required when a privacy protocol is specified"}, + }, + } + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + x, err := NewClient(tc.config) + var got result + if err != nil { + got.err = err.Error() + assert.Nil(t, x) + } else { + got.config = x.config + } + assert.Equal(t, tc.want, got) + }) + } +} diff --git a/helper_test.go b/helper_test.go index aac7b1c..d16fee0 100644 --- a/helper_test.go +++ b/helper_test.go @@ -21,8 +21,7 @@ var testsInvalidSNMPResponses = []string{ } func TestInvalidSNMPResponses(t *testing.T) { - g := newTestClient() - g.Target = "127.0.0.1" + g := mustClient(testConfig()) for i, test := range testsInvalidSNMPResponses { testBytes, _ := base64.StdEncoding.DecodeString(test) diff --git a/ids.go b/ids.go index c9e2dc5..3d3e55e 100644 --- a/ids.go +++ b/ids.go @@ -21,35 +21,17 @@ func randomID() uint32 { return binary.BigEndian.Uint32(b[:]) % math.MaxInt32 } -// nextRequestID advances the request ID counter, which starts at a random -// value on first use unless SetRequestID set it, and returns it without its -// top bit, so request IDs wrap to 0 after 2147483647. +// 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 { - if !x.requestIDSet.Load() { - x.SetRequestID(randomID()) - } - return x.requestID.Add(1) & math.MaxInt32 + x.requestID++ + return x.requestID & math.MaxInt32 } -// nextMsgID advances the msgID counter, which starts at a random value on -// first use unless SetMsgID set it, and returns it without its top bit. +// nextMsgID advances the msgID counter, which NewClient seeds with a random +// value, and returns it without its top bit. func (x *Client) nextMsgID() uint32 { - if !x.msgIDSet.Load() { - x.SetMsgID(randomID()) - } - return x.msgID.Add(1) & math.MaxInt32 -} - -// SetRequestID sets the request ID counter: the next request ID is reqID+1, -// without its top bit. Connect does not change the counter. -func (x *Client) SetRequestID(reqID uint32) { - x.requestID.Store(reqID & math.MaxInt32) - x.requestIDSet.Store(true) -} - -// SetMsgID sets the SNMPv3 msgID counter: the next msgID is msgID+1, -// without its top bit. Connect does not change the counter. -func (x *Client) SetMsgID(msgID uint32) { - x.msgID.Store(msgID & math.MaxInt32) - x.msgIDSet.Store(true) + x.msgID++ + return x.msgID & math.MaxInt32 } diff --git a/marshal_test.go b/marshal_test.go index 786d2d7..5222183 100644 --- a/marshal_test.go +++ b/marshal_test.go @@ -1508,30 +1508,30 @@ func TestSendOneRequest_dups(t *testing.T) { } defer srvr.Close() - x := &Client{ + x := mustClient(Config{ Version: Version2c, Target: srvr.LocalAddr().(*net.UDPAddr).IP.String(), Port: uint16(srvr.LocalAddr().(*net.UDPAddr).Port), Timeout: time.Millisecond * 100, Retries: 2, - } + }) if err = x.Connect(context.Background()); err != nil { t.Fatalf("error connecting: %s", err) } - go serveResponses(t, srvr, x, sendCopies(srvr, x.Retries+2)) + go serveResponses(t, srvr, x, sendCopies(srvr, x.config.Retries+2)) pdus := []VarBind{{Name: ".1.2", Value: NullValue()}} // This is not actually a Response, but we need something our test server can unmarshal. reqPkt := x.NewMessage(Response, pdus, 0, 0) - _, _, err = x.sendOneRequest(new(x.prepareRequest(context.Background())), reqPkt, false, attemptSecurity{}) + _, _, err = x.sendOneRequest(context.Background(), reqPkt, false, attemptSecurity{}) if err != nil { t.Errorf("error: %s", err) return } - _, _, err = x.sendOneRequest(new(x.prepareRequest(context.Background())), reqPkt, false, attemptSecurity{}) + _, _, err = x.sendOneRequest(context.Background(), reqPkt, false, attemptSecurity{}) if err != nil { t.Errorf("error: %s", err) return diff --git a/netsnmp/gosnmp_netsnmp.go b/netsnmp/gosnmp_netsnmp.go index 301ba0c..7c90362 100644 --- a/netsnmp/gosnmp_netsnmp.go +++ b/netsnmp/gosnmp_netsnmp.go @@ -113,7 +113,7 @@ func verToSnmpVer(in gosnmp.Version) (C.int, error) { } } -func netSnmpPduPkt(fname string, gopdu gosnmp.VarBind, gosess *gosnmp.Client, reqid uint32, verbose bool) ([]byte, error) { +func netSnmpPduPkt(fname string, gopdu gosnmp.VarBind, config gosnmp.Config, reqid uint32, verbose bool) ([]byte, error) { var errout *C.char var err error @@ -131,15 +131,15 @@ func netSnmpPduPkt(fname string, gopdu gosnmp.VarBind, gosess *gosnmp.Client, re // create session sess := &C.struct_snmp_session{ version: C.SNMP_DEFAULT_VERSION, - community: (*C.uchar)(unsafe.Pointer(C.CString(gosess.Community))), - community_len: C.size_t(len(gosess.Community)), + community: (*C.uchar)(unsafe.Pointer(C.CString(config.Community))), + community_len: C.size_t(len(config.Community)), } defer C.free(unsafe.Pointer(sess.community)) // create pdu pdu := C.snmp_pdu_create(C.SNMP_MSG_SET) defer C.free(unsafe.Pointer(pdu)) - tmp, err := verToSnmpVer(gosess.Version) + tmp, err := verToSnmpVer(config.Version) if err != nil { return nil, err } diff --git a/netsnmp/gosnmp_playback.go b/netsnmp/gosnmp_playback.go index d8966e4..44ebd23 100644 --- a/netsnmp/gosnmp_playback.go +++ b/netsnmp/gosnmp_playback.go @@ -14,6 +14,6 @@ func isPlayback() bool { return true } -func netSnmpPduPkt(fname string, _ gosnmp.VarBind, _ *gosnmp.Client, _ uint32, _ bool) ([]byte, error) { +func netSnmpPduPkt(fname string, _ gosnmp.VarBind, _ gosnmp.Config, _ uint32, _ bool) ([]byte, error) { return readRecording(fname) } diff --git a/netsnmp/gosnmp_test.go b/netsnmp/gosnmp_test.go index c538f92..c6019e2 100644 --- a/netsnmp/gosnmp_test.go +++ b/netsnmp/gosnmp_test.go @@ -96,7 +96,11 @@ func TestPDU(t *testing.T) { } } - sess := &gosnmp.Client{Community: "public", Version: gosnmp.Version2c} + config := gosnmp.Config{Community: "public", Version: gosnmp.Version2c} + sess, err := gosnmp.NewClient(config) + if err != nil { + t.Fatal(err) + } for i, tc := range pduCases { tstpdu := tc @@ -108,7 +112,7 @@ func TestPDU(t *testing.T) { pkt := sess.NewMessage(gosnmp.SetRequest, pdus, 0, 0) pkt.RequestID++ - exp, err := netSnmpPduPkt(fname, pdus[0], sess, pkt.RequestID, testing.Verbose()) + exp, err := netSnmpPduPkt(fname, pdus[0], config, pkt.RequestID, testing.Verbose()) if err != nil { t.Fatal(err) } @@ -229,7 +233,10 @@ func TestDecodeRecorded(t *testing.T) { t.Fatal(err) } - x := &gosnmp.Client{} + x, err := gosnmp.NewClient(gosnmp.Config{}) + if err != nil { + t.Fatal(err) + } res, err := x.DecodeMessage(pkt) if err != nil { t.Fatal(err) diff --git a/oid_boundary_test.go b/oid_boundary_test.go index 79e2afa..fa9e210 100644 --- a/oid_boundary_test.go +++ b/oid_boundary_test.go @@ -71,7 +71,7 @@ func TestOIDPackedFirstSubidentifier(t *testing.T) { } }) t.Run("decode", func(t *testing.T) { - got, err := (&Client{}).DecodeMessage(field.wire) + got, err := mustClient(Config{}).DecodeMessage(field.wire) if err != nil { t.Fatal(err) } diff --git a/receiver_timeliness_test.go b/receiver_timeliness_test.go index 299c40b..384d62b 100644 --- a/receiver_timeliness_test.go +++ b/receiver_timeliness_test.go @@ -300,7 +300,7 @@ func TestTrapEncodedReplay(t *testing.T) { "learned": {LearnUsers: []User{user}, MaxLearned: 1}, } { t.Run(name, func(t *testing.T) { - sender := &Client{Version: Version3, SecurityLevel: AuthPriv, User: user} + sender := mustClient(Config{Version: Version3, SecurityLevel: AuthPriv, User: user}) seedEngine(usmCharEngineID, 3, 77)(sender) wire, err := sender.EncodeMessage(SNMPv2Trap, usmPlainVars, 0, 0) require.NoError(t, err) diff --git a/request.go b/request.go index 949fcbc..6e2c999 100644 --- a/request.go +++ b/request.go @@ -18,11 +18,11 @@ import ( // for a message it encodes itself. func (x *Client) NewMessage(pduType PDUType, varBinds []VarBind, nonRepeaters uint8, maxRepetitions uint32) *Message { return &Message{ - Version: x.Version, - Community: x.Community, - SecurityLevel: x.SecurityLevel, - SecurityParameters: SecurityParameters{UserName: x.User.Name}, - ContextName: x.ContextName, + Version: x.config.Version, + Community: x.config.Community, + SecurityLevel: x.config.SecurityLevel, + SecurityParameters: SecurityParameters{UserName: x.config.User.Name}, + ContextName: x.config.ContextName, ErrorStatus: 0, ErrorIndex: 0, PDUType: pduType, @@ -51,8 +51,8 @@ func (x *Client) Get(ctx context.Context, oids []string) (result *Message, err e // 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.MaxOids { - return nil, fmt.Errorf("oid count (%d) is greater than MaxOids (%d)", len(oids), x.MaxOids) + if len(oids) > x.config.MaxOids { + return nil, fmt.Errorf("oid count (%d) is greater than MaxOids (%d)", len(oids), x.config.MaxOids) } pdus := make([]VarBind, 0, len(oids)) for _, oid := range oids { diff --git a/request_test.go b/request_test.go index f3d4478..89c0143 100644 --- a/request_test.go +++ b/request_test.go @@ -15,10 +15,10 @@ import ( ) // TestWalkRequestChecks pins the checks a walk makes before its first -// request, in their order, on a client without Connect (MaxOids zero unless -// set): the root, then BulkWalkAll's max-repetitions against 2147483647, then -// GetBulk on SNMPv1, then MaxOids against the one OID a request carries, then -// a nil context. +// request, in their order, on a client without Connect: the root, then +// BulkWalkAll's max-repetitions against 2147483647, then GetBulk on SNMPv1, +// then a nil context. MaxOids, at least 1, never refuses a walk's request, +// which carries one OID. func TestWalkRequestChecks(t *testing.T) { tests := map[string]struct { version Version @@ -32,12 +32,7 @@ func TestWalkRequestChecks(t *testing.T) { "root before SNMPv1": { version: Version1, bulk: true, root: "1.3.6.x", wantErr: `unable to marshal OID "1.3.6.x": invalid object identifier`, }, - "SNMPv1 before MaxOids": {version: Version1, bulk: true, root: walkSystem, wantErr: "GETBULK not supported in SNMPv1"}, - "MaxOids, GetNext": {version: Version2c, root: walkSystem, wantErr: "oid count (1) is greater than MaxOids (0)"}, - "MaxOids, GetBulk": {version: Version2c, bulk: true, root: walkSystem, wantErr: "oid count (1) is greater than MaxOids (0)"}, - "MaxOids before the context": { - version: Version2c, root: walkSystem, nilContext: true, wantErr: "oid count (1) is greater than MaxOids (0)", - }, + "SNMPv1": {version: Version1, bulk: true, root: walkSystem, wantErr: "GETBULK not supported in SNMPv1"}, "nil context, GetNext": {version: Version2c, root: walkSystem, maxOids: 1, nilContext: true, wantErr: "nil context"}, "nil context, GetBulk": { version: Version2c, bulk: true, root: walkSystem, maxOids: 1, nilContext: true, wantErr: "nil context", @@ -50,7 +45,7 @@ func TestWalkRequestChecks(t *testing.T) { version: Version1, bulk: true, root: walkSystem, maxRepetitions: 1 << 31, wantErr: "max-repetitions 2147483648 is more than 2147483647", }, - "max-repetitions before MaxOids": { + "max-repetitions": { version: Version2c, bulk: true, root: walkSystem, maxRepetitions: 1 << 31, wantErr: "max-repetitions 2147483648 is more than 2147483647", }, @@ -65,7 +60,7 @@ func TestWalkRequestChecks(t *testing.T) { } for name, tc := range tests { t.Run(name, func(t *testing.T) { - x := &Client{Version: tc.version, MaxOids: tc.maxOids} + x := mustClient(Config{Version: tc.version, MaxOids: tc.maxOids}) walk := x.WalkAll if tc.bulk { walk = func(ctx context.Context, rootOid string) ([]VarBind, error) { @@ -84,9 +79,9 @@ func TestWalkRequestChecks(t *testing.T) { } // TestEncodeMessageErrors pins that EncodeMessage returns no message with each -// of its errors: the client's configuration, the message's version, a varbind, -// and the SNMPv3 keys an authenticated or private message needs before the -// client knows the agent's engine (TestEncodeMessageEmptyKey). +// of its errors: a varbind, and the SNMPv3 keys an authenticated or private +// message needs before the client knows the agent's engine +// (TestEncodeMessageEmptyKey). func TestEncodeMessageErrors(t *testing.T) { authPriv := User{ Name: "codec-user", @@ -100,20 +95,13 @@ func TestEncodeMessageErrors(t *testing.T) { pdus []VarBind wantErr string }{ - "invalid parameters": { - x: &Client{Version: Version2c, MaxOids: -1}, wantErr: "field MaxOids cannot be less than 0", - }, - "unknown version": { - x: &Client{Version: Version(7)}, - wantErr: "unable to marshal SNMP version 7: not 1, 2c or 3", - }, "unencodable varbind": { - x: &Client{Version: Version2c, Community: "public"}, + x: mustClient(Config{Version: Version2c, Community: "public"}), pdus: []VarBind{{Name: "not an oid", Value: NullValue()}}, wantErr: "invalid object identifier", }, "private before the engine is known": { - x: &Client{Version: Version3, SecurityLevel: AuthPriv, User: authPriv}, + x: mustClient(Config{Version: Version3, SecurityLevel: AuthPriv, User: authPriv}), pdus: []VarBind{{Name: engineOID, Value: NullValue()}}, wantErr: "usm: encrypting: no privacy key, want 16 octets", }, @@ -132,11 +120,11 @@ func TestEncodeMessageErrors(t *testing.T) { // engine state has no engine ID to derive a key for, and the signer refuses // the empty key with the rule's error and no message. func TestEncodeMessageEmptyKey(t *testing.T) { - x := &Client{ + x := mustClient(Config{ Version: Version3, SecurityLevel: AuthNoPriv, User: User{Name: "codec-user", AuthProtocol: SHA, AuthPassphrase: "codec-auth-pass"}, - } + }) out, err := x.EncodeMessage(GetRequest, []VarBind{{Name: engineOID, Value: NullValue()}}, 0, 0) require.EqualError(t, err, "usm: no authentication key, want 20 octets") assert.Nil(t, out) @@ -144,18 +132,17 @@ func TestEncodeMessageEmptyKey(t *testing.T) { } // TestRequestAndMsgIDs pins, through the encoded messages, the request ID and -// msgID counters: each starts at a random value on first use unless -// SetRequestID or SetMsgID set it, counts up and wraps to 0 after 2147483647, -// and Connect leaves both as they are. +// msgID counters: each starts at a random value NewClient draws, counts up and +// wraps to 0 after 2147483647, and Connect leaves both as they are. func TestRequestAndMsgIDs(t *testing.T) { newClient := func() *Client { - return &Client{ + return mustClient(Config{ Target: "127.0.0.1", Port: unusedUDPPort(t), Version: Version3, SecurityLevel: NoAuthNoPriv, User: User{Name: "codec-user"}, - } + }) } ids := func(x *Client) [2]uint32 { t.Helper() @@ -181,19 +168,17 @@ func TestRequestAndMsgIDs(t *testing.T) { connect(x) assert.Equal(t, next(next(first)), ids(x), "a second Connect resets nothing") }) - t.Run("set counters survive Connect", func(t *testing.T) { + t.Run("counters survive Connect and wrap", func(t *testing.T) { x := newClient() - x.SetRequestID(5) - x.SetMsgID(70) + x.requestID, x.msgID = 5, 70 connect(x) assert.Equal(t, [2]uint32{6, 71}, ids(x)) - x.SetRequestID(0x7FFFFFFF) - x.SetMsgID(0x7FFFFFFF) + x.requestID, x.msgID = 0x7FFFFFFF, 0x7FFFFFFF assert.Equal(t, [2]uint32{0, 0}, ids(x), "wrap") }) t.Run("random start without Connect", func(t *testing.T) { - // An unseeded counter would start at 1 (a 2^-31 chance of a false - // failure for each). + // A counter NewClient did not seed would start at 1 (a 2^-31 chance + // of a false failure for each). id := ids(newClient()) assert.NotEqual(t, uint32(1), id[0], "request ID") assert.NotEqual(t, uint32(1), id[1], "msgID") diff --git a/salt_test.go b/salt_test.go index 9751811..a32bdd1 100644 --- a/salt_test.go +++ b/salt_test.go @@ -31,7 +31,7 @@ func TestReencodeDrawsNewSalt(t *testing.T) { t.Helper() resp := *in resp.PDUType = Response - out, marshalErr := resp.Encode(&decoder.User) + out, marshalErr := resp.Encode(&decoder.config.User) require.NoError(t, marshalErr) return out } diff --git a/snmp_users_test.go b/snmp_users_test.go index 36a51b2..dbdc269 100644 --- a/snmp_users_test.go +++ b/snmp_users_test.go @@ -109,7 +109,8 @@ func TestSnmpUsers(t *testing.T) { names[u.name] = true assert.Equal(t, u.auth > NoAuth, u.authPass != "", "user %q: authentication passphrase", u.name) assert.Equal(t, u.priv > NoPriv, u.privPass != "", "user %q: privacy passphrase", u.name) - assert.NoError(t, newTestClientV3(u.msgFlags(), u.securityParameters()).prepare(), "user %q", u.name) + _, err := NewClient(testConfigV3(u.msgFlags(), u.securityParameters())) + assert.NoError(t, err, "user %q", u.name) } assert.Equal(t, want, got) } diff --git a/testclient_test.go b/testclient_test.go index 4cfab9f..ba13be3 100644 --- a/testclient_test.go +++ b/testclient_test.go @@ -8,24 +8,30 @@ import ( "time" ) -// newTestClient returns an unconnected SNMPv2c client. -func newTestClient() *Client { - return &Client{ - Port: 161, +// testConfig returns the configuration of an SNMPv2c client. +func testConfig() Config { + return Config{ Community: "public", Version: Version2c, Timeout: 2 * time.Second, Retries: 3, - MaxOids: MaxOids, } } -// newTestClientV3 returns an unconnected SNMPv3 client of the User-based -// Security Model with msgFlags and user. -func newTestClientV3(msgFlags SecurityLevel, user User) *Client { - gs := newTestClient() - gs.Version = Version3 - gs.SecurityLevel = msgFlags - gs.User = user - return gs +// testConfigV3 returns the configuration of an SNMPv3 client with level and +// user. +func testConfigV3(level SecurityLevel, user User) Config { + c := testConfig() + c.Version, c.SecurityLevel, c.User = Version3, level, user + return c +} + +// mustClient returns the client NewClient makes of config; it panics on an +// error, a bug of the test. +func mustClient(config Config) *Client { + x, err := NewClient(config) + if err != nil { + panic(err) + } + return x } diff --git a/testdata/engine/requests.golden b/testdata/engine/requests.golden index 94f0af5..655ef1b 100644 --- a/testdata/engine/requests.golden +++ b/testdata/engine/requests.golden @@ -14,7 +14,7 @@ 0s read from 127.0.0.2:161: 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s read from 127.0.0.2:161: 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s result: packet 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client after: retries=2 next request id=1003 +0s client after: next request id=1003 == requests/answer/empty 0s client: 2c timeout=1s retries=2 @@ -23,7 +23,7 @@ 0s agent answers #1 after 0s 0s read from 127.0.0.2:161: 2c "public" Response id=1001 [] 0s result: packet 2c "public" Response id=1001 [], no error -0s client after: retries=2 next request id=1002 +0s client after: next request id=1002 == requests/answer/empty-with-error-status-wrong-id 0s client: 2c timeout=1s retries=2 @@ -43,7 +43,7 @@ 2s read from 127.0.0.2:161: 2c "public" Response id=1103 error=GenErr index=0 [] 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: retries=2 next request id=1004 +3s client after: next request id=1004 == requests/answer/empty-wrong-id 0s client: 2c timeout=1s retries=2 @@ -63,7 +63,7 @@ 2s read from 127.0.0.2:161: 2c "public" Response id=1103 [] 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: retries=2 next request id=1004 +3s client after: next request id=1004 == requests/answer/empty-wrong-id-then-valid 0s client: 2c timeout=1s retries=2 @@ -74,7 +74,7 @@ 0s read from 127.0.0.2:161: 2c "public" Response id=1101 [] 0s read from 127.0.0.2:161: 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s result: packet 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client after: retries=2 next request id=1002 +0s client after: next request id=1002 == requests/answer/error-status 0s client: 2c timeout=1s retries=2 @@ -83,7 +83,7 @@ 0s agent answers #1 after 0s 0s read from 127.0.0.2:161: 2c "public" Response id=1001 error=NoSuchName index=1 [.1.3.6.1.2.1.1.1.0] 0s result: packet 2c "public" Response id=1001 error=NoSuchName index=1 [.1.3.6.1.2.1.1.1.0], no error -0s client after: retries=2 next request id=1002 +0s client after: next request id=1002 == requests/answer/first-result-after-second-get 0s client: 2c timeout=1s retries=2 @@ -96,7 +96,7 @@ 0s agent answers #2 after 0s 0s read from 127.0.0.2:161: 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent 2"] 0s result: packet 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent 1"], no error -0s client after: retries=2 next request id=1003 +0s client after: next request id=1003 == requests/answer/garbage 0s client: 2c timeout=1s retries=2 @@ -116,7 +116,7 @@ 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 verifying packet sanity: invalid packet length: TLV length exceeds the remaining input" *gosnmp.attemptsError (is os.ErrDeadlineExceeded, ErrASNParse, net.Error timeout) -3s client after: retries=2 next request id=1004 +3s client after: next request id=1004 == requests/answer/garbage-then-valid 0s client: 2c timeout=1s retries=2 @@ -127,7 +127,7 @@ 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) 0s read from 127.0.0.2:161: 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s result: packet 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client after: retries=2 next request id=1002 +0s client after: next request id=1002 == requests/answer/largest-udp 0s client: 2c timeout=1s retries=2 @@ -136,7 +136,7 @@ 0s agent answers #1 after 0s 0s read from 127.0.0.2:161: 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"xxxxxxxxxxxxxxxx"... (65483 octets)] 0s result: packet 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"xxxxxxxxxxxxxxxx"... (65483 octets)], no error -0s client after: retries=2 next request id=1002 +0s client after: next request id=1002 == requests/answer/late 0s client: 2c timeout=1s retries=2 @@ -148,7 +148,7 @@ 1s write #2: 2c "public" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] 1.5s read from 127.0.0.2:161: 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 1.5s result: packet 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -1.5s client after: retries=2 next request id=1003 +1.5s client after: next request id=1003 == requests/answer/late-by-two-attempts 0s client: 2c timeout=1s retries=2 @@ -163,7 +163,7 @@ 2s write #3: 2c "public" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] 2.5s read from 127.0.0.2:161: 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 2.5s result: packet 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -2.5s client after: retries=2 next request id=1004 +2.5s client after: next request id=1004 == requests/answer/late-reply-read-by-next-request 0s client: 2c timeout=1s retries=2 @@ -181,7 +181,7 @@ 1.5s read from 127.0.0.2:161: 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 1.8s read from 127.0.0.2:161: 2c "public" Response id=1003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 1.8s result: packet 2c "public" Response id=1003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -1.8s client after: retries=2 next request id=1004 +1.8s client after: next request id=1004 == requests/answer/not-a-response 0s client: 2c timeout=1s retries=2 @@ -201,7 +201,7 @@ 2s read from 127.0.0.2:161: 2c "public" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 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: retries=2 next request id=1004 +3s client after: next request id=1004 == requests/answer/other-community 0s client: 2c timeout=1s retries=2 @@ -210,7 +210,7 @@ 0s agent answers #1 after 0s 0s read from 127.0.0.2:161: 2c "private" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s result: packet 2c "private" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client after: retries=2 next request id=1002 +0s client after: next request id=1002 == requests/answer/other-version 0s client: 2c timeout=1s retries=2 @@ -230,7 +230,7 @@ 2s read from 127.0.0.2:161: 1 "public" Response id=1003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 3s read from 127.0.0.2:161: deadline 3s result: packet nil, error "request timeout (after 2 retries): last discarded reply: the reply is of another SNMP version than the request" *gosnmp.attemptsError (is os.ErrDeadlineExceeded, ErrUnmatchedReply, net.Error timeout) -3s client after: retries=2 next request id=1004 +3s client after: next request id=1004 == requests/answer/other-version-then-valid 0s client: 2c timeout=1s retries=2 @@ -241,7 +241,7 @@ 0s read from 127.0.0.2:161: 1 "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s read from 127.0.0.2:161: 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s result: packet 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client after: retries=2 next request id=1002 +0s client after: next request id=1002 == requests/answer/other-version-v3 0s client: 2c timeout=1s retries=2 @@ -261,7 +261,7 @@ 2s read from 127.0.0.2:161: 3 msgID=0 noAuthNoPriv user="public" engine="" boots=0 time=0 context=""/"" Response id=1003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 3s read from 127.0.0.2:161: deadline 3s result: packet nil, error "request timeout (after 2 retries): last discarded reply: the reply is of another SNMP version than the request" *gosnmp.attemptsError (is os.ErrDeadlineExceeded, ErrUnmatchedReply, net.Error timeout) -3s client after: retries=2 next request id=1004 +3s client after: next request id=1004 == requests/answer/other-version-v3-get-response 0s client: 2c timeout=1s retries=2 @@ -281,7 +281,7 @@ 2s read from 127.0.0.2:161: 3 msgID=7 noAuthNoPriv user="public" engine="" boots=0 time=0 scoped PDU not decodable 3s read from 127.0.0.2:161: deadline 3s result: packet nil, error "request timeout (after 2 retries): last discarded reply: the reply is of another SNMP version than the request" *gosnmp.attemptsError (is os.ErrDeadlineExceeded, ErrUnmatchedReply, net.Error timeout) -3s client after: retries=2 next request id=1004 +3s client after: next request id=1004 == requests/answer/other-version-v3-msg-id-zero 0s client: 2c timeout=1s retries=2 @@ -301,7 +301,7 @@ 2s read from 127.0.0.2:161: 3 msgID=0 noAuthNoPriv user="public" engine="" boots=0 time=0 scoped PDU not decodable 3s read from 127.0.0.2:161: deadline 3s result: packet nil, error "request timeout (after 2 retries): last discarded reply: the reply is of another SNMP version than the request" *gosnmp.attemptsError (is os.ErrDeadlineExceeded, ErrUnmatchedReply, net.Error timeout) -3s client after: retries=2 next request id=1004 +3s client after: next request id=1004 == requests/answer/other-version-v3-report 0s client: 2c timeout=1s retries=2 @@ -321,7 +321,7 @@ 2s read from 127.0.0.2:161: 3 msgID=7 noAuthNoPriv user="public" engine="" boots=0 time=0 scoped PDU not decodable 3s read from 127.0.0.2:161: deadline 3s result: packet nil, error "request timeout (after 2 retries): last discarded reply: the reply is of another SNMP version than the request" *gosnmp.attemptsError (is os.ErrDeadlineExceeded, ErrUnmatchedReply, net.Error timeout) -3s client after: retries=2 next request id=1004 +3s client after: next request id=1004 == requests/answer/other-version-v3-unknown-engine-report 0s client: 2c timeout=1s retries=2 @@ -341,7 +341,7 @@ 2s read from 127.0.0.2:161: 3 msgID=7 noAuthNoPriv user="public" engine="" boots=0 time=0 scoped PDU not decodable 3s read from 127.0.0.2:161: deadline 3s result: packet nil, error "request timeout (after 2 retries): last discarded reply: the reply is of another SNMP version than the request" *gosnmp.attemptsError (is os.ErrDeadlineExceeded, ErrUnmatchedReply, net.Error timeout) -3s client after: retries=2 next request id=1004 +3s client after: next request id=1004 == requests/answer/reflected-request 0s client: 2c timeout=1s retries=2 @@ -361,7 +361,7 @@ 2s read from 127.0.0.2:161: 2c "public" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] 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: retries=2 next request id=1004 +3s client after: next request id=1004 == requests/answer/report 0s client: 2c timeout=1s retries=2 @@ -381,7 +381,7 @@ 2s read from 127.0.0.2:161: 2c "public" Report id=1003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 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: retries=2 next request id=1004 +3s client after: next request id=1004 == requests/answer/second-attempt 0s client: 2c timeout=1s retries=2 @@ -393,7 +393,7 @@ 1s agent answers #2 after 0s 1s read from 127.0.0.2:161: 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 1s result: packet 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -1s client after: retries=2 next request id=1003 +1s client after: next request id=1003 == requests/answer/too-big-udp 0s client: 2c timeout=1s retries=1 @@ -406,7 +406,7 @@ 0s agent answers #2 after 0s 0s read from 127.0.0.2:161: 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"xxxxxxxxxxxxxxxx"... (65484 octets)] 0s result: packet nil, error "response buffer too small" *errors.errorString -0s client after: retries=1 next request id=1003 +0s client after: next request id=1003 == requests/answer/undecodable-other-request 0s client: 2c timeout=1s retries=2 @@ -426,7 +426,7 @@ 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) 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: retries=2 next request id=1004 +3s client after: next request id=1004 == requests/answer/undecodable-then-garbage 0s client: 2c timeout=1s retries=2 @@ -452,7 +452,7 @@ 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 client after: retries=2 next request id=1004 +3s client after: next request id=1004 == requests/answer/unknown-pdu-type 0s client: 2c timeout=1s retries=2 @@ -472,7 +472,7 @@ 2s read from 127.0.0.2:161: 52 octets, not decodable (unknown PDUType 0xaf) 3s read from 127.0.0.2:161: deadline 3s result: packet nil, error "request timeout (after 2 retries): last discarded reply: unknown PDUType 0xaf" *gosnmp.attemptsError (is os.ErrDeadlineExceeded, ErrASNParse, net.Error timeout) -3s client after: retries=2 next request id=1004 +3s client after: next request id=1004 == requests/answer/v1-trap 0s client: 2c timeout=1s retries=2 @@ -492,7 +492,7 @@ 2s read from 127.0.0.2:161: 1 "public" Trap id=0 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 3s read from 127.0.0.2:161: deadline 3s result: packet nil, error "request timeout (after 2 retries): last discarded reply: the reply is of another SNMP version than the request" *gosnmp.attemptsError (is os.ErrDeadlineExceeded, ErrUnmatchedReply, net.Error timeout) -3s client after: retries=2 next request id=1004 +3s client after: next request id=1004 == requests/answer/wrong-id 0s client: 2c timeout=1s retries=2 @@ -512,7 +512,7 @@ 2s read from 127.0.0.2:161: 2c "public" Response id=1103 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 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: retries=2 next request id=1004 +3s client after: next request id=1004 == requests/answer/zero-id 0s client: 2c timeout=1s retries=2 @@ -532,7 +532,7 @@ 2s read from 127.0.0.2:161: 2c "public" Response id=0 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 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: retries=2 next request id=1004 +3s client after: next request id=1004 == requests/answer/zero-id-then-valid 0s client: 2c timeout=1s retries=2 @@ -543,7 +543,7 @@ 0s read from 127.0.0.2:161: 2c "public" Response id=0 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s read from 127.0.0.2:161: 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s result: packet 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client after: retries=2 next request id=1002 +0s client after: next request id=1002 == requests/close/after-the-reply 0s client: 2c timeout=1s retries=2 @@ -554,13 +554,13 @@ 0s the Conn's read #1 closes the client 0s close 0s result: packet 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client after: retries=2 next request id=1002 +0s client after: next request id=1002 == requests/close/before-request 0s close 0s client: 2c timeout=1s retries=2 0s result: packet nil, error "the client was closed: use of closed network connection" *fmt.wrapError (is net.ErrClosed) -0s client after: retries=2 next request id=1001 +0s client after: next request id=1001 == requests/close/between-attempts 0s client: 2c timeout=1s retries=2 @@ -571,7 +571,7 @@ 1s close 1s deadline +1s 1s result: packet nil, error "the client was closed: use of closed network connection" *fmt.wrapError (is net.ErrClosed) -1s client after: retries=2 next request id=1002 +1s client after: next request id=1002 == requests/close/during-attempt 0s client: 2c timeout=1s retries=2 @@ -581,7 +581,7 @@ 0s close 0s read from 127.0.0.2:161: read udp: use of closed network connection 0s result: packet nil, error "the client was closed: use of closed network connection" *fmt.wrapError (is net.ErrClosed) -0s client after: retries=2 next request id=1002 +0s client after: next request id=1002 == requests/close/from-another-goroutine 0s client: 2c timeout=1s retries=2 @@ -590,7 +590,7 @@ 300ms close 300ms read from 127.0.0.2:161: read udp: use of closed network connection 300ms result: packet nil, error "the client was closed: use of closed network connection" *fmt.wrapError (is net.ErrClosed) -300ms client after: retries=2 next request id=1002 +300ms client after: next request id=1002 == requests/context/canceled-after-request 0s client: 2c timeout=1s retries=2 @@ -603,12 +603,12 @@ 0s agent answers #2 after 0s 0s read from 127.0.0.2:161: 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s result: packet 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client after: retries=2 next request id=1003 +0s client after: next request id=1003 == requests/context/canceled-before 0s client: 2c timeout=1s retries=2 0s result: packet nil, error "context canceled" *errors.errorString (equals context.Canceled) -0s client after: retries=2 next request id=1001 +0s client after: next request id=1001 == requests/context/canceled-before-a-reply 0s client: 2c timeout=1s retries=2 @@ -619,7 +619,7 @@ 200ms interrupt released 200ms deadline in the past 200ms result: packet 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -200ms client after: retries=2 next request id=1002 +200ms client after: next request id=1002 == requests/context/canceled-before-deadline 0s client: 2c timeout=1s retries=2 @@ -628,7 +628,7 @@ 300ms deadline in the past 300ms read from 127.0.0.2:161: deadline 300ms result: packet nil, error "context canceled" *errors.errorString (equals context.Canceled) -300ms client after: retries=2 next request id=1002 +300ms client after: next request id=1002 == requests/context/canceled-between-attempts 0s client: 2c timeout=1s retries=2 @@ -636,7 +636,7 @@ 0s write #1: 2c "public" GetRequest id=1001 [.1.3.6.1.2.1.1.1.0] 1s read from 127.0.0.2:161: deadline 1s result: packet nil, error "context canceled" *errors.errorString (equals context.Canceled) -1s client after: retries=2 next request id=1002 +1s client after: next request id=1002 == requests/context/canceled-in-last-attempt 0s client: 2c timeout=1s retries=2 @@ -651,7 +651,7 @@ 2.3s deadline in the past 2.3s read from 127.0.0.2:161: deadline 2.3s result: packet nil, error "context canceled" *errors.errorString (equals context.Canceled) -2.3s client after: retries=2 next request id=1004 +2.3s client after: next request id=1004 == requests/context/canceled-then-closed-while-interrupting 0s client: 2c timeout=1s retries=2 @@ -664,7 +664,7 @@ 200ms interrupt released 200ms deadline in the past 200ms result: packet nil, error "the client was closed: use of closed network connection" *fmt.wrapError (is net.ErrClosed) -200ms client after: retries=2 next request id=1002 +200ms client after: next request id=1002 == requests/context/canceled-while-waiting 0s client: 2c timeout=1s retries=2 @@ -673,12 +673,12 @@ 300ms deadline in the past 300ms read from 127.0.0.2:161: deadline 300ms result: packet nil, error "context canceled" *errors.errorString (equals context.Canceled) -300ms client after: retries=2 next request id=1002 +300ms client after: next request id=1002 == requests/context/canceled-with-cause-before 0s client: 2c timeout=1s retries=2 0s result: packet nil, error "context canceled" *errors.errorString (equals context.Canceled) -0s client after: retries=2 next request id=1001 +0s client after: next request id=1001 == requests/context/canceled-with-cause-while-waiting 0s client: 2c timeout=1s retries=2 @@ -687,7 +687,7 @@ 300ms deadline in the past 300ms read from 127.0.0.2:161: deadline 300ms result: packet nil, error "context canceled" *errors.errorString (equals context.Canceled) -300ms client after: retries=2 next request id=1002 +300ms client after: next request id=1002 == requests/context/deadline-after-all-attempts 0s client: 2c timeout=1s retries=2 @@ -701,7 +701,7 @@ 2s write #3: 2c "public" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] 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: retries=2 next request id=1004 +3s client after: next request id=1004 == requests/context/deadline-equal-to-timeout 0s client: 2c timeout=1s retries=0 @@ -709,7 +709,7 @@ 0s write #1: 2c "public" GetRequest id=1001 [.1.3.6.1.2.1.1.1.0] 1s read from 127.0.0.2:161: deadline 1s result: packet nil, error "context deadline exceeded" context.deadlineExceededError (equals context.DeadlineExceeded; is net.Error timeout) -1s client after: retries=0 next request id=1002 +1s client after: next request id=1002 == requests/context/deadline-in-first-attempt 0s client: 2c timeout=1s retries=2 @@ -717,7 +717,7 @@ 0s write #1: 2c "public" GetRequest id=1001 [.1.3.6.1.2.1.1.1.0] 700ms read from 127.0.0.2:161: deadline 700ms result: packet nil, error "context deadline exceeded" context.deadlineExceededError (equals context.DeadlineExceeded; is net.Error timeout) -700ms client after: retries=2 next request id=1002 +700ms client after: next request id=1002 == requests/context/deadline-in-third-attempt 0s client: 2c timeout=1s retries=2 @@ -731,7 +731,7 @@ 2s write #3: 2c "public" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] 2.5s read from 127.0.0.2:161: deadline 2.5s result: packet nil, error "context deadline exceeded" context.deadlineExceededError (equals context.DeadlineExceeded; is net.Error timeout) -2.5s client after: retries=2 next request id=1004 +2.5s client after: next request id=1004 == requests/context/deadline-passed-in-conn-write 0s client: 2c timeout=1s retries=2 @@ -740,7 +740,7 @@ 0s the Conn's write #1 takes 1s 1s read from 127.0.0.2:161: read udp: connection refused 1s result: packet nil, error "context deadline exceeded" context.deadlineExceededError (equals context.DeadlineExceeded; is net.Error timeout) -1s client after: retries=2 next request id=1002 +1s client after: next request id=1002 == requests/context/deadline-unreported-equal-to-timeout 0s client: 2c timeout=1s retries=0 @@ -748,7 +748,7 @@ 0s write #1: 2c "public" GetRequest id=1001 [.1.3.6.1.2.1.1.1.0] 1s read from 127.0.0.2:161: deadline 1s result: packet nil, error "context deadline exceeded" context.deadlineExceededError (equals context.DeadlineExceeded; is net.Error timeout) -1s client after: retries=0 next request id=1002 +1s client after: next request id=1002 == requests/context/deadline-unreported-in-first-attempt 0s client: 2c timeout=1s retries=2 @@ -756,18 +756,18 @@ 0s write #1: 2c "public" GetRequest id=1001 [.1.3.6.1.2.1.1.1.0] 700ms read from 127.0.0.2:161: deadline 700ms result: packet nil, error "context deadline exceeded" context.deadlineExceededError (equals context.DeadlineExceeded; is net.Error timeout) -700ms client after: retries=2 next request id=1002 +700ms client after: next request id=1002 == requests/context/nil 0s client: 2c timeout=1s retries=2 0s result: packet nil, error "nil context" *errors.errorString -0s client after: retries=2 next request id=1001 +0s client after: next request id=1001 == requests/deadline-error 0s client: 2c timeout=1s retries=2 0s deadline +1s 0s result: packet nil, error "codec deadline failure" *errors.errorString -0s client after: retries=2 next request id=1001 +0s client after: next request id=1001 == requests/get 0s client: 2c timeout=1s retries=2 @@ -776,13 +776,13 @@ 0s agent answers #1 after 0s 0s read from 127.0.0.2:161: 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s result: packet 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client after: retries=2 next request id=1002 +0s client after: next request id=1002 == requests/get/invalid-oid 0s client: 2c timeout=1s retries=2 0s deadline +1s 0s result: packet nil, error "marshal: unable to marshal varbind list: unable to marshal OID \".1.3.6.1.x\": invalid object identifier" *fmt.wrapError -0s client after: retries=2 next request id=1002 +0s client after: next request id=1002 == requests/get/max-oids/at-limit 0s client: 2c timeout=1s retries=2 @@ -791,17 +791,17 @@ 0s agent answers #1 after 0s 0s read from 127.0.0.2:161: 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s result: packet 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client after: retries=2 next request id=1002 +0s client after: next request id=1002 == requests/get/max-oids/over-limit 0s client: 2c timeout=1s retries=2 0s result: packet nil, error "oid count (3) is greater than MaxOids (2)" *errors.errorString -0s client after: retries=2 next request id=1001 +0s client after: next request id=1001 == requests/get/no-conn 0s client: 2c timeout=1s retries=2 0s result: packet nil, error "the client is not connected: call Connect first" *errors.errorString -0s client after: retries=2 next request id=1001 +0s client after: next request id=1001 == requests/get/v1 0s client: 1 timeout=1s retries=2 @@ -810,7 +810,7 @@ 0s agent answers #1 after 0s 0s read from 127.0.0.2:161: 1 "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s result: packet 1 "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client after: retries=2 next request id=1002 +0s client after: next request id=1002 == requests/mk-snmp-packet 0s client: 2c timeout=1s retries=2 @@ -819,7 +819,7 @@ 0s agent answers #1 after 0s 0s read from 127.0.0.2:161: 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s result: packet 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client after: retries=2 next request id=1002 +0s client after: next request id=1002 == requests/panics/after-read 0s client: 2c timeout=1s retries=2 @@ -835,7 +835,7 @@ 0s agent answers #2 after 0s 0s read from 127.0.0.2:161: 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s result: packet 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client after: retries=2 next request id=1003 +0s client after: next request id=1003 == requests/panics/after-write-runtime-error 0s client: 2c timeout=1s retries=2 @@ -851,7 +851,7 @@ 0s read from 127.0.0.2:161: 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s read from 127.0.0.2:161: 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s result: packet 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client after: retries=2 next request id=1003 +0s client after: next request id=1003 == requests/panics/before-retry-deadline 0s client: 2c timeout=1s retries=2 @@ -866,7 +866,7 @@ 1s agent answers #2 after 0s 1s read from 127.0.0.2:161: 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 1s result: packet 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -1s client after: retries=2 next request id=1003 +1s client after: next request id=1003 == requests/panics/read 0s client: 2c timeout=1s retries=2 @@ -882,7 +882,7 @@ 0s read from 127.0.0.2:161: 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s read from 127.0.0.2:161: 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s result: packet 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client after: retries=2 next request id=1003 +0s client after: next request id=1003 == requests/panics/write 0s client: 2c timeout=1s retries=2 @@ -890,7 +890,7 @@ 0s write #1: 2c "public" GetRequest id=1001 [.1.3.6.1.2.1.1.1.0] 0s the Conn's write #1 panics 0s result: packet nil, error "request panicked: codec write failure" *errors.errorString -0s client after: retries=2 next request id=1002 +0s client after: next request id=1002 == requests/panics/write-error 0s client: 2c timeout=1s retries=2 @@ -904,7 +904,7 @@ 0s agent answers #2 after 0s 0s read from 127.0.0.2:161: 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s result: packet 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client after: retries=2 next request id=1003 +0s client after: next request id=1003 == requests/read-eof/udp 0s client: 2c timeout=1s retries=2 @@ -916,7 +916,7 @@ 0s agent answers #2 after 0s 0s read from 127.0.0.2:161: 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s result: packet 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client after: retries=2 next request id=1003 +0s client after: next request id=1003 == requests/read-error/always 0s client: 2c timeout=1s retries=2 @@ -933,7 +933,7 @@ 0s agent answers #3 after 0s 0s read from 127.0.0.2:161: read udp: connection refused 0s result: packet nil, error "error reading from socket: read udp: connection refused" *fmt.wrapError (is syscall.ECONNREFUSED) -0s client after: retries=2 next request id=1004 +0s client after: next request id=1004 == requests/read-error/closed 0s client: 2c timeout=1s retries=2 @@ -942,7 +942,7 @@ 0s agent answers #1 after 0s 0s read from 127.0.0.2:161: read udp: use of closed network connection 0s result: packet nil, error "error reading from socket: read udp: use of closed network connection" *fmt.wrapError (is net.ErrClosed) -0s client after: retries=2 next request id=1002 +0s client after: next request id=1002 == requests/read-error/once 0s client: 2c timeout=1s retries=2 @@ -954,7 +954,7 @@ 0s agent answers #2 after 0s 0s read from 127.0.0.2:161: 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s result: packet 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client after: retries=2 next request id=1003 +0s client after: next request id=1003 == requests/request-id/set 0s client: 2c timeout=1s retries=2 @@ -963,7 +963,7 @@ 0s agent answers #1 after 0s 0s read from 127.0.0.2:161: 2c "public" Response id=6 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s result: packet 2c "public" Response id=6 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client after: retries=2 next request id=7 +0s client after: next request id=7 == requests/request-id/wraps 0s client: 2c timeout=1s retries=2 @@ -972,7 +972,7 @@ 0s agent answers #1 after 0s 0s read from 127.0.0.2:161: 2c "public" Response id=0 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s result: packet 2c "public" Response id=0 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client after: retries=2 next request id=1 +0s client after: next request id=1 == requests/request-id/wraps-between-attempts 0s client: 2c timeout=1s retries=2 @@ -984,7 +984,7 @@ 1s agent answers #2 after 0s 1s read from 127.0.0.2:161: 2c "public" Response id=0 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 1s result: packet 2c "public" Response id=0 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -1s client after: retries=2 next request id=1 +1s client after: next request id=1 == requests/timeout 0s client: 2c timeout=1s retries=2 @@ -998,15 +998,21 @@ 2s write #3: 2c "public" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] 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: retries=2 next request id=1004 +3s client after: next request id=1004 -== requests/timeout/negative-retries -0s client: 2c timeout=1s retries=-3 -0s deadline +1s +== requests/timeout/configured +0s client: 2c timeout=3s retries=2 +0s deadline +3s 0s write #1: 2c "public" GetRequest id=1001 [.1.3.6.1.2.1.1.1.0] -1s read from 127.0.0.2:161: deadline -1s result: packet nil, error "request timeout (after 0 retries)" *gosnmp.attemptsError (is os.ErrDeadlineExceeded, net.Error timeout) -1s client after: retries=-3 next request id=1002 +3s read from 127.0.0.2:161: deadline +3s deadline +3s +3s write #2: 2c "public" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] +6s read from 127.0.0.2:161: deadline +6s deadline +3s +6s write #3: 2c "public" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] +9s read from 127.0.0.2:161: deadline +9s result: packet nil, error "request timeout (after 2 retries)" *gosnmp.attemptsError (is os.ErrDeadlineExceeded, net.Error timeout) +9s client after: next request id=1004 == requests/timeout/no-retries 0s client: 2c timeout=1s retries=0 @@ -1014,37 +1020,16 @@ 0s write #1: 2c "public" GetRequest id=1001 [.1.3.6.1.2.1.1.1.0] 1s read from 127.0.0.2:161: deadline 1s result: packet nil, error "request timeout (after 0 retries)" *gosnmp.attemptsError (is os.ErrDeadlineExceeded, net.Error timeout) -1s client after: retries=0 next request id=1002 +1s client after: next request id=1002 == requests/timeout/zero -0s client: 2c timeout=0s retries=2 -0s deadline +0s -0s write #1: 2c "public" GetRequest id=1001 [.1.3.6.1.2.1.1.1.0] -0s write #1: deadline -0s deadline +0s -0s write #2: 2c "public" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s write #2: deadline -0s deadline +0s -0s write #3: 2c "public" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] -0s write #3: deadline -0s result: packet nil, error "request timeout (after 2 retries)" *gosnmp.attemptsError (is os.ErrDeadlineExceeded, net.Error timeout) -0s client after: retries=2 next request id=1004 - -== requests/user-code/sets-retries 0s client: 2c timeout=1s retries=2 0s deadline +1s 0s write #1: 2c "public" GetRequest id=1001 [.1.3.6.1.2.1.1.1.0] -0s the Conn's write #1 sets Retries to 0 -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] -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] -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 configuration changed: Retries -3s client after: retries=0 next request id=1004 +0s agent answers #1 after 0s +0s read from 127.0.0.2:161: 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] +0s result: packet 2c "public" Response id=1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error +0s client after: next request id=1002 == requests/write-error/always 0s client: 2c timeout=1s retries=2 @@ -1058,7 +1043,7 @@ 0s write #3: 2c "public" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] 0s write #3 fails: codec write failure 0s result: packet nil, error "codec write failure" *errors.errorString (equals errEngineWrite) -0s client after: retries=2 next request id=1004 +0s client after: next request id=1004 == requests/write-error/closed 0s client: 2c timeout=1s retries=2 @@ -1066,7 +1051,7 @@ 0s write #1: 2c "public" GetRequest id=1001 [.1.3.6.1.2.1.1.1.0] 0s write #1 fails: write udp: use of closed network connection 0s result: packet nil, error "write udp: use of closed network connection" *net.OpError (is net.ErrClosed) -0s client after: retries=2 next request id=1002 +0s client after: next request id=1002 == requests/write-error/once 0s client: 2c timeout=1s retries=2 @@ -1078,7 +1063,7 @@ 0s agent answers #2 after 0s 0s read from 127.0.0.2:161: 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] 0s result: packet 2c "public" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client after: retries=2 next request id=1003 +0s client after: next request id=1003 == requests/write-error/timeout-in-text 0s client: 2c timeout=1s retries=2 @@ -1092,4 +1077,4 @@ 0s write #3: 2c "public" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] 0s write #3 fails: codec timeout of the write queue 0s result: packet nil, error "codec timeout of the write queue" *errors.errorString -0s client after: retries=2 next request id=1004 +0s client after: next request id=1004 diff --git a/testdata/engine/v3-fips.golden b/testdata/engine/v3-fips.golden index e4f731e..b610bfd 100644 --- a/testdata/engine/v3-fips.golden +++ b/testdata/engine/v3-fips.golden @@ -1,11 +1,5 @@ # Engine characterization results (v3-fips). Generated by go test -update; do not edit. -== v3-fips/discovery/md5 -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s first Get: packet nil, error "crypto/md5: use of MD5 is not allowed in FIPS 140-only mode" *errors.errorString -0s result: packet nil, error "crypto/md5: use of MD5 is not allowed in FIPS 140-only mode" *errors.errorString -0s client after: engine="" boots=0 time=0 keys=none context engine="" - == v3-fips/discovery/noauth 0s client: user="codec-noauth" noAuthNoPriv timeout=1s retries=2 0s deadline +1s @@ -21,12 +15,6 @@ 0s result: packet 3 msgID=2002 noAuthNoPriv Response id=1002 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-noauth"/"\x80\x00\x1f\x88\x04codec-agent"/7/1000 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error 0s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=none context engine="\x80\x00\x1f\x88\x04codec-agent" -== v3-fips/discovery/sha-aes -0s client: user="codec-sha-aes" authPriv timeout=1s retries=2 -0s first Get: packet nil, error "crypto/sha1: use of SHA-1 is not allowed in FIPS 140-only mode" *errors.errorString -0s result: packet nil, error "crypto/sha1: use of SHA-1 is not allowed in FIPS 140-only mode" *errors.errorString -0s client after: engine="" boots=0 time=0 keys=none context engine="" - == v3-fips/discovery/sha256-aes 0s client: user="codec-sha256-aes" authPriv timeout=1s retries=2 0s deadline +1s diff --git a/testdata/engine/v3.golden b/testdata/engine/v3.golden index f15e68d..91ac3d6 100644 --- a/testdata/engine/v3.golden +++ b/testdata/engine/v3.golden @@ -821,28 +821,6 @@ 1s result: packet 3 msgID=2003 authNoPriv Response id=1003 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error 1s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1001 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" -== v3/caller/changed-passphrase -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s deadline +1s -0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #2 with Response id=1002 msgID=2002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -0s agent answers #2 after 0s -0s read from 127.0.0.2:161: 3 msgID=2002 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -10s caller changes the authentication passphrase -10s deadline +1s -10s write #3: 3 msgID=2003 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] -10s agent: answers #3 with Report id=1003 msgID=2003 [.1.3.6.1.6.3.15.1.1.5.0=Counter32:1] at noAuthNoPriv (wrong digest) -10s agent answers #3 after 0s -10s read from 127.0.0.2:161: 3 msgID=2003 noAuthNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1003 [.1.3.6.1.6.3.15.1.1.5.0=Counter32:1] -10s result: packet nil, error "wrong digest" *gosnmp.categorized (is ErrAnswered, ErrWrongDigest) -10s client configuration changed: User -10s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - == v3/caller/encode-after-forget-engine 0s client: user="codec-md5" authNoPriv timeout=1s retries=2 0s deadline +1s @@ -913,29 +891,6 @@ 10s result: packet 3 msgID=2002 authNoPriv Response id=1002 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1000 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error 10s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" -== v3/caller/encode-after-other-user -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s deadline +1s -0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #2 with Response id=1002 msgID=2002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -0s agent answers #2 after 0s -0s read from 127.0.0.2:161: 3 msgID=2002 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -10s caller sets another user -10s EncodeMessage: msgID=2003 authNoPriv+reportable user="codec-sha-aes" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0], digest checks; client engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" -10s deadline +1s -10s write #3: 3 msgID=2004 authNoPriv+reportable user="codec-sha-aes" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1004 [.1.3.6.1.2.1.1.1.0] -10s agent: answers #3 with Response id=1004 msgID=2004 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -10s agent answers #3 after 0s -10s read from 127.0.0.2:161: 3 msgID=2004 authNoPriv user="codec-sha-aes" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1004 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -10s result: packet 3 msgID=2004 authNoPriv Response id=1004 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-sha-aes"/"\x80\x00\x1f\x88\x04codec-agent"/7/1010 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -10s client configuration changed: User -10s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - == v3/caller/forged-discovery-then-forget-engine 0s client: user="codec-md5" authNoPriv timeout=1s retries=2 0s deadline +1s @@ -989,28 +944,6 @@ 10s result: packet 3 msgID=2004 authNoPriv Response id=1004 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1010 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error 10s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" -== v3/caller/other-user -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s deadline +1s -0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #2 with Response id=1002 msgID=2002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -0s agent answers #2 after 0s -0s read from 127.0.0.2:161: 3 msgID=2002 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -10s caller sets another user -10s deadline +1s -10s write #3: 3 msgID=2003 authNoPriv+reportable user="codec-sha-aes" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] -10s agent: answers #3 with Response id=1003 msgID=2003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -10s agent answers #3 after 0s -10s read from 127.0.0.2:161: 3 msgID=2003 authNoPriv user="codec-sha-aes" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -10s result: packet 3 msgID=2003 authNoPriv Response id=1003 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-sha-aes"/"\x80\x00\x1f\x88\x04codec-agent"/7/1010 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -10s client configuration changed: User -10s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - == v3/clock/boots-max-after-update 0s client: user="codec-md5" authNoPriv timeout=1s retries=2 0s deadline +1s @@ -1262,34 +1195,6 @@ 21s result: packet 3 msgID=2004 authNoPriv Response id=1004 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/11 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error 21s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=11 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" -== v3/clock/noauth/authenticated-then-unauthenticated -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s deadline +1s -0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #2 with Response id=1002 msgID=2002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -0s agent answers #2 after 0s -0s read from 127.0.0.2:161: 3 msgID=2002 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -0s Get 1: packet 3 msgID=2002 authNoPriv Response id=1002 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1000 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -10s deadline +1s -10s write #3: 3 msgID=2003 noAuthNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] -10s agent: answers #3 with Response id=1003 msgID=2003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at noAuthNoPriv (noAuthNoPriv answer with an engine time 500 s ahead) -10s agent answers #3 after 0s -10s read from 127.0.0.2:161: 3 msgID=2003 noAuthNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1510 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -10s Get 2: packet 3 msgID=2003 noAuthNoPriv Response id=1003 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1510 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -20s deadline +1s -20s write #4: 3 msgID=2004 noAuthNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1020 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1004 [.1.3.6.1.2.1.1.1.0] -20s agent: answers #4 with Response id=1004 msgID=2004 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at noAuthNoPriv (request accepted) -20s agent answers #4 after 0s -20s read from 127.0.0.2:161: 3 msgID=2004 noAuthNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1020 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1004 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -20s result: packet 3 msgID=2004 noAuthNoPriv Response id=1004 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1020 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -20s client configuration changed: SecurityLevel -20s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - == v3/clock/noauth/engine-boots-max 0s client: user="codec-noauth" noAuthNoPriv timeout=1s retries=2 0s deadline +1s @@ -1310,62 +1215,6 @@ 10s result: packet 3 msgID=2003 noAuthNoPriv Response id=1003 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-noauth"/"\x80\x00\x1f\x88\x04codec-agent"/2147483647/1010 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error 10s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=2147483647 time=1010 keys=none context engine="\x80\x00\x1f\x88\x04codec-agent" -== v3/clock/noauth/verified-after-discovery-time-ahead -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID, an engine time 1000 s ahead) -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=2000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s deadline +1s -0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=2000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #2 with Response id=1002 msgID=2002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (authNoPriv answer) -0s agent answers #2 after 0s -0s read from 127.0.0.2:161: 3 msgID=2002 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -0s Get 1: packet 3 msgID=2002 authNoPriv Response id=1002 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1000 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -10s deadline +1s -10s write #3: 3 msgID=2003 noAuthNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] -10s agent: answers #3 with Response id=1003 msgID=2003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at noAuthNoPriv (request accepted) -10s agent answers #3 after 0s -10s read from 127.0.0.2:161: 3 msgID=2003 noAuthNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -10s result: packet 3 msgID=2003 noAuthNoPriv Response id=1003 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1010 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -10s client configuration changed: SecurityLevel -10s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - -== v3/clock/noauth/verified-old-time -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s deadline +1s -0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #2 with Response id=1002 msgID=2002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -0s agent answers #2 after 0s -0s read from 127.0.0.2:161: 3 msgID=2002 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -0s Get 1: packet 3 msgID=2002 authNoPriv Response id=1002 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1000 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -10s deadline +1s -10s write #3: 3 msgID=2003 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] -10s agent: answers #3 with Response id=1003 msgID=2003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (authNoPriv answer with an engine time 200 s old) -10s agent answers #3 after 0s -10s read from 127.0.0.2:161: 3 msgID=2003 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=810 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -11s read from 127.0.0.2:161: deadline -11s deadline +1s -11s write #4: 3 msgID=2004 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1011 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1004 [.1.3.6.1.2.1.1.1.0] -11s agent: answers #4 with Response id=1004 msgID=2004 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -11s agent answers #4 after 0s -11s read from 127.0.0.2:161: 3 msgID=2004 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1011 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1004 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -11s Get 2: packet 3 msgID=2004 authNoPriv Response id=1004 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1011 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -21s deadline +1s -21s write #5: 3 msgID=2005 noAuthNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1021 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1005 [.1.3.6.1.2.1.1.1.0] -21s agent: answers #5 with Response id=1005 msgID=2005 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at noAuthNoPriv (request accepted) -21s agent answers #5 after 0s -21s read from 127.0.0.2:161: 3 msgID=2005 noAuthNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1021 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1005 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -21s result: packet 3 msgID=2005 noAuthNoPriv Response id=1005 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1021 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -21s client configuration changed: SecurityLevel -21s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1011 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - == v3/clock/resend-answers-outside-window 0s client: user="codec-md5" authNoPriv timeout=1s retries=2 0s deadline +1s @@ -1497,6 +1346,26 @@ 0s result: packet nil, error "not in time window" *gosnmp.categorized (is ErrAnswered, ErrNotInTimeWindow) 0s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1100 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" +== v3/clock/verified-after-discovery-time-ahead +0s client: user="codec-md5" authNoPriv timeout=1s retries=2 +0s deadline +1s +0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] +0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID, an engine time 1000 s ahead) +0s agent answers #1 after 0s +0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=2000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] +0s deadline +1s +0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=2000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] +0s agent: answers #2 with Response id=1002 msgID=2002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (authNoPriv answer) +0s agent answers #2 after 0s +0s read from 127.0.0.2:161: 3 msgID=2002 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] +10s deadline +1s +10s write #3: 3 msgID=2003 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] +10s agent: answers #3 with Response id=1003 msgID=2003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) +10s agent answers #3 after 0s +10s read from 127.0.0.2:161: 3 msgID=2003 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] +10s result: packet 3 msgID=2003 authNoPriv Response id=1003 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1010 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error +10s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" + == v3/context/canceled-after-discovery 0s client: user="codec-md5" authNoPriv timeout=1s retries=2 0s deadline +1s @@ -2597,13 +2466,6 @@ 0s result: packet 3 msgID=2002 authNoPriv Response id=1002 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1000 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error 0s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" -== v3/empty-passphrase/auth-protocol-without-passphrase -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s caller clears the authentication passphrase -0s result: packet nil, error "usm: no authentication key, want 16 octets" *fmt.wrapError -0s client configuration changed: User -0s client after: engine="" boots=0 time=0 keys=none context engine="" - == v3/engine-change 0s client: user="codec-md5" authNoPriv timeout=1s retries=2 0s deadline +1s @@ -3719,50 +3581,6 @@ 0s result: packet nil, error "unknown username" *gosnmp.categorized (is ErrAnswered, ErrUnknownUsername) 0s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=none context engine="\x80\x00\x1f\x88\x04codec-agent" -== v3/resync/security-level-changed-during-request -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s deadline +1s -0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #2 with Report id=1002 msgID=2002 [.1.3.6.1.6.3.15.1.1.2.0=Counter32:1] at authNoPriv (not in time window) -0s agent answers #2 after 0s -0s read from 127.0.0.2:161: 3 msgID=2002 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1002 [.1.3.6.1.6.3.15.1.1.2.0=Counter32:1] -0s the Conn's read #2 sets the client's security level to noAuthNoPriv -0s deadline +1s -0s write #3: 3 msgID=2003 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #3 with Response id=1003 msgID=2003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -0s agent answers #3 after 0s -0s read from 127.0.0.2:161: 3 msgID=2003 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -0s result: packet 3 msgID=2003 authNoPriv Response id=1003 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1000 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client configuration changed: SecurityLevel -0s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - -== v3/resync/version-changed-during-request -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s deadline +1s -0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #2 with Report id=1002 msgID=2002 [.1.3.6.1.6.3.15.1.1.2.0=Counter32:1] at authNoPriv (not in time window) -0s agent answers #2 after 0s -0s read from 127.0.0.2:161: 3 msgID=2002 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1002 [.1.3.6.1.6.3.15.1.1.2.0=Counter32:1] -0s the Conn's read #2 sets the client's version to 2c -0s deadline +1s -0s write #3: 3 msgID=2003 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #3 with Response id=1003 msgID=2003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -0s agent answers #3 after 0s -0s read from 127.0.0.2:161: 3 msgID=2003 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -0s result: packet 3 msgID=2003 authNoPriv Response id=1003 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1000 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client configuration changed: Version -0s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - == v3/time-window/always-not-in-time-window 0s client: user="codec-md5" authNoPriv timeout=1s retries=2 0s deadline +1s @@ -4158,28 +3976,6 @@ 10s result: packet 3 msgID=2004 authPriv Response id=1004 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-sha-aes"/"\x80\x00\x1f\x88\x04codec-agent"/8/0 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error 10s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=8 time=0 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" -== v3/unauthenticated-report/security-level-changed-during-request -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s deadline +1s -0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #2 with Report id=1002 msgID=2002 [.1.3.6.1.6.3.15.1.1.2.0=Counter32:1] at noAuthNoPriv (not in time window, unauthenticated) -0s agent answers #2 after 0s -0s read from 127.0.0.2:161: 3 msgID=2002 noAuthNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1002 [.1.3.6.1.6.3.15.1.1.2.0=Counter32:1] -0s the Conn's read #2 sets the client's security level to noAuthNoPriv -0s deadline +1s -0s write #3: 3 msgID=2003 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #3 with Response id=1003 msgID=2003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -0s agent answers #3 after 0s -0s read from 127.0.0.2:161: 3 msgID=2003 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -0s result: packet 3 msgID=2003 authNoPriv Response id=1003 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1000 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client configuration changed: SecurityLevel -0s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - == v3/unauthenticated-report/silent-after-unknown-engine 0s client: user="codec-md5" authNoPriv timeout=1s retries=2 0s deadline +1s @@ -4396,28 +4192,6 @@ 1s result: packet 3 msgID=2003 authNoPriv Response id=1003 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error 1s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1001 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" -== v3/unauthenticated-report/version-changed-during-request -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s deadline +1s -0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #2 with Report id=1002 msgID=2002 [.1.3.6.1.6.3.15.1.1.2.0=Counter32:1] at noAuthNoPriv (not in time window, unauthenticated) -0s agent answers #2 after 0s -0s read from 127.0.0.2:161: 3 msgID=2002 noAuthNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1002 [.1.3.6.1.6.3.15.1.1.2.0=Counter32:1] -0s the Conn's read #2 sets the client's version to 2c -0s deadline +1s -0s write #3: 3 msgID=2003 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #3 with Response id=1003 msgID=2003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -0s agent answers #3 after 0s -0s read from 127.0.0.2:161: 3 msgID=2003 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -0s result: packet 3 msgID=2003 authNoPriv Response id=1003 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1000 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client configuration changed: Version -0s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - == v3/unauthenticated-report/without-scoped-pdu 0s client: user="codec-md5" authNoPriv timeout=1s retries=2 0s deadline +1s @@ -4531,65 +4305,6 @@ 0s result: packet nil, error "unknown security level" *gosnmp.categorized (is ErrAnswered, ErrUnknownSecurityLevel) 0s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" -== v3/user-code/answer-changes-version -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s deadline +1s -0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #2 with Response id=1002 msgID=2002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -0s agent answers #2 after 0s -0s read from 127.0.0.2:161: 3 msgID=2002 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -0s the Conn's read #2 sets the client's version to 2c -0s result: packet 3 msgID=2002 authNoPriv Response id=1002 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1000 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client configuration changed: Version -0s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - -== v3/user-code/discovery-answer-changes-client -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s the Conn's read #1 sets Retries to 0 and Timeout to 5s -0s deadline +1s -0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s agent: drops #2 (no answer) -1s read from 127.0.0.2:161: deadline -1s deadline +1s -1s write #3: 3 msgID=2003 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1001 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] -1s agent: drops #3 (no answer) -2s read from 127.0.0.2:161: deadline -2s deadline +1s -2s write #4: 3 msgID=2004 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1002 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1004 [.1.3.6.1.2.1.1.1.0] -2s agent: answers #4 with Response id=1004 msgID=2004 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -2s agent answers #4 after 0s -2s read from 127.0.0.2:161: 3 msgID=2004 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1002 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1004 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -2s result: packet 3 msgID=2004 authNoPriv Response id=1004 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -2s client configuration changed: Retries, Timeout -2s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1002 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - -== v3/user-code/discovery-answer-changes-version -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s the Conn's read #1 sets the client's version to 2c -0s deadline +1s -0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #2 with Response id=1002 msgID=2002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -0s agent answers #2 after 0s -0s read from 127.0.0.2:161: 3 msgID=2002 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -0s result: packet 3 msgID=2002 authNoPriv Response id=1002 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1000 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client configuration changed: Version -0s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - == v3/user-code/discovery-answer-forgets-engine 0s client: user="codec-md5" authNoPriv timeout=1s retries=2 0s deadline +1s @@ -4616,80 +4331,6 @@ 10s result: packet 3 msgID=2004 authNoPriv Response id=1004 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1010 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error 10s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" -== v3/user-code/discovery-write-changes-context-name -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s the Conn's write #1 sets the client's context name -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s deadline +1s -0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #2 with Response id=1002 msgID=2002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -0s agent answers #2 after 0s -0s read from 127.0.0.2:161: 3 msgID=2002 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -0s result: packet 3 msgID=2002 authNoPriv Response id=1002 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1000 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client configuration changed: ContextName -0s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - -== v3/user-code/discovery-write-changes-security-level -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s the Conn's write #1 sets the client's security level to noAuthNoPriv -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s deadline +1s -0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #2 with Response id=1002 msgID=2002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -0s agent answers #2 after 0s -0s read from 127.0.0.2:161: 3 msgID=2002 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -0s result: packet 3 msgID=2002 authNoPriv Response id=1002 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1000 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client configuration changed: SecurityLevel -0s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - -== v3/user-code/discovery-write-changes-user -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s the Conn's write #1 sets another user -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s deadline +1s -0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #2 with Response id=1002 msgID=2002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -0s agent answers #2 after 0s -0s read from 127.0.0.2:161: 3 msgID=2002 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -0s first Get: packet 3 msgID=2002 authNoPriv Response id=1002 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1000 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -10s deadline +1s -10s write #3: 3 msgID=2003 authNoPriv+reportable user="codec-sha-aes" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] -10s agent: answers #3 with Response id=1003 msgID=2003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -10s agent answers #3 after 0s -10s read from 127.0.0.2:161: 3 msgID=2003 authNoPriv user="codec-sha-aes" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -10s result: packet 3 msgID=2003 authNoPriv Response id=1003 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-sha-aes"/"\x80\x00\x1f\x88\x04codec-agent"/7/1010 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -10s client configuration changed: User -10s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - -== v3/user-code/discovery-write-changes-version -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s the Conn's write #1 sets the client's version to 2c -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s deadline +1s -0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #2 with Response id=1002 msgID=2002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -0s agent answers #2 after 0s -0s read from 127.0.0.2:161: 3 msgID=2002 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -0s result: packet 3 msgID=2002 authNoPriv Response id=1002 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1000 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -0s client configuration changed: Version -0s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - == v3/user-code/panic-after-discovery 0s client: user="codec-md5" authNoPriv timeout=1s retries=2 0s deadline +1s @@ -4707,100 +4348,6 @@ 10s result: packet 3 msgID=2002 authNoPriv Response id=1002 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1010 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error 10s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" -== v3/user-code/privacy-protocol-changed-in-request-write -0s client: user="codec-sha-aes" authPriv timeout=1s retries=1 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s deadline +1s -0s write #2: 3 msgID=2002 authPriv+reportable user="codec-sha-aes" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 salt=0000000000000101 encrypted -0s agent: #2 decrypts to context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s agent: drops #2 (no answer) -0s the Conn's write #2 sets the client's privacy protocol to DES -1s read from 127.0.0.2:161: deadline -1s deadline +1s -1s write #3: 3 msgID=2003 authPriv+reportable user="codec-sha-aes" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1001 salt=0000000000000102 encrypted -1s agent: #3 decrypts to context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] -1s agent: answers #3 with Response id=1003 msgID=2003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authPriv (request accepted) -1s agent answers #3 after 0s -1s read from 127.0.0.2:161: 3 msgID=2003 authPriv user="codec-sha-aes" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1001 salt=0000000000000103 encrypted -1s result: packet 3 msgID=2003 authPriv Response id=1003 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-sha-aes"/"\x80\x00\x1f\x88\x04codec-agent"/7/1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -1s client configuration changed: User -1s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1001 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - -== v3/user-code/read-lowers-security-level -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s deadline +1s -0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #2 with Report id=1002 msgID=2002 [.1.3.6.1.6.3.15.1.1.3.0=Counter32:1] at authNoPriv (Report signed with another key) -0s agent answers #2 after 0s -0s read from 127.0.0.2:161: 3 msgID=2002 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=99 time=5 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1002 [.1.3.6.1.6.3.15.1.1.3.0=Counter32:1] -0s the Conn's read #2 sets the client's security level to noAuthNoPriv -1s read from 127.0.0.2:161: deadline -1s deadline +1s -1s write #3: 3 msgID=2003 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1001 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] -1s agent: answers #3 with Response id=1003 msgID=2003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -1s agent answers #3 after 0s -1s read from 127.0.0.2:161: 3 msgID=2003 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1001 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -1s result: packet 3 msgID=2003 authNoPriv Response id=1003 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -1s client configuration changed: SecurityLevel -1s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1001 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - -== v3/user-code/request-answer-changes-user -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s deadline +1s -0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #2 with Response id=1002 msgID=2002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -0s agent answers #2 after 0s -0s read from 127.0.0.2:161: 3 msgID=2002 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1002 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -0s the Conn's read #2 sets another user -10s deadline +1s -10s write #3: 3 msgID=2003 authNoPriv+reportable user="codec-sha-aes" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] -10s agent: answers #3 with Response id=1003 msgID=2003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -10s agent answers #3 after 0s -10s read from 127.0.0.2:161: 3 msgID=2003 authNoPriv user="codec-sha-aes" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1003 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -10s result: packet 3 msgID=2003 authNoPriv Response id=1003 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-sha-aes"/"\x80\x00\x1f\x88\x04codec-agent"/7/1010 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -10s client configuration changed: User -10s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1010 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - -== v3/user-code/resync-report-changes-client -0s client: user="codec-md5" authNoPriv timeout=1s retries=2 -0s deadline +1s -0s write #1: 3 msgID=2001 noAuthNoPriv+reportable user="" engine="" boots=0 time=0 context=""/"" GetRequest id=1001 [] -0s agent: answers #1 with Report id=1001 msgID=2001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] at noAuthNoPriv (unknown engine ID) -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 3 msgID=2001 noAuthNoPriv user="" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1001 [.1.3.6.1.6.3.15.1.1.4.0=Counter32:1] -0s deadline +1s -0s write #2: 3 msgID=2002 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1002 [.1.3.6.1.2.1.1.1.0] -0s agent: answers #2 with Report id=1002 msgID=2002 [.1.3.6.1.6.3.15.1.1.2.0=Counter32:1] at authNoPriv (not in time window) -0s agent answers #2 after 0s -0s read from 127.0.0.2:161: 3 msgID=2002 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" Report id=1002 [.1.3.6.1.6.3.15.1.1.2.0=Counter32:1] -0s the Conn's read #2 sets Retries to 0 -0s deadline +1s -0s write #3: 3 msgID=2003 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1000 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1003 [.1.3.6.1.2.1.1.1.0] -0s agent: drops #3 (no answer) -1s read from 127.0.0.2:161: deadline -1s deadline +1s -1s write #4: 3 msgID=2004 authNoPriv+reportable user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1001 context="\x80\x00\x1f\x88\x04codec-agent"/"" GetRequest id=1004 [.1.3.6.1.2.1.1.1.0] -1s agent: answers #4 with Response id=1004 msgID=2004 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] at authNoPriv (request accepted) -1s agent answers #4 after 0s -1s read from 127.0.0.2:161: 3 msgID=2004 authNoPriv user="codec-md5" engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1001 context="\x80\x00\x1f\x88\x04codec-agent"/"" Response id=1004 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"] -1s result: packet 3 msgID=2004 authNoPriv Response id=1004 context="\x80\x00\x1f\x88\x04codec-agent"/"" usm="codec-md5"/"\x80\x00\x1f\x88\x04codec-agent"/7/1001 [.1.3.6.1.2.1.1.1.0=OctetString:"codec agent"], no error -1s client configuration changed: Retries -1s client after: engine="\x80\x00\x1f\x88\x04codec-agent" boots=7 time=1001 keys=current context engine="\x80\x00\x1f\x88\x04codec-agent" - == v3/wrong-passphrase 0s client: user="codec-md5" authNoPriv timeout=1s retries=2 0s deadline +1s diff --git a/testdata/engine/walk.golden b/testdata/engine/walk.golden index 985705b..3e56301 100644 --- a/testdata/engine/walk.golden +++ b/testdata/engine/walk.golden @@ -1115,51 +1115,6 @@ 0s values: [.1.3.6.1.2.1.2.2.1.2.1=OctetString:"lo" .1.3.6.1.2.1.2.2.1.2.2=OctetString:"eth0" .1.3.6.1.2.1.2.2.1.2.10=OctetString:"eth1"] 0s result: no error -== walk/user-code/sets-max-oids-0 -0s client: 2c root=".1.3.6.1.2.1.2.2.1.2" bulk=false max-repetitions=0 -0s deadline +1s -0s write #1: 2c "public" GetNextRequest id=1001 [.1.3.6.1.2.1.2.2.1.2] -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 2c "public" Response id=1001 [.1.3.6.1.2.1.2.2.1.2.1=OctetString:"lo"] -0s the Conn's read sets MaxOids to 0 -0s values: [.1.3.6.1.2.1.2.2.1.2.1=OctetString:"lo"] -0s result: error "oid count (1) is greater than MaxOids (0)" *errors.errorString - -== walk/user-code/sets-version-1 -0s client: 2c root=".1.3.6.1.2.1.2.2.1.2" bulk=true max-repetitions=1 -0s deadline +1s -0s write #1: 2c "public" GetBulkRequest id=1001 nonRepeaters=0 maxRepetitions=1 [.1.3.6.1.2.1.2.2.1.2] -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 2c "public" Response id=1001 [.1.3.6.1.2.1.2.2.1.2.1=OctetString:"lo"] -0s the Conn's read sets Version to 1 -0s values: [.1.3.6.1.2.1.2.2.1.2.1=OctetString:"lo"] -0s result: error "GETBULK not supported in SNMPv1" *errors.errorString - -== walk/user-code/sets-version-1/getnext -0s client: 2c root=".1.3.6.1.2.1.2.2.1.2" bulk=false max-repetitions=0 -0s deadline +1s -0s write #1: 2c "public" GetNextRequest id=1001 [.1.3.6.1.2.1.2.2.1.2] -0s agent answers #1 after 0s -0s read from 127.0.0.2:161: 2c "public" Response id=1001 [.1.3.6.1.2.1.2.2.1.2.1=OctetString:"lo"] -0s the Conn's read sets Version to 1 -0s deadline +1s -0s write #2: 1 "public" GetNextRequest id=1002 [.1.3.6.1.2.1.2.2.1.2.1] -0s agent answers #2 after 0s -0s read from 127.0.0.2:161: 1 "public" Response id=1002 [.1.3.6.1.2.1.2.2.1.2.2=OctetString:"eth0"] -0s the Conn's read sets Version to 1 -0s deadline +1s -0s write #3: 1 "public" GetNextRequest id=1003 [.1.3.6.1.2.1.2.2.1.2.2] -0s agent answers #3 after 0s -0s read from 127.0.0.2:161: 1 "public" Response id=1003 [.1.3.6.1.2.1.2.2.1.2.10=OctetString:"eth1"] -0s the Conn's read sets Version to 1 -0s deadline +1s -0s write #4: 1 "public" GetNextRequest id=1004 [.1.3.6.1.2.1.2.2.1.2.10] -0s agent answers #4 after 0s -0s read from 127.0.0.2:161: 1 "public" Response id=1004 [.1.3.6.1.4.1.99.1.0=Integer:7] -0s the Conn's read sets Version to 1 -0s values: [.1.3.6.1.2.1.2.2.1.2.1=OctetString:"lo" .1.3.6.1.2.1.2.2.1.2.2=OctetString:"eth0" .1.3.6.1.2.1.2.2.1.2.10=OctetString:"eth1"] -0s result: no error - == walk/v1-bulk 0s client: 1 root=".1.3.6.1.2.1.1" bulk=true max-repetitions=0 0s values: [] diff --git a/transport.go b/transport.go index 4834d60..bdeb895 100644 --- a/transport.go +++ b/transport.go @@ -13,25 +13,28 @@ import ( "time" ) -// Connect readies the client and opens its connection, a UDP socket connected -// to Target and Port (see the package documentation), the only connection a -// client has; a client connects before its requests. ctx bounds Connect only, -// its lookup of Target and its dial, with Timeout; each request takes its own. -// It sends nothing, so it succeeds whether or not an agent answers. The new -// connection replaces the client's, which Connect closes; when Connect fails, -// the client keeps the connection it had. A nil ctx fails Connect before it -// changes the client. +// Connect opens the client's connection, a UDP socket connected to the +// configuration's Target and Port (see the package documentation), the only +// connection a client has; a client connects before its requests. ctx bounds +// Connect only, its lookup of Target and its dial, with Timeout; each request +// takes its own. It sends nothing, so it succeeds whether or not an agent +// 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 { if ctx == nil { return errNilContext } - if err := x.prepare(); err != nil { - return err + if x.config.Target == "" { + return errNoTarget } - conn, err := dial(ctx, x.Timeout, net.JoinHostPort(x.Target, strconv.Itoa(int(x.Port)))) + conn, err := dial(ctx, x.config.Timeout, net.JoinHostPort(x.config.Target, strconv.Itoa(int(x.config.Port)))) if err != nil { return fmt.Errorf("error establishing connection to host: %w", err) } + if x.rx == nil { + x.rx = new(receiveBuffer) + } x.mu.Lock() old := x.conn x.conn, x.closed = conn, false @@ -151,10 +154,11 @@ func (x *Client) interrupt(seq uint64) { } // errNoConn is the error of a request on a client Connect never connected -// (and Close never closed), errClosed after Close, and errNilContext of a -// request or Connect given a nil context. +// (and Close never closed), errClosed after Close, errNilContext of a request +// or Connect given a nil context, and errNoTarget of Connect without a Target. var ( errNoConn = errors.New("the client is not connected: call Connect first") + errNoTarget = errors.New("Config.Target is empty") errClosed = fmt.Errorf("the client was closed: %w", net.ErrClosed) errNilContext = errors.New("nil context") ) @@ -192,8 +196,7 @@ type transport interface { } // dial opens a UDP socket connected to address, "host:port", within ctx and -// timeout, which bound the dial and its lookup of the host's name together; a -// zero timeout sets no limit. +// timeout, which bound the dial and its lookup of the host's name together. func dial(ctx context.Context, timeout time.Duration, address string) (*net.UDPConn, error) { dialer := net.Dialer{Timeout: timeout} conn, err := dialer.DialContext(ctx, "udp", address) diff --git a/transport_test.go b/transport_test.go index 2e68775..272be31 100644 --- a/transport_test.go +++ b/transport_test.go @@ -28,55 +28,49 @@ type connectResult struct { err string // "" for no error connected bool // the client has a connection local string // the IP of the connection's local address - maxOids int // MaxOids after Connect: the default once it readied the client } -// TestConnect pins how Connect validates the client and dials, on a loopback -// socket. +// TestConnect pins how Connect checks the client's Target and dials, on a +// loopback socket. func TestConnect(t *testing.T) { udpPort := unusedUDPPort(t) canceled, cancel := context.WithCancel(context.Background()) cancel() tests := map[string]struct { - setup func(x *Client) - ctx context.Context // background unless set - nil bool // a nil context - want connectResult + target *string // 127.0.0.1 unless set + ctx context.Context // background unless set + nil bool // a nil context + want connectResult }{ "udp": { - want: connectResult{connected: true, local: "127.0.0.1", maxOids: MaxOids}, - }, - "invalid parameters": { - setup: func(x *Client) { x.MaxOids = -1 }, - want: connectResult{err: "field MaxOids cannot be less than 0", maxOids: -1}, - }, - "negative timeout": { - setup: func(x *Client) { x.Timeout = -time.Second }, - want: connectResult{ - err: "error establishing connection to host: dial udp 127.0.0.1:" + strconv.Itoa(int(udpPort)) + ": i/o timeout", - maxOids: MaxOids, - }, + want: connectResult{connected: true, local: "127.0.0.1"}, }, "canceled context": { ctx: canceled, want: connectResult{ - err: "error establishing connection to host: dial udp 127.0.0.1:" + strconv.Itoa(int(udpPort)) + ": operation was canceled", - maxOids: MaxOids, + err: "error establishing connection to host: dial udp 127.0.0.1:" + strconv.Itoa(int(udpPort)) + ": operation was canceled", }, }, - // A nil context fails Connect before it readies the client or dials. + // An empty Target fails Connect before it dials. + "empty target": { + target: new(""), + want: connectResult{err: "Config.Target is empty"}, + }, + // A nil context fails Connect before it checks the Target or dials. "nil context": { - nil: true, - want: connectResult{err: "nil context"}, + target: new(""), + nil: true, + want: connectResult{err: "nil context"}, }, } for name, tc := range tests { t.Run(name, func(t *testing.T) { - x := &Client{Target: "127.0.0.1", Port: udpPort, Version: Version2c, Community: "public", Timeout: time.Second} - if tc.setup != nil { - tc.setup(x) + config := Config{Target: "127.0.0.1", Port: udpPort, Version: Version2c, Community: "public", Timeout: time.Second} + if tc.target != nil { + config.Target = *tc.target } + x := mustClient(config) ctx := cmp.Or(tc.ctx, context.Background()) if tc.nil { ctx = nil @@ -85,7 +79,6 @@ func TestConnect(t *testing.T) { if err := x.Connect(ctx); err != nil { got.err = err.Error() } - got.maxOids = x.MaxOids if x.conn != nil { got.connected = true host, _, err := net.SplitHostPort(x.conn.(*net.UDPConn).LocalAddr().String()) @@ -98,55 +91,38 @@ func TestConnect(t *testing.T) { } } -// TestUDPAgentAddress checks where a request goes after Port changed from -// agent A's to agent B's: to A, the peer the socket Connect dialed. -func TestUDPAgentAddress(t *testing.T) { - agent := func(name string) uint16 { - port, _ := udpAgent(t, func(_ int, req []byte) []byte { - return replyTo(req, nil, VarBind{Name: engineOID, Value: OctetStringValue([]byte(name))}) - }) - return port - } - portA, portB := agent("A"), agent("B") - x := &Client{ - Target: "127.0.0.1", Port: portA, Version: Version2c, Community: "public", - Timeout: 500 * time.Millisecond, - } +// TestConnectDefaultPort checks that Connect dials port 161 when Port is zero: +// NewClient's default. +func TestConnectDefaultPort(t *testing.T) { + x := mustClient(Config{Target: "127.0.0.1", Version: Version2c, Community: "public"}) require.NoError(t, x.Connect(context.Background())) defer x.Close() - x.Port = portB - - res, err := x.Get(context.Background(), []string{engineOID}) - require.NoError(t, err) - require.Len(t, res.VarBinds, 1) - got, _ := res.VarBinds[0].Value.Bytes() - assert.Equal(t, "A", string(got)) + remote, ok := x.conn.(*net.UDPConn).RemoteAddr().(*net.UDPAddr) + require.True(t, ok) + assert.Equal(t, 161, remote.Port) } -// TestRequestResolvesNoName checks that a request resolves no name: after -// Target changed to a name since Connect, it goes over the socket Connect -// dialed, with no lookup. +// TestRequestResolvesNoName checks that a request resolves no name: Connect +// looks up a Target that is a name, and a request then goes over the socket +// Connect dialed, with no lookup, while the name no longer resolves. func TestRequestResolvesNoName(t *testing.T) { - var lookups atomic.Int32 - defaultResolver := net.DefaultResolver - net.DefaultResolver = &net.Resolver{PreferGo: true, Dial: func(context.Context, string, string) (net.Conn, error) { - lookups.Add(1) - return nil, errors.New("codec: no lookups during a request") - }} - defer func() { net.DefaultResolver = defaultResolver }() - + dns := newStubDNS(t) port, _ := udpAgent(t, func(_ int, req []byte) []byte { return replyTo(req, nil, sysDescr) }) - x := &Client{ - Target: "127.0.0.1", Port: port, Version: Version2c, Community: "public", + x := mustClient(Config{ + Target: "agent.codec.invalid.", Port: port, Version: Version2c, Community: "public", Timeout: 500 * time.Millisecond, - } + }) require.NoError(t, x.Connect(context.Background())) defer x.Close() - x.Target = "agent.invalid" + dns.answering.Store(false) - _, err := x.Get(context.Background(), []string{engineOID}) + // A lookup now waits in the stub DNS: the context bounds a request that + // would make one. + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + _, err := x.Get(ctx, []string{engineOID}) require.NoError(t, err) - assert.Equal(t, int32(0), lookups.Load(), "lookups") + assert.Empty(t, dns.held, "lookups during the request") } // TestRetryOnConnectedSocket checks, on a loopback socket, a retry over the @@ -159,10 +135,10 @@ func TestRetryOnConnectedSocket(t *testing.T) { } return replyTo(req, nil, sysDescr) }) - x := &Client{ + x := mustClient(Config{ Target: "127.0.0.1", Port: port, Version: Version2c, Community: "public", Timeout: 200 * time.Millisecond, Retries: 1, - } + }) require.NoError(t, x.Connect(context.Background())) defer x.Close() @@ -195,10 +171,10 @@ func TestConnectIPv6Target(t *testing.T) { _ = agent.Close() <-served }() - x := &Client{ + x := mustClient(Config{ Target: "::1", Port: uint16(agent.LocalAddr().(*net.UDPAddr).Port), //nolint:gosec // a UDP port Version: Version2c, Community: "public", Timeout: 500 * time.Millisecond, - } + }) require.NoError(t, x.Connect(context.Background())) defer x.Close() remote := x.conn.(*net.UDPConn).RemoteAddr() @@ -216,10 +192,10 @@ func TestConnectedSocketOtherSource(t *testing.T) { srvr, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}) require.NoError(t, err) defer srvr.Close() - x := &Client{ + x := mustClient(Config{ Target: "127.0.0.1", Port: uint16(srvr.LocalAddr().(*net.UDPAddr).Port), //nolint:gosec // a UDP port Version: Version2c, Community: "public", Timeout: 100 * time.Millisecond, Retries: 2, - } + }) require.NoError(t, x.Connect(context.Background())) defer x.Close() go serveResponses(t, srvr, x, sendFromNewSocket) @@ -341,20 +317,22 @@ func TestConnectLookupWithinBounds(t *testing.T) { dns.answering.Store(false) ctx, cancel := context.WithCancel(context.Background()) defer cancel() - x := &Client{ + x := mustClient(Config{ Target: "agent.codec.invalid.", Port: 161, Version: Version2c, Community: "public", Timeout: bound.timeout, - } + }) result := make(chan error, 1) go func() { result <- x.Connect(ctx) }() dns.awaitHeld(t) if bound.cancel { cancel() } + // Well within the 1 s default Timeout, so that the bound is the + // configured one. select { case err := <-result: assert.ErrorIs(t, err, bound.want) - case <-time.After(2 * time.Second): + case <-time.After(500 * time.Millisecond): dns.release() t.Errorf("Connect waits for the lookup; after its release: %v", <-result) } @@ -380,7 +358,7 @@ func (c *closeErrConn) Close() error { // and leaves no connection, and that a client without one closes cleanly: // one whose connection Close already closed, and one that never had any. func TestCloseOnce(t *testing.T) { - assert.NoError(t, (&Client{}).Close(), "a client that never had a connection") + assert.NoError(t, mustClient(Config{}).Close(), "a client that never had a connection") c := &closeErrConn{} x := &Client{conn: c} assert.ErrorIs(t, x.Close(), errCloseConn) @@ -399,8 +377,10 @@ func TestConnectReplacesConnection(t *testing.T) { connNil bool firstOpen bool // the first connection is still open } + canceled, cancel := context.WithCancel(context.Background()) + cancel() tests := map[string]struct { - failDial bool + failDial bool // the second Connect's dial fails: its context is canceled want outcome }{ "opens": {want: outcome{}}, @@ -411,18 +391,19 @@ func TestConnectReplacesConnection(t *testing.T) { agent, err := net.ListenPacket("udp4", "127.0.0.1:0") require.NoError(t, err) defer agent.Close() - x := &Client{ + x := mustClient(Config{ Target: "127.0.0.1", Port: uint16(agent.LocalAddr().(*net.UDPAddr).Port), //nolint:gosec // a UDP port Version: Version2c, Community: "public", Timeout: time.Second, - } + }) require.NoError(t, x.Connect(context.Background())) first := x.conn defer first.Close() defer x.Close() + ctx := context.Background() if tc.failDial { - x.Timeout = -time.Second + ctx = canceled } - err = x.Connect(context.Background()) + err = x.Connect(ctx) assert.Equal(t, tc.want, outcome{ err: err != nil, connFirst: x.conn == first, @@ -443,11 +424,8 @@ func TestRequestWithoutConnection(t *testing.T) { before func(t *testing.T, x *Client) want error }{ - "never connected": {want: errNoConn}, - // Connect, which would have checked the user, never ran. - "SNMPv3 never connected, a user of an unknown protocol": {v3: true, want: errNoConn, before: func(_ *testing.T, x *Client) { - x.User.AuthProtocol = 99 - }}, + "never connected": {want: errNoConn}, + "SNMPv3 never connected": {v3: true, want: errNoConn}, "after Close": {want: errClosed, before: func(t *testing.T, x *Client) { require.NoError(t, x.Connect(context.Background())) require.NoError(t, x.Close()) @@ -459,14 +437,14 @@ func TestRequestWithoutConnection(t *testing.T) { } for name, tc := range tests { t.Run(name, func(t *testing.T) { - x := &Client{ + config := Config{ Target: "127.0.0.1", Port: unusedUDPPort(t), Version: Version2c, Community: "public", - Timeout: time.Second, MaxOids: MaxOids, + Timeout: time.Second, } if tc.v3 { - x.Version, x.SecurityLevel = Version3, NoAuthNoPriv - x.User = User{Name: "codec"} + config.Version, config.SecurityLevel, config.User = Version3, NoAuthNoPriv, User{Name: "codec"} } + x := mustClient(config) if tc.before != nil { tc.before(t, x) } @@ -496,7 +474,7 @@ func TestCloseDuringRequest(t *testing.T) { } return replyTo(req, nil, sysDescr) }) - x := &Client{Target: "127.0.0.1", Port: port, Community: "public", Version: Version2c, Timeout: 10 * time.Second} + x := mustClient(Config{Target: "127.0.0.1", Port: port, Community: "public", Version: Version2c, Timeout: 10 * time.Second}) require.NoError(t, x.Connect(context.Background())) defer x.Close() @@ -539,7 +517,7 @@ func TestCloseDuringWalk(t *testing.T) { } return replyTo(req, nil, VarBind{Name: next, Value: OctetStringValue([]byte("codec"))}) }) - x := &Client{Target: "127.0.0.1", Port: port, Community: "public", Version: Version2c, Timeout: 10 * time.Second} + x := mustClient(Config{Target: "127.0.0.1", Port: port, Community: "public", Version: Version2c, Timeout: 10 * time.Second}) require.NoError(t, x.Connect(context.Background())) defer x.Close() @@ -581,7 +559,7 @@ func closeOnRelease(x *Client, n int, release func()) *sync.WaitGroup { func TestCloseDuringConnect(t *testing.T) { port, _ := udpAgent(t, func(_ int, req []byte) []byte { return replyTo(req, nil, sysDescr) }) for range 20 { - x := &Client{Target: "127.0.0.1", Port: port, Version: Version2c, Community: "public", Timeout: 10 * time.Second} + x := mustClient(Config{Target: "127.0.0.1", Port: port, Version: Version2c, Community: "public", Timeout: 10 * time.Second}) require.NoError(t, x.Connect(context.Background())) closed := make(chan error, 1) go func() { closed <- x.Close() }() @@ -610,10 +588,10 @@ func TestContextCancelDuringRequest(t *testing.T) { }) ctx, cancel := context.WithCancel(context.Background()) defer cancel() - x := &Client{ + x := mustClient(Config{ Target: "127.0.0.1", Port: port, Version: Version2c, Community: "public", Timeout: 10 * time.Second, - } + }) require.NoError(t, x.Connect(context.Background())) defer x.Close() @@ -637,10 +615,10 @@ func TestContextCancelDuringRequest(t *testing.T) { func TestConnectContextBoundsConnectOnly(t *testing.T) { port, _ := udpAgent(t, func(_ int, req []byte) []byte { return replyTo(req, nil, sysDescr) }) ctx, cancel := context.WithCancel(context.Background()) - x := &Client{ + x := mustClient(Config{ Target: "127.0.0.1", Port: port, Version: Version2c, Community: "public", Timeout: 10 * time.Second, - } + }) require.NoError(t, x.Connect(ctx)) defer x.Close() cancel() diff --git a/usm_characterization_test.go b/usm_characterization_test.go index 3c84f0f..c00c6c7 100644 --- a/usm_characterization_test.go +++ b/usm_characterization_test.go @@ -481,7 +481,7 @@ func TestUSMAuthFieldEmpty(t *testing.T) { in := buf[:len(msg):len(buf)] _, err := decoder().DecodeMessage(in) require.NoError(t, err, "DecodeMessage") - _, _, err = receiverAt(t, []byte(usmCharEngineID), decoder().User).Receive(in) + _, _, err = receiverAt(t, []byte(usmCharEngineID), decoder().config.User).Receive(in) assert.ErrorIs(t, err, errNotAuthentic, "Receive") assert.Equal(t, append(bytes.Clone(msg), bytes.Repeat([]byte{0xaa}, spare)...), buf, "the input and the octets after it") }) @@ -582,9 +582,8 @@ func TestUSMPasswordCache(t *testing.T) { } } -// TestUSMValidate pins which SNMPv3 users a Client rejects before decoding or -// encoding, and the messages it rejects them with. The users that pass decode -// a noAuthNoPriv message. +// TestUSMValidate pins which SNMPv3 users NewClient rejects, and the messages +// it rejects them with. The users that pass decode a noAuthNoPriv message. func TestUSMValidate(t *testing.T) { msg := craftedV3NoAuth(craftedScopedResp) @@ -598,29 +597,29 @@ func TestUSMValidate(t *testing.T) { }, "noAuthNoPriv without user": { flags: NoAuthNoPriv, user: User{}, - wantErr: "User.Name is required", + wantErr: "Config.User.Name is required", }, "noAuthNoPriv with a user name of 32 octets": { flags: NoAuthNoPriv, user: User{Name: strings.Repeat("u", 32)}, }, "noAuthNoPriv with a user name of 33 octets": { flags: NoAuthNoPriv, user: User{Name: strings.Repeat("u", 33)}, - wantErr: "User.Name is 33 octets, more than 32", + wantErr: "Config.User.Name is 33 octets, more than 32", }, "authNoPriv": { flags: AuthNoPriv, user: User{Name: "u", AuthProtocol: SHA, AuthPassphrase: "p"}, }, "authNoPriv without protocol": { flags: AuthNoPriv, user: User{Name: "u", AuthPassphrase: "p"}, - wantErr: "User.AuthProtocol is required", + wantErr: "Config.User.AuthProtocol is required", }, "authNoPriv without passphrase": { flags: AuthNoPriv, user: User{Name: "u", AuthProtocol: SHA}, - wantErr: "User.AuthPassphrase is required when an authentication protocol is specified", + wantErr: "Config.User.AuthPassphrase is required when an authentication protocol is specified", }, "authNoPriv without user": { flags: AuthNoPriv, user: User{AuthProtocol: SHA, AuthPassphrase: "p"}, - wantErr: "User.Name is required", + wantErr: "Config.User.Name is required", }, "authPriv": { flags: AuthPriv, user: User{ @@ -630,39 +629,41 @@ func TestUSMValidate(t *testing.T) { }, "authPriv without privacy protocol": { flags: AuthPriv, user: User{Name: "u", AuthProtocol: SHA, AuthPassphrase: "p"}, - wantErr: "User.PrivProtocol is required", + wantErr: "Config.User.PrivProtocol is required", }, "authPriv without authentication protocol": { flags: AuthPriv, user: User{Name: "u", PrivProtocol: AES, PrivPassphrase: "q"}, - wantErr: "User.AuthProtocol is required", + wantErr: "Config.User.AuthProtocol is required", }, "authPriv without privacy passphrase": { flags: AuthPriv, user: User{Name: "u", AuthProtocol: SHA, AuthPassphrase: "p", PrivProtocol: AES}, - wantErr: "User.PrivPassphrase is required when a privacy protocol is specified", + wantErr: "Config.User.PrivPassphrase is required when a privacy protocol is specified", }, "authPriv without either passphrase": { flags: AuthPriv, user: User{Name: "u", AuthProtocol: SHA, PrivProtocol: AES}, - wantErr: "User.PrivPassphrase is required when a privacy protocol is specified", + wantErr: "Config.User.PrivPassphrase is required when a privacy protocol is specified", }, "noAuthNoPriv with a privacy protocol and no passphrase": { flags: NoAuthNoPriv, user: User{Name: "u", PrivProtocol: AES}, - wantErr: "User.PrivPassphrase is required when a privacy protocol is specified", + wantErr: "Config.User.PrivPassphrase is required when a privacy protocol is specified", }, "privacy flag without authentication flag": { flags: 0x2, user: User{Name: "u"}, - wantErr: "validate: SecurityLevel must be populated with an appropriate security level", + wantErr: "Config.SecurityLevel SecurityLevel(2) is not NoAuthNoPriv, AuthNoPriv or AuthPriv", }, } for name, tc := range tests { t.Run(name, func(t *testing.T) { - x := &Client{Version: Version3, SecurityLevel: tc.flags, User: tc.user} - _, err := x.DecodeMessage(bytes.Clone(msg)) - if tc.wantErr == "" { - assert.NoError(t, err) + x, err := NewClient(Config{Version: Version3, SecurityLevel: tc.flags, User: tc.user}) + if tc.wantErr != "" { + assert.EqualError(t, err, tc.wantErr) + assert.Nil(t, x) return } - assert.EqualError(t, err, tc.wantErr) + require.NoError(t, err) + _, err = x.DecodeMessage(bytes.Clone(msg)) + assert.NoError(t, err) }) } } diff --git a/usm_fuzz_test.go b/usm_fuzz_test.go index 90ace59..6fa7b10 100644 --- a/usm_fuzz_test.go +++ b/usm_fuzz_test.go @@ -102,7 +102,7 @@ func FuzzDecodeV3(f *testing.F) { decode func(data []byte) (*Message, error) }{ {fuzzDecode, func(data []byte) (*Message, error) { - return (&Client{User: p.user()}).DecodeMessage(data) + return mustClient(Config{User: p.user()}).DecodeMessage(data) }}, {fuzzRegistered, func(data []byte) (*Message, error) { return usmFuzzReceive(t, receiverAt(t, []byte(usmCharEngineID), p.user()), data) diff --git a/v3.go b/v3.go index 5dc7f7d..12ceb46 100644 --- a/v3.go +++ b/v3.go @@ -55,12 +55,6 @@ func (f SecurityLevel) valid() bool { return f == NoAuthNoPriv || f == AuthNoPri // writes it, and the decoder accepts no other (RFC 3412 section 7.2 step 4). const usmSecurityModel = 3 -// validateParametersV3 checks the client's SNMPv3 configuration: a user that -// fits SecurityLevel. -func (x *Client) validateParametersV3() error { - return x.User.validate(x.SecurityLevel) -} - // sign writes the digest of the marshalled SNMPv3 message msg into the // content of its msgAuthenticationParameters, at offset auth, with keys when // the level asks for authentication; a key that does not fit the protocol is @@ -229,10 +223,6 @@ type v3Wire struct { // 3412 section 7.2 step 4). var errNotUSM = errors.New("error parsing SNMPV3: the security model is not USM") -// errInvalidLevel is the error of a client's security level that is not one -// of the three (validate). -var errInvalidLevel = errors.New("validate: SecurityLevel must be populated with an appropriate security level") - // errMsgFlags is the error of an SNMPv3 msgFlags that is not an OCTET STRING // of one octet (RFC 3412 section 6). var errMsgFlags = errors.New("error parsing SNMPV3 msgFlags: not an OCTET STRING of one octet") diff --git a/v3_discovery_test.go b/v3_discovery_test.go index 0ea654f..85645fa 100644 --- a/v3_discovery_test.go +++ b/v3_discovery_test.go @@ -215,11 +215,9 @@ func (m *mockAgentUnknownUserNames) marshalResponse(req *Message) ([]byte, error // NoAuthNoPriv SNMPv3, which knows no engine yet, so that the first request // starts with engine-ID discovery (discoveryPacket). func newV3NoAuthClientForDiscoveryTest(port uint16) *Client { - gs := newTestClientV3(NoAuthNoPriv, User{Name: "testUser"}) - gs.Target = "127.0.0.1" - gs.Port = port - gs.Retries = 0 - return gs + config := testConfigV3(NoAuthNoPriv, User{Name: "testUser"}) + config.Target, config.Port, config.Retries = "127.0.0.1", port, 0 + return mustClient(config) } // setupDiscoveryTest creates a mock agent and a connected SNMPv3 client for @@ -252,8 +250,8 @@ func TestV3DiscoveryUnknownUserNames(t *testing.T) { // NewMessage produces the same packet shape that Get() passes to // negotiateInitialSecurityParameters internally. pkt := ts.NewMessage(GetRequest, nil, 0, 0) - require.NoError(t, ts.startEngine()) - answer, err := ts.negotiateInitialSecurityParameters(new(ts.prepareRequest(context.Background())), pkt) + ts.startEngine() + answer, err := ts.negotiateInitialSecurityParameters(context.Background(), pkt) require.NoError(t, err, "negotiateInitialSecurityParameters must succeed even when the device "+ "responds with usmStatsUnknownUserNames during engine-ID discovery") require.Nil(t, answer, "a discovery that succeeds returns no answer") @@ -307,8 +305,8 @@ func TestV3DiscoveryUnknownUserNamesNoEngineID(t *testing.T) { t.Cleanup(func() { _ = ts.Close() }) pkt := ts.NewMessage(GetRequest, nil, 0, 0) - require.NoError(t, ts.startEngine()) - answer, err := ts.negotiateInitialSecurityParameters(new(ts.prepareRequest(context.Background())), pkt) + ts.startEngine() + answer, err := ts.negotiateInitialSecurityParameters(context.Background(), pkt) require.ErrorIs(t, err, ErrUnknownUsername, "ErrUnknownUsername must not be suppressed when the Report carries an empty engine ID") require.NotNil(t, answer, "the discovery returns the Report that ended it") @@ -354,8 +352,8 @@ func TestV3DiscoveryUnknownUserNamesOtherUser(t *testing.T) { t.Cleanup(func() { _ = ts.Close() }) pkt := ts.NewMessage(GetRequest, nil, 0, 0) - require.NoError(t, ts.startEngine()) - answer, err := ts.negotiateInitialSecurityParameters(new(ts.prepareRequest(context.Background())), pkt) + ts.startEngine() + answer, err := ts.negotiateInitialSecurityParameters(context.Background(), pkt) require.ErrorIs(t, err, errUnknownUser) require.Nil(t, answer, "no answer ended the discovery: it timed out") require.Empty(t, ts.engine.engineID) diff --git a/v3_parse_test.go b/v3_parse_test.go index c0babd1..b565a7b 100644 --- a/v3_parse_test.go +++ b/v3_parse_test.go @@ -240,7 +240,7 @@ func TestV3ReceiverRules(t *testing.T) { return err }}, {"DecodeMessage", func(u User, in []byte) error { - _, err := (&Client{User: u}).DecodeMessage(in) + _, err := mustClient(Config{User: u}).DecodeMessage(in) return err }}, } @@ -321,7 +321,7 @@ func TestV3DecodeKeyDerivation(t *testing.T) { user.PrivPassphrase = "receiver-priv-pass" keys, err := user.localize([]byte(usmCharEngineID)) require.NoError(t, err) - x := &Client{Version: Version3, SecurityLevel: AuthPriv, User: user} + x := mustClient(Config{Version: Version3, SecurityLevel: AuthPriv, User: user}) req := &Message{ Version: Version3, SecurityLevel: AuthPriv, SecurityParameters: signedTestHeader(usmCharEngineID, "codec-user"), MsgID: 7, PDUType: GetRequest, @@ -347,7 +347,7 @@ func TestV3ReplyDecode(t *testing.T) { user := signedTestUser(SHA, priv, "codec-user") keys, err := user.localize([]byte(usmCharEngineID)) require.NoError(t, err) - x := &Client{Version: Version3, SecurityLevel: flags, User: user} + x := mustClient(Config{Version: Version3, SecurityLevel: flags, User: user}) req := &Message{ Version: Version3, SecurityLevel: flags, SecurityParameters: signedTestHeader(usmCharEngineID, "codec-user"), MsgID: 7, PDUType: GetRequest, @@ -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: &Client{Version: Version2c}, packet: &Message{Version: Version2c, PDUType: GetRequest}} + e := &exchange{x: mustClient(Config{Version: Version2c}), packet: &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)))))) @@ -494,7 +494,7 @@ func TestV3ReplyDecode(t *testing.T) { }) t.Run("authNoPriv reply to a noAuthNoPriv request of a user without protocols", func(t *testing.T) { - x := &Client{Version: Version3, SecurityLevel: NoAuthNoPriv, User: User{Name: "codec-user"}} + x := mustClient(Config{Version: Version3, SecurityLevel: NoAuthNoPriv, User: User{Name: "codec-user"}}) req := &Message{ Version: Version3, SecurityLevel: NoAuthNoPriv, SecurityParameters: signedTestHeader(usmCharEngineID, "codec-user"), MsgID: 7, PDUType: GetRequest, @@ -597,7 +597,7 @@ func TestV3DigestField(t *testing.T) { } for name, tc := range tests { t.Run(name, func(t *testing.T) { - _, _, err := receiverFor(t, tc.in, decoder().User).Receive(tc.in) + _, _, err := receiverFor(t, tc.in, decoder().config.User).Receive(tc.in) require.ErrorIs(t, err, tc.want) }) } diff --git a/v3_usm.go b/v3_usm.go index 1569126..5251c6f 100644 --- a/v3_usm.go +++ b/v3_usm.go @@ -274,15 +274,17 @@ func (u *User) levelFloor() SecurityLevel { return NoAuthNoPriv } -// validate checks u for the security level: valid protocols, one of the three -// levels, the protocols the level needs, a name of 1..32 octets, and a -// passphrase for each protocol. +// validate checks u for the security level, as NewClient checks a Config's +// User and SecurityLevel: valid protocols, one of the three levels, the +// protocols the level needs, a name of 1..32 octets, and a passphrase for each +// protocol. Its errors name the field as a path from the Config, without +// "Config.": User.Name, SecurityLevel. func (u *User) validate(level SecurityLevel) error { if err := u.checkProtocols(); err != nil { return err } if !level.valid() { - return errInvalidLevel + return fmt.Errorf("SecurityLevel %v is not NoAuthNoPriv, AuthNoPriv or AuthPriv", level) } if err := checkLevel(u.AuthProtocol, u.PrivProtocol, level); err != nil { return err diff --git a/v3_usm_test.go b/v3_usm_test.go index 85a47ca..c2ae09c 100644 --- a/v3_usm_test.go +++ b/v3_usm_test.go @@ -201,10 +201,9 @@ func TestUSMUnsupportedProtocols(t *testing.T) { for name, tc := range tests { t.Run(name, func(t *testing.T) { t.Run("validate", func(t *testing.T) { - x := &Client{Version: Version3, SecurityLevel: tc.flags, User: user(tc.auth, tc.priv)} - // Validation runs before decoding, so an empty message reaches it. - _, err := x.DecodeMessage(nil) - assert.EqualError(t, err, tc.wantErr) + x, err := NewClient(Config{Version: Version3, SecurityLevel: tc.flags, User: user(tc.auth, tc.priv)}) + assert.EqualError(t, err, "Config."+tc.wantErr) + assert.Nil(t, x) }) t.Run("keys", func(t *testing.T) { u := user(tc.auth, tc.priv) @@ -623,7 +622,7 @@ func TestUSMFIPS140OnlyDecrypt(t *testing.T) { require.NoError(t, err) }) client := func() *Client { - return &Client{Version: Version3, SecurityLevel: AuthPriv, User: user} + return mustClient(Config{Version: Version3, SecurityLevel: AuthPriv, User: user}) } paths := map[string]func() error{ "receiver": func() error { diff --git a/value_test.go b/value_test.go index 45a8a93..8880303 100644 --- a/value_test.go +++ b/value_test.go @@ -239,7 +239,7 @@ func TestDecodedHeaderCopiesInput(t *testing.T) { user := codecUser(SHA, AES) decoders := map[string]func(t *testing.T, in []byte) (*Message, error){ "DecodeMessage": func(_ *testing.T, in []byte) (*Message, error) { - return (&Client{Version: Version3, SecurityLevel: AuthPriv, User: user}).DecodeMessage(in) + return mustClient(Config{Version: Version3, SecurityLevel: AuthPriv, User: user}).DecodeMessage(in) }, "Receive": func(t *testing.T, in []byte) (*Message, error) { return receiveMessage(receiverAt(t, []byte(codecEngineID), user), in) diff --git a/walk.go b/walk.go index 0f5d9f0..e5e2809 100644 --- a/walk.go +++ b/walk.go @@ -155,7 +155,7 @@ 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.Version == Version1 { + if w.x.config.Version == Version1 { return nil, errors.New("GETBULK not supported in SNMPv1") } maxReps = w.maxReps