xmppcore

package module
v0.0.0-...-449aa8d Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2021 License: MIT Imports: 23 Imported by: 2

README

Overview

A xmpp framework that supports totally configuration and extensions. you shall impelement your feature and whatever extensions like rfc6121, with Part::WithElemHandler and Part::WithFeature

  • insert your feature with Part::WithFeature
  • register element handler with Part::WithElemHandler
  • Flexiable & Extensiable
  • Super fast

Example

Server


package server

import (
	"crypto/md5"
	"crypto/sha1"
	"crypto/sha256"
	"crypto/sha512"
	"hash"
	"io"
	"os"
	"sync"

	xmppcore "github.com/yang-zzhong/xmpp-core"

	"github.com/gorilla/websocket"
)

type Server struct {
	config *Config
	logger xmppcore.Logger

	connGrabbers []xmppcore.ConnGrabber
	conns        []xmppcore.Conn
	wg           sync.WaitGroup
}

func New(conf *Config) *Server {
	return &Server{
		config:       conf,
		connGrabbers: []xmppcore.ConnGrabber{},
		conns:        []xmppcore.Conn{},
		logger:       xmppcore.NewLogger(os.Stdout)}
}

func (s *Server) Start() error {
	wsConnsConfig := DefaultConfig.WsConns
	if len(s.config.WsConns) > 0 {
		wsConnsConfig = s.config.WsConns
	}
	for _, conf := range wsConnsConfig {
		s.initConnGrabber(conf, func(c interface{}) xmppcore.ConnGrabber {
			conf := c.(WsConnConfig)
			ws := xmppcore.NewWsConnGrabber(
				conf.ListenOn,
				conf.Path,
				websocket.Upgrader{
					ReadBufferSize:  int(conf.ReadBufSize),
					WriteBufferSize: int(conf.WriteBufSize)}, s.logger)
            if conf.CertKey != "" && conf.KeyFile != "" {
                ws.UpgradeToTls(conf.CertFile, conf.KeyFile)
            }
            return ws
		})
	}
	tcpConnsConfig := DefaultConfig.TcpConns
	if len(s.config.TcpConns) > 0 {
		tcpConnsConfig = s.config.TcpConns
	}
	for _, conf := range tcpConnsConfig {
		s.initConnGrabber(conf, func(c interface{}) xmppcore.ConnGrabber {
			conf := c.(TcpConnConfig)
			tcp := xmppcore.NewTcpConnGrabber(conf.ListenOn, conf.For, s.logger)
            if conf.CertKey != "" && conf.KeyFile != "" {
                tcp.UpgradeToTls(conf.CertFile, conf.KeyFile)
            }
            return tcp
		})
	}
	s.wg.Wait()
	return nil
}

type connGrabberBuilder func(interface{}) xmppcore.ConnGrabber

func (s *Server) initConnGrabber(conf interface{}, builder connGrabberBuilder) {
	grabber := builder(conf)
	connChan := make(chan xmppcore.Conn)
	if err := grabber.Grab(connChan); err != nil {
		panic(err)
	}
	s.connGrabbers = append(s.connGrabbers, grabber)
	s.wg.Add(1)
	go func() {
		for {
			select {
			case conn := <-connChan:
				if conn == nil {
					s.wg.Done()
					return
				}
				s.conns = append(s.conns, conn)
				go func() {
					s.onConn(conn, grabber.For(), grabber.Type())
				}()
			}
		}
	}()
}

func (s *Server) Stop() {
	for _, conn := range s.conns {
		conn.Close()
	}
	for _, grabber := range s.connGrabbers {
		grabber.Cancel()
	}
}

var (
	memoryAuthUserFetcher      *xmppcore.MemoryAuthUserFetcher
	memoryPlainAuthUserFetcher *xmppcore.MemoryPlainAuthUserFetcher
	memoryAuthorized           *xmppcore.MemoryAuthorized
)

func init() {
	memoryAuthUserFetcher = xmppcore.NewMemoryAuthUserFetcher()
	memoryAuthUserFetcher.Add(xmppcore.NewMemomryAuthUser("test", "123456", map[string]func() hash.Hash{
		"MD5":     md5.New,
		"SHA-1":   sha1.New,
		"SHA-256": sha256.New,
		"SHA-512": sha512.New,
	}, 5))
	memoryPlainAuthUserFetcher = xmppcore.NewMemoryPlainAuthUserFetcher()
	memoryPlainAuthUserFetcher.Add(xmppcore.NewMemoryPlainAuthUser("test", string(md5.New().Sum([]byte("123456")))))
	memoryAuthorized = xmppcore.NewMemoryAuthorized()
}

