package netconf
import (
"iter"
)
const (
baseCap = "urn:ietf:params:netconf:base"
stdCapPrefix = "urn:ietf:params:netconf:capability"
CapNetConf10 = baseCap + ":1.0"
CapNetConf11 = baseCap + ":1.1"
)
// DefaultCapabilities are the capabilities sent by the client during the hello
// exchange by the server.
var DefaultCapabilities = []string{
CapNetConf10,
CapNetConf11,
// XXX: these seems like server capabilities and i don't see why
// a client would need to send them
// "urn:ietf:params:netconf:capability:writable-running:1.0",
// "urn:ietf:params:netconf:capability:candidate:1.0",
// "urn:ietf:params:netconf:capability:confirmed-commit:1.0",
// "urn:ietf:params:netconf:capability:rollback-on-error:1.0",
// "urn:ietf:params:netconf:capability:startup:1.0",
// "urn:ietf:params:netconf:capability:url:1.0?scheme=http,ftp,file,https,sftp",
// "urn:ietf:params:netconf:capability:validate:1.0",
// "urn:ietf:params:netconf:capability:xpath:1.0",
// "urn:ietf:params:netconf:capability:notification:1.0",
// "urn:ietf:params:netconf:capability:interleave:1.0",
// "urn:ietf:params:netconf:capability:with-defaults:1.0",
}
// ExpandCapability will automatically add the standard capability prefix of
// `urn:ietf:params:netconf:capability` if not already present.
func ExpandCapability(s string) string {
if s == "" {
return ""
}
if s[0] != ':' {
return s
}
return stdCapPrefix + s
}
type CapabilitySet struct {
caps map[string]struct{}
}
// NewCapabilitySet creates a new CapabilitySet and adds any provided
// capabilities.
func NewCapabilitySet(capabilities ...string) CapabilitySet {
cs := CapabilitySet{
caps: make(map[string]struct{}),
}
for _, cap := range capabilities {
cap = ExpandCapability(cap)
cs.caps[cap] = struct{}{}
}
return cs
}
// Len returns the number of capabilities in the set.
func (cs CapabilitySet) Len() int {
return len(cs.caps)
}
// All returns an iterator over all capabilities in the set. If you want a
// slice use `slices.Collect(cs.All())`.
func (cs CapabilitySet) All() iter.Seq[string] {
return func(yield func(string) bool) {
for cap := range cs.caps {
if !yield(cap) {
return
}
}
}
}
// Has will return true if the capability is present in the set. The given
// capability is expanded with `ExpandCapability` if needed.
func (cs CapabilitySet) Has(s string) bool {
s = ExpandCapability(s)
_, ok := cs.caps[s]
return ok
}
package netconf
import (
"encoding/xml"
"errors"
"fmt"
"io"
"slices"
"strings"
"time"
)
// RPC maps the xml value of <rpc> in RFC6241
type RPC struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 rpc"`
// Managed by the session. Will be overwritten when sent on the wire.
MessageID string `xml:"message-id,attr"`
// User-defined attributes (e.g. xmlns:ex="..."). Per RFC6241 sec 7.3, these
// must be preserved and reflected in the associated <rpc-reply>.
Attributes []xml.Attr `xml:",attr"`
// The inner XML of the RPC message (e.g. <get-config>, <edit-config>)
Operation any `xml:",innerxml"` // The operation payload (e.g. <get-config>)
}
// RPCOption represents an option that can be passed to NewRPC to customize the
// created RPC message.
type RPCOption interface {
apply(*RPC)
}
type attributesOpt []xml.Attr
func (o attributesOpt) apply(rpc *RPC) {
rpc.Attributes = append(rpc.Attributes, o...)
}
// WithAttributes adds the given XML attributes to be added to the <rpc>
// element. NETCONF servers are required to reflect these attributes in the
// associated <rpc-reply>.
func WithAttributes(attrs ...xml.Attr) RPCOption { return attributesOpt(attrs) }
// NewRPC creates a new RPC message with the given operation as the body.
func NewRPC(op any, opts ...RPCOption) *RPC {
rpc := &RPC{
Operation: op,
}
for _, opt := range opts {
opt.apply(rpc)
}
return rpc
}
// Clone does a shallow copy of the RPC. Operation is not deeply copied.
func (r *RPC) Clone() *RPC {
return &RPC{
MessageID: r.MessageID,
Attributes: slices.Clone(r.Attributes),
Operation: r.Operation,
}
}
// RPCReply maps the xml value of <rpc-reply> in RFC6241.
type RPCReply struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 rpc-reply"`
// The message-id must match that of the associated <rpc>
MessageID string `xml:"message-id,attr"`
// Additional attributes on the <rpc-reply>.
Attributes []xml.Attr `xml:",attr"`
RPCErrors RPCErrors `xml:"rpc-error,omitempty"`
}
// Error types, severities, and tags as defined in RFC6241 sec 6.4.1
type ErrSeverity string
const (
SevError ErrSeverity = "error"
SevWarning ErrSeverity = "warning"
)
// ErrType represents the error-type of a NETCONF RPC error.
type ErrType string
const (
ErrTypeTransport ErrType = "transport"
ErrTypeRPC ErrType = "rpc"
ErrTypeProtocol ErrType = "protocol"
ErrTypeApp ErrType = "app"
)
// ErrTag represents the error-tag of a NETCONF RPC error.
type ErrTag string
const (
ErrInUse ErrTag = "in-use"
ErrInvalidValue ErrTag = "invalid-value"
ErrTooBig ErrTag = "too-big"
ErrMissingAttribute ErrTag = "missing-attribute"
ErrBadAttribute ErrTag = "bad-attribute"
ErrUnknownAttribute ErrTag = "unknown-attribute"
ErrMissingElement ErrTag = "missing-element"
ErrBadElement ErrTag = "bad-element"
ErrUnknownElement ErrTag = "unknown-element"
ErrUnknownNamespace ErrTag = "unknown-namespace"
ErrAccesDenied ErrTag = "access-denied"
ErrLockDenied ErrTag = "lock-denied"
ErrResourceDenied ErrTag = "resource-denied"
ErrRollbackFailed ErrTag = "rollback-failed"
ErrDataExists ErrTag = "data-exists"
ErrDataMissing ErrTag = "data-missing"
ErrOperationNotSupported ErrTag = "operation-not-supported"
ErrOperationFailed ErrTag = "operation-failed"
ErrPartialOperation ErrTag = "partial-operation"
ErrMalformedMessage ErrTag = "malformed-message"
)
// RPCError maps the xml value of <rpc-error> in RFC6241 sec 6.4.1.
type RPCError struct {
Type ErrType `xml:"error-type"`
Tag ErrTag `xml:"error-tag"`
Severity ErrSeverity `xml:"error-severity"`
AppTag string `xml:"error-app-tag,omitempty"`
Path string `xml:"error-path,omitempty"`
Message string `xml:"error-message,omitempty"`
Info RawXML `xml:"error-info,omitempty"`
}
func (e RPCError) Error() string {
return fmt.Sprintf("netconf error: %s %s: %s", e.Type, e.Tag, e.Message)
}
// RPCErrors represents a list of RPCError returned from a NETCONF rpc-reply.
type RPCErrors []RPCError
// Filter returns a new RPCErrors slice containing only errors with the given
// severity.
func (errs RPCErrors) Filter(severity ErrSeverity) RPCErrors {
if len(errs) == 0 {
return nil
}
filteredErrs := make(RPCErrors, 0, len(errs))
for _, err := range errs {
if err.Severity != severity {
continue
}
filteredErrs = append(filteredErrs, err)
}
return filteredErrs
}
func (errs RPCErrors) Error() string {
if len(errs) == 0 {
return ""
}
if len(errs) == 1 {
return errs[0].Error()
}
var sb strings.Builder
sb.WriteString("multiple netconf errors:\n")
for i, err := range errs {
if i > 0 {
sb.WriteRune('\n')
}
sb.WriteString(err.Error())
}
return sb.String()
}
func (errs RPCErrors) Unwrap() error {
if len(errs) == 0 {
return nil
}
if len(errs) == 1 {
return errs[0]
}
unboxedErrs := make([]error, len(errs))
for i, err := range errs {
unboxedErrs[i] = err
}
return errors.Join(unboxedErrs...)
}
// Notification maps the xml value of <notification> in RFC5277
type Notification struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:notification:1.0 notification"`
EventTime time.Time `xml:"eventTime"`
}
// Hello maps the xml value of the <hello> message in RFC6241 sec 3.3.
type Hello struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 hello"`
SessionID uint64 `xml:"session-id,omitempty"`
Capabilities []string `xml:"capabilities>capability"`
}
// Message represents a generic NETCONF stream message. This could either be a
// response to a rpc invokcation (with the envelope og <rpc-reply>) or a
// notification message (with a envelope of <notification>).
//
// Messages MUST BE closed (with a call to Close(), or callind Decode() with
// will close for you) when no longer needed to release the session to process
// new messages.
type Message struct {
// Additional XML attributes from the envelope (rpc-reply or notification)
Attributes []xml.Attr // Any other attributes on the envelope
reader io.ReadCloser
messageID *string // cached message-id attribute
}
// MessageID returns the message-id attribute from the rpc-reply envelope. If
// the message doesn't have a message-id attribute (for example it is a
// notification), an empty string is returned.
func (d *Message) MessageID() string {
// check for a cached value first
if d.messageID != nil {
return *d.messageID
}
for _, attr := range d.Attributes {
if attr.Name.Local == "message-id" {
d.messageID = &attr.Value
return attr.Value
}
}
return ""
}
func (d *Message) Read(p []byte) (n int, err error) {
if d.reader == nil {
return 0, io.EOF
}
return d.reader.Read(p)
}
func (d *Message) Close() error {
if d.reader == nil {
return nil
}
return d.reader.Close()
}
// Decode will decode the response XML into the provided value v and then close
// the message releasing the session to process new messages.
func (d *Message) Decode(v any) (err error) {
defer func() {
err = errors.Join(err, d.Close())
}()
if err := xml.NewDecoder(d).Decode(v); err != nil {
return fmt.Errorf("failed to decode response: %w", err)
}
return err
}
// RawXML is a helper type for getting innerxml content as a byte slice.
type RawXML []byte
func (x *RawXML) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var inner struct {
Data []byte `xml:",innerxml"`
}
if err := d.DecodeElement(&inner, &start); err != nil {
return err
}
*x = inner.Data
return nil
}
func (x RawXML) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
inner := struct {
Data []byte `xml:",innerxml"`
}{
Data: []byte(x),
}
return e.EncodeElement(&inner, start)
}
package rpc
import (
"context"
"encoding/xml"
"fmt"
"nemith.io/netconf"
)
// Datastore represents a NETCONF configuration datastore as defined in
// RFC6241 section 7.1
type Datastore string
func (d Datastore) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
if d == "" {
return fmt.Errorf("datastore name cannot be empty")
}
for i := range len(d) {
c := d[i]
if (c < 'a' || c > 'z') &&
(c < 'A' || c > 'Z') &&
(c < '0' || c > '9') &&
c != '_' && c != '-' && c != '.' {
return fmt.Errorf("invalid datastore name: %q", d)
}
}
inner := struct {
Elem string `xml:",innerxml"`
}{Elem: "<" + string(d) + "/>"}
// EncodeElement(nil, ...) creates a self-closing tag <running/>
return e.EncodeElement(&inner, start)
}
const (
// Running configuration datastore. Required by RFC6241
Running Datastore = "running"
// Candidate configuration configuration datastore. Supported with the
// `:candidate` capability defined in RFC6241 section 8.3
Candidate Datastore = "candidate"
// Startup configuration configuration datastore. Supported with the
// `:startup` capability defined in RFC6241 section 8.7
Startup Datastore = "startup"
)
type URL string
func (u URL) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
v := struct {
URL string `xml:"url"`
}{string(u)}
return e.EncodeElement(&v, start)
}
// GetConfig implements the <get-config> rpc operation defined in [RFC6241 7.1].
// `source` is the datastore to query.
//
// [RFC6241 7.1]: https://www.rfc-editor.org/rfc/rfc6241.html#section-7.1
type GetConfig struct {
Source Datastore
Filter Filter
WithDefaults WithDefaultsMode
}
func (op GetConfig) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
req := struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 get-config"`
Source Datastore `xml:"source"`
Filter Filter `xml:"filter,omitempty"`
WithDefaults *withDefaultsElement `xml:",omitempty"`
}{
Source: op.Source,
Filter: op.Filter,
}
if op.WithDefaults != "" {
req.WithDefaults = &withDefaultsElement{Mode: op.WithDefaults}
}
return e.Encode(&req)
}
func (rpc GetConfig) Exec(ctx context.Context, session *netconf.Session) ([]byte, error) {
var reply GetConfigReply
if err := session.Exec(ctx, rpc, &reply); err != nil {
return nil, err
}
return reply.Config, nil
}
type GetConfigReply struct {
Config []byte
}
func (r *GetConfigReply) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
type dataWrapper struct {
Data struct {
Inner []byte `xml:",innerxml"`
} `xml:"data"`
}
var wrapper dataWrapper
if err := d.DecodeElement(&wrapper, &start); err != nil {
return err
}
r.Config = wrapper.Data.Inner
return nil
}
// DefaultOperation defines the strategies for merging configuration in a
// `<edit-config> operation`.
type DefaultOperation string
const (
// MergeConfig configuration elements are merged together at the level at
// which this specified. Can be used for config elements as well as default.
MergeConfig DefaultOperation = "merge"
// ReplaceConfig defines that the incoming config change should replace the
// existing config at the level which it is specified. This can be
// specified on individual config elements or set as the default strategy.
ReplaceConfig DefaultOperation = "replace"
// NoneOperation indicates that no default operation should be applied and
// nothing is applied to the target configuration unless there are
// operations defined on the configs subelements.
NoneOperation DefaultOperation = "none"
)
// TestOption defines the behavior for testing configuration before applying it
// in a `<edit-config>` operation.
type TestOption string
const (
// TestThenSet will validate the configuration and only if is is valid then
// apply the configuration to the datastore.
TestThenSet TestOption = "test-then-set"
// SetOnly will not do any testing before applying it.
SetOnly TestOption = "set"
// Test only will validatate the incoming configuration and return the
// results without modifying the underlying store.
TestOnly TestOption = "test-only"
)
// ErrorOption defines the behavior when an error is encountered during a
// `<edit-config>` operation.
type ErrorOption string
const (
// StopOnError will abort the `<edit-config>` operation on the first error.
StopOnError ErrorOption = "stop-on-error"
// ContinueOnError will continue to parse the configuration data even if an
// error is encountered. Errors are still recorded and reported in the
// reply.
ContinueOnError ErrorOption = "continue-on-error"
// RollbackOnError will restore the configuration back to before the
// `<edit-config>` operation took place. This requires the device to
// support the `:rollback-on-error` capability.
RollbackOnError ErrorOption = "rollback-on-error"
)
// EditConfig issues the `<edit-config>` operation defined in [RFC6241 7.2] for
// updating an existing target config datastore.
//
// [RFC6241 7.2]: https://www.rfc-editor.org/rfc/rfc6241.html#section-7.2
type EditConfig struct {
Target Datastore
DefaultOperation DefaultOperation
TestOption TestOption
ErrorOption ErrorOption
Config any
}
func (rpc EditConfig) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
req := struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 edit-config"`
Target Datastore `xml:"target"`
DefaultOperation DefaultOperation `xml:"default-operation,omitempty"`
TestOption TestOption `xml:"test-option,omitempty"`
ErrorOption ErrorOption `xml:"error-option,omitempty"`
Config any `xml:"config,omitempty"`
URL string `xml:"url,omitempty"`
}{
Target: rpc.Target,
DefaultOperation: rpc.DefaultOperation,
TestOption: rpc.TestOption,
ErrorOption: rpc.ErrorOption,
}
switch v := rpc.Config.(type) {
case URL:
req.URL = string(v)
case string:
req.Config = struct {
Inner string `xml:",innerxml"`
}{Inner: v}
case []byte:
req.Config = struct {
Inner []byte `xml:",innerxml"`
}{Inner: v}
default:
req.Config = rpc.Config
}
return e.Encode(&req)
}
func (rpc EditConfig) Exec(ctx context.Context, session *netconf.Session) error {
var resp OkReply
if err := session.Exec(ctx, rpc, &resp); err != nil {
return err
}
if !resp.OK {
return fmt.Errorf("edit-config: operation failed, <ok> not received")
}
return nil
}
// CopyConfig issues the `<copy-config>` operation as defined in [RFC6241 7.3]
// for copying an entire config to/from a source and target datastore.
//
// A `<config>` element defining a full config can be used as the source.
//
// If a device supports the `:url` capability than a [URL] object can be used
// for the source or target datastore.
//
// [RFC6241 7.3] https://www.rfc-editor.org/rfc/rfc6241.html#section-7.3
type CopyConfig struct {
Source any
Target any
WithDefaults WithDefaultsMode
}
func (rpc CopyConfig) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
req := struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 copy-config"`
Source any `xml:"source"`
Target any `xml:"target"`
WithDefaults *withDefaultsElement `xml:",omitempty"`
}{
Source: rpc.Source,
Target: rpc.Target,
}
if rpc.WithDefaults != "" {
req.WithDefaults = &withDefaultsElement{Mode: rpc.WithDefaults}
}
return e.Encode(&req)
}
func (rpc CopyConfig) Exec(ctx context.Context, session *netconf.Session) error {
var resp OkReply
if err := session.Exec(ctx, rpc, &resp); err != nil {
return err
}
if !resp.OK {
return fmt.Errorf("copy-config: operation failed, <ok> not received")
}
return nil
}
// DeleteConfigReq represents the `<delete-config>` operation defined in
// [RFC6241 7.4] for deleting a configuration datastore.
//
// [RFC6241 7.4]: https://www.rfc-editor.org/rfc/rfc6241.html#section-7.4
type DeleteConfig struct {
Target Datastore
}
func (rpc DeleteConfig) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
req := struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 delete-config"`
Target any `xml:"target"`
}{
Target: rpc.Target,
}
return e.Encode(&req)
}
func (rpc DeleteConfig) Exec(ctx context.Context, session *netconf.Session) error {
var resp OkReply
if err := session.Exec(ctx, rpc, &resp); err != nil {
return err
}
if !resp.OK {
return fmt.Errorf("delete-config: operation failed, <ok> not received")
}
return nil
}
// LockReq represents the `<lock>` operation defined in [RFC6241 7.5] for
// locking a configuration datastore.
//
// [RFC6241 7.5]: https://www.rfc-editor.org/rfc/rfc6241.html#section-7.5
type Lock struct {
Target Datastore
}
func (rpc Lock) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
req := struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 lock"`
Target Datastore `xml:"target"`
}{
Target: rpc.Target,
}
return e.Encode(&req)
}
func (rpc Lock) Exec(ctx context.Context, session *netconf.Session) error {
var resp OkReply
if err := session.Exec(ctx, rpc, &resp); err != nil {
return err
}
if !resp.OK {
return fmt.Errorf("lock: operation failed, <ok> not received")
}
return nil
}
type Unlock struct {
Target Datastore
}
func (rpc Unlock) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
req := struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 unlock"`
Target Datastore `xml:"target"`
}{
Target: rpc.Target,
}
return e.Encode(&req)
}
func (rpc Unlock) Exec(ctx context.Context, session *netconf.Session) error {
var resp OkReply
if err := session.Exec(ctx, rpc, &resp); err != nil {
return err
}
if !resp.OK {
return fmt.Errorf("unlock: operation failed, <ok> not received")
}
return nil
}
// PartialLock locks specific subtrees of the running datastore using XPath
// expressions as defined in RFC 5717.
type PartialLock struct {
Select []string
}
func (rpc PartialLock) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
if len(rpc.Select) == 0 {
return fmt.Errorf("partial-lock: must have at least one lock selection (xpath)")
}
type selectExpr struct {
XMLName xml.Name `xml:"select"`
Expr string `xml:",innerxml"`
}
selects := make([]selectExpr, len(rpc.Select))
for i, s := range rpc.Select {
selects[i] = selectExpr{Expr: s}
}
req := struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:partial-lock:1.0 partial-lock"`
Select []selectExpr
}{
Select: selects,
}
return e.Encode(&req)
}
// PartialLockReply is the response from a successful partial-lock operation.
type PartialLockReply struct {
netconf.RPCReply
LockID uint32 `xml:"lock-id"`
LockedNodes []string `xml:"locked-node"`
RunningErrors []string `xml:"running>error,omitempty"`
}
func (rpc PartialLock) Exec(ctx context.Context, session *netconf.Session) (*PartialLockReply, error) {
var resp PartialLockReply
if err := session.Exec(ctx, rpc, &resp); err != nil {
return nil, err
}
return &resp, nil
}
// PartialUnlock releases a partial lock acquired by PartialLock.
type PartialUnlock struct {
LockID uint32
}
func (rpc PartialUnlock) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
if rpc.LockID == 0 {
return fmt.Errorf("partial-unlock: lock id is not set")
}
req := struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:partial-lock:1.0 partial-unlock"`
LockID uint32 `xml:"lock-id"`
}{
LockID: rpc.LockID,
}
return e.Encode(&req)
}
func (rpc PartialUnlock) Exec(ctx context.Context, session *netconf.Session) error {
var resp OkReply
if err := session.Exec(ctx, rpc, &resp); err != nil {
return err
}
if !resp.OK {
return fmt.Errorf("partial-unlock: operation failed, <ok> not received")
}
return nil
}
type Validate struct {
Source any
}
func (rpc Validate) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
req := struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 validate"`
Source any `xml:"source"`
}{
Source: rpc.Source,
}
return e.Encode(&req)
}
func (rpc Validate) Exec(ctx context.Context, session *netconf.Session) error {
var resp OkReply
if err := session.Exec(ctx, rpc, &resp); err != nil {
return err
}
if !resp.OK {
return fmt.Errorf("validate: operation failed, <ok> not received")
}
return nil
}
// Commit represents the `<commit>` operation defined in [RFC6241 8.5] for
// committing candidate configuration to the running datastore.
//
// [RFC6241 8.5]: https://www.rfc-editor.org/rfc/rfc6241.html#section-8.5
type Commit struct {
// Confirmed indicates that the commit must be confirmed with a follow-up
// commit within the confirm-timeout period (default 600 seconds). If not
// confirmed, the commit will be reverted.
//
// Device must support :confirmed-commit:1.1 capability.
Confirmed bool
// ConfirmTimeout is the time in seconds to wait before reverting a
// confirmed commit.
//
// Device must support :confirmed-commit:1.1 capability.
ConfirmTimeout int64
// Persist indicates that the confirmed commit can be persisted across
// sessions and confirmed in a different session.
//
// If Confirmed is set this expands to the <persist> element.
//
// If Confirmed is not set this expands to the <persist-id> element to
// confirm a previous commit with the same id.
PersistID string
}
func (rpc Commit) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
req := struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 commit"`
Confirmed ExtantBool `xml:"confirmed,omitempty"`
ConfirmTimeout int64 `xml:"confirm-timeout,omitempty"`
Persist string `xml:"persist,omitempty"`
PersistID string `xml:"persist-id,omitempty"`
}{
Confirmed: ExtantBool(rpc.Confirmed),
ConfirmTimeout: rpc.ConfirmTimeout,
}
if rpc.PersistID != "" {
if rpc.Confirmed {
req.Persist = rpc.PersistID
} else {
req.PersistID = rpc.PersistID
}
}
return e.Encode(&req)
}
func (rpc Commit) Exec(ctx context.Context, session *netconf.Session) error {
var resp OkReply
if err := session.Exec(ctx, rpc, &resp); err != nil {
return err
}
if !resp.OK {
return fmt.Errorf("commit: operation failed, <ok> not received")
}
return nil
}
type CancelCommit struct {
PersistID string
}
func (rpc CancelCommit) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
req := struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 cancel-commit"`
PersistID string `xml:"persist-id,omitempty"`
}{
PersistID: rpc.PersistID,
}
return e.Encode(&req)
}
func (rpc CancelCommit) Exec(ctx context.Context, session *netconf.Session) error {
var resp OkReply
if err := session.Exec(ctx, rpc, &resp); err != nil {
return err
}
if !resp.OK {
return fmt.Errorf("cancel-commit: operation failed, <ok> not received")
}
return nil
}
// DiscardChanges represents the `<discard-changes>` operation defined in
// [RFC6241 8.3.4.2] for reverting the candidate configuration to the current
// running configuration.
//
// This operation discards any uncommitted changes by resetting the candidate
// configuration with the content of the running configuration.
//
// Device must support the `:candidate` capability.
//
// [RFC6241 8.3.4.2]: https://www.rfc-editor.org/rfc/rfc6241.html#section-8.3.4.2
type DiscardChanges struct{}
func (rpc DiscardChanges) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
req := struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 discard-changes"`
}{}
return e.Encode(&req)
}
func (rpc DiscardChanges) Exec(ctx context.Context, session *netconf.Session) error {
var resp OkReply
if err := session.Exec(ctx, rpc, &resp); err != nil {
return err
}
if !resp.OK {
return fmt.Errorf("discard-changes: operation failed, <ok> not received")
}
return nil
}
package rpc
import (
"encoding/xml"
"maps"
"slices"
)
type Filter interface {
xml.Marshaler
filter()
}
type subtreeFilter struct {
f any
}
func (f subtreeFilter) filter() {}
func (f subtreeFilter) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: "type"}, Value: "subtree"})
switch v := f.f.(type) {
case string:
inner := struct {
Data string `xml:",innerxml"`
}{Data: v}
return e.EncodeElement(&inner, start)
case []byte:
inner := struct {
Data []byte `xml:",innerxml"`
}{Data: v}
return e.EncodeElement(&inner, start)
default:
return e.EncodeElement(f.f, start)
}
}
// SubtreeFilter creates a filter matching the provided XML structure(s).
// Multiple arguments are merged into a single filter element as siblings.
func SubtreeFilter(filter any) Filter {
return subtreeFilter{f: filter}
}
type xpathFilter struct {
Select string
Namespaces map[string]string
}
func (f xpathFilter) filter() {}
func (f xpathFilter) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
start.Attr = append(start.Attr,
xml.Attr{Name: xml.Name{Local: "type"}, Value: "xpath"},
xml.Attr{Name: xml.Name{Local: "select"}, Value: f.Select},
)
for _, prefix := range slices.Sorted(maps.Keys(f.Namespaces)) {
uri := f.Namespaces[prefix]
attrName := "xmlns:" + prefix
start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: attrName}, Value: uri})
}
return e.EncodeElement(struct{}{}, start)
}
// XPathFilter creates a filter using XPath 1.0 expression.
// namespaces map prefixes used in the path to their URIs.
func XPathFilter(path string, namespaces map[string]string) Filter {
return xpathFilter{Select: path, Namespaces: namespaces}
}
package rpc
import (
"context"
"encoding/xml"
"fmt"
"time"
"nemith.io/netconf"
)
// CreateSubscription represents the `<create-subscription>` operation defined
// in [RFC 5277 Section 2.1.1] for initiating a notification subscription.
//
// The subscription will cause the server to begin sending event notifications
// to the client as they occur. If StartTime is specified, the server will first
// replay historical events from that time (if supported).
//
// [RFC 5277 Section 2.1.1]: https://www.rfc-editor.org/rfc/rfc5277.html#section-2.1.1
type CreateSubscription struct {
// Stream indicates which notification stream to subscribe to.
// If empty, the default NETCONF stream is used.
Stream string
// Filter selects a subset of notifications.
Filter Filter
// StartTime triggers replay of notifications from the specified time.
// Requires server support for notification replay.
StartTime *time.Time
// StopTime automatically terminates the subscription at the specified time.
// Requires StartTime to be set.
StopTime *time.Time
}
func (rpc *CreateSubscription) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
createSub := struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:notification:1.0 create-subscription"`
Stream string `xml:"stream,omitempty"`
Filter Filter `xml:"filter,omitempty"`
StartTime *time.Time `xml:"startTime,omitempty"`
StopTime *time.Time `xml:"stopTime,omitempty"`
}{
Stream: rpc.Stream,
Filter: rpc.Filter,
StartTime: rpc.StartTime,
StopTime: rpc.StopTime,
}
return e.Encode(createSub)
}
func (rpc *CreateSubscription) Exec(ctx context.Context, session *netconf.Session) error {
if rpc.StopTime != nil {
if rpc.StartTime == nil {
return fmt.Errorf("create-subscription: StopTime specified without StartTime")
}
if rpc.StopTime.Before(*rpc.StartTime) {
return fmt.Errorf("create-subscription: StopTime is before StartTime")
}
}
var resp OkReply
if err := session.Exec(ctx, rpc, &resp); err != nil {
return err
}
if !resp.OK {
return fmt.Errorf("create-subscription: operation failed, <ok> not received")
}
return nil
}
package rpc
import (
"context"
"encoding/xml"
"nemith.io/netconf"
)
type ExtantBool bool
func (b ExtantBool) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
if !b {
return nil
}
// This produces a empty start/end tag (i.e <tag></tag>) vs a self-closing
// tag (<tag/>) which should be the same in XML, however I know certain
// vendors may have issues with this format. We may have to process this
// after xml encoding.
//
// See https://github.com/golang/go/issues/21399
// or https://github.com/golang/go/issues/26756 for a different hack.
return e.EncodeElement(struct{}{}, start)
}
func (b *ExtantBool) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
*b = true
return d.Skip()
}
type OkReply struct {
netconf.RPCReply
OK ExtantBool `xml:"ok"`
}
type Get struct {
Filter Filter
WithDefaults WithDefaultsMode
}
func (rpc *Get) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
req := struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 get"`
Filter Filter `xml:"filter,omitempty"`
WithDefaults *withDefaultsElement `xml:",omitempty"`
}{
Filter: rpc.Filter,
}
if rpc.WithDefaults != "" {
req.WithDefaults = &withDefaultsElement{Mode: rpc.WithDefaults}
}
return e.Encode(&req)
}
type GetReply struct {
netconf.RPCReply
Data struct {
XML []byte `xml:",innerxml"`
} `xml:"data"`
}
func (rpc *Get) Exec(ctx context.Context, session *netconf.Session) ([]byte, error) {
var resp GetReply
if err := session.Exec(ctx, rpc, &resp); err != nil {
return nil, err
}
return resp.Data.XML, nil
}
package rpc
import (
"context"
"encoding/xml"
"fmt"
"nemith.io/netconf"
)
// KillSessionReq represents the `<kill-session>` operation defined in
// [RFC6241 7.6] for terminating a NETCONF session.
//
// [RFC6241 7.6]: https://www.rfc-editor.org/rfc/rfc6241.html#section-7.6
type KillSession struct {
SessionID uint
}
func (rpc *KillSession) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
req := struct {
XMLName xml.Name `xml:"urn:ietf:params:xml:ns:netconf:base:1.0 kill-session"`
SessionID uint `xml:"session-id"`
}{
SessionID: rpc.SessionID,
}
return e.EncodeElement(&req, start)
}
func (rpc *KillSession) Exec(ctx context.Context, session *netconf.Session) error {
var resp OkReply
if err := session.Exec(ctx, rpc, &resp); err != nil {
return err
}
if !resp.OK {
return fmt.Errorf("kill-session: operation failed, <ok> not received")
}
return nil
}
package netconf
import (
"bytes"
"context"
"encoding/xml"
"errors"
"fmt"
"io"
"log/slog"
"net"
"slices"
"strconv"
"sync"
"sync/atomic"
"syscall"
"time"
"nemith.io/netconf/transport"
)
const (
NetconfNamespace = "urn:ietf:params:xml:ns:netconf:base:1.0"
NotificationNamespace = "urn:ietf:params:xml:ns:netconf:notification:1.0"
)
var (
ErrClosed = errors.New("closed connection")
ErrHandshakeTimeout = errors.New("handshake timeout")
)
// NotificationHandler is called when a notification message is received from
// the server. The handler is called asynchronously in its own goroutine.
// The Message contains the raw notification data and must be closed when done.
// The context is cancelled when the session closes or encounters an error.
//
// If the handler returns an error, it will be logged but will not terminate
// the session or stop future notifications from being delivered.
type NotifHandlerFunc func(ctx context.Context, msg *Message)
func (h NotifHandlerFunc) HandleNotification(ctx context.Context, msg *Message) {
h(ctx, msg)
}
type NotifHandler interface {
HandleNotification(ctx context.Context, msg *Message)
}
// DefaultHelloTimeout is the default timeout for the hello handshake.
const DefaultHelloTimeout = 30 * time.Second
type sessionConfig struct {
clientCaps []string
logger *slog.Logger
notifHandler NotifHandler
helloTimeout time.Duration
}
type SessionOption interface {
apply(*sessionConfig)
}
type capabilityOpt []string
func (o capabilityOpt) apply(cfg *sessionConfig) {
cfg.clientCaps = []string(o)
}
func WithCapability(capabilities ...string) SessionOption {
return capabilityOpt(capabilities)
}
type loggerOpt struct {
logger *slog.Logger
}
func (o loggerOpt) apply(cfg *sessionConfig) {
cfg.logger = o.logger
}
// WithLogger sets a custom slog.Logger for the session.
// If not provided, slog.Default() will be used.
// To disable logging, pass slog.New(slog.NewTextHandler(io.Discard, nil)).
func WithLogger(logger *slog.Logger) SessionOption {
if logger == nil {
logger = slog.New(slog.DiscardHandler)
}
return loggerOpt{logger: logger}
}
type notifHandlerOpt struct {
handler NotifHandler
}
func (o notifHandlerOpt) apply(cfg *sessionConfig) {
cfg.notifHandler = o.handler
}
// WithNotifiHandler sets a handler for notifications received from the
// server. The handler will be called asynchronously for each notification.
// See NotifiHandler documentation for details on error handling and
// context cancellation.
func WithNotifHandler(handler NotifHandler) SessionOption {
return notifHandlerOpt{handler: handler}
}
// WithNotifHandlerFunc allows passing in a function for notification handler instead
// of a implementation of NotifHandler.
func WithNotifHandlerFunc(handlerFunc func(context.Context, *Message)) SessionOption {
return notifHandlerOpt{handler: NotifHandlerFunc(handlerFunc)}
}
type helloTimeoutOpt time.Duration
func (o helloTimeoutOpt) apply(cfg *sessionConfig) {
cfg.helloTimeout = time.Duration(o)
}
// WithHelloTimeout sets the timeout for the hello handshake exchange.
// If not set, DefaultHelloTimeout (30 seconds) is used.
// Set to 0 to disable the timeout (not recommended).
func WithHelloTimeout(d time.Duration) SessionOption {
return helloTimeoutOpt(d)
}
// Session is represents a netconf session to a one given device.
type Session struct {
tr transport.Transport
sessionID uint64
seq atomic.Uint64
helloTimeout time.Duration
clientCaps CapabilitySet
serverCaps CapabilitySet
mu sync.Mutex
reqs map[string]*pendingResp
// outQ serializes outbound messages since the transport
// only allows one active writer at a time
outQ chan *writeReq
// closing is closed when Close() is called, signaling session shutdown
closing chan struct{}
// sendDone is closed when sendLoop exits
sendDone chan struct{}
// closeOnce ensures Close() logic only runs once
closeOnce sync.Once
notifHandler NotifHandler
notifCtx context.Context
notifCancel context.CancelFunc
logger *slog.Logger
}
func newSession(transport transport.Transport, opts ...SessionOption) *Session {
cfg := sessionConfig{
clientCaps: DefaultCapabilities,
logger: slog.Default(),
helloTimeout: DefaultHelloTimeout,
}
for _, opt := range opts {
opt.apply(&cfg)
}
notifCtx, notifCancel := context.WithCancel(context.Background())
s := &Session{
tr: transport,
clientCaps: NewCapabilitySet(cfg.clientCaps...),
reqs: make(map[string]*pendingResp),
outQ: make(chan *writeReq),
closing: make(chan struct{}),
sendDone: make(chan struct{}),
notifHandler: cfg.notifHandler,
notifCtx: notifCtx,
notifCancel: notifCancel,
logger: cfg.logger,
helloTimeout: cfg.helloTimeout,
}
return s
}
// NewSession will create a new Session with the given transport and open it with the
// necessary hello messages.
func NewSession(transport transport.Transport, opts ...SessionOption) (*Session, error) {
s := newSession(transport, opts...)
ctx := context.Background()
if s.helloTimeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeoutCause(ctx, s.helloTimeout, ErrHandshakeTimeout)
defer cancel()
}
if err := s.handshake(ctx); err != nil {
if closeErr := s.tr.Close(); closeErr != nil {
s.logger.Warn("failed to close transport after handshake error", "error", closeErr)
}
return nil, err
}
go s.sendLoop()
go s.recvLoop()
return s, nil
}
// handshake exchanges handshake messages and reports if there are any errors.
func (s *Session) handshake(ctx context.Context) error {
// If context times out or is cancelled, close the transport to unblock
// any pending read/write operations.
stop := context.AfterFunc(ctx, func() {
_ = s.tr.Close()
})
defer stop()
clientMsg := Hello{
Capabilities: slices.Collect(s.clientCaps.All()),
}
// Handshake happens before sendLoop starts, so we write directly
w, err := s.tr.MsgWriter()
if err != nil {
if ctx.Err() != nil {
return fmt.Errorf("hello handshake: %w", ctx.Err())
}
return fmt.Errorf("failed to get hello message writer: %w", err)
}
if err := xml.NewEncoder(w).Encode(&clientMsg); err != nil {
_ = w.Close()
if ctx.Err() != nil {
return fmt.Errorf("hello handshake: %w", ctx.Err())
}
return fmt.Errorf("failed to write hello message: %w", err)
}
if err := w.Close(); err != nil {
if ctx.Err() != nil {
return fmt.Errorf("hello handshake: %w", ctx.Err())
}
return fmt.Errorf("failed to close hello message writer: %w", err)
}
r, err := s.tr.MsgReader()
if err != nil {
if ctx.Err() != nil {
return fmt.Errorf("hello handshake: %w", ctx.Err())
}
return fmt.Errorf("failed to get hello message reader: %w", err)
}
defer func() {
_ = r.Close()
}()
var serverMsg Hello
if err := xml.NewDecoder(r).Decode(&serverMsg); err != nil {
if ctx.Err() != nil {
return fmt.Errorf("hello handshake: %w", ctx.Err())
}
return fmt.Errorf("failed to read server hello message: %w", err)
}
if serverMsg.SessionID == 0 {
return fmt.Errorf("server did not return a session-id")
}
if len(serverMsg.Capabilities) == 0 {
return fmt.Errorf("server did not return any capabilities")
}
s.serverCaps = NewCapabilitySet(serverMsg.Capabilities...)
s.sessionID = serverMsg.SessionID
// upgrade the transport if we are on a larger version and the transport
// supports it.
if s.serverCaps.Has(CapNetConf11) && s.clientCaps.Has(CapNetConf11) {
if upgrader, ok := s.tr.(interface{ Upgrade() }); ok {
upgrader.Upgrade()
}
}
return nil
}
// SessionID returns the current session ID exchanged in the hello messages.
// Will return 0 if there is no session ID.
func (s *Session) SessionID() uint64 {
return s.sessionID
}
// ClientCaps will return the capabilities initialized with the session.
func (s *Session) ClientCaps() *CapabilitySet {
return &s.clientCaps
}
// ServerCaps will return the capabilities returned by the server in
// it's hello message.
func (s *Session) ServerCaps() *CapabilitySet {
return &s.serverCaps
}
// startElement will walk though a xml.Decode until it finds a start element
// and returns it.
func startElement(d *xml.Decoder) (*xml.StartElement, error) {
for {
tok, err := d.Token()
if err != nil {
return nil, err
}
if start, ok := tok.(xml.StartElement); ok {
return &start, nil
}
}
}
type pendingResp struct {
msg chan *Message
ctx context.Context
}
// writeReq represents a queued write request
type writeReq struct {
writeFn func(io.Writer) error
done chan error
ctx context.Context
}
type msgReader struct {
io.Reader
closer io.Closer
done chan struct{}
once sync.Once
}
func (r *msgReader) Close() error {
var err error
r.once.Do(func() {
err = r.closer.Close()
close(r.done)
})
return err
}
// queueSend queues a message for writing and waits for completion.
// Returns an error if the write fails or context is cancelled.
func (s *Session) queueSend(ctx context.Context, marshal func(io.Writer) error) error {
// Check if we're closed before attempting to send
select {
case <-s.closing:
return ErrClosed
default:
}
done := make(chan error, 1)
req := &writeReq{
writeFn: marshal,
done: done,
ctx: ctx,
}
select {
case s.outQ <- req:
// Successfully queued, wait for result
select {
case err := <-done:
return err
case <-ctx.Done():
return ctx.Err()
}
case <-s.closing:
// Session is closing, stop accepting sends
return ErrClosed
case <-ctx.Done():
return ctx.Err()
}
}
// sendMsg writes a message to the transport. Only one write is allowed at a time.
// This method assumes it has exclusive access to MsgWriter().
func (s *Session) sendMsg(marshal func(io.Writer) error) (err error) {
w, err := s.tr.MsgWriter()
if err != nil {
return fmt.Errorf("failed to get message writer: %w", err)
}
defer func() {
if closeErr := w.Close(); closeErr != nil && err == nil {
err = fmt.Errorf("failed to flush message: %w", closeErr)
}
}()
return marshal(w)
}
// sendLoop processes the outbound write queue, ensuring only one message
// is written to the transport at a time.
func (s *Session) sendLoop() {
defer close(s.sendDone)
for outMsg := range s.outQ {
// Check if context was cancelled while queued
select {
case <-outMsg.ctx.Done():
outMsg.done <- outMsg.ctx.Err()
continue
default:
}
// Send the message and report result
outMsg.done <- s.sendMsg(outMsg.writeFn)
}
}
// recvLoop is the main receive loop. It runs concurrently to be able to handle
// interleaved messages (like notifications).
func (s *Session) recvLoop() {
// buffer used to "peel" into the message enough to read the first element
// (i.e <rpc-reply> or <notification>)
buf := make([]byte, 4096)
for {
if err := s.recvMsg(buf); err != nil {
// Only log errors for unexpected failures (not graceful shutdown)
select {
case <-s.closing:
// Graceful shutdown, don't log
default:
if !errors.Is(err, io.EOF) {
s.logger.Error("failed to receive message", "error", err)
}
}
break
}
}
// Final cleanup when the loop exits
s.mu.Lock()
for _, req := range s.reqs {
close(req.msg)
}
s.mu.Unlock()
_ = s.tr.Close()
select {
case <-s.closing:
// Graceful shutdown
default:
s.logger.Warn("connection closed unexpectedly")
}
}
func getMessageID(attrs []xml.Attr) string {
for _, attr := range attrs {
if attr.Name.Local == "message-id" {
return attr.Value
}
}
return ""
}
func (s *Session) recvMsg(buf []byte) error {
r, err := s.tr.MsgReader()
if err != nil {
return err
}
defer func() {
if err := r.Close(); err != nil {
s.logger.Warn("failed to close message reader", "error", err)
}
}()
// 3. Peek/Read the start of the message
n, err := r.Read(buf)
if err != nil && !errors.Is(err, io.EOF) {
return err
}
chunk := buf[:n]
decoder := xml.NewDecoder(bytes.NewReader(chunk))
startElem, err := startElement(decoder)
if err != nil {
return fmt.Errorf("failed to parse message start: %w", err)
}
combinedReader := io.MultiReader(bytes.NewReader(chunk), r)
switch startElem.Name {
case xml.Name{Space: NetconfNamespace, Local: "rpc-reply"}:
msgID := getMessageID(startElem.Attr)
if msgID == "" {
s.logger.Warn("rpc-reply missing message-id")
return nil // Continue loop
}
s.mu.Lock()
req, ok := s.reqs[msgID]
delete(s.reqs, msgID)
s.mu.Unlock()
if !ok {
s.logger.Warn("unexpected rpc-reply", "message-id", msgID, "note", "possible timeout")
return nil // Continue loop
}
readDone := make(chan struct{})
reader := &msgReader{
Reader: combinedReader,
closer: r, // The raw transport reader
done: readDone,
}
select {
case req.msg <- &Message{
reader: reader,
messageID: &msgID,
Attributes: startElem.Attr,
}:
// We wait for the user to call Close() on the replyReader.
<-readDone
return nil
case <-req.ctx.Done():
return nil
}
case xml.Name{Space: NotificationNamespace, Local: "notification"}:
if s.notifHandler == nil {
s.logger.Warn("received notification but no handler configured")
return nil
}
// Create a reader for the notification that will close the transport reader
readDone := make(chan struct{})
reader := &msgReader{
Reader: combinedReader,
closer: r,
done: readDone,
}
// Call handler asynchronously to avoid blocking the receive loop
go s.handleNotification(reader, startElem.Attr)
// Wait for handler to finish reading/closing the message
<-readDone
return nil
default:
return fmt.Errorf("netconf: unknown message type: %s", startElem.Name.Local)
}
}
// handleNotification invokes the notification handler asynchronously.
// It ensures the message is properly closed and logs any errors from the handler.
func (s *Session) handleNotification(reader *msgReader, attrs []xml.Attr) {
msg := &Message{
reader: reader,
Attributes: attrs,
}
s.notifHandler.HandleNotification(s.notifCtx, msg)
// Ensure the message is closed even if handler didn't close it
if err := msg.Close(); err != nil && !errors.Is(err, io.EOF) {
s.logger.Warn("failed to close notification message", "error", err)
}
}
func (s *Session) nextMessageID() string {
return strconv.FormatUint(s.seq.Add(1), 10)
}
// Prepare will prepare the given rpc by assigning it a message-id if it
// doesn't have one already.
func (s *Session) Prepare(rpc *RPC) *RPC {
if rpc.MessageID == "" {
rpc = rpc.Clone()
rpc.MessageID = s.nextMessageID()
}
return rpc
}
// Do will send the given rpc message and wait for the response message.
func (s *Session) Do(ctx context.Context, rpc *RPC) (*Message, error) {
rpc = s.Prepare(rpc)
// Setup request/reply channel
ch := make(chan *Message, 1)
s.mu.Lock()
_, ok := s.reqs[rpc.MessageID]
if ok {
s.mu.Unlock()
return nil, fmt.Errorf("rpc with message-id %q is already pending", rpc.MessageID)
}
s.reqs[rpc.MessageID] = &pendingResp{
msg: ch,
ctx: ctx,
}
s.mu.Unlock()
// Cleanup if context triggers before send/recv
defer func() {
s.mu.Lock()
delete(s.reqs, rpc.MessageID)
s.mu.Unlock()
}()
// Send through the queue - marshal function avoids buffer allocation
if err := s.queueSend(ctx, func(w io.Writer) error {
return xml.NewEncoder(w).Encode(rpc)
}); err != nil {
return nil, err
}
// Wait for the response
select {
case resp, ok := <-ch:
if !ok {
return nil, ErrClosed
}
return resp, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
// Exec issues a rpc message with `op` as the body and decodes the response into
// a pointer at `reply`. The Reply must include the full <rpc-reply> structure.
func (s *Session) Exec(ctx context.Context, op any, reply any) error {
rpc := NewRPC(op)
msg, err := s.Do(ctx, rpc)
if err != nil {
return err
}
defer func() {
_ = msg.Close()
}()
raw, err := io.ReadAll(msg)
if err != nil {
return fmt.Errorf("failed to read reply: %w", err)
}
var rpcReply RPCReply
if err := xml.Unmarshal(raw, &rpcReply); err != nil {
return fmt.Errorf("failed to parse rpc-reply: %w", err)
}
// filter out warnings
rpcErrors := rpcReply.RPCErrors.Filter(SevError)
if len(rpcErrors) > 0 {
return rpcErrors
}
if reply != nil {
if err := xml.Unmarshal(raw, reply); err != nil {
return fmt.Errorf("failed to decode response: %w", err)
}
}
return nil
}
// Close will gracefully close the sessions first by sending a `close-session`
// operation to the remote and then closing the underlying transport
func (s *Session) Close(ctx context.Context) error {
var closeErr error
s.closeOnce.Do(func() {
// Cancel notification context to signal handlers to stop
s.notifCancel()
type closeSession struct {
XMLName xml.Name `xml:"close-session"`
}
// This may fail so save the error but still close the underlying transport.
req := NewRPC(&closeSession{})
resp, _ := s.Do(ctx, req)
if resp != nil {
_ = resp.Close()
}
// Signal session is closing - this stops new sends from being queued
close(s.closing)
// Now safe to close outQ since no new sends can reach it
close(s.outQ)
// Wait for sendLoop to exit
select {
case <-s.sendDone:
// sendLoop finished cleanly
case <-ctx.Done():
// Context expired - close transport immediately
s.logger.Warn("close context expired before sendLoop finished", "error", ctx.Err())
}
// Close the connection and ignore errors if the remote side hung up first.
if err := s.tr.Close(); err != nil &&
!errors.Is(err, net.ErrClosed) &&
!errors.Is(err, io.EOF) &&
!errors.Is(err, syscall.EPIPE) {
closeErr = err
}
})
return closeErr
}
// Package netconftest provides test utilities for NETCONF sessions.
package testutil
import (
"bytes"
"encoding/xml"
"io"
"slices"
"strings"
"sync"
"nemith.io/netconf/transport"
)
// RequestHandler is called for each message written by the client.
// It receives the request and returns zero or more responses.
// Returning nil or empty slice means no response.
type RequestHandler func(req string) []string
// Transport mocks the underlying NETCONF transport layer.
// Messages flow synchronously: when the client writes a request,
// the handler is called and its responses are queued for reading.
// Use Push() to queue unsolicited messages like notifications.
type Transport struct {
mu sync.Mutex
handler RequestHandler
msgs []string // pending messages to read
msgReady chan struct{}
outputs []string
closed bool
activeWriter bool // tracks if a writer is currently active
activeReader bool // tracks if a reader is currently active
}
// NewTransport creates a new test Transport with a handler function.
// The handler is called synchronously for each client write.
func NewTransport(handler RequestHandler) *Transport {
return &Transport{
handler: handler,
msgReady: make(chan struct{}, 1),
}
}
func (t *Transport) MsgReader() (io.ReadCloser, error) {
for {
t.mu.Lock()
if t.closed {
t.mu.Unlock()
return nil, io.EOF
}
if t.activeReader {
t.mu.Unlock()
return nil, transport.ErrStreamBusy
}
if len(t.msgs) > 0 {
msg := t.msgs[0]
t.msgs = t.msgs[1:]
t.activeReader = true
t.mu.Unlock()
return &testReader{tt: t, r: strings.NewReader(msg)}, nil
}
t.mu.Unlock()
// Wait for messages or close
<-t.msgReady
}
}
func (t *Transport) MsgWriter() (io.WriteCloser, error) {
t.mu.Lock()
defer t.mu.Unlock()
if t.closed {
return nil, io.EOF
}
if t.activeWriter {
return nil, transport.ErrStreamBusy
}
t.activeWriter = true
return &testWriter{tt: t, buf: &bytes.Buffer{}}, nil
}
func (t *Transport) Close() error {
t.mu.Lock()
defer t.mu.Unlock()
if t.closed {
return nil
}
t.closed = true
// Signal any waiting readers
select {
case t.msgReady <- struct{}{}:
default:
}
return nil
}
// addResponses adds messages to the read queue (called internally after write)
func (t *Transport) addResponses(msgs []string) {
t.mu.Lock()
t.msgs = append(t.msgs, msgs...)
t.mu.Unlock()
// Signal that messages are ready
select {
case t.msgReady <- struct{}{}:
default:
}
}
// Push queues unsolicited messages (like notifications) for reading.
// These messages are delivered independently of any request/response flow.
func (t *Transport) Push(msgs ...string) {
t.addResponses(msgs)
}
// Outputs returns the messages the client sent to the server.
func (t *Transport) Outputs() []string {
t.mu.Lock()
defer t.mu.Unlock()
return slices.Clone(t.outputs)
}
// Closed returns whether the transport has been closed.
func (t *Transport) Closed() bool {
t.mu.Lock()
defer t.mu.Unlock()
return t.closed
}
type testReader struct {
tt *Transport
r *strings.Reader
}
func (tr *testReader) Read(p []byte) (int, error) {
tr.tt.mu.Lock()
closed := tr.tt.closed
tr.tt.mu.Unlock()
if closed {
return 0, io.EOF
}
return tr.r.Read(p)
}
func (tr *testReader) Close() error {
tr.tt.mu.Lock()
tr.tt.activeReader = false
tr.tt.mu.Unlock()
return nil
}
type testWriter struct {
tt *Transport
buf *bytes.Buffer
closed bool
}
func (w *testWriter) Write(p []byte) (int, error) {
w.tt.mu.Lock()
defer w.tt.mu.Unlock()
if w.tt.closed || w.closed {
return 0, io.EOF
}
return w.buf.Write(p)
}
func (w *testWriter) Close() error {
w.tt.mu.Lock()
if w.closed {
w.tt.mu.Unlock()
return nil
}
w.closed = true
w.tt.activeWriter = false // Release the writer lock
msg := w.buf.String()
w.tt.outputs = append(w.tt.outputs, msg)
handler := w.tt.handler
closed := w.tt.closed
w.tt.mu.Unlock()
// Call handler synchronously and queue responses
if handler != nil && !closed {
if responses := handler(msg); len(responses) > 0 {
w.tt.addResponses(responses)
}
}
return nil
}
// ExtractMessageID extracts the message-id attribute from an XML message.
func ExtractMessageID(msg string) string {
decoder := xml.NewDecoder(strings.NewReader(msg))
for {
tok, err := decoder.Token()
if err != nil {
return ""
}
if start, ok := tok.(xml.StartElement); ok {
for _, attr := range start.Attr {
if attr.Name.Local == "message-id" {
return attr.Value
}
}
return ""
}
}
}
// Reply creates an rpc-reply with the given message-id and body.
func Reply(msgID, body string) string {
return `<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="` + msgID + `">` + body + `</rpc-reply>`
}
// OKReply creates an rpc-reply with <ok/> for the given message-id.
func OKReply(msgID string) string {
return Reply(msgID, "<ok/>")
}
package transport
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"math"
"sync"
)
var ErrStreamBusy = errors.New("transport: stream is already active")
// Framer is a wrapper used for transports that implement the framing defined in
// RFC6242. This supports End-of-Message and Chunked framing methods and
// will move from End-of-Message to Chunked framing after the `Upgrade` method
// has been called.
//
// This is not a transport on it's own (missing the `Close` method) and is
// intended to be embedded into other transports.
type Framer struct {
r io.Reader
w io.Writer
br *bufio.Reader
bw *bufio.Writer
mu sync.Mutex
chunkFraming bool
activeReader bool
activeWriter bool
}
// NewFramer return a new Framer to be used against the given io.Reader and io.Writer.
func NewFramer(r io.Reader, w io.Writer) *Framer {
return &Framer{
r: r,
w: w,
br: bufio.NewReader(r),
bw: bufio.NewWriter(w),
}
}
// DebugCapture will copy all *framed* input/output to the the given
// `io.Writers` for sent or recv data. Either sent of recv can be nil to not
// capture any data. Useful for displaying to a screen or capturing to a file
// for debugging.
//
// This needs to be called before `MsgReader` or `MsgWriter`.
func (f *Framer) DebugCapture(input, output io.Writer) {
f.mu.Lock()
defer f.mu.Unlock()
if f.activeReader ||
f.activeWriter ||
f.bw.Buffered() > 0 ||
f.br.Buffered() > 0 {
panic("debug capture added with active reader or writer")
}
if input != nil {
f.br = bufio.NewReader(io.TeeReader(f.r, input))
}
if output != nil {
f.bw = bufio.NewWriter(io.MultiWriter(f.w, output))
}
}
// Upgrade will cause the Framer to switch from End-of-Message framing to
// Chunked framing. This is usually called after netconf exchanged the hello
// messages.
func (f *Framer) Upgrade() {
f.mu.Lock()
defer f.mu.Unlock()
f.chunkFraming = true
}
func (f *Framer) closeReader() {
if f == nil {
return
}
f.mu.Lock()
defer f.mu.Unlock()
f.activeReader = false
}
func (f *Framer) closeWriter() {
if f == nil {
return
}
f.mu.Lock()
defer f.mu.Unlock()
f.activeWriter = false
}
func (f *Framer) MsgReader() (io.ReadCloser, error) {
f.mu.Lock()
defer f.mu.Unlock()
if f.activeReader {
return nil, ErrStreamBusy
}
f.activeReader = true
if f.chunkFraming {
return &chunkedReader{
r: f.br,
f: f,
}, nil
}
return &markedReader{
r: f.br,
f: f,
}, nil
}
func (f *Framer) MsgWriter() (io.WriteCloser, error) {
f.mu.Lock()
defer f.mu.Unlock()
if f.activeWriter {
return nil, ErrStreamBusy
}
f.activeWriter = true
if f.chunkFraming {
return &chunkedWriter{
w: f.bw,
f: f,
}, nil
}
return &markedWriter{
w: f.bw,
f: f,
}, nil
}
var endOfChunks = []byte("\n##\n")
// maxChunkSize is the maximum chunk size for RFC 6242 chunked framing. RFC 6242
// allows up to MaxUint32 (4294967295), but on 32-bit systems slice lengths are
// limited to MaxInt (32-bit *signed*). We use the minimum of both to ensure
// compatibility across all architectures.
const maxChunkSize = min(math.MaxUint32, math.MaxInt)
// ErrMalformedChunk represents a message that invalid as defined in the chunk
// framing in RFC6242
var ErrMalformedChunk = errors.New("netconf: invalid chunk")
type chunkedReader struct {
f *Framer
r *bufio.Reader
chunkLeft uint32
eof bool
}
func (r *chunkedReader) readHeader() (uint32, error) {
// Peek at marker to check for "\n#"
marker, err := r.r.Peek(4)
if err != nil {
if errors.Is(err, io.EOF) {
return 0, io.ErrUnexpectedEOF
}
return 0, err
}
if marker[0] != '\n' || marker[1] != '#' {
return 0, ErrMalformedChunk
}
if marker[2] == '#' && marker[3] == '\n' {
// Discard the end-of-chunks marker
if _, err := r.r.Discard(4); err != nil {
return 0, err
}
return 0, nil // Signal end of message with 0 chunk size
}
// Discard the "\n#" preamble
if _, err := r.r.Discard(2); err != nil {
return 0, err
}
line, err := r.r.ReadSlice('\n')
if err != nil {
if err == io.EOF {
return 0, io.ErrUnexpectedEOF
}
// ReadSlice returns err if '\n' is missing (EOF or buffer full)
return 0, err
}
// Cut off the '\n' from the end for parsing
digits := line[:len(line)-1]
// If the line was just "\n", digits is empty (chunks must have size)
if len(digits) == 0 {
return 0, ErrMalformedChunk
}
var chunkSize uint32
for _, c := range digits {
if c < '0' || c > '9' {
return 0, ErrMalformedChunk
}
if chunkSize > math.MaxUint32/10 {
return 0, ErrMalformedChunk
}
chunkSize = chunkSize * 10
digit := uint32(c - '0')
if chunkSize > math.MaxUint32-digit {
return 0, ErrMalformedChunk
}
chunkSize += digit
}
if chunkSize == 0 {
return 0, ErrMalformedChunk
}
return chunkSize, nil
}
func (r *chunkedReader) Read(p []byte) (int, error) {
if r.r == nil {
return 0, ErrInvalidIO
}
if len(p) > maxChunkSize {
p = p[:maxChunkSize]
}
// If we have no bytes left in the current chunk, we must read a new header
if r.chunkLeft <= 0 {
chunkSize, err := r.readHeader()
if err != nil {
return 0, err
}
// Zero chunk size indicates "End of Chunks" (\n##\n)
if chunkSize == 0 {
r.eof = true
return 0, io.EOF
}
r.chunkLeft = chunkSize
}
toRead := min(uint32(len(p)), r.chunkLeft)
n, err := r.r.Read(p[:toRead])
r.chunkLeft -= uint32(n)
return n, err
}
func (r *chunkedReader) ReadByte() (byte, error) {
if r.r == nil {
return 0, ErrInvalidIO
}
// done with existing chunk so grab the next one
if r.chunkLeft <= 0 {
n, err := r.readHeader()
if err != nil {
return 0, err
}
if n == 0 {
r.eof = true
return 0, io.EOF
}
r.chunkLeft = n
}
b, err := r.r.ReadByte()
if err != nil {
return 0, err
}
r.chunkLeft--
return b, nil
}
func (r *chunkedReader) Close() error {
if r.r == nil {
return nil
}
defer func() {
r.r = nil
r.f.closeReader()
}()
// If we have already read to the end, nothing to do
if r.eof {
return nil
}
// Drain the rest of the chunks until we hit the end-of-chunks marker
for {
if r.chunkLeft <= 0 {
// readHeader return 0, nil when it hits the end-of-chunks
n, err := r.readHeader()
if err != nil {
return err
}
if n == 0 {
return nil
}
r.chunkLeft = n
}
for r.chunkLeft > 0 {
// Protect against int overflow on 32-bit systems
toDiscard := int(r.chunkLeft)
if uint(r.chunkLeft) > uint(math.MaxInt) {
toDiscard = math.MaxInt
}
n, err := r.r.Discard(toDiscard)
r.chunkLeft -= uint32(n)
if err != nil {
return err
}
}
}
}
type chunkedWriter struct {
f *Framer
w *bufio.Writer
}
func (w *chunkedWriter) Write(p []byte) (int, error) {
if w.w == nil {
return 0, ErrInvalidIO
}
totalWritten := 0
for len(p) > 0 {
chunkSize := min(len(p), maxChunkSize)
// Write chunk header
if _, err := fmt.Fprintf(w.w, "\n#%d\n", chunkSize); err != nil {
return totalWritten, err
}
// Note: we are not checking for a partial writes as bufio.Writer
// will only return a short write if the underlying writer returns an
// error.
n, err := w.w.Write(p[:chunkSize])
totalWritten += n
if err != nil {
return totalWritten, err
}
// Advance
p = p[n:]
}
return totalWritten, nil
}
func (w *chunkedWriter) Close() error {
if w.w == nil {
return nil
}
defer func() {
w.w = nil
w.f.closeWriter()
}()
// write the end-of-chunks marker
if _, err := w.w.Write(endOfChunks); err != nil {
return err
}
return w.w.Flush()
}
var endOfMsg = []byte("]]>]]>")
type markedReader struct {
f *Framer
r *bufio.Reader
eof bool
}
func (r *markedReader) Read(p []byte) (int, error) {
for i := 0; i < len(p); i++ {
b, err := r.ReadByte()
if err != nil {
return i, err
}
p[i] = b
}
return len(p), nil
}
func (r *markedReader) ReadByte() (byte, error) {
if r.r == nil {
return 0, ErrInvalidIO
}
if r.eof {
return 0, io.EOF
}
b, err := r.r.ReadByte()
if err != nil {
if err == io.EOF {
return b, io.ErrUnexpectedEOF
}
return b, err
}
// look for the end of the message marker
if b == endOfMsg[0] {
peeked, err := r.r.Peek(len(endOfMsg) - 1)
if err != nil {
if err == io.EOF {
return 0, io.ErrUnexpectedEOF
}
return 0, err
}
// check if we are at the end of the message
if bytes.Equal(peeked, endOfMsg[1:]) {
if _, err := r.r.Discard(len(endOfMsg) - 1); err != nil {
return 0, err
}
r.eof = true
return 0, io.EOF
}
}
return b, nil
}
func (r *markedReader) Close() error {
if r.r == nil {
return nil
}
defer func() {
r.r = nil
r.f.closeReader()
}()
// If we have already read to the end, nothing to do
if r.eof {
return nil
}
var err error
for err == nil {
_, err = r.ReadByte()
if errors.Is(err, io.EOF) {
return nil
}
}
return err
}
type markedWriter struct {
f *Framer
w *bufio.Writer
}
func (w *markedWriter) Write(p []byte) (int, error) {
if w.w == nil {
return 0, ErrInvalidIO
}
return w.w.Write(p)
}
func (w *markedWriter) Close() error {
if w.w == nil {
return nil
}
defer func() {
w.w = nil
w.f.closeWriter()
}()
if _, err := w.w.Write(endOfMsg); err != nil {
return err
}
return w.w.Flush()
}
package ssh
import (
"context"
"errors"
"fmt"
"io"
"net"
"golang.org/x/crypto/ssh"
"nemith.io/netconf/transport"
)
// alias it to a private type so we can make it private when embedding
type framer = transport.Framer
// Transport implements RFC6242 for implementing NETCONF protocol over SSH.
type Transport struct {
c *ssh.Client
sess *ssh.Session
stdin io.WriteCloser
// set to true if the transport is managing the underlying ssh connection
// and should close it when the transport is closed. This is is set to true
// when used with `Dial`.
managedConn bool
*framer
}
// Dial will connect to a ssh server and issues a transport, it's used as a
// convenience function as essentially is the same as
//
// c, err := ssh.Dial(network, addr, config)
// if err != nil { /* ... handle error ... */ }
// t, err := NewTransport(c)
//
// When the transport is closed the underlying connection is also closed.
func Dial(ctx context.Context, network, addr string, config *ssh.ClientConfig) (*Transport, error) {
d := net.Dialer{Timeout: config.Timeout}
conn, err := d.DialContext(ctx, network, addr)
if err != nil {
return nil, err
}
// Setup a go routine to monitor the context and close the connection. This
// is needed as the ssh library doesn't support contexts for dialing so this
// approximates a context based cancelation/timeout for the ssh handshake.
//
// Since writing this code, Go 1.20 added DialContext to ssh.ClientConn but it doesn't support a custom configuration
done := make(chan struct{})
defer close(done)
go func() {
select {
case <-ctx.Done():
_ = conn.Close()
case <-done:
}
}()
sshConn, chans, reqs, err := ssh.NewClientConn(conn, addr, config)
if err != nil {
// ssh.NewClientConn closes the underlying connection so no need to call conn.Close()
if ctx.Err() != nil {
return nil, ctx.Err()
}
return nil, err
}
client := ssh.NewClient(sshConn, chans, reqs)
t, err := newTransport(client, true)
if err != nil {
// Close the client to not leak it on transport failure.
_ = client.Close()
if ctx.Err() != nil {
return nil, ctx.Err()
}
return nil, err
}
return t, nil
}
// NewTransport will create a new ssh transport as defined in RFC6242 for use
// with netconf. Unlike Dial, the underlying client will not be automatically
// closed when the transport is closed (however any sessions and subsystems
// are still closed).
func NewTransport(client *ssh.Client) (*Transport, error) {
return newTransport(client, false)
}
func newTransport(client *ssh.Client, managed bool) (*Transport, error) {
sess, err := client.NewSession()
if err != nil {
return nil, fmt.Errorf("failed to create ssh session: %w", err)
}
w, err := sess.StdinPipe()
if err != nil {
return nil, fmt.Errorf("failed to create stdin pipe: %w", err)
}
r, err := sess.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("failed to create stdout pipe: %w", err)
}
const subsystem = "netconf"
if err := sess.RequestSubsystem(subsystem); err != nil {
return nil, fmt.Errorf("failed to start netconf ssh subsytem: %w", err)
}
return &Transport{
c: client,
managedConn: managed,
sess: sess,
stdin: w,
framer: transport.NewFramer(r, w),
}, nil
}
// Close will close the underlying transport. If the connection was created
// with Dial then then underlying ssh.Client is closed as well. If not only
// the sessions is closed.
func (t *Transport) Close() error {
// will save previous errors but try to close everything returning just the
// "lowest" abstraction layer error
var retErr error
if err := t.stdin.Close(); err != nil {
retErr = errors.Join(retErr, fmt.Errorf("failed to close ssh stdin: %w", err))
}
if err := t.sess.Close(); err != nil {
retErr = errors.Join(retErr, fmt.Errorf("failed to close ssh channel: %w", err))
}
// If this is a "managed connection" (i.e one created with Dial) then we are
// responsible to close the connection.
if t.managedConn {
if err := t.c.Close(); err != nil {
return errors.Join(retErr, fmt.Errorf("failed to close ssh connection: %w", err))
}
}
return retErr
}
package tls
import (
"context"
"crypto/tls"
"net"
"nemith.io/netconf/transport"
)
// alias it to a private type so we can make it private when embedding
type framer = transport.Framer
// Transport implements RFC7589 for implementing NETCONF over TLS.
type Transport struct {
conn *tls.Conn
*framer
}
// Dial will connect to a NETCONF tls port and creates a new Transport. It's
// used as a convenience function and essentially is the same as:
//
// c, err := tls.Dial(network, addr, config)
// if err != nil { /* ... handle error ... */ }
// t, err := NewTransport(c)
//
// When the transport is closed the underlying connection is also closed.
func Dial(ctx context.Context, network, addr string, config *tls.Config) (*Transport, error) {
var d net.Dialer
conn, err := d.DialContext(ctx, network, addr)
if err != nil {
return nil, err
}
tlsConn := tls.Client(conn, config)
if err := tlsConn.HandshakeContext(ctx); err != nil {
_ = tlsConn.Close()
return nil, err
}
return NewTransport(tlsConn), nil
}
// NewTransport takes an already connected tls transport and returns a new
// Transport.
func NewTransport(conn *tls.Conn) *Transport {
return &Transport{
conn: conn,
framer: transport.NewFramer(conn, conn),
}
}
// Close will close the transport and the underlying TLS connection.
func (t *Transport) Close() error {
return t.conn.Close()
}