kmipserver

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2025 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const DEFAULT_MAX_BODY_SIZE = 1 * 1024 * 1024 // Max body size is 1 MB

Variables

View Source
var (
	ErrOperationNotSupported = Errorf(kmip.ResultReasonOperationNotSupported, "Operation not supported")
	ErrFeatureNotSupported   = Errorf(kmip.ResultReasonFeatureNotSupported, "Feature not supported")
	ErrMissingData           = Errorf(kmip.ResultReasonMissingData, "Missing data")
	ErrItemNotFound          = Errorf(kmip.ResultReasonItemNotFound, "Item not found")
	ErrPermissionDenied      = Errorf(kmip.ResultReasonPermissionDenied, "Permission denied")
	ErrInvalidMessage        = Errorf(kmip.ResultReasonInvalidMessage, "Invalid message")
	ErrInvalidField          = Errorf(kmip.ResultReasonInvalidField, "Invalid field")
)
View Source
var ErrShutdown = errors.New("Server is shutting down")

Functions

func ClearIdPlaceholder

func ClearIdPlaceholder(ctx context.Context)

ClearIdPlaceholder resets the idPlaceholder in the given context. This is typically used to clear any temporary identifier placeholders within a batch operation context.

func Errorf

func Errorf(reason kmip.ResultReason, format string, args ...any) error

Errorf creates a new Error with the specified kmip.ResultReason and a formatted message. The message is formatted according to the given format specifier and arguments, similar to fmt.Sprintf.

Parameters:

  • reason: The kmip.ResultReason indicating the reason for the error.
  • format: A format string compatible with fmt.Sprintf.
  • args: Variadic arguments to be formatted into the message.

Returns:

  • error: An Error instance containing the reason and formatted message.

func GetIdOrPlaceholder

func GetIdOrPlaceholder(ctx context.Context, reqId string) (string, error)

GetIdOrPlaceholder returns the provided reqId if it is not empty. If reqId is empty, it attempts to retrieve an ID placeholder from the context. If neither is available, it returns an error indicating that the ID placeholder is empty.

func GetProtocolVersion

func GetProtocolVersion(ctx context.Context) kmip.ProtocolVersion

GetProtocolVersion retrieves the KMIP protocol version from the provided context. It panics if used outside the context of kmip request processing. Returns the ProtocolVersion from the batch header.

func GetRequestHeader added in v0.5.0

func GetRequestHeader(ctx context.Context) kmip.RequestHeader

GetRequestHeader retrieves the KMIP request header from the provided context. It panics if used outside the context of kmip request processing. Returns the RequestHeader from the batch.

func IdPlaceholder

func IdPlaceholder(ctx context.Context) string

IdPlaceholder retrieves the idPlaceholder stored in the provided context. If no idPlaceholder is found in the context, it returns an empty string.

func NewHTTPHandler

func NewHTTPHandler(hdl RequestHandler) http.Handler

NewHTTPHandler creates a new HTTP handler that wraps the provided RequestHandler. It returns an http.Handler that can be used to serve HTTP requests using the given handler logic.

The method ServeHTTP handles incoming HTTP requests for the KMIP server. It supports POST requests with Content-Type headers of "text/xml", "application/json", or "application/octet-stream", and unmarshals the request body accordingly. The function enforces a maximum body size and validates the Content-Length header. It processes the KMIP request message and marshals the response using the appropriate format. If an error occurs during unmarshalling, a KMIP error response is sent back. Only POST requests are allowed; other methods receive a 405 Method Not Allowed response. Unsupported Content-Type headers result in a 406 Not Acceptable response, and requests with invalid or missing Content-Length headers receive a 411 Length Required response.

func PeerCertificates

func PeerCertificates(ctx context.Context) []*x509.Certificate

PeerCertificates retrieves the peer certificates from the TLS connection state stored in the provided context. If no TLS connection state is present, it returns nil.

Parameters:

  • ctx: The context containing connection data.

Returns a slice of x509.Certificate pointers representing the peer certificates, or nil if unavailable.

func RemoteAddr

func RemoteAddr(ctx context.Context) string

RemoteAddr retrieves the remote address associated with the given context. If the value is not present or of the wrong type, it returns an empty string.

func SetIdPlaceholder

func SetIdPlaceholder(ctx context.Context, id string)

SetIdPlaceholder sets the idPlaceholder in the given context. This function is intended to be used within a batch context to update the placeholder ID. It will panic if used outside the context of kmip request processing.

Types

