xmpp

package module
v0.0.0-...-77fa510 Latest Latest
Warning

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

Go to latest
Published: Jul 6, 2026 License: MIT Imports: 37 Imported by: 0

README

xmpp-go

An XMPP library for Go supporting both client and server roles, with a plugin architecture and building blocks for 50+ XEPs.

Project status

The client and server work end to end and are covered by integration tests (real client ↔ real server over TCP, WebSocket, and BOSH):

  • Connection: full stream negotiation over TCP (<stream:stream>), WebSocket (RFC 7395 <open/> framing), and BOSH (XEP-0124/0206 HTTP long-polling, Client.WithBOSH + Server.BOSHHandler), plus STARTTLS and resource binding.
  • Authentication: SASL SCRAM-SHA-1/256/512 and their -PLUS channel-binding variants (client and server; tls-server-end-point, RFC 5929, negotiated automatically over TLS), PLAIN (refused over cleartext unless explicitly overridden), ANONYMOUS, and EXTERNAL on both sides — the server maps a verified TLS client certificate to a local identity (WithServerClientCertAuth). Auth failures surface as a typed *AuthError.
  • Federation (s2s): server-to-server streams authenticated with XEP-0220 Server Dialback (WithServerS2S); stanzas to remote domains are routed over authenticated s2s streams, and inbound s2s streams are verified via a dialback callback to the originating server.
  • Routing & services: message/presence/IQ routing; service IQs for disco#info/#items, XEP-0199 ping, XEP-0092 version, and RFC 6121 roster get/set; clients auto-answer pings.
  • Presence (RFC 6121): the subscribe/subscribed/unsubscribe state machine with roster updates, roster pushes, and presence broadcast to subscribed contacts.
  • Plugins: an inbound-handler framework routes incoming stanzas to plugins by payload namespace. On the client the disco, ping, version, and roster plugins respond to and issue requests (Client.SendIQ). On the server, WithServerPluginFactory gives each session its own plugin instances with inbound IQ dispatch.
  • Stream Management (XEP-0198): enable/enabled, inbound counting, r/a acknowledgement (delivery confirmation via Session.RequestSMAck), and resumption — a dropped session is parked for a resumption window, stanzas addressed to it are buffered, and Client.Resume restores the bound resource and replays unacknowledged stanzas.
  • BOSH robustness (XEP-0124): request acknowledgements (ack), retransmission recovery via a per-rid response cache (§14.2), pipelined requests with forward-gap ordering, and hold-release so a send is never stalled behind an idle long-poll. The bundled client keeps a concurrent long-poll (requests='2') and retransmits failed requests.
  • JIDs: RFC 7622 normalization — IDNA A-labels for domains, PRECIS UsernameCaseMapped localparts, OpaqueString resources. Stanza extensions round-trip without corruption.

The core RFCs (6120/6121/7622), all three transports (TCP, WebSocket, BOSH), the full SASL mechanism set, Stream Management with resumption, and s2s dialback federation are implemented and integration-tested. Higher-level XEPs beyond the core (MUC, PubSub, MAM, OMEMO, Jingle, …) are provided as plugin building blocks under plugins/; see the feature checklist below.

Features

  • Unified client/server Session type
  • Plugin architecture with dependency resolution
  • Streaming XML parser optimized for XMPP
  • Multiple transports: TCP, WebSocket, BOSH
  • Full SASL support: PLAIN, SCRAM-SHA-1/256/512 (+PLUS), EXTERNAL, ANONYMOUS
  • STARTTLS with certificate verification
  • Stanza multiplexer with middleware support
  • DNS SRV and host-meta resolution
  • Pluggable storage backends: Memory, File, SQLite, PostgreSQL, MySQL, MongoDB, Redis

Installation

go get github.com/meszmate/xmpp-go

Docker / Compose

This repo ships a ready-to-run server binary in cmd/xmppd with Docker and Compose support.

Quick start (self-signed TLS, file storage, default accounts):

docker compose --profile xmpp up --build

The default config lives in docker/xmppd.env. Common overrides:

  • XMPP_DOMAIN (default example.com)
  • XMPP_STORAGE (file|sqlite|postgres|mysql|mongodb|redis|memory)
  • XMPP_STORAGE_DSN (for DB backends)
  • XMPP_PLUGINS (comma list or all)
  • XMPP_DEFAULT_ACCOUNTS (user:pass,user2:pass)
  • XMPP_TLS_SELF_SIGNED=true (auto-generate certs)

Server-side XEP-0077 registration is supported and configurable via:

  • XMPP_REGISTRATION_POLICY (open|closed|invite|admin)
  • XMPP_REGISTRATION_FIELDS (comma list, e.g. username,password,email)
  • XMPP_REGISTRATION_INVITES (comma list of invite tokens)
  • XMPP_REGISTRATION_ADMIN_TOKENS (comma list)
  • XMPP_REGISTRATION_RATE_LIMIT (requests per window)
  • XMPP_REGISTRATION_RATE_WINDOW (Go duration, e.g. 1m)
  • XMPP_REGISTRATION_SCRAM_ITERATIONS (default 4096)
  • XMPP_REGISTRATION_DATAFORM (true|false)

To use a database, enable the matching profile and set XMPP_STORAGE + XMPP_STORAGE_DSN:

docker compose --profile xmpp --profile postgres up --build

GHCR image publishing is wired via .github/workflows/docker.yml and publishes to ghcr.io/meszmate/xmpp-go.

CI notes:

  • No GoReleaser is used. Docker publishing is handled by GitHub Actions and pushes to GHCR on main and tags.
  • docker-compose.yml uses ghcr.io/meszmate/xmpp-go:latest by default.

Pull from GHCR (after CI pushes):

docker pull ghcr.io/meszmate/xmpp-go:latest

Quick Start

package main

import (
    "context"
    "log"

    xmpp "github.com/meszmate/xmpp-go"
    "github.com/meszmate/xmpp-go/jid"
    "github.com/meszmate/xmpp-go/stanza"
    "github.com/meszmate/xmpp-go/plugins/disco"
    "github.com/meszmate/xmpp-go/plugins/roster"
)

