bosh

package module
v0.0.0-...-58e6f22 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2022 License: BSD-2-Clause Imports: 13 Imported by: 0

README

Go BOSH

GoDoc License

A BOSH connection manager and client in Go.

License

The package may be used under the terms of the BSD 2-Clause License a copy of which may be found in the file LICENSE.md.

Documentation

Overview

Package bosh is an implementation of XEP-0124: Bidirectional-streams Over Synchronous HTTP (BOSH).

For more information see the spec: https://xmpp.org/extensions/xep-0124.html

Be advised: This API is still unstable and is subject to change.

Index

Examples

Constants

View Source
const (
	SupportedProtocolVersion = "1.11"
	DefaultWaitTime          = 5 // Seconds
)
View Source
const (
	HTTPBind      = "http://jabber.org/protocol/httpbind"
	XBOSH         = "urn:xmpp:xbosh"
	JabberStreams = "http://etherx.jabber.org/streams"
)

Variables

View Source
var (
	ErrInvalidAck        = &ProtocolError{"invalid or missing ack"}
	ErrInvalidHold       = &ProtocolError{"invalid or missing hold attribute"}
	ErrInvalidInactivity = &ProtocolError{"invalid or missing inactivity period"}
	ErrInvalidMaxReqs    = &ProtocolError{"invalid or missing max requests num"}
	ErrInvalidPolling    = &ProtocolError{"invalid or missing polling interval"}
	ErrInvalidSID        = &ProtocolError{"invalid or missing session ID"}
	ErrInvalidWait       = &ProtocolError{"invalid or missing wait attribute"}
	ErrInvalidXML        = &ProtocolError{"bad XML data received"}
)

Functions

func RIDFromContext

func RIDFromContext(ctx context.Context) (rid uint64, ok bool)

RIDFromContext extracts the request ID from ctx, if present.

func SIDFromContext

func SIDFromContext(ctx context.Context) (sid string, ok bool)

SIDFromContext extracts the session ID from ctx, if present.

Types

type Addr

type Addr struct {
	*url.URL
}

Addr is an implementation of net.Addr for BOSH.

func (*Addr) Network

func (addr *Addr) Network() string

Network returns the network type for BOSH, "bosh".

func (*Addr) String

func (addr *Addr) String() string

String returns a URL string for the address.

type BindingCondition

type BindingCondition struct {
	XMLName   xml.Name `xml:"http://jabber.org/protocol/httpbind body"`
	Condition string   `xml:"condition,attr,omitempty"`
	Type      string   `xml:"type,attr"`
	InnerXML  []byte   `xml:",innerxml"`
	CharData  []byte   `xml:",chardata"`
}

BindingCondition is an error that represents a terminal or remote binding condition and is marshalable and unmarshalable from XML.

Example (Marshal)
b, _ := xml.Marshal(UndefinedCondition("The server is dead, Jim."))
fmt.Println(string(b))
b, _ = xml.Marshal(SeeOtherURI("https://likeabosh.hipchat.com/http-bind"))
fmt.Println(string(b))
Output:

<body xmlns="http://jabber.org/protocol/httpbind" condition="undefined-condition" type="terminate">The server is dead, Jim.</body>
<body xmlns="http://jabber.org/protocol/httpbind" condition="see-other-uri" type="terminate"><uri>https://likeabosh.hipchat.com/http-bind</uri></body>
Example (Unmarshal)
e := []byte(`<body condition='see-other-uri'
                     type='terminate'
                     xmlns='http://jabber.org/protocol/httpbind'>
    <uri>https://likeabosh.hipchat.com/http-bind</uri>
</body>
`)
bc := BindingCondition{}
xml.Unmarshal(e, &bc)
fmt.Printf("%s: %s", bc.Error(), bytes.TrimSpace(bc.InnerXML))
Output:

