stun

package module
v0.0.0-...-9e22a7a Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2018 License: BSD-2-Clause Imports: 12 Imported by: 0

README

Package stun provides basic functions for the manipulation of messages used in the Session Traversal Utilities for NAT (STUN), Traversal Using Relays around NAT (TURN) and Interactive Connectivity Establishment (ICE) protocols.

GoDoc Build Status Build status Go Report Card

Documentation

Overview

Package stun provides basic functions for the manipulation of messages used in the Session Traversal Utilities for NAT (STUN), Traversal Using Relays around NAT (TURN) and Interactive Connectivity Establishment (ICE) protocols.

STUN is defined in RFC 5389. TURN is defined in RFC 5766. Traversal Using Relays around NAT (TURN) Extensions for TCP Allocations is defined in RFC 6062. Traversal Using Relays around NAT (TURN) Extension for IPv6 is defined in RFC 6156. ICE is defined in RFC 5245. Explicit Congestion Notification (ECN) for RTP over UDP is defined in RFC 6679. An Origin Attribute for the STUN Protocol is defined in https://tools.ietf.org/html/draft-ietf-tram-stun-origin.

Also see https://tools.ietf.org/html/draft-ietf-tram-stunbis and https://tools.ietf.org/html/draft-ietf-tram-turnbis.

Note: THIRD-PARTY-AUTHORIZATION and ACCESS-TOKEN attributes defined in RFC 7635 are not implemented yet and you can use DefaultAttr for those attributes.

Index

Examples

Constants

View Source
const (
	StatusTryAlternate                 = 300 // Try Alternate
	StatusBadRequest                   = 400 // Bad Request
	StatusUnauthorized                 = 401 // Unauthorized
	StatusForbidden                    = 403 // Forbidden
	StatusMobilityForbidden            = 405 // Mobility Forbidden
	StatusUnknownAttribute             = 420 // Unknown Attribute
	StatusAllocationMismatch           = 437 // Allocation Mismatch
	StatusStaleNonce                   = 438 // Stale Nonce
	StatusAddressFamilynotSupported    = 440 // Address Family not Supported
	StatusWrongCredentials             = 441 // Wrong Credentials
	StatusUnsupportedTransportProtocol = 442 // Unsupported Transport Protocol
	StatusPeerAddressFamilyMismatch    = 443 // Peer Address Family Mismatch
	StatusConnectionAlreadyExists      = 446 // Connection Already Exists
	StatusConnectionTimeoutorFailure   = 447 // Connection Timeout or Failure
	StatusAllocationQuotaReached       = 486 // Allocation Quota Reached
	StatusRoleConflict                 = 487 // Role Conflict
	StatusServerError                  = 500 // Server Error
	StatusInsufficientCapacity         = 508 // Insufficient Capacity
)

Session Traversal Utilities for NAT (STUN) Parameters, STUN Error Codes, Updated: 2016-09-30

Variables

View Source
var MagicCookie = []byte{0x21, 0x12, 0xa4, 0x42}

MagicCookie is the fixed cookie value defined in RFC 5389.

Functions

func TransactionID

func TransactionID() ([]byte, error)

TransactionID returns a 96-bit random identifier.

Types

type Addr

type Addr struct {
	Port int    // port number
	IP   net.IP // IP address
}

An Addr represents a STUN transport address.

func (*Addr) Network

func (a *Addr) Network() string

Network returns the address's network name, "stun".

func (*Addr) String

func (a *Addr) String() string

type AlternateDomain

type AlternateDomain string

An AlternateDomain represents a STUN ALTERNATE-DOMAIN attribute.

func (AlternateDomain) Len

func (ad AlternateDomain) Len() int

Len implements the Len method of Attribute interface.

type AlternateServer

type AlternateServer Addr

An AlternateServer represents a STUN ALTERNATE-SERVER attribute.

func (*AlternateServer) Len

func (as *AlternateServer) Len() int

Len implements the Len method of Attribute interface.

type Attribute

type Attribute interface {
	// Len returns the length of STUN attribute value not
	// including the 4 byte attribute type and length fields, and
	// attribute padding bytes.
	Len() int
}

An Attribute represents a STUN attribute.

type AttributeError

type AttributeError struct {
	// Type is the STUN attribute type.
	Type int

	// Err is the error that occurred.
	Err error
}

An AttributeError represents a STUN attribute error.

func (*AttributeError) Error

func (ae *AttributeError) Error() string

type ChannelData

type ChannelData struct {
	// Number specifies the channel number.
	Number Type

	// Data specifies the channel data.
	// It just refers to the underlying buffer when the returned
	// value from ParseMessage.
	Data []byte
}

