sip

package
v0.0.0-...-b5ee3c3 Latest Latest
Warning

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

Go to latest
Published: May 11, 2026 License: BSD-2-Clause Imports: 25 Imported by: 0

README

SIP stack in GO

This SIP stack for RFC:

https://datatracker.ietf.org/doc/html/rfc3261

Stack:

  • Encoding/Decoding with Parser optimized for fast parsing
  • Transport Layer and support for different protocols
  • Transaction Layer with transaction sessions managing and state machine

Parser

Parser by default parses set of headers that are mostly present in messages. From,To,Via,Cseq,Content-Type,Content-Length... This headers are accessible via fast reference msg.Via(), msg.From()...

This can be configured using WithHeadersParsers and reducing this to increase performance. SIP stack in case needed will use fast reference and lazy parsing.

Transport Layer

TransportLayer runs the UDP / TCP / TLS / WS / WSS listeners that drive the SIP stack. Options are passed to NewTransportLayer and apply to all configured protocols.

UDP peer-pool eviction (opt-in)

A long-lived UDP listener (one that never exits ServeUDP for the lifetime of the process) accumulates one connectionPool entry per distinct inbound source address. Under normal operation the cardinality is tiny, but under adversarial source-port churn the map grows unbounded.

tp := sip.NewTransportLayer(
    net.DefaultResolver,
    sip.NewParser(),
    nil,
    sip.WithTransportLayerUDPPeerIdleTTL(5*time.Minute),
)

Behavior:

  • A peer's pool entry is evicted on the next sweep after ttl of idleness.
  • The sweep is skipped when the listener connection has an elevated refcount (a transaction is in flight). For UDP listeners the refcount is shared across every per-peer mapping, so this is a conservative per-listener gate, not a per-peer one — the TTL behaves as a lower bound while idle rather than an upper bound under sustained load.
  • Default (ttl == 0) preserves the pre-existing accumulate-until-exit behavior.
Monitoring pool cardinality

(*TransportLayer).UDPPoolSize() returns the current number of entries in the UDP connection pool (listener self-entry + per-peer mappings + any client-dialed connections). Expose it as a gauge to keep eviction tuning observable.

Documentation

Index

Constants

View Source
const (
	// https://datatracker.ietf.org/doc/html/rfc3261#section-21
	StatusTrying            = 100
	StatusRinging           = 180
	StatusCallIsForwarded   = 181
	StatusQueued            = 182
	StatusSessionInProgress = 183

	StatusOK       = 200
	StatusAccepted = 202

	StatusMovedPermanently = 301
	StatusMovedTemporarily = 302
	StatusUseProxy         = 305

	StatusBadRequest                   = 400
	StatusUnauthorized                 = 401
	StatusPaymentRequired              = 402
	StatusForbidden                    = 403
	StatusNotFound                     = 404
	StatusMethodNotAllowed             = 405
	StatusNotAcceptable                = 406
	StatusProxyAuthRequired            = 407
	StatusRequestTimeout               = 408
	StatusConflict                     = 409
	StatusGone                         = 410
	StatusRequestEntityTooLarge        = 413
	StatusRequestURITooLong            = 414
	StatusUnsupportedMediaType         = 415
	StatusRequestedRangeNotSatisfiable = 416
	StatusBadExtension                 = 420
	StatusExtensionRequired            = 421
	StatusIntervalToBrief              = 423
	StatusTemporarilyUnavailable       = 480
	StatusCallTransactionDoesNotExists = 481
	StatusLoopDetected                 = 482
	StatusTooManyHops                  = 483
	StatusAddressIncomplete            = 484
	StatusAmbiguous                    = 485
	StatusBusyHere                     = 486
	StatusRequestTerminated            = 487
	StatusNotAcceptableHere            = 488
	StatusRequestPending               = 491

	StatusInternalServerError = 500
	StatusNotImplemented      = 501
	StatusBadGateway          = 502
	StatusServiceUnavailable  = 503
	StatusGatewayTimeout      = 504
	StatusVersionNotSupported = 505
	StatusMessageTooLarge     = 513

	StatusGlobalBusyEverywhere       = 600
	StatusGlobalDecline              = 603
	StatusGlobalDoesNotExistAnywhere = 604
	StatusGlobalNotAcceptable        = 606
)
View Source
const (
	DefaultProtocol = "UDP"

	DefaultUdpPort int = 5060
	DefaultTcpPort int = 5060
	DefaultTlsPort int = 5061
	DefaultWsPort  int = 80
	DefaultWssPort int = 443
)
View Source
const (
	FsmInputNone fsmInput = iota
)

FSM Inputs

View Source
const (
	RFC3261BranchMagicCookie = "z9hG4bK"
)

Variables

View Source
var (
	ErrParseLineNoCRLF = errors.New("line has no CRLF")
	ErrParseEOF        = errors.New("EOF on reading line")

	// Stream parse errors
	ErrParseSipPartial         = errors.New("SIP partial data")
	ErrParseReadBodyIncomplete = errors.New("reading body incomplete")
	ErrMessageTooLarge         = errors.New("Message exceeds ParseMaxMessageLength")
)
View Source
var (
	// SIP timers are exposed for manipulation but best approach is using SetTimers
	// where all timers get populated based on
	// T1: Round-trip time (RTT) estimate, Default 500ms
	T1,

	T2,

	T4,

	Timer_A,

	Timer_B,
	Timer_D,
	Timer_E,

	Timer_F,
	Timer_G,
	Timer_H,
	Timer_I,
	Timer_J,
	Timer_K,
	Timer_L,
	Timer_M time.Duration

	Timer_1xx = 200 * time.Millisecond

	TxSeperator = "__"

	TransactionFSMDebug bool
)
View Source
var (
	// Transaction Layer Errors can be detected and handled with different response on caller side
	// https://www.rfc-editor.org/rfc/rfc3261#section-8.1.3.1
	ErrTransactionTimeout    = errors.New("transaction timeout")
	ErrTransactionTransport  = errors.New("transaction transport error")
	ErrTransactionCanceled   = errors.New("transaction canceled")
	ErrTransactionTerminated = errors.New("transaction terminated")
)
View Source
var (

	// TransportIdleConnection will keep connections idle even after transaction terminate
	// -1 	- single response or request will close
	// 0 	- close connection immediatelly after transaction terminate
	// 1 	- keep connection idle after transaction termination
	TransportIdleConnection int = 1

	// TransportBufferReadSize sets this buffer size to use on reading SIP messages.
	TransportBufferReadSize uint16 = 32768
)
View Source
var (
	UDPMTUSize = 1500

	ErrUDPMTUCongestion = errors.New("size of packet larger than MTU")
)
View Source
var (

	// Errors
	ErrTransportNotSuported = errors.New("protocol not supported")
)
View Source
var (
	ParseMaxMessageLength = 65535
)
View Source
var (
	SIPDebug bool
)
View Source
var (
	// WebSocketProtocols is used in setting websocket header
	// By default clients must accept protocol sip
	WebSocketProtocols = []string{"sip"}
)

Functions

func ASCIIToLower

func ASCIIToLower(s string) string

ASCIIToLower is faster than go version. It avoids one more loop

func ASCIIToLowerInPlace

func ASCIIToLowerInPlace(s []byte)

func ASCIIToUpper

func ASCIIToUpper(s string) string

func ClientTxKeyMake

func ClientTxKeyMake(msg Message) (string, error)

ClientTxKeyMake creates client key for matching responses - RFC 3261 17.1.3.

func CopyHeaders

func CopyHeaders(name string, from, to Message)

Copy all headers of one type from one message to another. Appending to any headers that were already there.

func DefaultHeadersParser

func DefaultHeadersParser() map[string]HeaderParser

DefaultHeadersParser returns minimal version header parser. It can be extended or overwritten.

func DefaultLogger

func DefaultLogger() *slog.Logger

func DefaultPort

func DefaultPort(transport string) int