func (s *Server) onConn(conn xmppcore.Conn, connFor xmppcore.ConnFor, connType xmppcore.ConnType) {
	if connFor == xmppcore.ForC2S {
		s.c2sHandler(conn, connType)
	} else if connFor == xmppcore.ForS2S {
		s.s2sHandler(conn, connType)
	}
}

func (s *Server) c2sHandler(conn xmppcore.Conn, connType xmppcore.ConnType) {
	part := xmppcore.NewXPart(conn, domain, logger)
    // add sasl feature
    sasl := xmppcore.NewSASLFeature(memoryAuthorized)
    sasl.Support(xmppcore.SM_PLAIN, xmppcore.NewPlainAuth(memoryPlainAuthUserFetcher, md5.New))
	if s.config.CertFile != "" && s.config.KeyFile != "" || connType == xmppcore.TLSConn || connType == xmppcore.WSTLSConn {
		if connType == xmppcore.TCPConn || connType == xmppcore.WSConn {
			part.WithFeature(xmppcore.NewTlsFeature(s.config.CertFile, s.config.KeyFile, true))
		}
		sasl.Support(xmppcore.SM_SCRAM_SHA_1_PLUS, xmppcore.NewScramAuth(memoryAuthUserFetcher, sha1.New, true))
		sasl.Support(xmppcore.SM_SCRAM_SHA_256_PLUS, xmppcore.NewScramAuth(memoryAuthUserFetcher, sha256.New, true))
		sasl.Support(xmppcore.SM_SCRAM_SHA_512_PLUS, xmppcore.NewScramAuth(memoryAuthUserFetcher, sha512.New, true))
	} else {
		sasl.Support(xmppcore.SM_SCRAM_SHA_1, xmppcore.NewScramAuth(memoryAuthUserFetcher, sha1.New, false)).
		sasl.Support(xmppcore.SM_SCRAM_SHA_256, xmppcore.NewScramAuth(memoryAuthUserFetcher, sha256.New, false)).
		sasl.Support(xmppcore.SM_SCRAM_SHA_512, xmppcore.NewScramAuth(memoryAuthUserFetcher, sha512.New, false))
	}
    part.WithFeature(sasl)
    compress := xmppcore.NewCompressionFeature()
    compress.Support(xmppcore.ZLIB, func(conn io.ReadWriter) xmppcore.Compressor {
		return xmppcore.NewCompZlib(conn)
	})
    // add compress feature
    part.WithFeature(compress)
    // add bind feature
    part.WithFeature(xmppcore.NewBindFeature(memoryAuthorized))
	part.WithElemHandler(xmppcore.NewMessageRouter(memoryAuthorized))
	if err := part.Run(); err != nil {
		s.logger.Printf(xmppcore.Error, err.Error())
	}
}

func (s *Server) s2sHandler(conn xmppcore.Conn, connType xmppcore.ConnType) {
	s.c2sHandler(conn, connType)
}

Documentation

Index

Constants