func main() {
    client, err := xmpp.NewClient(
        jid.MustParse("user@example.com"),
        "password",
        xmpp.WithPlugins(disco.New(), roster.New()),
    )
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    ctx := context.Background()
    if err := client.Connect(ctx); err != nil {
        log.Fatal(err)
    }

    msg := stanza.NewMessage(stanza.MessageChat)
    msg.To = jid.MustParse("friend@example.com")
    msg.Body = "Hello from xmpp-go!"
    _ = client.Send(ctx, msg)
}

In-Band Registration (XEP-0077)

xmpp-go provides a standalone registration flow in plugins/register for account creation before authentication. The helper functions automatically handle stream setup, STARTTLS upgrade, classic register fields, and data-form registration.

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "github.com/meszmate/xmpp-go/plugins/register"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    form, err := register.FetchRegistrationForm(ctx, "example.com", 5222)
    if err != nil {
        log.Fatal(err)
    }

    fields := map[string]string{
        "username": "newuser",
        "password": "strong-password",
        "email":    "newuser@example.com",
    }

    result, err := register.SubmitRegistration(
        ctx,
        "example.com",
        5222,
        fields,
        form.IsDataForm,
        form.FormType,
    )
    if err != nil {
        log.Fatal(err)
    }
    if !result.Success {
        log.Fatal(result.Error)
    }

    fmt.Println("Registered JID:", result.JID)
}

For data-form registration, include all required fields from the fetched form in fields (including hidden fields and CAPTCHA answers when requested).

Feature Checklist

Core (RFC 6120/6121/7622)
  • JID parsing and validation (RFC 7622)
  • JID escaping (XEP-0106)
  • XML stream reader/writer
  • Stream error conditions
  • STARTTLS negotiation
  • SASL authentication
  • Resource binding
  • Stanza types: Message, Presence, IQ
  • Stanza error conditions
  • Roster management (RFC 6121)
  • Presence management (RFC 6121)
Transports
  • TCP transport
  • WebSocket transport (RFC 7395)
  • BOSH transport (XEP-0124/0206)
SASL Mechanisms
  • PLAIN
  • SCRAM-SHA-1 / SCRAM-SHA-1-PLUS
  • SCRAM-SHA-256 / SCRAM-SHA-256-PLUS
  • SCRAM-SHA-512 / SCRAM-SHA-512-PLUS
  • EXTERNAL
  • ANONYMOUS
Service Discovery & Capabilities
  • XEP-0030: Service Discovery
  • XEP-0115: Entity Capabilities
Messaging
  • XEP-0085: Chat State Notifications
  • XEP-0184: Message Delivery Receipts
  • XEP-0280: Message Carbons
  • XEP-0308: Last Message Correction
  • XEP-0313: Message Archive Management
  • XEP-0333: Chat Markers
  • XEP-0334: Message Processing Hints
  • XEP-0359: Unique/Stable Stanza IDs
  • XEP-0393: Message Styling
  • XEP-0424: Message Retraction
  • XEP-0444: Message Reactions
Group Chat
  • XEP-0045: Multi-User Chat
  • XEP-0249: Direct MUC Invitations
  • XEP-0369: MIX Core
  • XEP-0403/0405/0406/0407: MIX extensions
  • XEP-0425: Message Moderation
Stream Management
  • XEP-0198: Stream Management
PubSub & Storage
  • XEP-0004: Data Forms
  • XEP-0060: Publish-Subscribe
  • XEP-0163: Personal Eventing Protocol
  • XEP-0402: PEP Native Bookmarks
User Profile
  • XEP-0054: vcard-temp
  • XEP-0084: User Avatar
  • XEP-0092: Software Version
  • XEP-0153: vCard-Based Avatars
  • XEP-0292: vCard4 over XMPP
File Transfer
  • XEP-0047: In-Band Bytestreams
  • XEP-0065: SOCKS5 Bytestreams
  • XEP-0066: Out of Band Data
  • XEP-0234: Jingle File Transfer
  • XEP-0363: HTTP File Upload
  • XEP-0446/0447/0448: Stateless File Sharing
Encryption
Jingle (Voice/Video)
  • XEP-0166: Jingle
  • XEP-0167: Jingle RTP Sessions
  • XEP-0176: Jingle ICE-UDP Transport
  • XEP-0177: Jingle Raw UDP Transport
  • XEP-0320: DTLS-SRTP in Jingle
  • XEP-0353: Jingle Message Initiation
Mobile & Push
  • XEP-0352: Client State Indication
  • XEP-0357: Push Notifications
Server Features
  • XEP-0012: Last Activity
  • XEP-0050: Ad-Hoc Commands
  • XEP-0059: Result Set Management
  • XEP-0077: In-Band Registration
  • XEP-0114: Jabber Component Protocol
  • XEP-0191: Blocking Command
  • XEP-0215: External Service Discovery
  • XEP-0220: Server Dialback
  • XEP-0288: Bidirectional Server-to-Server
Utilities
  • XEP-0082: Date/Time Profiles
  • XEP-0156: DNS/host-meta resolution
  • XEP-0199: XMPP Ping
  • XEP-0202: Entity Time
  • XEP-0203: Delayed Delivery
  • XEP-0231: Bits of Binary
  • XEP-0297: Stanza Forwarding
  • XEP-0300: Cryptographic Hash Functions
  • XEP-0368: SRV records for XMPP over TLS
Modern Authentication
  • XEP-0386: Bind 2
  • XEP-0388: SASL2
  • XEP-0440: SASL Channel-Binding Type Capability
  • XEP-0484: FAST

Storage Backends

xmpp-go includes a pluggable storage layer. All stateful plugins (roster, blocking, vcard, MUC, MAM, PubSub, bookmarks) automatically use the configured backend, falling back to in-memory storage when none is set.