DefaultPort returns transport default port by network.

func DialogIDFromRequestUAC

func DialogIDFromRequestUAC(msg *Request) (string, error)

DialogIDFromRequestUAC creates dialog ID of message if receiver has UAC role. returns error if callid or to tag or from tag does not exists

func DialogIDFromRequestUAS

func DialogIDFromRequestUAS(msg *Request) (string, error)

DialogIDFromRequestUAS creates dialog ID of message if receiver has UAS role. returns error if callid or to tag or from tag does not exists

func DialogIDFromResponse

func DialogIDFromResponse(msg *Response) (string, error)

DialogIDFromResponse creates dialog ID of message. returns error if callid or to tag or from tag does not exists

func DialogIDMake

func DialogIDMake(callID, innerID, externalID string) string

func GenerateBranch

func GenerateBranch() string

GenerateBranch returns random unique branch ID.

func GenerateBranchN

func GenerateBranchN(n int) string

GenerateBranchN returns random unique branch ID in format MagicCookie.<n chars>

func GenerateTagN

func GenerateTagN(n int) string

func HeaderToLower

func HeaderToLower(s string) string

HeaderToLower is fast ASCII lower string

func IsReliable

func IsReliable(network string) bool

func NetworkToLower

func NetworkToLower(network string) string

NetworkToLower is faster function converting UDP, TCP to udp, tcp

func NetworkToUpper

func NetworkToUpper(network string) string

NetworkToUpper is faster function converting udp, tcp to UDP, tcp

func NonceWrite

func NonceWrite(buf []byte)

func ParseAddr

func ParseAddr(addr string) (host string, port int, err error)

func ParseAddressValue

func ParseAddressValue(addressText string, uri *Uri, headerParams *HeaderParams) (displayName string, err error)

ParseAddressValue parses an address - such as from a From, To, or Contact header. It returns: See RFC 3261 section 20.10 for details on parsing an address.

func ParseUri

func ParseUri(uriStr string, uri *Uri) (err error)

ParseUri converts a string representation of a URI into a Uri object. Following https://datatracker.ietf.org/doc/html/rfc3261#section-19.1.1 sip:user:password@host:port;uri-parameters?headers

func ResolveInterfaceIp

func ResolveInterfaceIp(iface net.Interface, network string, targetIP *net.IPNet) (net.IP, error)

func ResolveInterfacesIP

func ResolveInterfacesIP(network string, targetIP *net.IPNet) (net.IP, net.Interface, error)

ResolveInterfaceIP will check current interfaces and resolve to IP Using targetIP it will try to match interface with same subnet network can be "ip" "ip4" "ip6" by default it avoids loopack IP unless targetIP is loopback

func SIPDebugTracer

func SIPDebugTracer(t SIPTracer)

func ServerTransactionContext

func ServerTransactionContext(tx ServerTransaction) context.Context

ServerTransactionContext creates server transaction cancelation via context.Context This is useful if you want to pass this on underhood APIs Should not be called more than once per transaction

func ServerTxKeyMake

func ServerTxKeyMake(msg Message) (string, error)

ServerTxKeyMake creates server key for matching retransmitting requests - RFC 3261 17.2.3.

func SetDefaultLogger

func SetDefaultLogger(l *slog.Logger)

SetDefaultLogger sets default logger that will be used withing sip package Must be called before any usage of library

func SetTimers

func SetTimers(t1, t2, t4 time.Duration)

func UnmarshalHeaderParams

func UnmarshalHeaderParams(s string, seperator rune, ending rune, p *HeaderParams) (n int, err error)

func UriIsSIP

func UriIsSIP(s string) bool

Check uri is SIP fast

func UriIsSIPS

func UriIsSIPS(s string) bool

Types

type Addr

type Addr struct {
	IP       net.IP // Must be in IP format
	Port     int
	Hostname string // Original hostname before resolved to IP
	Zone     string
}

func (*Addr) Copy

func (a *Addr) Copy(d *Addr)

func (*Addr) String

func (a *Addr) String() string

type CSeqHeader

type CSeqHeader struct {
	SeqNo      uint32
	MethodName RequestMethod
}

CSeq is CSeq header

func (*CSeqHeader) Name

func (h *CSeqHeader) Name() string

func (*CSeqHeader) String

func (h *CSeqHeader) String() string

func (*CSeqHeader) StringWrite

func (h *CSeqHeader) StringWrite(buffer io.StringWriter)

func (*CSeqHeader) Value

func (h *CSeqHeader) Value() string

type CallIDHeader

type CallIDHeader string

CallIDHeader is a Call-ID header presentation

func (*CallIDHeader) Name

func (h *CallIDHeader) Name() string

func (*CallIDHeader) String

func (h *CallIDHeader) String() string

func (*CallIDHeader) StringWrite

func (h *CallIDHeader) StringWrite(buffer io.StringWriter)

func (*CallIDHeader) Value

func (h *CallIDHeader) Value() string

type ClientTransaction

type ClientTransaction interface {
	Transaction
	// Responses returns channel with all responses for transaction
	Responses() <-chan *Response

	// Register response retransmission hook.
	OnRetransmission(f FnTxResponse) bool
}

type ClientTx

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

func NewClientTx

func NewClientTx(key string, origin *Request, conn Connection, logger *slog.Logger) *ClientTx

func (*ClientTx) Connection

func (tx *ClientTx) Connection() Connection

func (*ClientTx) Done

func (tx *ClientTx) Done() <-chan struct{}

func (*ClientTx) Err

func (tx *ClientTx) Err() error

func (*ClientTx) Init

func (tx *ClientTx) Init() error

func (*ClientTx) Key

func (tx *ClientTx) Key() string

func (*ClientTx) OnRetransmission

func (tx *ClientTx) OnRetransmission(f FnTxResponse) bool

func (*ClientTx) OnTerminate

func (tx *ClientTx) OnTerminate(f FnTxTerminate) bool

OnTerminate is experimental Callback function can not call any fsm related functions as it will cause deadlock like. Err must not be called,instead error is passed

func (*ClientTx) Origin

func (tx *ClientTx) Origin() *Request

func (*ClientTx) Receive

func (tx *ClientTx) Receive(res *Response)

Receive will process response in safe way and change transaction state NOTE: it could block while passing response to client, therefore running in seperate goroutine is needed

func (*ClientTx) Responses

func (tx *ClientTx) Responses() <-chan *Response

func (*ClientTx) String

func (tx *ClientTx) String() string

func (*ClientTx) Terminate

func (tx *ClientTx) Terminate()

type Connection

type Connection interface {
	// LocalAddr used for connection
	LocalAddr() net.Addr
	// WriteMsg marshals message and sends to socket
	WriteMsg(msg Message) error
	// Reference of connection can be increased/decreased to prevent closing to earlyss
	Ref(i int) int
	// Close decreases reference and if ref = 0 closes connection. Returns last ref. If 0 then it is closed
	TryClose() (int, error)

	Close() error
}

type ContactHeader

type ContactHeader struct {
	// The display name from the header, may be omitted.
	DisplayName string
	Address     Uri
	// Any parameters present in the header.
	Params HeaderParams
}

ContactHeader is Contact header representation

func (*ContactHeader) Clone

func (h *ContactHeader) Clone() *ContactHeader

func (*ContactHeader) Name

func (h *ContactHeader) Name() string

func (*ContactHeader) String

func (h *ContactHeader) String() string

func (*ContactHeader) StringWrite

func (h *ContactHeader) StringWrite(buffer io.StringWriter)

func (*ContactHeader) Value

func (h *ContactHeader) Value() string

type ContentLengthHeader

type ContentLengthHeader uint32

ContentLengthHeader is Content-Length header representation

func (*ContentLengthHeader) Name

func (h *ContentLengthHeader) Name() string

func (ContentLengthHeader) String

func (h ContentLengthHeader) String() string

func (ContentLengthHeader) StringWrite

func (h ContentLengthHeader) StringWrite(buffer io.StringWriter)