see-other-uri: <uri>https://likeabosh.hipchat.com/http-bind</uri>
var (
	// BadRequest indicates that the format of an HTTP header or binding element
	// received from the client is unacceptable (e.g., syntax error).
	BadRequest BindingCondition = terminalCondition("bad-request")

	// HostGone indicates that the target domain specified in the 'to' attribute
	// or the target host or port specified in the 'route' attribute is no longer
	// serviced by the connection manager.
	HostGone BindingCondition = terminalCondition("hots-gone")

	// HostUnknown indicates that the target domain specified in the 'to'
	// attribute or the target host or port specified in the 'route' attribute is
	// unknown to the connection manager.
	HostUnknown BindingCondition = terminalCondition("host-unknown")

	// ImproperAddressing indicates that the initialization element lacks a 'to'
	// or 'route' attribute (or the attribute has no value) but the connection
	// manager requires one.
	ImproperAddressing BindingCondition = terminalCondition("improper-addressing")

	// InternalServerError indicates that the connection manager has experienced
	// an internal error that prevents it from servicing the request.
	InternalServerError BindingCondition = terminalCondition("internal-server-error")

	// ItemNotFound indicates that (1) 'sid' is not valid, (2) 'stream' is not
	// valid, (3) 'rid' is larger than the upper limit of the expected window, (4)
	// connection manager is unable to resend response, or (5) 'key' sequence is
	// invalid.
	ItemNotFound BindingCondition = terminalCondition("item-not-found")

	// OtherRequest indicates that another request being processed at the same
	// time as this request caused the session to terminate.
	OtherRequest BindingCondition = terminalCondition("other-request")

	// PolicyViolation indicates that the client has broken the session rules
	// (polling too frequently, requesting too frequently, sending too many
	// simultaneous requests).
	PolicyViolation BindingCondition = terminalCondition("policy-violation")

	// RemoteConnectionFailed indicates that the connection manager was unable to
	// connect to, or unable to connect securely to, or has lost its connection
	// to, the server.
	RemoteConnectionFailed BindingCondition = terminalCondition("remote-connection-failed")

	// RemoteStreamError encapsulates an error in the protocol being transported.
	RemoteStreamError BindingCondition = terminalCondition("remote-stream-error")

	// SystemShutdown indicates that the connection manager is being shut down.
	// All active HTTP sessions are being terminated. No new sessions can be
	// created.
	SystemShutdown BindingCondition = terminalCondition("system-shutdown")
)

func SeeOtherURI

func SeeOtherURI(uri string) BindingCondition

SeeOtherURI returns an error that indicates that the connection manager does not operate at this URI (e.g., the connection manager accepts only SSL or TLS connections at some https: URI rather than the http: URI requested by the client). The provided URI will be set as the contents of the <uri/> child element.

func UndefinedCondition

func UndefinedCondition(innererr interface{}) BindingCondition

UndefinedCondition returns an error that acts as an application-level terminal condition. The innererr is marshaled into the undefined-condition error's inner XML or as char data if a string, byte array, or error is provided.

func (BindingCondition) Error

func (bc BindingCondition) Error() string

Error satisfies the error interface by returning the name of the binding condition (eg. "policy-violation").

type Config

type Config struct {
	// BOSH protocol version
	Version string

	// A BOSH server address.
	Location *url.URL

	// A BOSH client origin.
	Origin *url.URL

	// Ack indicates that the client will be using acknowledgements throughout the
	// session.
	Ack bool

	// Wait specifies the longest time (in seconds) that the connection manager is
	// allowed to wait before responding to any request during the session. If it
	// is set on a server connection, it is the maximum wait time that a client
	// may request. This enables the client to limit the delay before it discovers
	// any network failure, and to prevent its HTTP/TCP connection from expiring
	// due to inactivity.
	Wait int

	// To specifies the target domain of the first stream; note that it is the
	// domain being served, not the hostname of the machine that is serving the
	// domain.
	To string

	// From specifies the originator of the first stream which enables the
	// connection manager to forward the originating entity's identity to the
	// application server (e.g., the JabberID of an entity that is connecting to
	// an XMPP server).
	From string

	// Header contains additional header fields to be sent with each HTTP request
	// or response.
	Header http.Header

	// Hold specifies the maximum number of requests the connection manager is
	// allowed to keep waiting at any one time during the session. If the client
	// is able to reuse connections, this value SHOULD be set to "1" (the default
	// if the NewConfig function is used to create this config).
	Hold int

	// Content is the value of the Content-Type header that should be returned for
	// every request by the server. Defaults to "text/xml; charset=utf-8". This
	// should probably never be modified.
	Content string

	// Lang specifies the default language of any human-readable XML character
	// data sent or received during the session.
	Lang language.Tag

	// Route is an optional value that specifies the protocol, hostname, and port
	// of the server with which we want to communicate, formatted as
	// "proto:host:port" (e.g., "xmpp:example.com:9999"). It is used to route
	// traffic to a specific host when connecting to proxy BOSH servers (or acting
	// as one) that serve multiple domains. Route may be ignored.
	Route string

	// Requests enables the connection manager to limit the number of simultaneous
	// requests the client makes. This value must be larger than the 'hold'
	// attribute value specified in the session request. Clients wlil keep open at
	// most this number of requests (if not set, defaults to Hold + 1) or whatever
	// the server specifies, whichever is smaller.
	Requests int

	// Inactivity specifies the longest allowable inactivity period (in seconds).
	// This value is only applicable to server configs.
	Inactivity int
}

