{"modulePath":"github.com/foxcpp/maddy","version":"v0.3.3","isLatest":false,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package module\n\nPackage module contains modules registry and interfaces implemented by modules.\n\nInterfaces are placed here to prevent circular dependencies.\n\nEach interface required by maddy for operation is provided by some object called \"module\".  This includes authentication, storage backends, DKIM, email filters, etc.  Each module may serve multiple functions. I.e. it can be IMAP storage backend, SMTP downstream and authentication provider at the same moment.\n\nEach module gets its own unique name (sql for go-imap-sql, proxy for proxy module, local for local delivery perhaps, etc). Each module instance also can have its own unique name can be used to refer to it in configuration.\n\n## Variables\n\n```go\nvar (\n\t// ErrUnknownCredentials should be returned by auth. provider if supplied\n\t// credentials are valid for it but are not recognized (e.g. not found in\n\t// used DB).\n\tErrUnknownCredentials = errors.New(\"unknown credentials\")\n)\n```\n\n```go\nvar (\n\tInitialized = make(map[string]bool)\n)\n```\n\n## Functions\n\n```go\nfunc GenerateMsgID() (string, error)\n```\nGenerateMsgID generates a string usable as MsgID field in module.MsgMeta.\n\n```go\nfunc HasInstance(name string) bool\n```\n\n```go\nfunc Register(name string, factory FuncNewModule)\n```\nRegister adds module factory function to global registry.\n\nname must be unique. Register will panic if module with specified name already exists in registry.\n\nYou probably want to call this function from func init() of module package.\n\n```go\nfunc RegisterAlias(aliasName, instName string)\n```\nRegisterAlias creates an association between a certain name and instance name.\n\nAfter RegisterAlias, module.GetInstance(aliasName) will return the same result as module.GetInstance(instName).\n\n```go\nfunc RegisterEndpoint(name string, factory FuncNewEndpoint)\n```\nRegisterEndpoint registers an endpoint module.\n\nSee FuncNewEndpoint for information about differences of endpoint modules from regular modules.\n\n```go\nfunc RegisterInstance(inst Module, cfg *config.Map)\n```\nRegisterInstance adds module instance to the global registry.\n\nInstance name must be unique. Second RegisterInstance with same instance name will replace previous.\n\n## Types\n\n```go\ntype Check interface {\n\t// CheckStateForMsg initializes the \"internal\" check state required for\n\t// processing of the new message.\n\t//\n\t// NOTE: Returned CheckState object must be hashable (usable as a map key).\n\t// This is used to deduplicate Check* calls, the easiest way to achieve\n\t// this is to have CheckState as a pointer to some struct, all pointers\n\t// are hashable.\n\tCheckStateForMsg(ctx context.Context, msgMeta *MsgMetadata) (CheckState, error)\n}\n```\nCheck is the module interface that is meant for read-only (with the exception of the message header modifications) (meta-)data checking.\n\n```go\ntype CheckResult struct {\n\t// Reason is the error that is reported to the message source\n\t// if check decided that the message should be rejected.\n\tReason error\n\n\t// Reject is the flag that specifies that the message\n\t// should be rejected.\n\tReject bool\n\n\t// Quarantine is the flag that specifies that the message\n\t// is considered \"possibly malicious\" and should be\n\t// put into Junk mailbox.\n\t//\n\t// This value is copied into MsgMetadata by the msgpipeline.\n\tQuarantine bool\n\n\t// AuthResult is the information that is supposed to\n\t// be included in Authentication-Results header.\n\tAuthResult []authres.Result\n\n\t// Header is the header fields that should be\n\t// added to the header after all checks.\n\tHeader textproto.Header\n}\n```\n\n```go\ntype CheckState interface {\n\t// CheckConnection is executed once when client sends a new message.\n\t//\n\t// Result may be cached for the whole client connection so this function\n\t// may not be called sometimes.\n\tCheckConnection(ctx context.Context) CheckResult\n\n\t// CheckSender is executed once when client sends the message sender\n\t// information (e.g. on the MAIL FROM command).\n\tCheckSender(ctx context.Context, mailFrom string) CheckResult\n\n\t// CheckRcpt is executed for each recipient when its address is received\n\t// from the client (e.g. on the RCPT TO command).\n\tCheckRcpt(ctx context.Context, rcptTo string) CheckResult\n\n\t// CheckBody is executed once after the message body is received and\n\t// buffered in memory or on disk.\n\t//\n\t// Check code should use passed mutex when working with the message header.\n\t// Body can be read without locking it since it is read-only.\n\tCheckBody(ctx context.Context, header textproto.Header, body buffer.Buffer) CheckResult\n\n\t// Close is called after the message processing ends, even if any of the\n\t// Check* functions return an error.\n\tClose() error\n}\n```\n\n```go\ntype ConnState struct {\n\t// IANA name (ESMTP, ESMTPS, etc) of the protocol message was received\n\t// over. If the message was generated locally, this field is empty.\n\tProto string\n\n\t// Information about the SMTP connection, including HELO hostname and\n\t// source IP. Valid only if Proto refers the SMTP protocol or its variant\n\t// (e.g. LMTP).\n\tsmtp.ConnectionState\n\n\t// The RDNSName field contains the result of Reverse DNS lookup on the\n\t// client IP.\n\t//\n\t// The underlying type is the string or untyped nil value. It is the\n\t// message source responsibility to populate this field.\n\t//\n\t// Valid values of this field consumers need to be aware of:\n\t// RDNSName = nil\n\t//   The reverse DNS lookup is not applicable for that message source.\n\t//   Typically the case for messages generated locally.\n\t// RDNSName != nil, but Get returns nil\n\t//   The reverse DNS lookup was attempted, but resulted in an error.\n\t//   Consumers should assume that the PTR record doesn't exist.\n\tRDNSName *future.Future\n\n\t// If the client successfully authenticated using a username/password pair.\n\t// This field contains the username.\n\tAuthUser string\n\n\t// If the client successfully authenticated using a username/password pair.\n\t// This field should be cleaned if the ConnState object is serialized\n\tAuthPassword string\n}\n```\nConnState structure holds the state information of the protocol used to accept this message.\n\n```go\ntype Delivery interface {\n\t// AddRcpt adds the target address for the message.\n\t//\n\t// The domain part of the address is assumed to be U-labels with NFC normalization\n\t// and case-folding applied. The message source should ensure that by\n\t// calling address.CleanDomain if necessary.\n\t//\n\t// Implementation should assume that no case-folding or deduplication was\n\t// done by caller code. Its implementation responsibility to do so if it is\n\t// necessary. It is not recommended to reject duplicated recipients,\n\t// however. They should be silently ignored.\n\t//\n\t// Implementation should do as much checks as possible here and reject\n\t// recipients that can't be used.  Note: MsgMetadata object passed to Start\n\t// contains BodyLength field. If it is non-zero, it can be used to check\n\t// storage quota for the user before Body.\n\tAddRcpt(ctx context.Context, rcptTo string) error\n\n\t// Body sets the body and header contents for the message.\n\t// If this method fails, message is assumed to be undeliverable\n\t// to all recipients.\n\t//\n\t// Implementation should avoid doing any persistent changes to the\n\t// underlying storage until Commit is called. If that is not possible,\n\t// Abort should (attempt to) rollback any such changes.\n\t//\n\t// If Body can't be implemented without per-recipient failures,\n\t// then delivery object should also implement PartialDelivery interface\n\t// for use by message sources that are able to make sense of per-recipient\n\t// errors.\n\t//\n\t// Here is the example of possible implementation for maildir-based\n\t// storage:\n\t// Calling Body creates a file in tmp/ directory.\n\t// Commit moves the created file to new/ directory.\n\t// Abort removes the created file.\n\tBody(ctx context.Context, header textproto.Header, body buffer.Buffer) error\n\n\t// Abort cancels message delivery.\n\t//\n\t// All changes made to the underlying storage should be aborted at this\n\t// point, if possible.\n\tAbort(ctx context.Context) error\n\n\t// Commit completes message delivery.\n\t//\n\t// It generally should never fail, since failures here jeopardize\n\t// atomicity of the delivery if multiple targets are used.\n\tCommit(ctx context.Context) error\n}\n```\n\n```go\ntype DeliveryTarget interface {\n\t// Start starts the delivery of a new message.\n\t//\n\t// The domain part of the MAIL FROM address is assumed to be U-labels with\n\t// NFC normalization and case-folding applied. The message source should\n\t// ensure that by calling address.CleanDomain if necessary.\n\tStart(ctx context.Context, msgMeta *MsgMetadata, mailFrom string) (Delivery, error)\n}\n```\nDeliveryTarget interface represents abstract storage for the message data (typically persistent) or other kind of component that can be used as a final destination for the message.\n\n```go\ntype Dummy struct {\n\t// contains filtered or unexported fields\n}\n```\nDummy is a struct that implements PlainAuth and DeliveryTarget interfaces but does nothing. Useful for testing.\n\nIt is always registered under the 'dummy' name and can be used in both tests and the actual server code (but the latter is kinda pointless).\n\n```go\nfunc (d *Dummy) AuthPlain(username, _ string) error\n```\n\n```go\nfunc (d *Dummy) Init(_ *config.Map) error\n```\n\n```go\nfunc (d *Dummy) InstanceName() string\n```\n\n```go\nfunc (d *Dummy) Lookup(_ string) (string, bool, error)\n```\n\n```go\nfunc (d *Dummy) Name() string\n```\n\n```go\nfunc (d *Dummy) Start(ctx context.Context, msgMeta *MsgMetadata, mailFrom string) (Delivery, error)\n```\n\n```go\ntype EarlyCheck interface {\n\tCheckConnection(ctx context.Context, state *smtp.ConnectionState) error\n}\n```\nEarlyCheck is an optional module interface that can be implemented by module implementing Check.\n\nIt is used as an optimization to reject obviously malicious connections before allocating resources for SMTP session.\n\nThe Status of this check is accept (no error) or reject (error) only, no advanced handling is available (such as 'quarantine' action and headers prepending).\n\n```go\ntype FuncNewEndpoint func(modName string, addrs []string) (Module, error)\n```\nFuncNewEndpoint is a function that creates new instance of endpoint module.\n\nCompared to regular modules, endpoint module instances are: - Not registered in the global registry. - Can't be defined inline. - Don't have an unique name - All config arguments are always passed as an 'addrs' slice and not used as names.\n\nAs a consequence of having no per-instance name, InstanceName of the module object always returns the same value as Name.\n\n```go\nfunc GetEndpoint(name string) FuncNewEndpoint\n```\nGetEndpoints returns an endpoint module from global registry.\n\nNil is returned if no module with specified name is registered.\n\n```go\ntype FuncNewModule func(modName, instName string, aliases, inlineArgs []string) (Module, error)\n```\nFuncNewModule is function that creates new instance of module with specified name.\n\nModule.InstanceName() of the returned module object should return instName. aliases slice contains other names that can be used to reference created module instance.\n\nIf module is defined inline, instName will be empty and all values specified after module name in configuration will be in inlineArgs.\n\n```go\nfunc Get(name string) FuncNewModule\n```\nGet returns module from global registry.\n\nThis function does not return endpoint-type modules, use GetEndpoint for that. Nil is returned if no module with specified name is registered.\n\n```go\ntype ManageableStorage interface {\n\tStorage\n\n\tListIMAPAccts() ([]string, error)\n\tCreateIMAPAcct(username string) error\n\tDeleteIMAPAcct(username string) error\n}\n```\nManageableStorage is an extended Storage interface that allows to list existing accounts, create and delete them.\n\n```go\ntype Modifier interface {\n\t// ModStateForMsg initializes modifier \"internal\" state\n\t// required for processing of the message.\n\tModStateForMsg(ctx context.Context, msgMeta *MsgMetadata) (ModifierState, error)\n}\n```\nModifier is the module interface for modules that can mutate the processed message or its meta-data.\n\nCurrently, the message body can't be mutated for efficiency and correctness reasons: It would require \"rebuffering\" (see buffer.Buffer doc), can invalidate assertions made on the body contents before modification and will break DKIM signatures.\n\nOnly message header can be modified. Furthermore, it is highly discouraged for modifiers to remove or change existing fields to prevent issues outlined above.\n\nCalls on ModifierState are always strictly ordered. RewriteRcpt is newer called before RewriteSender and RewriteBody is never called before RewriteRcpts. This allows modificator code to save values passed to previous calls for use in later operations.\n\n```go\ntype ModifierState interface {\n\t// RewriteSender allows modifier to replace MAIL FROM value.\n\t// If no changes are required, this method returns its\n\t// argument, otherwise it returns a new value.\n\t//\n\t// Note that per-source/per-destination modifiers are executed\n\t// after routing decision is made so changed value will have no\n\t// effect on it.\n\t//\n\t// Also note that MsgMeta.OriginalFrom will still contain the original value\n\t// for purposes of tracing. It should not be modified by this method.\n\tRewriteSender(ctx context.Context, mailFrom string) (string, error)\n\n\t// RewriteRcpt replaces RCPT TO value.\n\t// If no changed are required, this method returns its argument, otherwise\n\t// it returns a new value.\n\t//\n\t// MsgPipeline will take of populating MsgMeta.OriginalRcpts. RewriteRcpt\n\t// doesn't do it.\n\tRewriteRcpt(ctx context.Context, rcptTo string) (string, error)\n\n\t// RewriteBody modifies passed Header argument and may optionally\n\t// inspect the passed body buffer to make a decision on new header field values.\n\t//\n\t// There is no way to modify the body and RewriteBody should avoid\n\t// removing existing header fields and changing their values.\n\tRewriteBody(ctx context.Context, h *textproto.Header, body buffer.Buffer) error\n\n\t// Close is called after the message processing ends, even if any of the\n\t// Rewrite* functions return an error.\n\tClose() error\n}\n```\n\n```go\ntype Module interface {\n\t// Init performs actual initialization of the module.\n\t//\n\t// It is not done in FuncNewModule so all module instances are\n\t// registered at time of initialization, thus initialization does not\n\t// depends on ordering of configuration blocks and modules can reference\n\t// each other without any problems.\n\t//\n\t// Module can use passed config.Map to read its configuration variables.\n\tInit(*config.Map) error\n\n\t// Name method reports module name.\n\t//\n\t// It is used to reference module in the configuration and in logs.\n\tName() string\n\n\t// InstanceName method reports unique name of this module instance or empty\n\t// string if module instance is unnamed.\n\tInstanceName() string\n}\n```\nModule is the interface implemented by all maddy module instances.\n\nIt defines basic methods used to identify instances.\n\nAdditionally, module can implement io.Closer if it needs to perform clean-up on shutdown. If module starts long-lived goroutines - they should be stopped \\*before\\* Close method returns to ensure graceful shutdown.\n\n```go\nfunc GetInstance(name string) (Module, error)\n```\nGetInstance returns module instance from global registry, initializing it if necessary.\n\nError is returned if module initialization fails or module instance does not exists.\n\n```go\ntype MsgMetadata struct {\n\t// Unique identifier for this message. Randomly generated by the\n\t// message source module.\n\tID string\n\n\t// Original message sender address as it was received by the message source.\n\t//\n\t// Note that this field is meant for use for tracing purposes.\n\t// All routing and other decisions should be made based on the sender address\n\t// passed separately (for example, mailFrom argument for CheckSender function)\n\t// Note that addresses may contain unescaped Unicode characters.\n\tOriginalFrom string\n\n\t// If set - no SrcHostname and SrcAddr will be added to Received\n\t// header. These fields are still written to the server log.\n\tDontTraceSender bool\n\n\t// Quarantine is a message flag that is should be set if message is\n\t// considered \"suspicious\" and should be put into \"Junk\" folder\n\t// in the storage.\n\t//\n\t// This field should not be modified by the checks that verify\n\t// the message. It is set only by the message pipeline.\n\tQuarantine bool\n\n\t// OriginalRcpts contains the mapping from the final recipient to the\n\t// recipient that was presented by the client.\n\t//\n\t// MsgPipeline will update that field when recipient modifiers\n\t// are executed.\n\t//\n\t// It should be used when reporting information back to client (via DSN,\n\t// for example) to prevent disclosing information about aliases\n\t// which is usually unwanted.\n\tOriginalRcpts map[string]string\n\n\t// SMTPOpts contains the SMTP MAIL FROM command arguments, if the message\n\t// was accepted over SMTP or SMTP-like protocol (such as LMTP).\n\t//\n\t// Note that the Size field should not be used as source of information about\n\t// the body size. Especially since it counts the header too whereas\n\t// Buffer.Len does not.\n\tSMTPOpts smtp.MailOptions\n\n\t// Conn contains the information about the underlying protocol connection\n\t// that was used to accept this message. The referenced instance may be shared\n\t// between multiple messages.\n\t//\n\t// It can be nil for locally generated messages.\n\tConn *ConnState\n}\n```\nMsgMetadata structure contains all information about the origin of the message and all associated flags indicating how it should be handled by components.\n\nAll fields should be considered read-only except when otherwise is noted. Module instances should avoid keeping reference to the instance passed to it and copy the structure using DeepCopy method instead.\n\nCompatibility with older values should be considered when changing this structure since it is serialized to the disk by the queue module using JSON. Modules should correctly handle missing or invalid values.\n\n```go\nfunc (msgMeta *MsgMetadata) DeepCopy() *MsgMetadata\n```\nDeepCopy creates a copy of the MsgMetadata structure, also copying contents of the maps and slices.\n\nThere are a few exceptions, however: - SrcAddr is not copied and copy field references original value.\n\n```go\ntype MutableTable interface {\n\tTable\n\tKeys() ([]string, error)\n\tRemoveKey(k string) error\n\tSetKey(k, v string) error\n}\n```\n\n```go\ntype PartialDelivery interface {\n\t// BodyNonAtomic is similar to Body method of the regular Delivery interface\n\t// with the except that it allows target to reject the body only for some\n\t// recipients by setting statuses using passed collector object.\n\t//\n\t// This interface is preferred by the LMTP endpoint and queue implementation\n\t// to ensure correct handling of partial failures.\n\tBodyNonAtomic(ctx context.Context, c StatusCollector, header textproto.Header, body buffer.Buffer)\n}\n```\nPartialDelivery is an optional interface that may be implemented by the object returned by DeliveryTarget.Start. See PartialDelivery.BodyNonAtomic documentation for details.\n\n```go\ntype PlainAuth interface {\n\tAuthPlain(username, password string) error\n}\n```\nPlainAuth is the interface implemented by modules providing authentication using username:password pairs.\n\n```go\ntype PlainUserDB interface {\n\tPlainAuth\n\tListUsers() ([]string, error)\n\tCreateUser(username, password string) error\n\tSetUserPassword(username, password string) error\n\tDeleteUser(username string) error\n}\n```\nPlainUserDB is a local credentials store that can be managed using maddyctl utility.\n\n```go\ntype StatusCollector interface {\n\t// SetStatus sets the error associated with the recipient.\n\t//\n\t// rcptTo should match exactly the value that was passed to the\n\t// AddRcpt, i.e. if any translations was made by the target,\n\t// they should not affect the rcptTo argument here.\n\t//\n\t// It should not be called multiple times for the same\n\t// value of rcptTo. It also should not be called\n\t// after BodyNonAtomic returns.\n\t//\n\t// SetStatus is goroutine-safe. Implementations\n\t// provide necessary serialization.\n\tSetStatus(rcptTo string, err error)\n}\n```\nStatusCollector is an object that is passed by message source that is interested in intermediate status reports about partial delivery failures.\n\n```go\ntype Storage interface {\n\t// GetOrCreateIMAPAcct returns User associated with storage account specified by\n\t// the name.\n\t//\n\t// If it doesn't exists - it should be created.\n\tGetOrCreateIMAPAcct(username string) (imapbackend.User, error)\n\tGetIMAPAcct(username string) (imapbackend.User, error)\n\n\t// Extensions returns list of IMAP extensions supported by backend.\n\tIMAPExtensions() []string\n}\n```\nStorage interface is a slightly modified go-imap's Backend interface (authentication is removed).\n\n```go\ntype Table interface {\n\tLookup(s string) (string, bool, error)\n}\n```\nTabele is the interface implemented by module that implementation string-to-string translation.\n\n","path":"github.com/foxcpp/maddy/internal/module","name":"module","synopsis":"Package module contains modules registry and interfaces implemented by modules.","isRedistributable":true}