func (ContentLengthHeader) Value

func (h ContentLengthHeader) Value() string

type ContentTypeHeader

type ContentTypeHeader string

ContentTypeHeader is Content-Type header representation.

func (*ContentTypeHeader) Name

func (h *ContentTypeHeader) Name() string

func (*ContentTypeHeader) String

func (h *ContentTypeHeader) String() string

func (*ContentTypeHeader) StringWrite

func (h *ContentTypeHeader) StringWrite(buffer io.StringWriter)

func (*ContentTypeHeader) Value

func (h *ContentTypeHeader) Value() string

type CopyHeader

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

CopyHeader is internal interface for cloning headers. Maybe it will be full exposed later

type DialogState

type DialogState int
const (
	// Dialog received 200 response
	DialogStateEstablished DialogState = 1
	// Dialog received ACK
	DialogStateConfirmed DialogState = 2
	// Dialog received BYE
	DialogStateEnded DialogState = 3
)

func (DialogState) String

func (s DialogState) String() string

type ErrorHandler

type ErrorHandler func(err error)

type ExpiresHeader

type ExpiresHeader uint32

ExpiresHeader is Expires header representation

func (*ExpiresHeader) Name

func (h *ExpiresHeader) Name() string

func (*ExpiresHeader) String

func (h *ExpiresHeader) String() string

func (*ExpiresHeader) StringWrite

func (h *ExpiresHeader) StringWrite(buffer io.StringWriter)

func (ExpiresHeader) Value

func (h ExpiresHeader) Value() string

type FnTxCancel

type FnTxCancel func(r *Request)

type FnTxResponse

type FnTxResponse func(r *Response)

type FnTxTerminate

type FnTxTerminate func(key string, err error)

type FromHeader

type FromHeader struct {
	// The display name from the header, may be omitted.
	DisplayName string

	Address Uri

	// Any parameters present in the header.
	Params HeaderParams
}

func (*FromHeader) AsTo

func (h *FromHeader) AsTo() ToHeader

func (*FromHeader) Name

func (h *FromHeader) Name() string

func (*FromHeader) String

func (h *FromHeader) String() string

func (*FromHeader) StringWrite

func (h *FromHeader) StringWrite(buffer io.StringWriter)

func (*FromHeader) Value

func (h *FromHeader) Value() string
type Header interface {
	// Name returns underlying header name.
	Name() string
	Value() string
	String() string
	// StringWrite is better way to reuse single buffer
	StringWrite(w io.StringWriter)
	// contains filtered or unexported methods
}

Header is a single SIP header.

func HeaderClone

func HeaderClone(h Header) Header

HeaderClone is generic function for cloning header

func NewHeader

func NewHeader(name, value string) Header

NewHeader creates generic type of header

type HeaderKV

type HeaderKV struct {
	K string
	V string
}

HeaderKV is a key-value pair for URI or header params.

type HeaderParams

type HeaderParams []HeaderKV

HeaderParams are key value params.

func NewParams

func NewParams() HeaderParams

NewParams creates an empty set of parameters.

func (*HeaderParams) Add

func (hp *HeaderParams) Add(key string, val string) HeaderParams

Add will add new key-value. If key exists it will be overwritten.

func (HeaderParams) Clone

func (hp HeaderParams) Clone() HeaderParams

Clone returns underneath params copied

func (HeaderParams) Equals

func (hp HeaderParams) Equals(other interface{}) bool

Equals check if two maps of parameters are equal in the sense of having the same keys with the same values. This does not rely on any ordering of the keys of the map in memory.

func (HeaderParams) Get

func (hp HeaderParams) Get(key string) (string, bool)

Get returns a value for a given key, if it exists.

func (HeaderParams) GetOr

func (hp HeaderParams) GetOr(key, def string) string

GetOr returns a value for a given key, oe a default, if it doesn't exist.

func (HeaderParams) Has

func (hp HeaderParams) Has(key string) bool

Has checks does key exists

func (HeaderParams) Items

func (hp HeaderParams) Items() map[string]string

Items returns the entire parameter map.

func (HeaderParams) Keys

func (hp HeaderParams) Keys() []string

Keys return a slice of keys, in order of appearance.

func (HeaderParams) Length

func (hp HeaderParams) Length() int

Length returns number of params.

func (*HeaderParams) Remove

func (hp *HeaderParams) Remove(key string) HeaderParams

Remove removes all values with a given key.

func (HeaderParams) String

func (hp HeaderParams) String() string

String returns params joined with '&' char.

func (HeaderParams) ToString

func (hp HeaderParams) ToString(sep byte) string

ToString renders params to a string. Note that this does not escape special characters, this should already have been done before calling this method.

func (HeaderParams) ToStringWrite

func (hp HeaderParams) ToStringWrite(sep byte, buffer io.StringWriter)

ToStringWrite is same as ToString but it stores to defined buffer instead returning string

type HeaderParser

type HeaderParser func(headerName []byte, headerData string) (Header, error)

A HeaderParser is any function that turns raw header data into one or more Header objects.

type HeadersParser

type HeadersParser map[string]HeaderParser

func (HeadersParser) ParseHeader

func (headersParser HeadersParser) ParseHeader(out []Header, line []byte) ([]Header, error)

ParseHeader parses a SIP header from the line and appends it to out.

type MaxForwardsHeader

type MaxForwardsHeader uint32

MaxForwardsHeader is Max-Forwards header representation

func (*MaxForwardsHeader) Dec

func (h *MaxForwardsHeader) Dec()

func (*MaxForwardsHeader) Name

func (h *MaxForwardsHeader) Name() string

func (*MaxForwardsHeader) String

func (h *MaxForwardsHeader) String() string

func (*MaxForwardsHeader) StringWrite

func (h *MaxForwardsHeader) StringWrite(buffer io.StringWriter)

func (MaxForwardsHeader) Val

func (h MaxForwardsHeader) Val() uint32

func (*MaxForwardsHeader) Value

func (h *MaxForwardsHeader) Value() string

type Message

type Message interface {
	// String returns string representation of SIP message in RFC 3261 form.
	String() string
	// String write is same as String but lets you to provide writter and reduce allocations
	StringWrite(io.StringWriter)
	// GetHeaders returns slice of headers of the given type.
	GetHeaders(name string) []Header
	// PrependHeader prepends header to message.
	PrependHeader(header ...Header)
	// AppendHeader appends header to message.
	AppendHeader(header Header)
	// CallID returns 'Call-ID' header.
	CallID() *CallIDHeader
	// Via returns the top 'Via' header field.
	Via() *ViaHeader
	// From returns 'From' header field.
	From() *FromHeader
	// To returns 'To' header field.
	To() *ToHeader
	// CSeq returns 'CSeq' header field.
	CSeq() *CSeqHeader
	// Content Length headers
	ContentLength() *ContentLengthHeader

	// Body returns message body.
	Body() []byte
	// SetBody sets message body.
	SetBody(body []byte)

	Transport() string
	SetTransport(tp string)
	Source() string
	SetSource(src string)
	Destination() string
	SetDestination(dest string)
	// contains filtered or unexported methods
}

func ParseMessage

func ParseMessage(msgData []byte) (Message, error)

type MessageData

type MessageData struct {

	// Set to 2.0 version by default
	SipVersion string
	// contains filtered or unexported fields
}

func (*MessageData) AppendHeader

func (hs *MessageData) AppendHeader(header Header)

AppendHeader adds header at end of header list

func (*MessageData) AppendHeaderAfter

func (hs *MessageData) AppendHeaderAfter(header Header, name string)

AppendHeaderAfter adds header after specified header. In case header does not exist normal AppendHeader is called Use it only if you need it

func (*MessageData) Body

func (msg *MessageData) Body() []byte

func (*MessageData) CSeq

func (hs *MessageData) CSeq() *CSeqHeader

CSeq returns underlying CSEQ parsed header or nil if not exists