A ChannelData represents a STUN channel data message.

func (*ChannelData) Len

func (m *ChannelData) Len() int

Len implements the Len method of Message interface.

func (*ChannelData) Marshal

func (m *ChannelData) Marshal(b []byte, _ hash.Hash) (int, error)

Marshal implements the Marshal method of Message interface.

type ChannelNumber

type ChannelNumber struct {
	Number Type // channel number
}

A ChannelNumber represents a STUN CHANNEL-NUMBER attribute.

func (*ChannelNumber) Len

func (cn *ChannelNumber) Len() int

Len implements the Len method of Attribute interface.

type Class

type Class int

A Class represents a STUN message class.

const (
	ClassRequest Class = iota
	ClassIndication
	ClassSuccessResponse
	ClassErrorResponse
)

func (Class) String

func (c Class) String() string

type ConnectionID

type ConnectionID uint

A ConnectionID represents a STUN CONNECTION-ID attribute.

func (ConnectionID) Len

func (_ ConnectionID) Len() int

Len implements the Len method of Attribute interface.

type Control

type Control struct {
	// Type specifies the message type.
	Type Type

	// Cookie specifies the 32-bit magic cookie.
	// If Cookie is nil, Marshal method of Message interface sets
	// an appropriate value.
	Cookie []byte

	// TID specifies the 96-bit transaction identifier.
	// If TID is nil, Marshal method of Message interface sets an
	// appropriate value.
	TID []byte

	// Attrs specifies the list of STUN attributes.
	Attrs []Attribute
}

A Control represents a STUN control message.

Example (ClientUDP)
package main

import (
	"bytes"
	"fmt"
	"log"
	"net"
	"time"

	"github.com/mikioh/stun"
)

func main() {
	dst, err := net.ResolveUDPAddr("udp", "stun.l.google.com:19302")
	if err != nil {
		log.Fatal(err)
	}
	c, err := net.ListenPacket("udp", ":0")
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()

	tid, err := stun.TransactionID()
	if err != nil {
		log.Fatal(err)
	}
	wm := stun.Control{
		Type: stun.MessageType(stun.ClassRequest, stun.MethodBinding),
		TID:  tid,
		Attrs: []stun.Attribute{
			stun.Software("github.com/mikioh/stun"),
			stun.ICEControlling(1),
			&stun.UseCandidate{},
			stun.Priority(1),
			stun.Fingerprint(0),
		},
	}
	wb := make([]byte, wm.Len())
	n, err := wm.Marshal(wb, nil)
	if err != nil {
		log.Fatal(err)
	}
	if _, err := c.WriteTo(wb[:n], dst); err != nil {
		log.Fatal(err)
	}

	rb := make([]byte, 1500)
	if err := c.SetReadDeadline(time.Now().Add(2 * time.Second)); err != nil {
		log.Fatal(err)
	}
	n, _, err = c.ReadFrom(rb)
	if err != nil {
		log.Fatal(err)
	}
	_, rm, err := stun.ParseMessage(rb[:n], nil)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(rm.(*stun.Control).Type.Class())
	fmt.Println(rm.(*stun.Control).Type.Method())
	if !bytes.Equal(rm.(*stun.Control).Cookie, stun.MagicCookie) {
		log.Fatalf("got %#v; want %#v", rm.(*stun.Control).Cookie, stun.MagicCookie)
	}
	if !bytes.Equal(rm.(*stun.Control).TID, wm.TID) {
		log.Fatalf("got %#v; want %#v", rm.(*stun.Control).TID, wm.TID)
	}
}
Output:

success response
binding

func (*Control) Len

func (m *Control) Len() int

Len implements the Len method of Message interface.

func (*Control) Marshal

func (m *Control) Marshal(b []byte, h hash.Hash) (int, error)

Marshal implements the Marshal method of Message interface.

type Data

type Data []byte

A Data represents a STUN DATA attribute. It just refers to the underlying buffer when the returned value from ParseMessage.

func (Data) Len

func (d Data) Len() int

Len implements the Len method of Attribute interface.

type DefaultAttr

type DefaultAttr struct {
	// Type specifies the attribute type.
	Type int

	// Data specifes the attribute value.
	Data []byte
}

A DefaultAttr reprensents the default STUN attribute. DefaultAttr is used for marshaling and parsing STUN attributes not supported in the package.

func (*DefaultAttr) Len

func (da *DefaultAttr) Len() int

Len implements the Len method of Attribute interface.

type DontFragment

type DontFragment struct{}

A DontFragment represents a STUN DONT-FRAGMENT attribute.

func (*DontFragment) Len

func (_ *DontFragment) Len() int