type BatchExecutor

type BatchExecutor struct {
	// contains filtered or unexported fields
}

BatchExecutor is responsible for executing KMIP batch operations. It maintains a mapping of KMIP operations to their corresponding handlers, a list of middleware functions to be applied to each operation, and a list of supported KMIP protocol versions.

func NewBatchExecutor

func NewBatchExecutor() *BatchExecutor

NewBatchExecutor creates and returns a new instance of BatchExecutor with initialized routes map, no middlewares, and the default set of supported KMIP protocol versions.

func (*BatchExecutor) BatchItemUse added in v0.5.0

func (exec *BatchExecutor) BatchItemUse(m ...BatchItemMiddleware)

func (*BatchExecutor) HandleRequest

func (exec *BatchExecutor) HandleRequest(ctx context.Context, req *kmip.RequestMessage) *kmip.ResponseMessage

HandleRequest processes a KMIP request message through a chain of middlewares and returns a response message. It initializes a middleware execution chain, passing the request and context through each middleware in order. If all middlewares are executed without error, the request is handled by the core request handler. If an error occurs during processing, it returns an error response message.

Parameters:

  • ctx: The context for request-scoped values, deadlines, and cancellation signals.
  • req: The KMIP request message to be processed.

Returns:

  • *kmip.ResponseMessage: The KMIP response message generated by the handler or error handler.

Errors:

  • This function does not return errors directly. If an error occurs during middleware or request handling, the error is converted into a KMIP error response message.

func (*BatchExecutor) Route

func (exec *BatchExecutor) Route(op kmip.Operation, hdl OperationHandler)

Route registers an OperationHandler for a specific KMIP operation. It associates the given handler (hdl) with the provided operation (op) in the BatchExecutor's routing table, allowing the executor to dispatch requests for that operation to the appropriate handler.

func (*BatchExecutor) SetSupportedProtocolVersions

func (exec *BatchExecutor) SetSupportedProtocolVersions(versions ...kmip.ProtocolVersion)

SetSupportedProtocolVersions sets the supported KMIP protocol versions for the BatchExecutor. If no versions are provided, it defaults to the predefined supported versions. The provided versions are sorted and duplicates are removed before being set.

func (*BatchExecutor) Use

func (exec *BatchExecutor) Use(m ...Middleware)

Use adds one or more Middleware functions to the BatchExecutor's middleware chain. The provided middleware will be executed in the order they are added.

type BatchItemMiddleware added in v0.5.0

type BatchItemMiddleware func(next BatchItemNext, ctx context.Context, bi *kmip.RequestBatchItem) (*kmip.ResponseBatchItem, error)

BatchItemMiddleware defines a function type that wraps the processing of a KMIP request batch item. It takes the next handler in the chain, a context, and the incoming KMIP request batch item, and returns a KMIP response batch item. This allows for implementing cross-cutting concerns specific to individual batch items, such as logging, authentication, or request validation.

type BatchItemNext added in v0.5.0

type BatchItemNext func(ctx context.Context, bi *kmip.RequestBatchItem) (*kmip.ResponseBatchItem, error)

BatchItemNext defines a middleware function signature for batch items that takes a context and a KMIP request batch item, and returns a KMIP response batch item. It is used to chain middleware handlers in the KMIP server's batch item processing pipeline.

type ConnectHook added in v0.5.0

type ConnectHook func(context.Context) (context.Context, error)

ConnectHook is a function that can be used to perform actions when a new connection is established. It takes a context.Context as input and returns a modified context.Context or an error that immediately terminates the connection, without calling any termination hook.

type Error

type Error struct {
	Reason  kmip.ResultReason
	Message string
}

Error represents a KMIP error with a specific reason and an optional message. It encapsulates the KMIP ResultReason and a human-readable error message.

func (Error) Error

func (e Error) Error() string

type Middleware

type Middleware func(next Next, ctx context.Context, msg *kmip.RequestMessage) (*kmip.ResponseMessage, error)

Middleware defines a function type that wraps the processing of a KMIP request message. It takes the next handler in the chain, a context, and the incoming KMIP request message, and returns a KMIP response message or an error. Middlewares can be used to implement cross-cutting concerns such as logging, authentication, or request validation.

func DebugMiddleware

func DebugMiddleware(out io.Writer, marshal func(data any) []byte) Middleware

DebugMiddleware returns a Middleware that logs the incoming KMIP request and the corresponding response to the provided io.Writer. It uses the given marshal function to serialize the request and response data, defaulting to ttlv.MarshalXML if marshal is nil. The middleware also logs the time taken to process the request. If the writer supports flushing, it will be flushed after logging. Any errors encountered during processing are also logged to the writer.

type Next

type Next func(context.Context, *kmip.RequestMessage) (*kmip.ResponseMessage, error)

Next defines a middleware function signature that takes a context and a KMIP request message, and returns a KMIP response message or an error. It is used to chain middleware handlers in the KMIP server processing pipeline.

type OperationHandler

type OperationHandler interface {
	HandleOperation(ctx context.Context, req kmip.OperationPayload) (kmip.OperationPayload, error)
}

OperationHandler defines an interface for handling KMIP operations. Implementations of this interface should provide logic to process a specific KMIP operation by handling the provided request payload and returning a response payload or an error if the operation fails.

func HandleFunc

func HandleFunc[Req, Resp kmip.OperationPayload](h func(ctx context.Context, req Req) (Resp, error)) OperationHandler

HandleFunc wraps a strongly-typed handler function into an OperationHandler. It accepts a handler function h that takes a context and a request of type Req, and returns a response of type Resp and an error. Both Req and Resp must satisfy the kmip.OperationPayload interface. The returned OperationHandler performs a type assertion on the incoming request payload and invokes the handler if the assertion succeeds. If the type assertion fails, it returns an error indicating an invalid payload. This function is intended to simplify the creation of operation handlers by providing type safety and reducing boilerplate code.

type RequestHandler

type RequestHandler interface {
	HandleRequest(ctx context.Context, req *kmip.RequestMessage) *kmip.ResponseMessage
}

RequestHandler defines an interface for handling KMIP request messages. Implementations of this interface should process the provided RequestMessage and return an appropriate ResponseMessage. The context.Context parameter allows for request-scoped values, cancellation, and timeouts.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server represents a KMIP server instance that manages incoming network connections, handles KMIP requests, and coordinates server lifecycle operations. It encapsulates the network listener, request handler, logging, context management for graceful shutdown, and a wait group for synchronizing goroutines. Additionally, it supports hooks for connect and terminate events, allowing customization of behavior when a client connects or disconnects.

func NewServer

func NewServer(listener net.Listener, handler RequestHandler) *Server

NewServer creates and returns a new Server instance using the provided net.Listener and RequestHandler. It panics if the handler is nil. The function initializes internal contexts for server control and request reception, as well as a WaitGroup for managing goroutines.

Parameters:

  • listener: The net.Listener to accept incoming connections.
  • handler: The RequestHandler to process KMIP requests.

Returns:

  • A pointer to the initialized Server.

func (*Server) Serve

func (srv *Server) Serve() error

Serve starts the KMIP server and listens for incoming client connections. It accepts connections in a loop, spawning a new goroutine to handle each connection. If the listener is closed, it returns ErrShutdown. Any other error encountered during Accept is returned immediately. The method blocks until the server is shut down.

func (*Server) Shutdown

func (srv *Server) Shutdown() error

Shutdown gracefully shuts down the server by performing the following steps: 1. Logs a warning message indicating shutdown initiation. 2. Closes the listener to prevent new incoming connections. 3. Cancels the receive context to stop processing new requests. 4. Sets a timeout to force server context cancellation after 3 seconds. 5. Waits for all running requests to complete. 6. Cancels the server's root context. Returns any error encountered while closing the listener.

func (*Server) WithConnectHook added in v0.5.0

func (srv *Server) WithConnectHook(hook ConnectHook) *Server

WithConnectHook sets the connect hook for the server, which is called when a new connection is established. This hook can be used to modify the context for the connection.

Parameters:

  • hook: The ConnectHook function to set.

Returns:

  • The Server instance with the connect hook set.

func (*Server) WithTerminateHook added in v0.5.0

func (srv *Server) WithTerminateHook(hook TerminateHook) *Server

WithTerminateHook sets the terminate hook for the server, which is called when a connection is terminated. This hook can be used to perform any necessary cleanup or logging.

Parameters:

  • hook: The TerminateHook function to set.

Returns:

  • The Server instance with the terminate hook set.

type TerminateHook added in v0.5.0

type TerminateHook func(context.Context)

TerminateHook is a function that can be used to perform cleanup actions when a connection is terminated. It takes a context.Context as input.

NOTE: That context may have already been canceled. To pass it to context-cancellable function consider using WithoutCancel().

Jump to

Keyboard shortcuts

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