func (*MessageData) CallID

func (hs *MessageData) CallID() *CallIDHeader

CallID returns underlying CallID parsed header or nil if not exists

func (*MessageData) CloneHeaders

func (hs *MessageData) CloneHeaders() []Header

CloneHeaders returns all cloned headers in slice.

func (*MessageData) Contact

func (hs *MessageData) Contact() *ContactHeader

Contact returns underlying Contact parsed header or nil if not exists

func (*MessageData) ContentLength

func (hs *MessageData) ContentLength() *ContentLengthHeader

ContentLength returns underlying Content-Length parsed header or nil if not exists

func (*MessageData) ContentType

func (hs *MessageData) ContentType() *ContentTypeHeader

ContentType returns underlying Content-Type parsed header or nil if not exists

func (*MessageData) Destination

func (msg *MessageData) Destination() string

func (*MessageData) From

func (hs *MessageData) From() *FromHeader

From returns underlying From parsed header or nil if not exists

func (*MessageData) GetHeader

func (hs *MessageData) GetHeader(name string) Header

GetHeader returns Header if exists, otherwise nil is returned Use lower case to avoid allocs Headers are pointers, always Clone them for change

func (*MessageData) GetHeaders

func (hs *MessageData) GetHeaders(name string) []Header

GetHeaders returns list of headers with same name Use lower case to avoid allocs Headers are pointers, always Clone them for change

func (*MessageData) Headers

func (hs *MessageData) Headers() []Header

Headers returns list of headers. NOT THREAD SAFE for updating. Clone them

func (*MessageData) MaxForwards

func (hs *MessageData) MaxForwards() *MaxForwardsHeader

MaxForwards returns underlying Max-Forwards parsed header or nil if not exists

func (*MessageData) PrependHeader

func (hs *MessageData) PrependHeader(headers ...Header)

PrependHeader adds header to the front of header list using as list reduces need of realloc underneath array

func (*MessageData) RecordRoute

func (hs *MessageData) RecordRoute() *RecordRouteHeader

RecordRoute returns underlying Record-Route parsed header or nil if not exists

func (*MessageData) ReferTo

func (hs *MessageData) ReferTo() *ReferToHeader

ReferTo parses underlying Refer-To header or nil if not exists

func (*MessageData) ReferredBy

func (hs *MessageData) ReferredBy() *ReferredByHeader

ReferredBy parses underlying Referred-By header or nil if not exists

func (*MessageData) RemoveHeader

func (hs *MessageData) RemoveHeader(name string) (removed bool)

RemoveHeader removes header by name

func (*MessageData) ReplaceHeader

func (hs *MessageData) ReplaceHeader(header Header)

ReplaceHeader replaces first header with same name

func (*MessageData) Route

func (hs *MessageData) Route() *RouteHeader

Route returns underlying Route parsed header or nil if not exists

func (*MessageData) SetBody

func (msg *MessageData) SetBody(body []byte)

SetBody sets message body, calculates it length and add 'Content-Length' header.

func (*MessageData) SetDestination

func (msg *MessageData) SetDestination(dest string)

func (*MessageData) SetSource

func (msg *MessageData) SetSource(src string)

func (*MessageData) SetTransport

func (msg *MessageData) SetTransport(tp string)

func (*MessageData) Source

func (msg *MessageData) Source() string

func (*MessageData) String

func (hs *MessageData) String() string

func (*MessageData) StringWrite

func (hs *MessageData) StringWrite(buffer io.StringWriter)

func (*MessageData) To

func (hs *MessageData) To() *ToHeader

To returns underlying To parsed header or nil if not exists

func (*MessageData) Transport

func (msg *MessageData) Transport() string

func (*MessageData) Via

func (hs *MessageData) Via() *ViaHeader

Via returns underlying Via parsed header or nil if not exists

type MessageHandler

type MessageHandler func(msg Message)

type Parser

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

Parser is implementation of SIPParser It is optimized with faster header parsing

func NewParser

func NewParser(options ...ParserOption) *Parser

Create a new Parser.

func (*Parser) NewSIPStream

func (p *Parser) NewSIPStream() *ParserStream

NewSIPStream implements SIP parsing contructor for IO that stream SIP message It should be created per each stream

func (*Parser) Parse

func (p *Parser) Parse(data []byte, stream bool) (Message, int, error)

Parse data to a SIP message. It returns the number of bytes read. Data must contain a full SIP message.

If the message is cut in the middle of a header or a first line, io.ErrUnexpectedEOF is returned. It may return an error wrapping ErrParseLineNoCRLF if one of the header lines is malformed, or if there's no CRLF (\r\n) delimiter after headers.

In case the end of the body cannot be determined, or the body is incomplete, an ErrParseReadBodyIncomplete is returned.

func (*Parser) ParseHeaders

func (p *Parser) ParseHeaders(data []byte, stream bool) (Message, int, error)

ParseHeaders parses all headers of a SIP message. It returns the number of bytes read. Data must contain a full SIP message header section, including double CRLF (\r\n).

If the message is cut in the middle of a header or the first line, io.ErrUnexpectedEOF is returned. It may return an error wrapping ErrParseLineNoCRLF if one of the header lines is malformed, or if there's no CRLF (\r\n) delimiter after headers.

func (*Parser) ParseSIP

func (p *Parser) ParseSIP(data []byte) (msg Message, err error)

ParseSIP converts data to sip message. Buffer must contain full sip message

type ParserOption

type ParserOption func(p *Parser)

ParserOption are addition option for NewParser. Check WithParser...

func WithHeadersParsers

func WithHeadersParsers(m map[string]HeaderParser) ParserOption

WithHeadersParsers allows customizing parser headers parsers Consider performance when adding custom parser. Add only if it will appear in almost every message

Check DefaultHeadersParser as starting point

type ParserStream

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

func (*ParserStream) Buffer

func (p *ParserStream) Buffer() *bytes.Buffer

Buffer returns an internal buffer used by the parser. This allows to inspect the current parser state and possibly recover the stream with Discard.

func (*ParserStream) Close

func (p *ParserStream) Close()

Close the parser and free the associated resources.

func (*ParserStream) Discard

func (p *ParserStream) Discard(n int)

Discard specified amount of data and reset the parser. Can be used to skip malformed messages and recover the stream.

func (*ParserStream) ParseNext

func (p *ParserStream) ParseNext() (Message, int, error)

ParseNext parses the next SIP message from an internal buffer. It may return io.ErrUnexpectedEOF, indicating that more data needs to be written with Write.

func (*ParserStream) ParseSIPStream

func (p *ParserStream) ParseSIPStream(data []byte, cb func(msg Message)) error

ParseSIPStream parses SIP stream and calls callback as soon first SIP message is parsed

func (*ParserStream) Reset

func (p *ParserStream) Reset()

Reset the parser and the internal buffer.

func (*ParserStream) Write

func (p *ParserStream) Write(data []byte) (int, error)

Write data to the internal buffer. Must be called before ParseNext.

type RecordRouteHeader

type RecordRouteHeader struct {
	Address Uri
}

RecordRouteHeader is Record-Route header representation.

func (*RecordRouteHeader) Clone

func (*RecordRouteHeader) Name

func (h *RecordRouteHeader) Name() string

func (*RecordRouteHeader) String

func (h *RecordRouteHeader) String() string

func (*RecordRouteHeader) StringWrite

func (h *RecordRouteHeader) StringWrite(buffer io.StringWriter)

func (*RecordRouteHeader) Value

func (h *RecordRouteHeader) Value() string

type ReferToHeader

type ReferToHeader struct {
	Address Uri
}

ReferToHeader is Refer-To header representation.

func (*ReferToHeader) Clone

func (h *ReferToHeader) Clone() *ReferToHeader

func (*ReferToHeader) Name

func (h *ReferToHeader) Name() string

func (*ReferToHeader) String

func (h *ReferToHeader) String() string

func (*ReferToHeader) StringWrite