Len implements the Len method of Attribute interface.

type ECNCheck

type ECNCheck struct {
	ECF int  // ECN echo value field
	V   bool // whether ECF is valid
}

A ECNCheck represents a STUN ECN-CHECK attribute.

func (*ECNCheck) Len

func (ec *ECNCheck) Len() int

Len implements the Len method of Attribute interface.

type Error

type Error struct {
	Code   int    // code consists of class and number
	Reason string // reason
}

An Error represents a STUN ERROR-CODE attribute.

func (*Error) Class

func (e *Error) Class() int

Class returns the error class.

func (*Error) Len

func (e *Error) Len() int

Len implements the Len method of Attribute interface.

func (*Error) Number

func (e *Error) Number() int

Number returns the error number.

type EvenPort

type EvenPort struct {
	R bool // request next-higher port number reservation
}

An EvenPort represents a STUN EVEN-PORT attribute.

func (*EvenPort) Len

func (ep *EvenPort) Len() int

Len implements the Len method of Attribute interface.

type Fingerprint

type Fingerprint uint

A Fingerprint represents a STUN FINGERPRINT attribute. It must be the last attribute in the message. If Fingerprint is zero, Marshal method of Message interface sets an appropriate value.

func (Fingerprint) Len

func (_ Fingerprint) Len() int

Len implements the Len method of Attribute interface.

type ICEControlled

type ICEControlled uint64

An ICEControlled represents a STUN ICE-CONTROLLED attribute.

func (ICEControlled) Len

func (_ ICEControlled) Len() int

Len implements the Len method of Attribute interface.

type ICEControlling

type ICEControlling uint64

An ICEControlling represents a STUN ICE-CONTROLLING attribute.

func (ICEControlling) Len

func (_ ICEControlling) Len() int

Len implements the Len method of Attribute interface.

type Lifetime

type Lifetime time.Duration

A Lifetime represents a STUN LIFETIME attribute.

func (Lifetime) Len

func (_ Lifetime) Len() int

Len implements the Len method of Attribute interface.

type Message

type Message interface {
	// Len returns the length of STUN message including the
	// message header and padding bytes.
	Len() int

	// Marshal writes the binary encoding of STUN message to b.
	// It returns the number of bytes marshaled.
	// H must be the HMAC-SHA1 when in use of STUN
	// MESSAGE-INTEGRITY attribute.
	Marshal(b []byte, h hash.Hash) (int, error)
}

A Message represents a STUN message.

func ParseMessage

func ParseMessage(b []byte, h hash.Hash) (int, Message, error)

ParseMessage parses b as a STUN message. It returns the number of bytes parsed and message. H must be the HMAC-SHA1 when in use of STUN MESSAGE-INTEGRITY attribute. It assumes that b contains padding bytes even if a channel data message and sent over UDP.

type MessageError

type MessageError struct {
	// Type is the STUN message type.
	Type Type

	// Err is the error that occurred.
	Err error
}

A MessageError represents a STUN message error.

func (*MessageError) Error

func (me *MessageError) Error() string

type MessageIntegrity

type MessageIntegrity []byte

A MessageIntegrity represents a STUN MESSAGE-INTEGRITY attribute. If MessageIntegrity is nil, Marshal method of Message interface sets an approrpiate value.

func (MessageIntegrity) Len

func (_ MessageIntegrity) Len() int

Len implements the Len method of Attribute interface.

type MessageIntegritySHA256

type MessageIntegritySHA256 []byte

A MessageIntegritySHA256 represents a STUN MESSAGE-INTEGRITY-SHA256 attribute. If MessageIntegrity is nil, Marshal method of Message interface sets an approrpiate value.

func (MessageIntegritySHA256) Len

func (_ MessageIntegritySHA256) Len() int

Len implements the Len method of Attribute interface.

type Method

type Method int

A Method represents a STUN message method.

const (
	MethodBinding           Method = 0x001 // Binding
	MethodAllocate          Method = 0x003 // Allocate
	MethodRefresh           Method = 0x004 // Refresh
	MethodSend              Method = 0x006 // Send
	MethodData              Method = 0x007 // Data
	MethodCreatePermission  Method = 0x008 // CreatePermission
	MethodChannelBind       Method = 0x009 // ChannelBind
	MethodConnect           Method = 0x00A // Connect
	MethodConnectionBind    Method = 0x00B // ConnectionBind
	MethodConnectionAttempt Method = 0x00C // ConnectionAttempt
)

Session Traversal Utilities for NAT (STUN) Parameters, STUN Methods, Updated: 2016-09-30

func (Method) String

func (m Method) String() string

type Nonce

type Nonce string