Backend Package External Dependency
Memory storage/memory None
File (JSON) storage/file None
SQLite storage/sqlite github.com/mattn/go-sqlite3
PostgreSQL storage/postgres github.com/jackc/pgx/v5
MySQL storage/mysql github.com/go-sql-driver/mysql
MongoDB storage/mongodb go.mongodb.org/mongo-driver/v2
Redis storage/redis github.com/redis/go-redis/v9
import (
    xmpp "github.com/meszmate/xmpp-go"
    "github.com/meszmate/xmpp-go/storage/memory"
)

server, _ := xmpp.NewServer("example.com",
    xmpp.WithServerStorage(memory.New()),
    // ...
)

Backends with external dependencies live in separate Go modules so the main module stays dependency-free. Install only what you need:

go get github.com/meszmate/xmpp-go/storage/postgres

See the Storage Guide for full details.

OMEMO Encryption

xmpp-go includes a standalone Signal protocol implementation at crypto/omemo/ for OMEMO v2 (XEP-0384) end-to-end encryption. It is a separate Go module with no dependency on the main library.

go get github.com/meszmate/xmpp-go/crypto/omemo

OMEMO works across both the server and client:

  • Server side: The PubSub plugin + storage backend persists device lists and bundles (public key material only). No OMEMO-specific configuration needed -- it uses standard PEP nodes.
  • Client side: The crypto/omemo package handles X3DH key agreement, Double Ratchet encryption, and AES-256-GCM. Private keys and session state are stored locally via the omemo.Store interface.
import "github.com/meszmate/xmpp-go/crypto/omemo"

// Client-side crypto store (private keys, sessions, trust)
store := omemo.NewMemoryStore(myDeviceID)
manager := omemo.NewManager(store)

// Generate bundle (private keys stay local, public parts go to server via PEP)
bundle, _ := manager.GenerateBundle(25)

// After fetching a contact's bundle from the server:
manager.ProcessBundle(addr, remoteBundleParsedFromXML)

// Encrypt for recipient devices
encMsg, _ := manager.Encrypt([]byte("Hello!"), recipientAddresses...)

// Decrypt incoming messages
plaintext, _ := manager.Decrypt(senderAddr, incomingMsg)

See the OMEMO Guide for the full server/client architecture, step-by-step setup, and conversion between XML and crypto types.

Documentation

License

MIT License - see LICENSE for details.

Documentation

Overview

Package xmpp provides a comprehensive, production-grade XMPP library for Go.

It supports both client and server roles, is fully extensible via a plugin architecture, and aims to cover every modern XMPP feature including OMEMO encryption, MUC, PubSub, Jingle, and more.

The library is organized into several layers:

  • Core: JID parsing, XML streaming, stanza types, transport abstractions
  • Session: Stream negotiation, SASL, TLS, resource binding, stanza routing
  • Client/Server: High-level APIs for building XMPP clients and servers
  • Plugin System: Extensible architecture for XEP implementations
  • Plugins: Ready-to-use implementations of 50+ XEPs
  • Storage: Pluggable backends (Memory, File, SQLite, PostgreSQL, MySQL, MongoDB, Redis)

Basic client usage:

client, err := xmpp.NewClient(
    jid.MustParse("user@example.com"),
    "password",
    xmpp.WithPlugins(
        disco.New(),
        roster.New(),
        carbons.New(),
    ),
)
if err != nil {
    log.Fatal(err)
}
defer client.Close()

if err := client.Connect(context.Background()); err != nil {
    log.Fatal(err)
}

Index

Constants

View Source
const LibraryVersion = "0.1.0"

LibraryVersion is reported by the server in XEP-0092 Software Version replies.

Variables

This section is empty.

Functions

func ErrBadRequest

func ErrBadRequest(text string) *stanza.StanzaError

func ErrConflict

func ErrConflict(text string) *stanza.StanzaError

func ErrFeatureNotImplemented

func ErrFeatureNotImplemented(text string) *stanza.StanzaError

func ErrForbidden

func ErrForbidden(text string) *stanza.StanzaError

func ErrInternalServerError

func ErrInternalServerError(text string) *stanza.StanzaError

func ErrItemNotFound

func ErrItemNotFound(text string) *stanza.StanzaError

func ErrNotAllowed

func ErrNotAllowed(text string) *stanza.StanzaError

func ErrNotAuthorized

func ErrNotAuthorized(text string) *stanza.StanzaError

func ErrRecipientUnavailable

func ErrRecipientUnavailable(text string) *stanza.StanzaError

func ErrServiceUnavailable

func ErrServiceUnavailable(text string) *stanza.StanzaError

Types

type AuthError

type AuthError struct {
	Condition string // SASL failure condition local name
	Text      string // optional human-readable description
}

AuthError is returned when SASL authentication fails. It exposes the SASL failure condition (e.g. "not-authorized") so callers can distinguish a bad password from other failures.

func (*AuthError) Error

func (e *AuthError) Error() string

type AuthFunc

type AuthFunc func(username, password string) (bool, error)

AuthFunc is a function that validates credentials.

type BindRequest

type BindRequest struct {
	XMLName  xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-bind bind"`
	Resource string   `xml:"resource,omitempty"`
}

BindRequest represents a resource bind request.

type BindResult

type BindResult struct {
	XMLName xml.Name `xml:"urn:ietf:params:xml:ns:xmpp-bind bind"`
	JID     string   `xml:"jid"`
}

BindResult represents a resource bind result.

type CertIdentityFunc

type CertIdentityFunc func(cert *x509.Certificate) (username string, ok bool)

CertIdentityFunc maps a verified client certificate to the local username the server should authenticate it as. Returning false rejects the certificate.

type Client

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

Client is a high-level XMPP client.

func NewClient

func NewClient(addr jid.JID, password string, opts ...ClientOption) (*Client, error)

NewClient creates a new XMPP client.

func (*Client) Close

func (c *Client) Close() error

Close closes the client connection.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context) error

Connect dials the server, performs full stream negotiation (STARTTLS, SASL authentication, and resource binding), initializes plugins, and starts the background receive loop.