func (h *ReferToHeader) StringWrite(buffer io.StringWriter)

func (*ReferToHeader) Value

func (h *ReferToHeader) Value() string

type ReferredByHeader

type ReferredByHeader struct {
	DisplayName string
	Address     Uri
	Params      HeaderParams
}

ReferredByHeader is Referred-By header representation.

func (*ReferredByHeader) Clone

func (h *ReferredByHeader) Clone() *ReferredByHeader

func (*ReferredByHeader) Name

func (h *ReferredByHeader) Name() string

func (*ReferredByHeader) String

func (h *ReferredByHeader) String() string

func (*ReferredByHeader) StringWrite

func (h *ReferredByHeader) StringWrite(buffer io.StringWriter)

func (*ReferredByHeader) Value

func (h *ReferredByHeader) Value() string

type Request

type Request struct {
	MessageData
	Method    RequestMethod
	Recipient Uri

	// Laddr is Connection local Addr used to sent request
	Laddr Addr
	// contains filtered or unexported fields
}

Request RFC 3261 - 7.1.

func NewRequest

func NewRequest(method RequestMethod, recipient Uri) *Request

NewRequest creates base for building sip Request A Request-Line contains a method name, a Request-URI, and the SIP/2.0 as version No headers are added. AppendHeader should be called to add Headers. r.SetBody can be called to set proper ContentLength header

func (*Request) AppendHeader

func (hs *Request) AppendHeader(header Header)

AppendHeader adds header at end of header list

func (*Request) AppendHeaderAfter

func (hs *Request) AppendHeaderAfter(header Header, name string)

AppendHeaderAfter adds header after specified header. In case header does not exist normal AppendHeader is called Use it only if you need it

func (*Request) CSeq

func (hs *Request) CSeq() *CSeqHeader

CSeq returns underlying CSEQ parsed header or nil if not exists

func (*Request) CallID

func (hs *Request) CallID() *CallIDHeader

CallID returns underlying CallID parsed header or nil if not exists

func (*Request) Clone

func (req *Request) Clone() *Request

Clone performs shallow clone, that is clones everything except Body If full clone is needed make sure body is also cloned

func (*Request) CloneHeaders

func (hs *Request) CloneHeaders() []Header

CloneHeaders returns all cloned headers in slice.

func (*Request) Contact

func (hs *Request) Contact() *ContactHeader

Contact returns underlying Contact parsed header or nil if not exists

func (*Request) ContentLength

func (hs *Request) ContentLength() *ContentLengthHeader

ContentLength returns underlying Content-Length parsed header or nil if not exists

func (*Request) ContentType

func (hs *Request) ContentType() *ContentTypeHeader

ContentType returns underlying Content-Type parsed header or nil if not exists

func (*Request) Destination

func (req *Request) Destination() string

TODO: return Addr instead string, to remove double string parsing

func (*Request) From

func (hs *Request) From() *FromHeader

From returns underlying From parsed header or nil if not exists

func (*Request) GetHeader

func (hs *Request) GetHeader(name string) Header

GetHeader returns Header if exists, otherwise nil is returned Use lower case to avoid allocs Headers are pointers, always Clone them for change

func (*Request) GetHeaders

func (hs *Request) GetHeaders(name string) []Header

GetHeaders returns list of headers with same name Use lower case to avoid allocs Headers are pointers, always Clone them for change

func (*Request) Headers

func (hs *Request) Headers() []Header

Headers returns list of headers. NOT THREAD SAFE for updating. Clone them

func (*Request) IsAck

func (req *Request) IsAck() bool

func (*Request) IsCancel

func (req *Request) IsCancel() bool

func (*Request) IsInvite

func (req *Request) IsInvite() bool

func (*Request) MaxForwards

func (hs *Request) MaxForwards() *MaxForwardsHeader

MaxForwards returns underlying Max-Forwards parsed header or nil if not exists

func (*Request) PrependHeader

func (hs *Request) PrependHeader(headers ...Header)

PrependHeader adds header to the front of header list using as list reduces need of realloc underneath array

func (*Request) RecordRoute

func (hs *Request) RecordRoute() *RecordRouteHeader

RecordRoute returns underlying Record-Route parsed header or nil if not exists

func (*Request) ReferTo

func (hs *Request) ReferTo() *ReferToHeader

ReferTo parses underlying Refer-To header or nil if not exists

func (*Request) ReferredBy

func (hs *Request) ReferredBy() *ReferredByHeader

ReferredBy parses underlying Referred-By header or nil if not exists

func (*Request) RemoveHeader

func (hs *Request) RemoveHeader(name string) (removed bool)

RemoveHeader removes header by name

func (*Request) ReplaceHeader

func (hs *Request) ReplaceHeader(header Header)

ReplaceHeader replaces first header with same name

func (*Request) Route

func (hs *Request) Route() *RouteHeader

Route returns underlying Route parsed header or nil if not exists

func (*Request) Short

func (req *Request) Short() string

func (*Request) Source

func (req *Request) Source() string

Source will return host:port address using what is set by SetSource or based on Via header value In case of network parsed request source will be connection remote address

func (*Request) StartLine

func (req *Request) StartLine() string

StartLine returns Request Line - RFC 2361 7.1.

func (*Request) StartLineWrite

func (req *Request) StartLineWrite(buffer io.StringWriter)

func (*Request) String

func (req *Request) String() string

func (*Request) StringWrite

func (req *Request) StringWrite(buffer io.StringWriter)

func (*Request) To

func (hs *Request) To() *ToHeader

To returns underlying To parsed header or nil if not exists

func (*Request) Transport

func (req *Request) Transport() string

func (*Request) Via

func (hs *Request) Via() *ViaHeader

Via returns underlying Via parsed header or nil if not exists

type RequestMethod

type RequestMethod string
const (
	INVITE    RequestMethod = "INVITE"
	ACK       RequestMethod = "ACK"
	CANCEL    RequestMethod = "CANCEL"
	BYE       RequestMethod = "BYE"
	REGISTER  RequestMethod = "REGISTER"
	OPTIONS   RequestMethod = "OPTIONS"
	SUBSCRIBE RequestMethod = "SUBSCRIBE"
	NOTIFY    RequestMethod = "NOTIFY"
	REFER     RequestMethod = "REFER"
	INFO      RequestMethod = "INFO"
	MESSAGE   RequestMethod = "MESSAGE"
	PRACK     RequestMethod = "PRACK"
	UPDATE    RequestMethod = "UPDATE"
	PUBLISH   RequestMethod = "PUBLISH"
)

method names are defined here as constants for convenience.

func (RequestMethod) String

func (r RequestMethod) String() string

type Response

type Response struct {
	MessageData

	Reason     string // e.g. "200 OK"
	StatusCode int    // e.g. 200
	// contains filtered or unexported fields
}

Response RFC 3261 - 7.2.

func CopyResponse

func CopyResponse(res *Response) *Response

func NewResponse

func NewResponse(
	statusCode int,
	reason string,
) *Response

NewResponse creates base structure of response.

func NewResponseFromRequest

func NewResponseFromRequest(
	req *Request,
	statusCode int,
	reason string,
	body []byte,
) *Response

RFC 3261 - 8.2.6

func NewSDPResponseFromRequest

func NewSDPResponseFromRequest(req *Request, body []byte) *Response

NewSDPResponseFromRequest is wrapper for 200 response with SDP body

func (*Response) AppendHeader

func (hs *Response) AppendHeader(header Header)

AppendHeader adds header at end of header list

func (*Response) AppendHeaderAfter

func (hs *Response) AppendHeaderAfter(header Header, name string)

AppendHeaderAfter adds header after specified header. In case header does not exist normal AppendHeader is called Use it only if you need it

func (*Response) CSeq

func (hs *Response) CSeq() *CSeqHeader

CSeq returns underlying CSEQ parsed header or nil if not exists

func (*Response) CallID

func (hs *Response) CallID() *CallIDHeader

