epplib

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 25, 2022 License: MIT Imports: 18 Imported by: 1

README

epp-lib

A collection of EPP nice to haves.

namespace

All namespaces we support at the Swedish Internet Foundation are gathered here as strings with some convenience methods.

status

All statuses a response can have from the server as described in https://datatracker.ietf.org/doc/html/rfc5730#section-3.

error

Error represents an EPP error - it holds all the information needed for an error response from the server.

xml

Some nice to have convenience methods for xml.
XMLString that automatically xml escape the given string when the Stringer interface is used.
ParseXMLBool function that handle 0, 1, true and false and converts to go bool.
XMLPathBuilder makes it easier to build xml paths.
Example:

// equals "name[namespace-uri()='urn:ietf:params:xml:ns:contact-1.0']"
NewXMLPathBuilder().AddOrphan("name", "urn:ietf:params:xml:ns:contact-1.0").String()

// equals "//command[namespace-uri()='random:namespace']/check[namespace-uri()='urn:ietf:params:xml:ns:contact-1.0']"
NewXMLPathBuilder().
  Add("//command", "random:namespace").
  Add("check", "urn:ietf:params:xml:ns:contact-1.0").String()

server

A working EPP server with configurable variables like timeouts and max message size allowed.
Example server initialization:

commandMux := &CommandMux{}

server := &Server{
    HandleCommand: commandMux.Handle,
    Greeting:      commandMux.GetGreeting,
    TLSConfig:     tls.Config{
            Certificates: []tls.Certificate{tlsCert},
            ClientAuth:   tls.RequireAnyClientCert,
            MinVersion: tls.VersionTLS12,
    },
    Timeout:        time.Hour,
    IdleTimeout:    350 * time.Second,
    WriteTimeout:   2 * time.Minute,
    ReadTimeout:    10 * time.Second,
    ErrorLog:       log, // whichever log you prefer that fit the interface
    MaxMessageSize: 1000,
}

listener, err := net.ListenTCP("tcp", tcpAddr)
if err != nil {
    panic(err)
}

if err := server.Serve(listener); err != nil {
    panic(err)
}

The server ConnContext can be used to set custom data on the context. For example if you want to create a session ID for the connection or something.

The server CloseConnHook if set is called when a connection is closed. It can be used to for example tear down any data for the connection.

handler

The CommandMux.Handle function parse the incoming commands and calls the correct CommandFunc if one has been configured for the specific command.

Example bind of commands:

commandMux := &CommandMux{}

commandMux.BindGreeting(funcThatHandlesGreetingCommand)
commandMux.Bind(
    xml.NewXMLPathBuilder().
        AddOrphan("//hello", NamespaceIETFEPP10.String()).String(),
    funcThatHandlesHelloCommand,
)
commandMux.BindCommand("info", NamespaceIETFContact10.String(),
    funcTharHandlesContactInfoCommand,
)

server.HandleCommand = commandMux.Handle
server.Greeting = commandMux.GetGreeting

Documentation

Index

Constants

View Source
const (
	StatusSuccess       = 1000
	StatusActionPending = 1001
	StatusNoMessage     = 1300
	StatusAckToDequeue  = 1301
	StatusEndingSession = 1500

	StatusUnknownCommand     = 2000
	StatusCommandSyntaxError = 2001
	StatusCommandUseError    = 2002
	StatusMissingParameter   = 2003
	StatusValueRangeError    = 2004
	StatusValueSyntaxError   = 2005

	StatusUnimplementedProtocolVersion = 2100
	StatusUnimplementedCommand         = 2101
	StatusUnimplementedOption          = 2102
	StatusUnimplementedExtension       = 2103
	StatusBillingFailure               = 2104
	StatusNotEligibleForRenewal        = 2105
	StatusNotEligibleForTransfer       = 2106

	StatusAuthenticationError             = 2200
	StatusAuthorizationError              = 2201
	StatusInvalidAuthorizationInformation = 2202

	StatusObjectPendingTransfer               = 2300
	StatusObjectNotPendingTransfer            = 2301
	StatusObjectExists                        = 2302
	StatusObjectDoesNotExist                  = 2303
	StatusObjectStatusProhibitsOperation      = 2304
	StatusObjectAssociationProhibitsOperation = 2305
	StatusParameterPolicyError                = 2306
	StatusUnimplementedObjectService          = 2307
	StatusDataManagementPolicyViolation       = 2308

	StatusCommandFailed                         = 2400
	StatusCommandFailedClosingConnection        = 2500
	StatusAuthenticationErrorClosingConnection  = 2501
	StatusSessionLimitExceededClosingConnection = 2502
)

EPP result codes as described in https://datatracker.ietf.org/doc/html/rfc5730#section-3

Variables