Config is a BOSH configuration. Normally, the NewConfig function should be used for creating new configurations.

func NewConfig

func NewConfig(server, origin string) (config *Config, err error)

NewConfig creates a new BOSH config for a client connection.

type Conn

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

Conn represents a BOSH connection.

Multiple goroutines may invoke methods on a Conn simultaneously.

func Dial

func Dial(url, origin string) (conn *Conn, err error)

Dial opens a new client connection to a BOSH server and starts a new session. The connection has an in-memory buffer that is flushed as new HTTP requests are made.

func DialConfig

func DialConfig(config *Config) (conn *Conn, err error)

DialConfig opens a new BOSH client connection with a config.

func NewClient

func NewClient(ctx context.Context, config *Config) (*Conn, error)

NewClient creates a new BOSH client connection using ctx as the base context for all requests made by the client.

func (*Conn) Close

func (conn *Conn) Close() error

Close implements the io.Closer interface.

func (*Conn) Config

func (conn *Conn) Config() *Config

Config returns the BOSH config.

func (*Conn) IsClientConn

func (conn *Conn) IsClientConn() bool

IsClientConn is true if the BOSH connection is a client connection.

func (*Conn) IsServerConn

func (conn *Conn) IsServerConn() bool

IsServerConn is true if the BOSH connection is a server connection.

func (*Conn) LocalAddr

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

LocalAddr returns Origin for a client connection, or Location for a server connection.

func (*Conn) Read

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

Read satisfies the io.Reader interface: It reads a single response from the BOSH connection and populates b with the contents of the <body/> element.

func (*Conn) RemoteAddr

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

RemoteAddr returns Location for a client connection, or Origin for a server connection.

func (*Conn) SetDeadline

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

SetDeadline sets the connection's network read & write deadlines.

func (*Conn) SetReadDeadline

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

SetReadDeadline sets the connection's network read deadline.

func (*Conn) SetWriteDeadline

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

SetWriteDeadline sets the connection's network write deadline.

func (*Conn) Write

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

Write satisfies the io.Writer interface: It writes the given bytes to the internal buffer to be sent in a later HTTP request or response.

type DialError

type DialError struct {
	*Config
	ErrString string
}

DialError is an error that occurs while dialling a BOSH server.

func (*DialError) Error

func (e *DialError) Error() string

Error satisfies the error interface.

type Handler

type Handler func(*Conn)

Handler is a simple http.Handler interface to BOSH.

func (Handler) ServeHTTP

func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements the http.Handler interface for BOSH.

type ProtocolError

type ProtocolError struct {
	ErrorString string
}

ProtocolError represents unrecoverable errors due to unexpected requests or responses in the BOSH protocol such as badly formatted XML.

func (*ProtocolError) Error

func (err *ProtocolError) Error() string

Error satisfies the error interface.

type Server

type Server struct {
	Config

	// Dial will be used when making new upstream connections.
	//
	// If Dial is nil, net.Dial is used.
	Dial func(network, addr string) (net.Conn, error)

	// Handler defines the behavior of the server. It can be used to handle
	// subprotocols such as XMPP, to proxy a BOSH connection to a different
	// protocol, etc.
	Handler

	// EventLog facilitates logging to the trace web interface, or to any
	// log.Logger that implements the EventLog interface.
	EventLog trace.EventLog
	// contains filtered or unexported fields
}

Server is a BOSH session manager.

func NewServer

func NewServer(ctx context.Context) *Server

Creates a new server that will use the given context as the base context for all requests. When the context is closed the server will attempt to shut down cleanly.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP satisfies the http.Handler interface.

Notes

Bugs

  • Server functionality is an API definition and doesn't work yet.

Directories

Path Synopsis
Package internal provides internal APIs used by the bosh package.
Package internal provides internal APIs used by the bosh package.

Jump to

Keyboard shortcuts

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