CallID returns underlying CallID parsed header or nil if not exists

func (*Response) Clone

func (res *Response) Clone() *Response

func (*Response) CloneHeaders

func (hs *Response) CloneHeaders() []Header

CloneHeaders returns all cloned headers in slice.

func (*Response) Contact

func (hs *Response) Contact() *ContactHeader

Contact returns underlying Contact parsed header or nil if not exists

func (*Response) ContentLength

func (hs *Response) ContentLength() *ContentLengthHeader

ContentLength returns underlying Content-Length parsed header or nil if not exists

func (*Response) ContentType

func (hs *Response) ContentType() *ContentTypeHeader

ContentType returns underlying Content-Type parsed header or nil if not exists

func (*Response) Destination

func (res *Response) Destination() string

Destination will return host:port address In case of building response from request, request source is set as destination This will sent response over same connection if request is parsed from network

func (*Response) From

func (hs *Response) From() *FromHeader

From returns underlying From parsed header or nil if not exists

func (*Response) GetHeader

func (hs *Response) GetHeader(name string) Header

GetHeader returns Header if exists, otherwise nil is returned Use lower case to avoid allocs Headers are pointers, always Clone them for change

func (*Response) GetHeaders

func (hs *Response) GetHeaders(name string) []Header

GetHeaders returns list of headers with same name Use lower case to avoid allocs Headers are pointers, always Clone them for change

func (*Response) Headers

func (hs *Response) Headers() []Header

Headers returns list of headers. NOT THREAD SAFE for updating. Clone them

func (*Response) IsAck

func (res *Response) IsAck() bool

func (*Response) IsCancel

func (res *Response) IsCancel() bool

func (*Response) IsClientError

func (res *Response) IsClientError() bool

func (*Response) IsGlobalError

func (res *Response) IsGlobalError() bool

func (*Response) IsProvisional

func (res *Response) IsProvisional() bool

func (*Response) IsRedirection

func (res *Response) IsRedirection() bool

func (*Response) IsServerError

func (res *Response) IsServerError() bool

func (*Response) IsSuccess

func (res *Response) IsSuccess() bool

func (*Response) MaxForwards

func (hs *Response) MaxForwards() *MaxForwardsHeader

MaxForwards returns underlying Max-Forwards parsed header or nil if not exists

func (*Response) PrependHeader

func (hs *Response) PrependHeader(headers ...Header)

PrependHeader adds header to the front of header list using as list reduces need of realloc underneath array

func (*Response) RecordRoute

func (hs *Response) RecordRoute() *RecordRouteHeader

RecordRoute returns underlying Record-Route parsed header or nil if not exists

func (*Response) ReferTo

func (hs *Response) ReferTo() *ReferToHeader

ReferTo parses underlying Refer-To header or nil if not exists

func (*Response) ReferredBy

func (hs *Response) ReferredBy() *ReferredByHeader

ReferredBy parses underlying Referred-By header or nil if not exists

func (*Response) RemoveHeader

func (hs *Response) RemoveHeader(name string) (removed bool)

RemoveHeader removes header by name

func (*Response) ReplaceHeader

func (hs *Response) ReplaceHeader(header Header)

ReplaceHeader replaces first header with same name

func (*Response) Route

func (hs *Response) Route() *RouteHeader

Route returns underlying Route parsed header or nil if not exists

func (*Response) Short

func (res *Response) Short() string

Short is textual short version of response

func (*Response) StartLine

func (res *Response) StartLine() string

StartLine returns Response Status Line - RFC 2361 7.2.

func (*Response) StartLineWrite

func (res *Response) StartLineWrite(buffer io.StringWriter)

func (*Response) String

func (res *Response) String() string

func (*Response) StringWrite

func (res *Response) StringWrite(buffer io.StringWriter)

func (*Response) To

func (hs *Response) To() *ToHeader

To returns underlying To parsed header or nil if not exists

func (*Response) Transport

func (res *Response) Transport() string

func (*Response) Via

func (hs *Response) Via() *ViaHeader

Via returns underlying Via parsed header or nil if not exists

type RouteHeader

type RouteHeader struct {
	Address Uri
}

RouteHeader is Route header representation.

func (*RouteHeader) Clone

func (h *RouteHeader) Clone() *RouteHeader

func (*RouteHeader) Name

func (h *RouteHeader) Name() string

func (*RouteHeader) String

func (h *RouteHeader) String() string

func (*RouteHeader) StringWrite

func (h *RouteHeader) StringWrite(buffer io.StringWriter)

func (*RouteHeader) Value

func (h *RouteHeader) Value() string

type SIPTracer

type SIPTracer interface {
	SIPTraceRead(transport string, laddr string, raddr string, sipmsg []byte)
	SIPTraceWrite(transport string, laddr string, raddr string, sipmsg []byte)
}

type ServerTransaction

type ServerTransaction interface {
	Transaction

	// Respond sends response. It is expected that is prebuilt with correct headers
	// Use NewResponseFromRequest to build response
	Respond(res *Response) error
	// Acks returns ACK during transaction.
	Acks() <-chan *Request

	// OnCancel will be fired when CANCEL request is received
	// It allows you to detect CANCEL request, which will be followed by termination.
	// It returns false in case transaction already terminated
	// NOTE: You must not block here too long. In that case fire go routine.
	//
	// Experimental
	OnCancel(f FnTxCancel) bool
}

type ServerTx

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

func NewServerTx

func NewServerTx(key string, origin *Request, conn Connection, logger *slog.Logger) *ServerTx

func (*ServerTx) Acks

func (tx *ServerTx) Acks() <-chan *Request

Acks makes channel for sending acks. Channel is created on demand

func (*ServerTx) Connection

func (tx *ServerTx) Connection() Connection

func (*ServerTx) Done

func (tx *ServerTx) Done() <-chan struct{}

func (*ServerTx) Err

func (tx *ServerTx) Err() error

func (*ServerTx) Init

func (tx *ServerTx) Init() error

func (*ServerTx) Key

func (tx *ServerTx) Key() string

func (*ServerTx) OnCancel

func (tx *ServerTx) OnCancel(f FnTxCancel) bool

OnCancel is experimental It is racy thing if not registered after transaction creation

func (*ServerTx) OnTerminate

func (tx *ServerTx) OnTerminate(f FnTxTerminate) bool

OnTerminate is experimental Callback function can not call any fsm related functions as it will cause deadlock like. Err must not be called,instead error is passed

func (*ServerTx) Origin

func (tx *ServerTx) Origin() *Request

func (*ServerTx) Receive

func (tx *ServerTx) Receive(req *Request) error

Receive is endpoint for handling received server requests. NOTE: it could block while passing request to client, therefore running in seperate goroutine is needed

func (*ServerTx) Respond

func (tx *ServerTx) Respond(res *Response) error

func (*ServerTx) String

func (tx *ServerTx) String() string

func (*ServerTx) Terminate

func (tx *ServerTx) Terminate()

func (*ServerTx) TerminateGracefully

func (tx *ServerTx) TerminateGracefully()

TerminateGracefully allows retransmission to happen before shuting down transaction

type TCPConnection

type TCPConnection struct {
	net.Conn
	// contains filtered or unexported fields
}

func (*TCPConnection) Close

func (c *TCPConnection) Close() error

func (*TCPConnection) Read

func (c *TCPConnection) Read(b []byte) (n int, err error)

func (*TCPConnection) Ref

func (c *TCPConnection) Ref(i int) int

func (*TCPConnection) TryClose

func (c *TCPConnection) TryClose() (int, error)

func (*TCPConnection) Write

func (c *TCPConnection) Write(b []byte) (n int, err error)

func (*TCPConnection) WriteMsg

func (c *TCPConnection) WriteMsg(msg Message) error

type ToHeader

type ToHeader struct {
	// The display name from the header, may be omitted.
	DisplayName string
	Address     Uri
	// Any parameters present in the header.
	Params HeaderParams
}