It returns only once the session has reached StateReady. Authentication failures are surfaced as *AuthError; a connection that cannot be established returns the underlying dial error.

func (*Client) Done

func (c *Client) Done() <-chan error

Done returns a channel that receives the receive-loop error when the session terminates (nil on a clean stream close). It is valid after Connect returns.

func (*Client) JID

func (c *Client) JID() jid.JID

JID returns the client's JID.

func (*Client) Plugin

func (c *Client) Plugin(name string) (plugin.Plugin, bool)

Plugin returns a registered plugin by name.

func (*Client) Resume

func (c *Client) Resume(ctx context.Context) error

Resume revives a dropped session using XEP-0198 §5 stream resumption: it dials a fresh connection, re-authenticates, and — if the previous session negotiated resumption — restores its bound resource and replays any unacknowledged stanzas rather than binding a new resource. If the server declines resumption, it transparently falls back to a fresh bind (a new resource).

Resume is used after the receive loop reports the connection dropped (see Done). It requires that the prior session had resumption enabled.

func (*Client) Send

func (c *Client) Send(ctx context.Context, st stanza.Stanza) error

Send sends a stanza.

func (*Client) SendIQ

func (c *Client) SendIQ(ctx context.Context, iq *stanza.IQ) (*stanza.IQ, error)

SendIQ sends an IQ request and waits for the correlated result/error IQ, or until ctx is done. The request ID is generated if empty.

func (*Client) Session

func (c *Client) Session() *Session

Session returns the underlying session.

type ClientOption

type ClientOption interface {
	// contains filtered or unexported methods
}

ClientOption configures a Client.

func WithBOSH

func WithBOSH(url string) ClientOption