View Source
const (
	NSBind   = "urn:ietf:params:xml:ns:xmpp-bind"
	NSStanza = "urn:ietf:params:xml:ns:xmpp-stanzas"

	BEResourceConstraint = "wait: resource constraint"
	BENotAllowed         = "cancel: not allowed"
)
View Source
const (
	NSStream  = "http://etherx.jabber.org/streams"
	NSFraming = "urn:ietf:params:xml:ns:xmpp-framing"
)
View Source
const (
	NSCompress = "http://jabber.org/protocol/compress"

	CESetupFailed       = "setup-failed"
	CEUnsupportedMethod = "unsupported-method"

	ZLIB = "zlib"
	LZW  = "lzw"
)
View Source
const (
	ForC2S = ConnFor("C2S")
	ForS2S = ConnFor("S2S")

	TCPConn   = ConnType("TCP")
	TLSConn   = ConnType("TLS")
	WSConn    = ConnType("WS-TCP")
	WSTLSConn = ConnType("WS-TLS")
)
View Source
const (
	LogDebug   = LogLevel(0)
	LogInfo    = LogLevel(1)
	LogWarning = LogLevel(2)
	LogError   = LogLevel(3)
	LogFatal   = LogLevel(4)
)
View Source
const (
	NSSasl = "urn:ietf:params:xml:ns:xmpp-sasl"

	SM_EXTERNAL           = "EXTERNAL"           // where authentication is implicit in the context (e.g., for protocols already using IPsec or TLS)
	SM_ANONYMOUS          = "ANONYMOUS"          // for unauthenticated guest access
	SM_PLAIN              = "PLAIN"              // a simple cleartext password mechanism, defined in RFC 4616
	SM_OTP                = "OTP"                // a one-time password mechanism. Obsoletes the SKEY mechanism
	SM_SKEY               = "SKEY"               // an S/KEY mechanism
	SM_DIGEST_MD5         = "DIGEST-MD5"         // partially HTTP Digest compatible challenge-response scheme based upon MD5. DIGEST-MD5 offered a data security layer.
	SM_SCRAM_SHA_1        = "SCRAM-SHA-1"        // (RFC 5802), modern challenge-response scheme based mechanism with channel binding support
	SM_SCRAM_SHA_1_PLUS   = "SCRAM-SHA-1-PLUS"   // (RFC 5802), modern challenge-response scheme based mechanism with channel binding support
	SM_SCRAM_SHA_256      = "SCRAM-SHA-256"      // (RFC 5802), modern challenge-response scheme based mechanism with channel binding support
	SM_SCRAM_SHA_256_PLUS = "SCRAM-SHA-256-PLUS" // (RFC 5802), modern challenge-response scheme based mechanism with channel binding support
	SM_SCRAM_SHA_512      = "SCRAM-SHA-512"      // (RFC 5802), modern challenge-response scheme based mechanism with channel binding support
	SM_SCRAM_SHA_512_PLUS = "SCRAM-SHA-512-PLUS" // (RFC 5802), modern challenge-response scheme based mechanism with channel binding support
	SM_NTLM               = "NTLM"               // an NT LAN Manager authentication mechanism
	SM_GS2_               = "GS2-"               // family of mechanisms supports arbitrary GSS-API mechanisms in SASL.[3] It is now standardized as RFC 5801.
	SM_GSSAPI             = "GSSAPI"             // for Kerberos V5 authentication via the GSSAPI. GSSAPI offers a data-security layer.
	SM_BROWSERID_AES128   = "BROWSERID-AES128"   // for Mozilla Persona authentication
	SM_EAP_AES128         = "EAP-AES128"         // for GSS EAP authentication
	SM_OAUTH_1            = "OAUTH-1"            // bearer tokens (RFC 6750), communicated through TLS
	SM_OAUTH_2            = "OAUTH-2"            // bearer tokens (RFC 6750), communicated through TLS

	SFAborted              = "aborted"
	SFAccountDisabled      = "account-disabled"
	SFCredentialsExpired   = "credentials-expired"
	SFEncryptionRequired   = "encryption-required"
	SFIncorrectEncoding    = "incorrect-encoding"
	SFInvalidAuthzid       = "invalid-authzid"
	SFInvalidMechanism     = "invalid-mechanism"
	SFMalformedRequest     = "malformed-request"
	SFMechanismTooWeak     = "mechanism-too-weak"
	SFNotAuthorized        = "not-authorized"
	SFTemporaryAuthFailure = "temporary-auth-failure"
)
View Source
const (
	NameIQ       = "iq"
	NamePresence = "presence"
	NameMsg      = "message"
	// for iq
	TypeGet    = StanzaType("get")
	TypeSet    = StanzaType("set")
	TypeResult = StanzaType("result")
	TypeError  = StanzaType("error")

	// for presence
	TypeSub         = StanzaType("subscribe")
	TypeUnsub       = StanzaType("unsubscribe")
	TypeSubed       = StanzaType("subscribed")
	TypeUnsubed     = StanzaType("unsubscribed")
	TypeUnavailable = StanzaType("unavailable")
)
View Source
const (
	ErrHashNotSupported = "hash not supported"
)
View Source
const (
	NSTls = "urn:ietf:params:xml:ns:xmpp-tls"
)

Variables

View Source
var (
	ErrNotHeaderStart       = errors.New("not a start header")
	ErrChannelClosed        = errors.New("channel closed")
	ErrNotForThisDomainHead = errors.New("not for this domain header")
)
View Source
var (
	ErrUnproperFromAttr     = errors.New("unproper from attr")
	ErrIncorrectJidEncoding = errors.New("incorrect jid encoding")
)
View Source
var (
	ErrNotRequiredFailure = errors.New("parsed element not a required failure")
	ErrNotStanzaErr       = errors.New("not stanza error")
)
View Source
var (
	ErrOnNextTokenTimeout      = errors.New("get next token timeout")
	ErrOnNextElementnTimeout   = errors.New("get next element timeout")
	ErrClientIgnoredTheFeature = errors.New("client ignored the feature")
	ErrUnhandledElement        = errors.New("unhandled element")
)
View Source
var (
	ErrBindTlsUniqueNotSupported = errors.New("bind tls unique not supported")
)
View Source
var ErrNoElement = errors.New("parser: no elements")

ErrNoElement will be returned by Parse when no elements are available to be parsed in the reader buffer stream.

View Source
var (
	ErrNotIqBind = errors.New("not iq bind")
)
View Source
var ErrStreamClosedByPeer = errors.New("parser: stream closed by peer")

ErrStreamClosedByPeer will be returned by Parse when stream closed element is parsed.

View Source
var ErrTooLargeStanza = errors.New("parser: too large stanza")

ErrTooLargeStanza will be returned Parse when the size of the incoming stanza is too large.

View Source
var ErrUnexpectedToken = errors.New("parser: unexpected token")

Functions

func AuthPayload

func AuthPayload(encoded string, payload *string) error

func BindFeature

func BindFeature(rsb ResourceBinder) bindFeature

func ClientBindFeature

func ClientBindFeature(rb ResourceBinder, resource string) clientBindFeature

func ClientCompressFeature

func ClientCompressFeature() clientCompressFeature

func ClientSASLFeature

func ClientSASLFeature() clientSASLFeature

func ClientTlsFeature

func ClientTlsFeature(conf *tls.Config) clientTlsFeature

func CompressFeature

func CompressFeature() compressionFeature

func ElemRunner

func ElemRunner(channel Channel) elemRunner

func ParseJID

func ParseJID(src string, jid *JID) error

func SASLFeature

func SASLFeature(authorized Authorized) saslFeature

func SaslFailureElem

func SaslFailureElem(tagName, desc string) stravaganza.Element

func SaslFailureElemFromError

func SaslFailureElemFromError(err error) stravaganza.Element

func SaslFailureError

func SaslFailureError(tagName, desc string) error

func TlsFailureElem

func TlsFailureElem() stravaganza.Element

func TlsFeature

func TlsFeature(certFile, keyFile string, mandatory bool) tlsFeature

Types

type Auth

type Auth interface {
	Auth(mechanism, authInfo string, part Part) (username string, err error)
}

type Authorized

type Authorized interface {
	Authorized(username string, part Part)
}

type BuildCompressor

type BuildCompressor func(io.ReadWriter) Compressor

type Channel

type Channel interface {
	Receiver
	Sender
	WaitHeader(*xml.StartElement) error
	Open(attr *PartAttr) error
	SetLogger(Logger)
	Close()
}

type ClientPart

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

func NewClientPart

func NewClientPart(conn Conn, logger Logger, s *PartAttr) *ClientPart

func (*ClientPart) Attr

func (od *ClientPart) Attr() *PartAttr

func (*ClientPart) Channel

func (od *ClientPart) Channel() Channel

func (*ClientPart) Conn

func (od *ClientPart) Conn() Conn

func (*ClientPart) ID

func (od *ClientPart) ID() string

func (*ClientPart) Logger

func (od *ClientPart) Logger() Logger

func (*ClientPart) Negotiate

func (od *ClientPart) Negotiate() error

func (*ClientPart) OnCloseToken

func (od *ClientPart) OnCloseToken()

func (*ClientPart) OnOpenHeader

func (od *ClientPart) OnOpenHeader(header xml.StartElement) error

func (*ClientPart) OnWhiteSpace

func (od *ClientPart) OnWhiteSpace(bs []byte)

func (*ClientPart) Quit

func (er *ClientPart) Quit()

func (*ClientPart) Run

func (od *ClientPart) Run() chan error

func (ClientPart) Running

func (er ClientPart) Running() bool

func (*ClientPart) SetHandleLimit