ToHeader introduces SIP 'To' header

func (*ToHeader) AsFrom

func (h *ToHeader) AsFrom() FromHeader

func (*ToHeader) Name

func (h *ToHeader) Name() string

func (*ToHeader) String

func (h *ToHeader) String() string

func (*ToHeader) StringWrite

func (h *ToHeader) StringWrite(buffer io.StringWriter)

func (*ToHeader) Value

func (h *ToHeader) Value() string

type Transaction

type Transaction interface {
	// Terminate will terminate transaction
	Terminate()

	// OnTerminate can be registered to be called when transaction terminates.
	// It is alternative to tx.Done where you avoid creating more goroutines.
	// It returns false if transaction already terminated.
	// NOTE: calling tx methods inside this func can DEADLOCK
	//
	// Experimental
	OnTerminate(f FnTxTerminate) bool

	// Done when transaction fsm terminates. Can be called multiple times
	Done() <-chan struct{}

	// Err that stopped transaction. Useful to check when transaction terminates
	Err() error
}

type TransactionLayer

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

func NewTransactionLayer

func NewTransactionLayer(tpl *TransportLayer, options ...TransactionLayerOption) *TransactionLayer

func (*TransactionLayer) Close

func (txl *TransactionLayer) Close()

func (*TransactionLayer) NewClientTransaction

func (txl *TransactionLayer) NewClientTransaction(ctx context.Context, req *Request) (*ClientTx, error)

func (*TransactionLayer) OnConnectionClose

func (txl *TransactionLayer) OnConnectionClose(conn Connection)

OnConnectionClose is called when a reliable transport connection (TCP, TLS, WS, WSS) is closed by the remote side or due to a read error.

func (*TransactionLayer) OnRequest

func (txl *TransactionLayer) OnRequest(h TransactionRequestHandler)

func (*TransactionLayer) Request

func (txl *TransactionLayer) Request(ctx context.Context, req *Request) (*ClientTx, error)

func (*TransactionLayer) Respond

func (txl *TransactionLayer) Respond(res *Response) (*ServerTx, error)

func (*TransactionLayer) Transport

func (txl *TransactionLayer) Transport() *TransportLayer

type TransactionLayerOption

type TransactionLayerOption func(tpl *TransactionLayer)

func WithTransactionLayerLogger

func WithTransactionLayerLogger(l *slog.Logger) TransactionLayerOption

func WithTransactionLayerTerminateOnConnClose

func WithTransactionLayerTerminateOnConnClose() TransactionLayerOption

WithTransactionLayerTerminateOnConnClose enables termination of pending client and server transactions when the underlying connection closes, instead of waiting for timers to expire.

Experimental

func WithTransactionLayerUnhandledResponseHandler

func WithTransactionLayerUnhandledResponseHandler(f func(r *Response)) TransactionLayerOption

type TransactionRequestHandler

type TransactionRequestHandler func(req *Request, tx *ServerTx)

type TransportLayer

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

TransportLayer implementation.

func NewTransportLayer

func NewTransportLayer(
	dnsResolver *net.Resolver,
	sipparser *Parser,
	tlsConfig *tls.Config,
	option ...TransportLayerOption,
) *TransportLayer

NewLayer creates transport layer. dns Resolver sip parser tls config - can be nil to use default tls

func (*TransportLayer) ClientRequestConnection

func (l *TransportLayer) ClientRequestConnection(ctx context.Context, req *Request) (c Connection, err error)

ClientRequestConnection is based on https://www.rfc-editor.org/rfc/rfc3261#section-18.1.1 It is wrapper for getting and creating connection

In case req destination is DNS resolved, destination will be cached or in other words SetDestination will be called

func (*TransportLayer) Close

func (l *TransportLayer) Close() error

func (*TransportLayer) GetConnection

func (l *TransportLayer) GetConnection(network, addr string) (Connection, error)

GetConnection gets existing or creates new connection based on addr

func (*TransportLayer) GetListenPort

func (l *TransportLayer) GetListenPort(network string) int

func (*TransportLayer) ListenPorts

func (l *TransportLayer) ListenPorts(network string) []int

func (*TransportLayer) OnMessage

func (l *TransportLayer) OnMessage(h MessageHandler)

OnMessage is main function which will be called on any new message by transport layer Consider there is no concurency and you need to make sure that you do not block too long This is intentional as higher concurency can slow things

func (*TransportLayer) ServeTCP

func (l *TransportLayer) ServeTCP(c net.Listener) error

ServeTCP will listen on tcp connection

func (*TransportLayer) ServeTLS

func (l *TransportLayer) ServeTLS(c net.Listener) error

ServeTLS will listen on tcp connection

func (*TransportLayer) ServeUDP

func (l *TransportLayer) ServeUDP(c net.PacketConn) error

ServeUDP will listen on udp connection

func (*TransportLayer) ServeWS

func (l *TransportLayer) ServeWS(c net.Listener) error

ServeWS will listen on ws connection

func (*TransportLayer) ServeWSS

func (l *TransportLayer) ServeWSS(c net.Listener) error

ServeWSS will listen on wss connection

func (*TransportLayer) UDPPoolSize

func (l *TransportLayer) UDPPoolSize() int

UDPPoolSize returns the current number of entries in the UDP transport's connection pool. This includes the listener self-entry plus one mapping per distinct inbound peer source address (and any client-dialed UDP connections held by the pool).

Intended for monitoring callers running a long-lived UDP listener with WithTransportLayerUDPPeerIdleTTL, where cardinality is otherwise opaque.

func (*TransportLayer) WriteMsg

func (l *TransportLayer) WriteMsg(msg Message) error

func (*TransportLayer) WriteMsgTo

func (l *TransportLayer) WriteMsgTo(msg Message, addr string, network string) error

type TransportLayerOption

type TransportLayerOption func(l *TransportLayer)

func WithTransportLayerConnectionReuse

func WithTransportLayerConnectionReuse(f bool) TransportLayerOption

func WithTransportLayerDNSLookupSRV

func WithTransportLayerDNSLookupSRV(preferSRV bool) TransportLayerOption

func WithTransportLayerLogger

func WithTransportLayerLogger(logger *slog.Logger) TransportLayerOption

func WithTransportLayerTransports

func WithTransportLayerTransports(conf TransportsConfig) TransportLayerOption

func WithTransportLayerUDPPeerIdleTTL

func WithTransportLayerUDPPeerIdleTTL(ttl time.Duration) TransportLayerOption

WithTransportLayerUDPPeerIdleTTL enables periodic eviction of UDP listener per-peer pool entries (one per distinct inbound source address) whose last seen packet is older than ttl. Pass 0 (the default) to disable eviction and preserve the unbounded-accumulation behavior expected by short-lived listeners.

Enable this when a UDP listener is long-lived and exposed to untrusted sources to bound the per-peer map against source-port churn.

In-flight protection: a sweep pass is skipped entirely when the shared listener connection has a refcount above its baseline of 1 (meaning a transaction is currently using the listener via pool.Get/Ref). This is intentionally coarse — for UDP listeners every per-peer pool entry points at the same underlying connection, so per-entry refcounting is not available. Practical consequences:

  • Under light traffic the TTL acts as a hard cap on how long idle peer entries linger.
  • Under sustained traffic the sweep effectively never runs and the TTL becomes a "lower bound while idle" rather than an upper bound under load. Idle peers will be reaped during the next quiet interval.

If a stronger guarantee is needed under load (e.g. adversarial source-port churn during a sustained transaction stream), a follow-up enhancement would track per-peer refcounts separately from the listener refcount; the current option is the conservative shape that does not change response- correlation semantics.

type TransportTCP

type TransportTCP struct {
	DialerCreate func(laddr net.Addr) net.Dialer
	// contains filtered or unexported fields
}

TCP transport implementation

func (*TransportTCP) Close

func (t *TransportTCP) Close() error

func (*TransportTCP) CreateConnection