WithBOSH connects over XMPP-over-BOSH (XEP-0124/0206) to the given HTTP(S) connection-manager endpoint (typically http(s)://host/http-bind) instead of a TCP connection.

func WithClientDialer

func WithClientDialer(d *dial.Dialer) ClientOption

WithClientDialer sets a custom dialer.

func WithClientTLS

func WithClientTLS(config *tls.Config) ClientOption

WithClientTLS sets the TLS configuration for the client.

func WithConnectAddr

func WithConnectAddr(addr string) ClientOption

WithConnectAddr pins the TCP address (host:port) the client dials, bypassing DNS SRV resolution of the JID domain. Useful for testing and for connecting to a server that is not discoverable via SRV.

func WithDirectTLS

func WithDirectTLS() ClientOption

WithDirectTLS enables Direct TLS (XEP-0368).

func WithHandler

func WithHandler(h Handler) ClientOption

WithHandler sets the stanza handler for the client.

func WithInsecureSASL

func WithInsecureSASL() ClientOption

WithInsecureSASL permits password-bearing SASL mechanisms (PLAIN) over an unencrypted connection. This is unsafe and intended only for testing against a local server; by default the client refuses to send a cleartext password without TLS.

func WithLang

func WithLang(lang string) ClientOption

WithLang sets the default xml:lang advertised in the client stream header.

func WithNoTLS

func WithNoTLS() ClientOption

WithNoTLS disables TLS (for testing only).

func WithPlugins

func WithPlugins(plugins ...plugin.Plugin) ClientOption

WithPlugins registers plugins to be initialized on connect.

func WithResource

func WithResource(resource string) ClientOption

WithResource requests a specific resource for the bound JID. If empty (the default) the server assigns one.

func WithSASLMechanisms

func WithSASLMechanisms(mechanisms ...string) ClientOption

WithSASLMechanisms overrides the client's SASL mechanism preference order. Only mechanisms in this list are attempted, most-preferred first. Recognized names: SCRAM-SHA-512, SCRAM-SHA-256, SCRAM-SHA-1, PLAIN. When unset the client prefers SCRAM-SHA-512 > SCRAM-SHA-256 > SCRAM-SHA-1 > PLAIN.

func WithWebSocket

func WithWebSocket(url string) ClientOption

WithWebSocket connects over XMPP-over-WebSocket (RFC 7395) to the given ws:// or wss:// endpoint instead of a TCP connection.

func WithoutStreamManagement

func WithoutStreamManagement() ClientOption

WithoutStreamManagement disables XEP-0198 Stream Management even when the server advertises it.

func WithoutStreamResumption

func WithoutStreamResumption() ClientOption

WithoutStreamResumption keeps XEP-0198 Stream Management enabled (stanza acknowledgement) but does not request resumption support, so the session cannot be revived after a dropped connection.

type Component

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

Component implements the Jabber Component Protocol (XEP-0114).

func NewComponent

func NewComponent(domain, secret string, opts ...ComponentOption) (*Component, error)

NewComponent creates a new XMPP component.

func (*Component) Close

func (c *Component) Close() error

Close closes the component connection.

func (*Component) Connect

func (c *Component) Connect(ctx context.Context) error

Connect establishes a connection using the component protocol.

func (*Component) Domain

func (c *Component) Domain() string

Domain returns the component domain.

func (*Component) Handshake

func (c *Component) Handshake(streamID string) string

Handshake generates the component handshake hash.

func (*Component) Send

func (c *Component) Send(ctx context.Context, st stanza.Stanza) error

Send sends a stanza via the component.

func (*Component) Session

func (c *Component) Session() *Session

Session returns the underlying session.

type ComponentOption

type ComponentOption interface {
	// contains filtered or unexported methods
}

ComponentOption configures a Component.

func WithComponentAddr

func WithComponentAddr(addr string) ComponentOption

WithComponentAddr sets the server address to connect to.

type Handler

type Handler interface {
	HandleStanza(ctx context.Context, session *Session, st stanza.Stanza) error
}

Handler handles incoming XMPP stanzas.

func Chain

func Chain(handler Handler, middleware ...Middleware) Handler

Chain applies a series of middleware to a handler.

type HandlerFunc

type HandlerFunc func(ctx context.Context, session *Session, st stanza.Stanza) error

HandlerFunc is an adapter to allow ordinary functions as handlers.

func (HandlerFunc) HandleStanza

func (f HandlerFunc) HandleStanza(ctx context.Context, session *Session, st stanza.Stanza) error

HandleStanza calls f(ctx, session, st).

type Middleware

type Middleware func(Handler) Handler

Middleware wraps a Handler to add cross-cutting behavior.

func LogMiddleware

func LogMiddleware() Middleware

LogMiddleware logs incoming stanzas.

func RecoverMiddleware

func RecoverMiddleware() Middleware

RecoverMiddleware recovers from panics in handlers.

type Mux

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

Mux is a stanza multiplexer that routes stanzas to handlers.

func NewMux

func NewMux(opts ...MuxOption) *Mux

NewMux creates a new Mux.

func (*Mux) Handle

func (m *Mux) Handle(name xml.Name, stanzaType string, handler Handler)

Handle registers a handler for stanzas matching the given XML name and type.

func (*Mux) HandleFunc

func (m *Mux) HandleFunc(name xml.Name, stanzaType string, f HandlerFunc)

HandleFunc registers a handler function.

func (*Mux) HandleStanza

func (m *Mux) HandleStanza(ctx context.Context, session *Session, st stanza.Stanza) error

HandleStanza routes a stanza to the appropriate handler.

A route's name is matched against the stanza element name (message, presence, iq) and, for IQ stanzas, against the IQ payload (child) element name. This lets plugins register for a payload namespace such as urn:xmpp:ping without caring that the wrapping element is <iq>.

func (*Mux) SetFallback

func (m *Mux) SetFallback(h Handler)

SetFallback sets the fallback handler for unmatched stanzas.

func (*Mux) Use

func (m *Mux) Use(mw ...Middleware)

Use adds middleware to the mux.

type MuxOption

type MuxOption func(*Mux)

MuxOption configures the Mux.

func WithRoute

func WithRoute(name xml.Name, stanzaType string, handler Handler) MuxOption

WithRoute returns a MuxOption that registers a route.

type Negotiator

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

Negotiator handles XMPP stream negotiation.

func NewNegotiator

func NewNegotiator(features ...StreamFeature) *Negotiator

NewNegotiator creates a new stream negotiator.

func (*Negotiator) AddFeature

func (n *Negotiator) AddFeature(f StreamFeature)

AddFeature adds a stream feature to the negotiator.

func (*Negotiator) Features

func (n *Negotiator) Features(state SessionState) []StreamFeature

Features returns the features available for the given session state.

func (*Negotiator) Negotiate

func (n *Negotiator) Negotiate(ctx context.Context, session *Session) error

Negotiate performs stream feature negotiation on a session.

type S2SResolver

type S2SResolver func(domain string) (addr string, ok bool)

S2SResolver maps a remote XMPP domain to a dialable "host:port" address. It replaces DNS SRV resolution of `_xmpp-server._tcp` and is required for server-to-server federation (also handy for testing and private deployments).

type Server

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

Server is a high-level XMPP server.

func NewServer

func NewServer(domain string, opts ...ServerOption) (*Server, error)

NewServer creates a new XMPP server.

func (*Server) Addr

func (s *Server) Addr() net.Addr

Addr returns the address the server is listening on, or nil if it is not yet listening.

func (*Server) BOSHHandler

func (s *Server) BOSHHandler() http.Handler

BOSHHandler returns an http.Handler implementing the server side of XMPP over BOSH (XEP-0124/0206). Mount it on an HTTP(S) endpoint (typically /http-bind):

http.Handle("/http-bind", srv.BOSHHandler())

Each BOSH session is bridged to the library's standard negotiation and routing, so SASL authentication, resource binding, presence, and message delivery all work identically to the TCP and WebSocket transports.

func (*Server) Close

func (s *Server) Close() error

Close stops the server.

func (*Server) Domain

func (s *Server) Domain() string

Domain returns the server domain.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe(ctx context.Context) error

ListenAndServe starts listening for XMPP connections.

func (*Server) Plugin

func (s *Server) Plugin(name string) (plugin.Plugin, bool)

Plugin returns a registered plugin by name.

func (*Server) SessionCount

func (s *Server) SessionCount() int

SessionCount returns the number of active sessions.

func (*Server) WebSocketHandler

func (s *Server) WebSocketHandler() http.Handler

WebSocketHandler returns an http.Handler that serves XMPP-over-WebSocket (RFC 7395) client connections using the server's negotiation and routing. The server must already be initialized (via ListenAndServe or Init).

Mount it on an HTTPS endpoint (path typically /xmpp-websocket):

http.Handle("/xmpp-websocket", srv.WebSocketHandler())

type ServerOption

type ServerOption interface {
	// contains filtered or unexported methods
}

ServerOption configures a Server.

func WithServerAddr

func WithServerAddr(addr string) ServerOption

WithServerAddr sets the listen address.

func WithServerAnonymous

func WithServerAnonymous() ServerOption

WithServerAnonymous enables the SASL ANONYMOUS mechanism, allowing clients to authenticate without credentials; each is assigned a random JID.

func WithServerAuth

func WithServerAuth(f AuthFunc) ServerOption

WithServerAuth sets the authentication handler.

func WithServerClientCertAuth

func WithServerClientCertAuth(caPool *x509.CertPool, identity CertIdentityFunc) ServerOption

WithServerClientCertAuth enables SASL EXTERNAL authentication via client certificates (RFC 6120 §6, mutual TLS). The server requests a client certificate during the TLS handshake, verifies it against caPool, and — when the client selects EXTERNAL — maps the presented certificate to a local username via identity. TLS must be configured (WithServerTLS or WithServerTLSConfig) for this to take effect.

func WithServerPluginFactory

func WithServerPluginFactory(factory func() []plugin.Plugin) ServerOption

WithServerPluginFactory registers a factory that produces a fresh set of plugins for each authenticated session. Each session's plugins are initialized with session-scoped send/handle hooks and receive inbound IQ dispatch (matched by payload namespace) after the built-in service handlers. Because a new instance is created per session, plugins may hold per-session state safely. The session's plugins are closed when the session ends.

func WithServerPlugins

func WithServerPlugins(plugins ...plugin.Plugin) ServerOption

WithServerPlugins registers server-global plugins, initialized once when the server starts. Use these for shared services with server-wide state. They do not receive per-session inbound-stanza dispatch; for that use WithServerPluginFactory.

func WithServerResumeTimeout

func WithServerResumeTimeout(d time.Duration) ServerOption

WithServerResumeTimeout sets how long a dropped but Stream-Management- resumable session is held for resumption before being torn down. The default is 120 seconds.

func WithServerS2S

func WithServerS2S(secret string, resolver S2SResolver) ServerOption

WithServerS2S enables server-to-server federation using XEP-0220 Server Dialback. secret is this server's private dialback secret (used to generate and verify dialback keys for its own domain), and resolver maps remote XMPP domains to dialable addresses (replacing DNS SRV lookup of `_xmpp-server._tcp`). Stanzas addressed to non-local domains are then routed over authenticated s2s streams, and inbound s2s streams are accepted and verified via dialback.

func WithServerSessionHandler

func WithServerSessionHandler(f SessionHandlerFunc) ServerOption

WithServerSessionHandler sets the handler for new sessions.

func WithServerStorage

func WithServerStorage(s storage.Storage) ServerOption

WithServerStorage sets the pluggable storage backend.

func WithServerTLS

func WithServerTLS(cert, key string) ServerOption

WithServerTLS sets TLS certificate and key files.

func WithServerTLSConfig

func WithServerTLSConfig(cfg *tls.Config) ServerOption

WithServerTLSConfig sets an explicit *tls.Config to use for STARTTLS instead of loading a certificate/key from files. It takes precedence over WithServerTLS. Useful for in-memory certificates and advanced TLS settings (client-certificate auth, custom cipher suites).

type Session

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

Session represents an XMPP session (client or server).

func NewSession

func NewSession(ctx context.Context, trans transport.Transport, opts ...SessionOption) (*Session, error)

NewSession creates a new XMPP session with the given transport and options.

func (*Session) Close

func (s *Session) Close() error

Close closes the session.

func (*Session) EnableSM

func (s *Session) EnableSM()

EnableSM marks Stream Management (XEP-0198) as active on the session.

func (*Session) Framing

func (s *Session) Framing() bool

Framing reports whether the session uses RFC 7395 <open/> framing.

func (*Session) LocalAddr

func (s *Session) LocalAddr() jid.JID

LocalAddr returns the local JID.

func (*Session) Mux

func (s *Session) Mux() *Mux

Mux returns the stanza multiplexer.

func (*Session) Reader

func (s *Session) Reader() *xmppxml.StreamReader

Reader returns the XML stream reader.

func (*Session) RemoteAddr

func (s *Session) RemoteAddr() jid.JID

RemoteAddr returns the remote JID.

func (*Session) RequestSMAck

func (s *Session) RequestSMAck(ctx context.Context) (uint32, error)

RequestSMAck sends an <r/> and waits for the peer's <a h='N'/>, returning the number of this session's outbound stanzas the peer reports as handled. It requires SM to be enabled.

func (*Session) Restart

func (s *Session) Restart()

Restart resets the stream reader and writer over the current transport.

It must be called after a stream-altering negotiation step (STARTTLS or SASL success) so that a fresh XML stream — with a new root <stream:stream> — is parsed and written over the possibly-upgraded transport. Callers must ensure no concurrent Send/Serve is in flight; during negotiation this is guaranteed because the receive loop has not yet started.

func (*Session) SASLMechanism

func (s *Session) SASLMechanism() string

SASLMechanism returns the SASL mechanism that authenticated the session, or "" if unauthenticated.

func (*Session) SMEnabled

func (s *Session) SMEnabled() bool

SMEnabled reports whether Stream Management is active.

func (*Session) SMHandled

func (s *Session) SMHandled() uint32

SMHandled returns the number of inbound stanzas handled ("h") since SM was enabled.

func (*Session) SMPrevID

func (s *Session) SMPrevID() string

SMPrevID returns the resumption id, or "" if resumption is not available.

func (*Session) SMResumable

func (s *Session) SMResumable() bool

SMResumable reports whether the session negotiated resumption support.

func (*Session) Send

func (s *Session) Send(ctx context.Context, st stanza.Stanza) error

Send sends a stanza through the session.

func (*Session) SendElement

func (s *Session) SendElement(ctx context.Context, v any) error

SendElement encodes an XML element to the stream.

func (*Session) SendRaw

func (s *Session) SendRaw(ctx context.Context, r io.Reader) error

SendRaw writes raw XML to the stream.

func (*Session) Serve

func (s *Session) Serve(handler Handler) error

Serve reads stanzas from the stream and dispatches them to the mux.

func (*Session) SetFraming

func (s *Session) SetFraming(v bool)

SetFraming selects RFC 7395 <open/> stream framing (used by WebSocket).

func (*Session) SetLocalAddr

func (s *Session) SetLocalAddr(j jid.JID)

SetLocalAddr sets the local JID.

func (*Session) SetRemoteAddr

func (s *Session) SetRemoteAddr(j jid.JID)

SetRemoteAddr sets the remote JID.

func (*Session) SetSASLMechanism

func (s *Session) SetSASLMechanism(name string)

SetSASLMechanism records the SASL mechanism used to authenticate.

func (*Session) SetSMResume

func (s *Session) SetSMResume(previd string, max int)

SetSMResume records the resumption id and negotiated timeout for the session.

func (*Session) SetState

func (s *Session) SetState(state SessionState)

SetState sets session state flags.

func (*Session) State

func (s *Session) State() SessionState

State returns the current session state.

func (*Session) Transport

func (s *Session) Transport() transport.Transport

Transport returns the underlying transport.

func (*Session) Writer

func (s *Session) Writer() *xmppxml.StreamWriter

Writer returns the XML stream writer.

type SessionHandlerFunc

type SessionHandlerFunc func(ctx context.Context, session *Session)

SessionHandlerFunc is called when a new session is established.

type SessionOption

type SessionOption interface {
	// contains filtered or unexported methods
}

SessionOption configures a Session.

func WithLocalAddr

func WithLocalAddr(j jid.JID) SessionOption

WithLocalAddr sets the local JID for the session.

func WithMux

func WithMux(mux *Mux) SessionOption

WithMux sets the stanza multiplexer.

func WithRemoteAddr

func WithRemoteAddr(j jid.JID) SessionOption

WithRemoteAddr sets the remote JID for the session.

func WithState

func WithState(state SessionState) SessionOption

WithState sets the initial session state.

type SessionState

type SessionState uint32

SessionState represents the state of an XMPP session.

const (
	StateSecure        SessionState = 1 << iota // TLS negotiated
	StateAuthenticated                          // SASL complete
	StateBound                                  // Resource bound
	StateReady                                  // Fully negotiated
	StateServer                                 // Server role
	StateS2S                                    // Server-to-server
)

type StreamError

type StreamError struct {
	Condition string
	Text      string
}

StreamError represents an XMPP stream-level error condition.

func (*StreamError) Error

func (e *StreamError) Error() string

type StreamFeature

type StreamFeature struct {
	// Name is the XML name of the feature element.
	Name xml.Name

	// Required indicates this feature must be negotiated.
	Required bool

	// Necessary is the state required before this feature can be negotiated.
	Necessary SessionState

	// Prohibited is the state that prevents this feature from being negotiated.
	Prohibited SessionState

	// List writes the feature advertisement to the stream.
	List func(ctx context.Context, e *xmppxml.Encoder) error

	// Parse reads the feature data from the stream.
	Parse func(ctx context.Context, d *xmppxml.Decoder, start *xml.StartElement) (any, error)

	// Negotiate performs the feature negotiation.
	Negotiate func(ctx context.Context, session *Session, data any) (SessionState, error)
}

StreamFeature represents a feature that can be negotiated during stream setup.

func BindFeature

func BindFeature() StreamFeature

BindFeature returns a StreamFeature for resource binding.

func SASLFeature

func SASLFeature(mechanisms []string) StreamFeature

SASLFeature returns a StreamFeature for SASL authentication.

func StartTLS

func StartTLS(config *tls.Config) StreamFeature

StartTLS returns a StreamFeature for STARTTLS negotiation.

Directories

Path Synopsis
cmd
xmppd module
crypto
omemo module
Package dial provides connection dialing with DNS SRV and host-meta resolution.
Package dial provides connection dialing with DNS SRV and host-meta resolution.
internal
bosh
Package bosh implements the framing codec shared by the BOSH (XEP-0124/0206) client transport and server connection manager: it splits a continuous XMPP byte stream into discrete top-level elements and wraps/unwraps them in HTTP <body/> envelopes.
Package bosh implements the framing codec shared by the BOSH (XEP-0124/0206) client transport and server connection manager: it splits a continuous XMPP byte stream into discrete top-level elements and wraps/unwraps them in HTTP <body/> envelopes.
ns
Package ns defines XML namespace constants used throughout the XMPP library.
Package ns defines XML namespace constants used throughout the XMPP library.
Package jid implements XMPP JID (Jabber ID) parsing, validation, and escaping per RFC 7622 and XEP-0106.
Package jid implements XMPP JID (Jabber ID) parsing, validation, and escaping per RFC 7622 and XEP-0106.
Package plugin defines the XMPP plugin interface and registry.
Package plugin defines the XMPP plugin interface and registry.
plugins
avatar
Package avatar implements XEP-0084 User Avatar and XEP-0153 vCard-Based Avatars.
Package avatar implements XEP-0084 User Avatar and XEP-0153 vCard-Based Avatars.
blocking
Package blocking implements XEP-0191 Blocking Command.
Package blocking implements XEP-0191 Blocking Command.
bob
Package bob implements XEP-0231 Bits of Binary.
Package bob implements XEP-0231 Bits of Binary.
bookmarks
Package bookmarks implements XEP-0402 PEP Native Bookmarks.
Package bookmarks implements XEP-0402 PEP Native Bookmarks.
caps
Package caps implements XEP-0115 Entity Capabilities.
Package caps implements XEP-0115 Entity Capabilities.
carbons
Package carbons implements XEP-0280 Message Carbons.
Package carbons implements XEP-0280 Message Carbons.
chatmarkers
Package chatmarkers implements XEP-0333 Chat Markers.
Package chatmarkers implements XEP-0333 Chat Markers.
chatstates
Package chatstates implements XEP-0085 Chat State Notifications.
Package chatstates implements XEP-0085 Chat State Notifications.
commands
Package commands implements XEP-0050 Ad-Hoc Commands.
Package commands implements XEP-0050 Ad-Hoc Commands.
correction
Package correction implements XEP-0308 Last Message Correction.
Package correction implements XEP-0308 Last Message Correction.
csi
Package csi implements XEP-0352 Client State Indication.
Package csi implements XEP-0352 Client State Indication.
delay
Package delay implements XEP-0203 Delayed Delivery.
Package delay implements XEP-0203 Delayed Delivery.
dialback
Package dialback implements XEP-0220 Server Dialback and XEP-0288 Bidirectional S2S.
Package dialback implements XEP-0220 Server Dialback and XEP-0288 Bidirectional S2S.
disco
Package disco implements XEP-0030 Service Discovery.
Package disco implements XEP-0030 Service Discovery.
extdisco
Package extdisco implements XEP-0215 External Service Discovery.
Package extdisco implements XEP-0215 External Service Discovery.
filetransfer
Package filetransfer implements XEP-0234 Jingle File Transfer and XEP-0446/0447/0448 Stateless File Sharing.
Package filetransfer implements XEP-0234 Jingle File Transfer and XEP-0446/0447/0448 Stateless File Sharing.
form
Package form implements XEP-0004 Data Forms.
Package form implements XEP-0004 Data Forms.
forward
Package forward implements XEP-0297 Stanza Forwarding.
Package forward implements XEP-0297 Stanza Forwarding.
hash
Package hash implements XEP-0300 Cryptographic Hash Functions.
Package hash implements XEP-0300 Cryptographic Hash Functions.
hints
Package hints implements XEP-0334 Message Processing Hints.
Package hints implements XEP-0334 Message Processing Hints.
ibb
Package ibb implements XEP-0047 In-Band Bytestreams.
Package ibb implements XEP-0047 In-Band Bytestreams.
jingle
Package jingle implements XEP-0166 Jingle and related extensions.
Package jingle implements XEP-0166 Jingle and related extensions.
lastactivity
Package lastactivity implements XEP-0012 Last Activity.
Package lastactivity implements XEP-0012 Last Activity.
mam
Package mam implements XEP-0313 Message Archive Management.
Package mam implements XEP-0313 Message Archive Management.
mix
Package mix implements XEP-0369 MIX and related extensions (XEP-0403/0405/0406/0407).
Package mix implements XEP-0369 MIX and related extensions (XEP-0403/0405/0406/0407).
moderation
Package moderation implements XEP-0425 Message Moderation.
Package moderation implements XEP-0425 Message Moderation.
muc
Package muc implements XEP-0045 Multi-User Chat and XEP-0249 Direct MUC Invitations.
Package muc implements XEP-0045 Multi-User Chat and XEP-0249 Direct MUC Invitations.
omemo
Package omemo implements XEP-0384 OMEMO Encryption, XEP-0380 EME, and XEP-0454 OMEMO Media Sharing.
Package omemo implements XEP-0384 OMEMO Encryption, XEP-0380 EME, and XEP-0454 OMEMO Media Sharing.
oob
Package oob implements XEP-0066 Out of Band Data.
Package oob implements XEP-0066 Out of Band Data.
ping
Package ping implements XEP-0199 XMPP Ping.
Package ping implements XEP-0199 XMPP Ping.
presence
Package presence implements RFC 6121 Presence Management.
Package presence implements RFC 6121 Presence Management.
pubsub
Package pubsub implements XEP-0060 Publish-Subscribe and XEP-0163 PEP.
Package pubsub implements XEP-0060 Publish-Subscribe and XEP-0163 PEP.
push
Package push implements XEP-0357 Push Notifications.
Package push implements XEP-0357 Push Notifications.
reactions
Package reactions implements XEP-0444 Message Reactions.
Package reactions implements XEP-0444 Message Reactions.
receipts
Package receipts implements XEP-0184 Message Delivery Receipts.
Package receipts implements XEP-0184 Message Delivery Receipts.
register
Package register implements XEP-0077 In-Band Registration.
Package register implements XEP-0077 In-Band Registration.
retraction
Package retraction implements XEP-0424 Message Retraction.
Package retraction implements XEP-0424 Message Retraction.
roster
Package roster implements RFC 6121 Roster Management.
Package roster implements RFC 6121 Roster Management.
rsm
Package rsm implements XEP-0059 Result Set Management.
Package rsm implements XEP-0059 Result Set Management.
sasl2
Package sasl2 implements XEP-0388 SASL2, XEP-0484 FAST, XEP-0386 Bind2, and XEP-0440 SASL Channel-Binding.
Package sasl2 implements XEP-0388 SASL2, XEP-0484 FAST, XEP-0386 Bind2, and XEP-0440 SASL Channel-Binding.
sm
Package sm implements XEP-0198 Stream Management.
Package sm implements XEP-0198 Stream Management.
socks5
Package socks5 implements XEP-0065 SOCKS5 Bytestreams.
Package socks5 implements XEP-0065 SOCKS5 Bytestreams.
stanzaid
Package stanzaid implements XEP-0359 Unique and Stable Stanza IDs.
Package stanzaid implements XEP-0359 Unique and Stable Stanza IDs.
styling
Package styling implements XEP-0393 Message Styling.
Package styling implements XEP-0393 Message Styling.
time
Package time implements XEP-0082 Date/Time Profiles and XEP-0202 Entity Time.
Package time implements XEP-0082 Date/Time Profiles and XEP-0202 Entity Time.
upload
Package upload implements XEP-0363 HTTP File Upload.
Package upload implements XEP-0363 HTTP File Upload.
vcard
Package vcard implements XEP-0054 vcard-temp and XEP-0292 vCard4 over XMPP.
Package vcard implements XEP-0054 vcard-temp and XEP-0292 vCard4 over XMPP.
version
Package version implements XEP-0092 Software Version.
Package version implements XEP-0092 Software Version.
Package sasl implements SASL authentication mechanisms for XMPP.
Package sasl implements SASL authentication mechanisms for XMPP.
Package stanza defines XMPP stanza types: Message, Presence, and IQ.
Package stanza defines XMPP stanza types: Message, Presence, and IQ.
Package storage defines the pluggable storage interfaces for xmpp-go.
Package storage defines the pluggable storage interfaces for xmpp-go.
file
Package file provides a file-based JSON storage backend for xmpp-go.
Package file provides a file-based JSON storage backend for xmpp-go.
memory
Package memory provides an in-memory implementation of the storage interfaces.
Package memory provides an in-memory implementation of the storage interfaces.
sql
Package sql provides a shared SQL storage implementation for xmpp-go.
Package sql provides a shared SQL storage implementation for xmpp-go.
storagetest
Package storagetest provides a conformance test suite for storage backends.
Package storagetest provides a conformance test suite for storage backends.
mongodb module
mysql module
postgres module
redis module
sqlite module
Package stream provides XMPP stream header types and stream management.
Package stream provides XMPP stream header types and stream management.
Package transport provides transport abstractions for XMPP connections.
Package transport provides transport abstractions for XMPP connections.
Package xml provides streaming XML encoding and decoding for XMPP streams.
Package xml provides streaming XML encoding and decoding for XMPP streams.

Jump to

Keyboard shortcuts

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