func (er *ClientPart) SetHandleLimit(limit int)

func (*ClientPart) Stop

func (od *ClientPart) Stop()

func (*ClientPart) WithElemHandler

func (er *ClientPart) WithElemHandler(handler ElemHandler)

func (*ClientPart) WithFeature

func (od *ClientPart) WithFeature(h ElemHandler)

type CompZlib

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

func NewCompZlib

func NewCompZlib(rw io.ReadWriter) *CompZlib

func (*CompZlib) Read

func (comp *CompZlib) Read(b []byte) (int, error)

func (*CompZlib) Write

func (comp *CompZlib) Write(b []byte) (int, error)

type CompressFailure

type CompressFailure struct {
	DescTag string
}

func (*CompressFailure) FromElem

func (cf *CompressFailure) FromElem(elem stravaganza.Element) error

func (CompressFailure) ToElem

func (cf CompressFailure) ToElem(elem *stravaganza.Element)

type Compressor

type Compressor interface {
	io.ReadWriter
}

type Conn

type Conn interface {
	net.Conn
	StartTLS(*tls.Config)
	BindTlsUnique(io.Writer) error
	StartCompress(BuildCompressor)
}

type ConnFor

type ConnFor string

type ConnGrabber

type ConnGrabber interface {
	Grab(chan Conn) error
	Cancel()
	For() ConnFor
	Type() ConnType
}

type ConnType

type ConnType string

type ElemHandler

type ElemHandler interface {
	ID() string
	Handle(elem stravaganza.Element, part Part) (catched bool, err error)
}

type ElementableError

type ElementableError interface {
	error
	ToElem(*stravaganza.Element)
}

type Err

type Err struct {
	Type string
	Desc []ErrDesc
}

func (Err) Error

func (err Err) Error() string

func (*Err) FromElem

func (err *Err) FromElem(elem stravaganza.Element)

func (Err) ToElem

func (err Err) ToElem(elem *stravaganza.Element)

type ErrDesc

type ErrDesc struct {
	Tag   string
	Xmlns string
}

type Failure

type Failure struct {
	Xmlns    string
	DescTag  string
	More     string
	MoreLang string
}

func (Failure) Error

func (f Failure) Error() string

func (*Failure) FromElem

func (f *Failure) FromElem(elem stravaganza.Element, xmlns string) error

func (Failure) ToElem

func (f Failure) ToElem(elem *stravaganza.Element)

type Feature

type Feature interface {
	Elem() stravaganza.Element
	Mandatory() bool
	Handled() bool
	ElemHandler
}

type IDAble

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

func CreateIDAble

func CreateIDAble() IDAble

func (IDAble) ID

func (idable IDAble) ID() string

type IqBind

type IqBind struct {
	IQ       Stanza
	Resource string
	JID      string
}

func (*IqBind) FromElem

func (ib *IqBind) FromElem(elem stravaganza.Element) error

func (IqBind) ToElem

func (ib IqBind) ToElem(elem *stravaganza.Element)

type IqErrHandler

type IqErrHandler interface {
	HandleIqError(StanzaErr, Part) error
}

type JID

type JID struct {
	Username string
	Domain   string
	Resource string
}

func (JID) Equal

func (jid JID) Equal(a JID) bool

func (JID) String

func (jid JID) String() string

type LocalConn

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

a conn mainly for test

func NewLocalConn

func NewLocalConn(comming, going chan []byte, localAddr, remoteAddr net.Addr) *LocalConn

func NewLocalConnPair

func NewLocalConnPair(oneAddr, twoAddr net.Addr) []*LocalConn

func (*LocalConn) BindTlsUnique

func (lc *LocalConn) BindTlsUnique(w io.Writer) error

func (*LocalConn) Close

func (lc *LocalConn) Close() error

func (*LocalConn) LocalAddr

func (lc *LocalConn) LocalAddr() net.Addr

func (*LocalConn) Read

func (lc *LocalConn) Read(b []byte) (n int, err error)

func (*LocalConn) RemoteAddr

func (lc *LocalConn) RemoteAddr() net.Addr

func (*LocalConn) SetDeadline

func (lc *LocalConn) SetDeadline(t time.Time) error

func (*LocalConn) SetReadDeadline

func (lc *LocalConn) SetReadDeadline(t time.Time) error

func (*LocalConn) SetWriteDeadline

func (lc *LocalConn) SetWriteDeadline(t time.Time) error

func (*LocalConn) StartTLS

func (lc *LocalConn) StartTLS(*tls.Config) error

func (*LocalConn) Write

func (lc *LocalConn) Write(b []byte) (n int, err error)

type LocalConnAddr

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

func NewLocalConnAddr

func NewLocalConnAddr(port string) *LocalConnAddr

func (*LocalConnAddr) Network

func (addr *LocalConnAddr) Network() string

func (*LocalConnAddr) String

func (addr *LocalConnAddr) String() string

type LogLevel

type LogLevel int

type LogMode

type LogMode int

type Logger

type Logger interface {
	Printf(level LogLevel, format string, v ...interface{})
	Writer() io.Writer
}

type MemoryAuthUser

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

func NewMemomryAuthUser

func NewMemomryAuthUser(username, password string, hash map[string]func() hash.Hash, ic int) *MemoryAuthUser

func (*MemoryAuthUser) ID

func (au *MemoryAuthUser) ID() string

func (*MemoryAuthUser) IterationCount

func (au *MemoryAuthUser) IterationCount() int

func (*MemoryAuthUser) Password

func (au *MemoryAuthUser) Password(hashName string) (string, error)

func (*MemoryAuthUser) Salt

func (au *MemoryAuthUser) Salt() string

func (*MemoryAuthUser) Username

func (au *MemoryAuthUser) Username() string

type MemoryAuthUserFetcher

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

func NewMemoryAuthUserFetcher

func NewMemoryAuthUserFetcher() *MemoryAuthUserFetcher

func (*MemoryAuthUserFetcher) Add

func (uf *MemoryAuthUserFetcher) Add(user *MemoryAuthUser)

func (*MemoryAuthUserFetcher) UserByUsername

func (uf *MemoryAuthUserFetcher) UserByUsername(username string) (ScramAuthUser, error)

type MemoryAuthorized

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

func NewMemoryAuthorized

func NewMemoryAuthorized() *MemoryAuthorized

func (*MemoryAuthorized) Authorized

func (ma *MemoryAuthorized) Authorized(_ string, part Part)

func (*MemoryAuthorized) BindResource

func (ma *MemoryAuthorized) BindResource(part Part, resource string) (string, error)

func (*MemoryAuthorized) FindPart

func (ma *MemoryAuthorized) FindPart(jid *JID) Part

type MemoryPlainAuthUser

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

func NewMemoryPlainAuthUser

func NewMemoryPlainAuthUser(username, password string) *MemoryPlainAuthUser

func (*MemoryPlainAuthUser) Password

func (mpu *MemoryPlainAuthUser) Password() string

func (*MemoryPlainAuthUser) Username

func (mpu *MemoryPlainAuthUser) Username() string

type MemoryPlainAuthUserFetcher

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

func NewMemoryPlainAuthUserFetcher

func NewMemoryPlainAuthUserFetcher() *MemoryPlainAuthUserFetcher

func (*MemoryPlainAuthUserFetcher) Add

func (*MemoryPlainAuthUserFetcher) UserByUsername

func (mpuf *MemoryPlainAuthUserFetcher) UserByUsername(username string) (PlainAuthUser, error)

type Parser

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

Parser parses arbitrary XML input and builds an array with the structure of all tag and data elements.

func NewParser

func NewParser(reader io.Reader, maxStanzaSize int) *Parser

New creates an empty Parser instance.

func (*Parser) Next

func (p *Parser) Next() (interface{}, error)

Parse parses next available XML element from reader.

type Part

type Part interface {
	ID() string
	Attr() *PartAttr
	Channel() Channel
	WithElemHandler(ElemHandler)
	Logger() Logger
	Conn() Conn

	OnOpenHeader(header xml.StartElement) error
	OnCloseToken()
	OnWhiteSpace([]byte)
}

type PartAttr

type PartAttr struct {
	ID      string
	JID     JID    // client's jid
	Domain  string // server domain
	Version string
	Xmlns   string
	XmlLang string
	OpenTag bool
}

func (*PartAttr) ParseToClient

func (sa *PartAttr) ParseToClient(elem xml.StartElement) error

func (*PartAttr) ParseToServer

func (sa *PartAttr) ParseToServer(elem xml.StartElement) error

func (*PartAttr) ToClientHead

func (attr *PartAttr) ToClientHead(elem *xml.StartElement)

func (*PartAttr) ToServerHead

func (attr *PartAttr) ToServerHead(elem *xml.StartElement)

type PlainAuth

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

func NewPlainAuth

func NewPlainAuth(uf PlainAuthUserFetcher, hashCreate func() hash.Hash) *PlainAuth

func (*PlainAuth) Auth

func (auth *PlainAuth) Auth(mechanism, authInfo string, part Part) (username string, err error)

type PlainAuthUser

type PlainAuthUser interface {
	Username() string
	Password() string
}

type PlainAuthUserFetcher

type PlainAuthUserFetcher interface {
	UserByUsername(string) (PlainAuthUser, error)
}

type Receiver

type Receiver interface {
	NextElement(elem *stravaganza.Element) error
	// contains filtered or unexported methods
}

type ResourceBinder

type ResourceBinder interface {
	BindResource(part Part, resource string) (string, error)
}

type ScramAuth

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

func NewScramAuth

func NewScramAuth(userFetcher ScramAuthUserFetcher, hashBuild func() hash.Hash, useCB bool) *ScramAuth

func (*ScramAuth) Auth

func (scram *ScramAuth) Auth(mechanism, authInfo string, part Part) (username string, err error)

type ScramAuthUser

type ScramAuthUser interface {
	Salt() string
	Password(hashName string) (string, error)
	ID() string
	IterationCount() int
}

type ScramAuthUserFetcher

type ScramAuthUserFetcher interface {
	UserByUsername(username string) (ScramAuthUser, error)
}

type ScramToAuth

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

func NewScramToAuth

func NewScramToAuth(u, p string, mechanism string, useCB bool) *ScramToAuth

func (*ScramToAuth) ToAuth

func (sta *ScramToAuth) ToAuth(mechemism string, part Part) error

type Sender

type Sender interface {
	Send([]byte) error
	SendToken(xml.Token) error
	SendElement(stravaganza.Element) error
}

type Stanza

type Stanza struct {
	Name string
	Type StanzaType
	ID   string
	From string
	To   string
}

func (*Stanza) FromElem

func (stanza *Stanza) FromElem(elem stravaganza.Element, name string) error

func (Stanza) ToElemBuilder

func (stanza Stanza) ToElemBuilder() *stravaganza.Builder

type StanzaErr

type StanzaErr struct {
	Stanza Stanza
	Err    Err
}

func BindErrFromError

func BindErrFromError(id string, err error) StanzaErr

func (*StanzaErr) FromElem

func (se *StanzaErr) FromElem(elem stravaganza.Element, name string) error

func (StanzaErr) ToElem

func (se StanzaErr) ToElem(elem *stravaganza.Element)

type StanzaErrHandler

type StanzaErrHandler struct {
	Name string
	// contains filtered or unexported fields
}

func (StanzaErrHandler) Handle

func (seh StanzaErrHandler) Handle(_ stravaganza.Element, part Part) error

func (*StanzaErrHandler) Match

func (seh *StanzaErrHandler) Match(elem stravaganza.Element) bool

type StanzaType

type StanzaType string

type TcpConn

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

func NewTcpConn

func NewTcpConn(underlying net.Conn, isClient bool) *TcpConn

func (*TcpConn) BindTlsUnique

func (conn *TcpConn) BindTlsUnique(w io.Writer) error

func (*TcpConn) Close

func (conn *TcpConn) Close() error

func (*TcpConn) LocalAddr

func (conn *TcpConn) LocalAddr() net.Addr

func (*TcpConn) Read

func (conn *TcpConn) Read(b []byte) (int, error)

func (*TcpConn) RemoteAddr

func (conn *TcpConn) RemoteAddr() net.Addr

func (*TcpConn) SetDeadline

func (conn *TcpConn) SetDeadline(t time.Time) error

func (*TcpConn) SetReadDeadline

func (conn *TcpConn) SetReadDeadline(t time.Time) error

func (*TcpConn) SetWriteDeadline

func (conn *TcpConn) SetWriteDeadline(t time.Time) error

func (*TcpConn) StartCompress

func (conn *TcpConn) StartCompress(buildCompress BuildCompressor)

func (*TcpConn) StartTLS

func (conn *TcpConn) StartTLS(conf *tls.Config)

func (*TcpConn) Write

func (conn *TcpConn) Write(b []byte) (int, error)

type TcpConnGrabber

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

func NewTcpConnGrabber

func NewTcpConnGrabber(listenOn string, connFor ConnFor, logger Logger) *TcpConnGrabber

func (*TcpConnGrabber) Cancel

func (tc *TcpConnGrabber) Cancel()

func (*TcpConnGrabber) For

func (tc *TcpConnGrabber) For() ConnFor

func (*TcpConnGrabber) Grab

func (tc *TcpConnGrabber) Grab(connChan chan Conn) error

func (*TcpConnGrabber) ReplaceLogger

func (tc *TcpConnGrabber) ReplaceLogger(logger Logger)

func (*TcpConnGrabber) Type

func (tc *TcpConnGrabber) Type() ConnType

func (*TcpConnGrabber) UpgradeToTls

func (tc *TcpConnGrabber) UpgradeToTls(certFile, keyFile string) error

type ToAuth

type ToAuth interface {
	ToAuth(mech string, part Part) error
}

type WsConnGrabber

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

func NewWsConnGrabber

func NewWsConnGrabber(listenOn string, path string, upgrader websocket.Upgrader, logger Logger) *WsConnGrabber

func (*WsConnGrabber) Cancel

func (wsc *WsConnGrabber) Cancel()

func (*WsConnGrabber) For

func (wsc *WsConnGrabber) For() ConnFor

func (*WsConnGrabber) Grab

func (wsc *WsConnGrabber) Grab(connChan chan Conn) error

func (*WsConnGrabber) Type

func (wsc *WsConnGrabber) Type() ConnType

func (*WsConnGrabber) UpgradeToTls

func (wsc *WsConnGrabber) UpgradeToTls(certFile, keyFile string) error

type XChannel

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

func NewXChannel

func NewXChannel(conn Conn, isServer bool) *XChannel

func (*XChannel) Close

func (xc *XChannel) Close()

func (*XChannel) NextElement

func (xc *XChannel) NextElement(elem *stravaganza.Element) error

func (*XChannel) Open

func (xc *XChannel) Open(attr *PartAttr) error

func (*XChannel) Send

func (gs *XChannel) Send(bs []byte) error

func (*XChannel) SendElement

func (gs *XChannel) SendElement(elem stravaganza.Element) error

func (*XChannel) SendToken

func (gs *XChannel) SendToken(token xml.Token) error

func (*XChannel) SetLogger

func (xc *XChannel) SetLogger(logger Logger)

func (*XChannel) WaitHeader

func (xc *XChannel) WaitHeader(header *xml.StartElement) error

func (*XChannel) WaitSecOnClose

func (xc *XChannel) WaitSecOnClose(sec int)

type XLogger

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

func NewLogger

func NewLogger(w io.Writer) *XLogger

func (*XLogger) Printf

func (logger *XLogger) Printf(level LogLevel, format string, v ...interface{})

func (*XLogger) SetLogLevel

func (logger *XLogger) SetLogLevel(level LogLevel)

func (*XLogger) Writer

func (logger *XLogger) Writer() io.Writer

type XPart

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

func NewXPart

func NewXPart(conn Conn, domain string, logger Logger) *XPart

func (*XPart) Attr

func (part *XPart) Attr() *PartAttr

func (*XPart) Channel

func (part *XPart) Channel() Channel

func (*XPart) Conn

func (part *XPart) Conn() Conn

func (*XPart) ID

func (part *XPart) ID() string

func (*XPart) Logger

func (part *XPart) Logger() Logger

func (*XPart) OnCloseToken

func (part *XPart) OnCloseToken()

func (*XPart) OnOpenHeader

func (part *XPart) OnOpenHeader(header xml.StartElement) error

func (*XPart) OnWhiteSpace

func (part *XPart) OnWhiteSpace([]byte)

func (*XPart) Quit

func (er *XPart) Quit()

func (*XPart) Run

func (part *XPart) Run() chan error

func (XPart) Running

func (er XPart) Running() bool

func (*XPart) SetHandleLimit

func (er *XPart) SetHandleLimit(limit int)

func (*XPart) Stop

func (part *XPart) Stop()

func (*XPart) WithElemHandler

func (er *XPart) WithElemHandler(handler ElemHandler)

func (*XPart) WithFeature

func (part *XPart) WithFeature(f Feature)

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

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