View Source
var ErrMessageSize = errors.New("message size exceeds limit")

ErrMessageSize represent an error where the incoming message size is bigger than allowed.

Functions

func MessageReader

func MessageReader(r io.Reader, msgLimit int64) (io.Reader, error)

MessageReader returns an io.Reader that reads one message according to the message size header. Blocks until a message size header is read. The message limit is in bytes.

func ParseXMLBool

func ParseXMLBool(value string) (bool, error)

ParseXMLBool parses an XML value according to the XML Schema Part 2: Datatypes 3.2.2 boolean specification. Note: does not properly handle the replace and collapse constraints.

func StatusText added in v0.1.1

func StatusText(code int) string

StatusText returns the EPP status text for the status code.

Types

type CommandFunc

type CommandFunc func(context.Context, Writer, *etree.Document)

CommandFunc is the signature of a function which handles commands. The command xml information is in the etree.Document and the response should be written on the ResponseWriter. type HandlerFunc func(context.Context, *ResponseWriter, *etree.Document).

type CommandMux

type CommandMux struct {
	Logger Logger
	// contains filtered or unexported fields
}

CommandMux parses and routes xml commands to bound handlers.

func (*CommandMux) Bind

func (c *CommandMux) Bind(path string, handlerFunc CommandFunc)

Bind will bind a handler to a path.

func (*CommandMux) BindCommand

func (c *CommandMux) BindCommand(command, ns string, handlerFunc CommandFunc)

BindCommand is a convenience method wrapping `Bind` with the common pattern used in epp. Note that it's currently hardcoded in the namespace-uri versions since there is currently only one.

func (*CommandMux) BindGreeting

func (c *CommandMux) BindGreeting(handler CommandFunc)

BindGreeting bind a greeting handler. Useful because EPP needs to send a greeting on connect.

func (*CommandMux) GetGreeting

func (c *CommandMux) GetGreeting(ctx context.Context, rw *ResponseWriter)

GetGreeting returns a greeting.

func (*CommandMux) Handle

func (c *CommandMux) Handle(ctx context.Context, rw *ResponseWriter, cmd io.Reader)

Handle handles a command. Commands will be routed according to how they are bound by the Bind function.

type DummyLogger

type DummyLogger struct{}

DummyLogger for the logger interface used for testing.

func (*DummyLogger) Debugf

func (*DummyLogger) Debugf(format string, args ...interface{})

Debugf for DummyLogger fmt.Printf the information.

func (*DummyLogger) Errorf

func (*DummyLogger) Errorf(format string, args ...interface{})

Errorf for DummyLogger fmt.Printf the information.

func (*DummyLogger) Infof

func (*DummyLogger) Infof(format string, args ...interface{})

Infof for DummyLogger fmt.Printf the information.

type EppError added in v0.1.1

type EppError struct {
	Code      int
	Message   string
	Values    []Value
	ExtValues []ExtValue
}

EppError represent the data needed for an EPP error.

func NewError

func NewError(code int) *EppError

NewError create a new Error.

func (*EppError) Error added in v0.1.1

func (err *EppError) Error() string

Error implements the error interface.

func (*EppError) WithExtValues added in v0.1.1

func (err *EppError) WithExtValues(extValue ...ExtValue) *EppError

WithExtValues add extvalue data to the error.

func (*EppError) WithValues added in v0.1.1

func (err *EppError) WithValues(value ...Value) *EppError

WithValues add value data to the error.

type ExtValue

type ExtValue struct {
	Element   string
	Value     string
	Namespace string
	Reason    string
}

ExtValue represent the extvalue element in an EPP error.

type KeepAliveConn

type KeepAliveConn interface {
	SetKeepAlive(b bool) error
	SetKeepAlivePeriod(d time.Duration) error
}

KeepAliveConn can set keep alive information.

type Listener

type Listener interface {
	Accept() (net.Conn, error)
	Close() error
	Addr() net.Addr
}

Listener can accept new connections.

type Logger

type Logger interface {
	Debugf(string, ...interface{})
	Errorf(string, ...interface{})
	Infof(string, ...interface{})
}

Logger hold all logging functions needed.

type MessageBuffer

type MessageBuffer struct {
	bytes.Buffer
}

MessageBuffer is a bytes.Buffer with a FlushTo method that will flush the contents of the buffer to a destination after writing the message size header.

func (*MessageBuffer) FlushTo

func (mb *MessageBuffer) FlushTo(dst io.Writer) error

FlushTo flushes the buffer to dst after writing the message size header.

type Namespace

type Namespace int

Namespace is the enum type for namespaces.