A Nonce represents a STUN NONCE attribute.

func (Nonce) Len

func (n Nonce) Len() int

Len implements the Len method of Attribute interface.

type Origin

type Origin string

An Origin represents a STUN ORIGIN attribute.

func (Origin) Len

func (o Origin) Len() int

Len implements the Len method of Attribute interface.

type PasswordAlgorithm

type PasswordAlgorithm struct {
	Number int    // algorithm number; 0x0001 for MD5, 0x0002 for SHA256
	Params []byte // algorithm parameters
}

A PasswordAlgorithm represents a STUN PASSWORD-ALGORITHM attribute.

func (*PasswordAlgorithm) Len

func (pa *PasswordAlgorithm) Len() int

Len implements the Len method of Attribute interface.

type PasswordAlgorithms

type PasswordAlgorithms []PasswordAlgorithm

A PasswordAlgorithms represents a STUN PASSWORD-ALGORITHMS attribute.

func (PasswordAlgorithms) Len

func (pas PasswordAlgorithms) Len() int

Len implements the Len method of Attribute interface.

type Priority

type Priority uint

A Priority represents a STUN PRIORITY attribute.

func (Priority) Len

func (_ Priority) Len() int

Len implements the Len method of Attribute interface.

type Realm

type Realm string

A Realm represents a STUN REALM attribute.

func (Realm) Len

func (r Realm) Len() int

Len implements the Len method of Attribute interface.

type RequestedAddrFamily

type RequestedAddrFamily struct {
	ID int // identifier; 0x01 for IPv4, 0x02 for IPv6
}

A RequestedAddrFamily represents a STUN REQUESTED-ADDRESS-FAMILY attribute.

func (*RequestedAddrFamily) Len

func (af *RequestedAddrFamily) Len() int

Len implements the Len method of Attribute interface.

type RequestedTransport

type RequestedTransport struct {
	Protocol int // protocol number
}

A RequestedTransport represents a STUN REQUESTED-TRANSPORT attribute.

func (*RequestedTransport) Len

func (rt *RequestedTransport) Len() int

Len implements the Len method of Attribute interface.

type ReservationToken

type ReservationToken []byte

A ReservationToken represents a STUN RESERVATION-TOKEN attribute.

func (ReservationToken) Len

func (_ ReservationToken) Len() int

Len implements the Len method of Attribute interface.

type Software

type Software string

A Software represents a STUN SOFTWARE attribute.

func (Software) Len

func (sw Software) Len() int

Len implements the Len method of Attribute interface.

type Type

type Type int

A Type reprensents a STUN message type or channel number.

func MessageType

func MessageType(c Class, m Method) Type

MessageType returns a message type consisting of c and m.

func ParseHeader

func ParseHeader(b []byte) (Type, int, error)

ParseHeader parses b as a STUN message header. It returns the message type or channel number, and the message length including the message header but not including padding bytes.

func (Type) Class

func (t Type) Class() Class

Class returns the message class of type.

func (Type) Method

func (t Type) Method() Method

Method returns the message method of type.

func (Type) String

func (t Type) String() string

type UnknownAttrs

type UnknownAttrs []int

An UnknownAttrs represents a STUN UNKNOWN-ATTRIBUTES attribute.

func (UnknownAttrs) Len

func (ua UnknownAttrs) Len() int

Len implements the Len method of Attribute interface.

type UseCandidate

type UseCandidate struct{}

A UseCandidate reprensents a STUN USE-CANDIDATE attribute.

func (*UseCandidate) Len

func (_ *UseCandidate) Len() int

Len implements the Len method of Attribute interface.

type Username

type Username string

A Username represents a STUN USERNAME attribute.

func (Username) Len

func (u Username) Len() int

Len implements the Len method of Attribute interface.

type XORMappedAddr

type XORMappedAddr Addr

An XORMappedAddr represents a STUN XOR-MAPPED-ADDRESS attribute.

func (*XORMappedAddr) Len

func (xa *XORMappedAddr) Len() int

Len implements the Len method of Attribute interface.

type XORPeerAddr

type XORPeerAddr Addr

An XORPeerAddr represents a STUN XOR-PEER-ADDRESS attribute.

func (*XORPeerAddr) Len

func (xa *XORPeerAddr) Len() int

Len implements the Len method of Attribute interface.

type XORRelayedAddr

type XORRelayedAddr Addr

An XORRelayedAddr represents a STUN XOR-RELAYED-ADDRESS attribute.

func (*XORRelayedAddr) Len

func (xa *XORRelayedAddr) Len() int

Len implements the Len method of Attribute interface.

Jump to

Keyboard shortcuts

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