func (t *TransportTCP) CreateConnection(ctx context.Context, laddr Addr, raddr Addr, handler MessageHandler) (Connection, error)

func (*TransportTCP) GetConnection

func (t *TransportTCP) GetConnection(addr string) Connection

func (*TransportTCP) Network

func (t *TransportTCP) Network() string

func (*TransportTCP) Serve

func (t *TransportTCP) Serve(l net.Listener, handler MessageHandler) error

Serve is direct way to provide conn on which this worker will listen

func (*TransportTCP) String

func (t *TransportTCP) String() string

type TransportTLS

type TransportTLS struct {
	*TransportTCP
	// contains filtered or unexported fields
}

TLS transport implementation

func (*TransportTLS) CreateConnection

func (t *TransportTLS) CreateConnection(ctx context.Context, laddr Addr, raddr Addr, handler MessageHandler) (Connection, error)

CreateConnection creates TLS connection for TCP transport

func (*TransportTLS) String

func (t *TransportTLS) String() string

type TransportUDP

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

UDP transport implementation

func (*TransportUDP) Close

func (t *TransportUDP) Close() error

func (*TransportUDP) CreateConnection

func (t *TransportUDP) CreateConnection(ctx context.Context, laddr Addr, raddr Addr, handler MessageHandler) (Connection, error)

CreateConnection will create new connection

func (*TransportUDP) GetConnection

func (t *TransportUDP) GetConnection(addr string) Connection

GetConnection will return same listener connection

func (*TransportUDP) Network

func (t *TransportUDP) Network() string

func (*TransportUDP) ResolveAddr

func (t *TransportUDP) ResolveAddr(addr string) (net.Addr, error)

func (*TransportUDP) Serve

func (t *TransportUDP) Serve(conn net.PacketConn, handler MessageHandler) error

ServeConn is direct way to provide conn on which this worker will listen

func (*TransportUDP) String

func (t *TransportUDP) String() string

type TransportWS

type TransportWS struct {
	DialerCreate func(laddr net.Addr) ws.Dialer
	// contains filtered or unexported fields
}

WS transport implementation

func (*TransportWS) Close

func (t *TransportWS) Close() error

func (*TransportWS) CreateConnection

func (t *TransportWS) CreateConnection(ctx context.Context, laddr Addr, raddr Addr, handler MessageHandler) (Connection, error)

func (*TransportWS) GetConnection

func (t *TransportWS) GetConnection(addr string) Connection

func (*TransportWS) Network

func (t *TransportWS) Network() string

func (*TransportWS) ResolveAddr

func (t *TransportWS) ResolveAddr(addr string) (net.Addr, error)

func (*TransportWS) Serve

func (t *TransportWS) Serve(l net.Listener, handler MessageHandler) error

Serve is direct way to provide conn on which this worker will listen

func (*TransportWS) String

func (t *TransportWS) String() string

type TransportWSS

type TransportWSS struct {
	*TransportWS
}

TLS transport implementation

func (*TransportWSS) CreateConnection

func (t *TransportWSS) CreateConnection(ctx context.Context, laddr Addr, raddr Addr, handler MessageHandler) (Connection, error)

CreateConnection creates WSS connection for TCP transport TODO Make this consisten with TCP

func (*TransportWSS) String

func (t *TransportWSS) String() string

type TransportsConfig

type TransportsConfig struct {
	UDP *TransportUDP
	TCP *TransportTCP
	TLS *TransportTLS
	WS  *TransportWS
	WSS *TransportWSS
}

type UDPConnection

type UDPConnection struct {
	PacketConn net.PacketConn
	PacketAddr string // For faster matching
	Listener   bool
	// contains filtered or unexported fields
}

func (*UDPConnection) Close

func (c *UDPConnection) Close() error

func (*UDPConnection) LocalAddr

func (c *UDPConnection) LocalAddr() net.Addr

func (*UDPConnection) ReadFrom

func (c *UDPConnection) ReadFrom(b []byte) (n int, addr net.Addr, err error)

func (*UDPConnection) Ref

func (c *UDPConnection) Ref(i int) int

func (*UDPConnection) TryClose

func (c *UDPConnection) TryClose() (int, error)

func (*UDPConnection) WriteMsg

func (c *UDPConnection) WriteMsg(msg Message) error

func (*UDPConnection) WriteTo

func (c *UDPConnection) WriteTo(b []byte, addr net.Addr) (n int, err error)

type UnhandledResponseHandler

type UnhandledResponseHandler func(req *Response)

type Uri

type Uri struct {
	Scheme string

	// If value is star (*)
	Wildcard bool

	// if // is present
	HierarhicalSlashes bool

	// The user part of the URI: the 'joe' in sip:joe@bloggs.com
	User string

	// The password field of the URI. This is represented in the URI as joe:hunter2@bloggs.com.
	// Note that if a URI has a password field, it *must* have a user field as well.
	// Note that RFC 3261 strongly recommends against the use of password fields in SIP URIs,
	// as they are fundamentally insecure.
	Password string

	// The host part of the URI. This can be a domain, or a string representation of an IP address.
	Host string

	// The port part of the URI. This is optional, and can be empty.
	Port int

	// Any parameters associated with the URI.
	// These are used to provide information about requests that may be constructed from the URI.
	// (For more details, see RFC 3261 section 19.1.1).
	// These appear as a semicolon-separated list of key=value pairs following the host[:port] part.
	UriParams HeaderParams

	// Any headers to be included on requests constructed from this URI.
	// These appear as a '&'-separated list at the end of the URI, introduced by '?'.
	Headers HeaderParams
}

Uri is parsed form of sip:user:password@host:port;uri-parameters?headers In case of `sips:“ Encrypted is set to true

func (*Uri) Addr

func (uri *Uri) Addr() string

Addr is uri part without headers and params. sip[s]:user@host[:port]

func (*Uri) Clone

func (uri *Uri) Clone() *Uri

Clone

func (*Uri) Endpoint

func (uri *Uri) Endpoint() string

Endpoint is uri user identifier. user@host[:port]

func (*Uri) HostPort

func (uri *Uri) HostPort() string

HostPort represents host:port part

func (*Uri) IsEncrypted

func (uri *Uri) IsEncrypted() bool

IsEncrypted returns true if uri is SIPS uri

func (*Uri) String

func (uri *Uri) String() string

Generates the string representation of a SipUri struct.

func (*Uri) StringWrite

func (uri *Uri) StringWrite(buffer io.StringWriter)

StringWrite writes uri string to buffer

type ViaHeader

type ViaHeader struct {
	// E.g. 'SIP'.
	ProtocolName string
	// E.g. '2.0'.
	ProtocolVersion string
	Transport       string
	Host            string
	Port            int // This is optional
	Params          HeaderParams
}

ViaHeader is Via header representation.

func (*ViaHeader) Clone

func (h *ViaHeader) Clone() *ViaHeader

func (*ViaHeader) Name

func (h *ViaHeader) Name() string

func (*ViaHeader) SentBy

func (hop *ViaHeader) SentBy() string

func (*ViaHeader) String

func (h *ViaHeader) String() string

func (*ViaHeader) StringWrite

func (h *ViaHeader) StringWrite(buffer io.StringWriter)

func (*ViaHeader) Value

func (h *ViaHeader) Value() string

type WSConnection

type WSConnection struct {
	net.Conn
	// contains filtered or unexported fields
}

func (*WSConnection) Close

func (c *WSConnection) Close() error

func (*WSConnection) Read

func (c *WSConnection) Read(b []byte) (n int, err error)

func (*WSConnection) Ref

func (c *WSConnection) Ref(i int) int

func (*WSConnection) TryClose

func (c *WSConnection) TryClose() (int, error)

func (*WSConnection) Write

func (c *WSConnection) Write(b []byte) (n int, err error)

func (*WSConnection) WriteMsg

func (c *WSConnection) WriteMsg(msg Message) error

Jump to

Keyboard shortcuts

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