const (
	NamespaceUnknown Namespace = iota
	NamespaceIETFEPP10
	NamespaceW3XSI
	NamespaceIETFHost10
	NamespaceIETFContact10
	NamespaceIETFDomain10
	NamespaceIETFSecDNS10
	NamespaceIETFSecDNS11
	NamespaceIISEpp12
	NamespaceIISRegistryLock10
)

Supported namespaces.

func NamespaceFromString added in v0.1.1

func NamespaceFromString(ns string) Namespace

NamespaceFromString return a namespace from a given string. If the namespace is not supported NamespaceUnknown will be returned.

func (Namespace) IsExtensionNamespace

func (n Namespace) IsExtensionNamespace() bool

IsExtensionNamespace can be used to see if a given namespace is of the extension type.

func (Namespace) IsObjectNamespace

func (n Namespace) IsObjectNamespace() bool

IsObjectNamespace can be used to see if a given namespace is of the object type.

func (Namespace) String

func (n Namespace) String() string

String return the namespace as a string.

type Namespaces

type Namespaces []Namespace

Namespaces is a list of namespaces.

func (Namespaces) HasNamespace

func (ns Namespaces) HasNamespace(wantedNs Namespace) bool

HasNamespace check if a given namespace is in the list of namespaces.

type ResponseWriter

type ResponseWriter struct {
	MessageBuffer
	// contains filtered or unexported fields
}

ResponseWriter is an io.Writer that buffers response data before writing it on the connection. Call CloseAfterWrite to close the connection after the response has been flushed.

func (*ResponseWriter) CloseAfterWrite

func (c *ResponseWriter) CloseAfterWrite()

CloseAfterWrite will set the flag to close the connection after the response has been flushed.

func (*ResponseWriter) ShouldCloseAfterWrite

func (c *ResponseWriter) ShouldCloseAfterWrite() bool

ShouldCloseAfterWrite get to know if you should close after write.

type Server

type Server struct {
	// HandleCommand handles commands for a connection. Write the response on rw and
	// read the command from cmd.
	HandleCommand func(ctx context.Context, rw *ResponseWriter, cmd io.Reader)

	// Greeting is called once when a new connection is established and should
	// write a greeting on rw.
	Greeting func(ctx context.Context, rw *ResponseWriter)

	// ConnContext can be used to add metadata to a connection. All future
	// calls to the Handler will include this context.
	ConnContext func(ctx context.Context, conn *tls.Conn) (context.Context, error)

	// CloseConnHook can be used to run a function after a connection has been closed,
	// taking the closed connection as an argument.
	CloseConnHook func(ctx context.Context, conn *tls.Conn)

	TLSConfig tls.Config

	// Timeout is the total time a connection can stay open on the server.
	// After this duration the connection is automatically closed.
	Timeout time.Duration

	// IdleTimeout is how long the connection will stay open without any
	// activity.
	IdleTimeout time.Duration

	// WriteTimeout is how long to wait for writes on the response writer.
	WriteTimeout time.Duration

	// ReadTimeout is how long to wait for reading a command.
	ReadTimeout time.Duration

	// MaxMessageSize if set will return an error if the incoming request
	// is bigger than the set size in bytes. 0 indicates no limit.
	MaxMessageSize int64

	// Logger logs errors when accepting connections, unexpected behavior
	// from handlers and underlying connection errors.
	Logger Logger
	// contains filtered or unexported fields
}

Server is an EPP server.

func (*Server) Close

func (s *Server) Close() error

Close will gracefully stop the server.

func (*Server) CloseConnection

func (s *Server) CloseConnection(conn *tls.Conn) error

CloseConnection will gracefully close the provided conn.

func (*Server) Serve

func (s *Server) Serve(listener Listener) error

Serve will start a server on the provided listener.

type Value

type Value struct {
	Element string
	Value   string
}

Value represent the value element in an EPP error.

type Writer

type Writer interface {
	io.Writer
	CloseAfterWrite()
	Reset()
}

Writer can write and close writers.

type XMLPathBuilder

type XMLPathBuilder string

XMLPathBuilder is a string with xml path functions.

func NewXMLPathBuilder

func NewXMLPathBuilder() XMLPathBuilder

NewXMLPathBuilder get a new xml path builder.

func (XMLPathBuilder) Add

func (b XMLPathBuilder) Add(tag, namespace string) XMLPathBuilder

Add a tag to the path. If no "/" is present in the beginning of the tag it will be added.

func (XMLPathBuilder) AddOrphan

func (b XMLPathBuilder) AddOrphan(tag, namespace string) XMLPathBuilder

AddOrphan add an orphaned (no parent - no "/" prefix) tag to the path.

func (XMLPathBuilder) String

func (b XMLPathBuilder) String() string

String get the path as a string.

type XMLString

type XMLString string

XMLString is a string that will be XML encoded when used.

func (XMLString) String

func (x XMLString) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL