Categorygithub.com/pion/stun/v3
modulepackage
3.0.0
Repository: https://github.com/pion/stun.git
Documentation: pkg.go.dev

# README


Pion STUN

A Go implementation of STUN

Pion stun Slack Widget
GitHub Workflow Status Go Reference Coverage Status Go Report Card License: MIT


Package stun implements Session Traversal Utilities for NAT (STUN) (RFC 5389) protocol and client with no external dependencies and zero allocations in hot paths. Client supports automatic request retransmissions.

Example

You can get your current IP address from any STUN server by sending binding request. See more idiomatic example at cmd/stun-client.

package main

import (
	"fmt"

	"github.com/pion/stun"
)

func main() {
	// Parse a STUN URI
	u, err := stun.ParseURI("stun:stun.l.google.com:19302")
	if err != nil {
		panic(err)
	}

	// Creating a "connection" to STUN server.
	c, err := stun.DialURI(u, &stun.DialConfig{})
	if err != nil {
		panic(err)
	}
	// Building binding request with random transaction id.
	message := stun.MustBuild(stun.TransactionID, stun.BindingRequest)
	// Sending request to STUN server, waiting for response message.
	if err := c.Do(message, func(res stun.Event) {
		if res.Error != nil {
			panic(res.Error)
		}
		// Decoding XOR-MAPPED-ADDRESS attribute from message.
		var xorAddr stun.XORMappedAddress
		if err := xorAddr.GetFrom(res.Message); err != nil {
			panic(err)
		}
		fmt.Println("your IP is", xorAddr.IP)
	}); err != nil {
		panic(err)
	}
}

RFCs

Implemented

Planned

Compatability notes

RFC 5389 obsoletes RFC 3489, so implementation was ignored by purpose, however, RFC 3489 can be easily implemented as separate package.

Stability

Package is currently stable, no backward incompatible changes are expected with exception of critical bugs or security fixes.

Additional attributes are unlikely to be implemented in scope of stun package, the only exception is constants for attribute or message types.

Requirements

Go 1.12 is currently supported and tested in CI.

Testing

Client behavior is tested and verified in many ways:

  • End-To-End with long-term credentials
    • coturn: The coturn server (linux)
  • Bunch of code static checkers (linters)
  • Standard unit-tests with coverage reporting (linux {amd64, arm64}, windows and darwin)
  • Explicit API backward compatibility check, see api directory

See TeamCity project and e2e directory for more information. Also the Wireshark .pcap files are available for e2e test in artifacts for build.

Benchmarks

Intel(R) Core(TM) i7-8700K:

version: 1.22.2
goos: linux
goarch: amd64
pkg: github.com/pion/stun
PASS
benchmark                                         iter       time/iter      throughput   bytes alloc        allocs
---------                                         ----       ---------      ----------   -----------        ------
BenchmarkMappedAddress_AddTo-12               32489450     38.30 ns/op                        0 B/op   0 allocs/op
BenchmarkAlternateServer_AddTo-12             31230991     39.00 ns/op                        0 B/op   0 allocs/op
BenchmarkAgent_GC-12                            431390   2918.00 ns/op                        0 B/op   0 allocs/op
BenchmarkAgent_Process-12                     35901940     36.20 ns/op                        0 B/op   0 allocs/op
BenchmarkMessage_GetNotFound-12              242004358      5.19 ns/op                        0 B/op   0 allocs/op
BenchmarkMessage_Get-12                      230520343      5.21 ns/op                        0 B/op   0 allocs/op
BenchmarkClient_Do-12                          1282231    943.00 ns/op                        0 B/op   0 allocs/op
BenchmarkErrorCode_AddTo-12                   16318916     75.50 ns/op                        0 B/op   0 allocs/op
BenchmarkErrorCodeAttribute_AddTo-12          21584140     54.80 ns/op                        0 B/op   0 allocs/op
BenchmarkErrorCodeAttribute_GetFrom-12       100000000     11.10 ns/op                        0 B/op   0 allocs/op
BenchmarkFingerprint_AddTo-12                 19368768     64.00 ns/op     687.81 MB/s        0 B/op   0 allocs/op
BenchmarkFingerprint_Check-12                 24167007     49.10 ns/op    1057.99 MB/s        0 B/op   0 allocs/op
BenchmarkBuildOverhead/Build-12                5486252    224.00 ns/op                        0 B/op   0 allocs/op
BenchmarkBuildOverhead/BuildNonPointer-12      2496544    517.00 ns/op                      100 B/op   4 allocs/op
BenchmarkBuildOverhead/Raw-12                  6652118    181.00 ns/op                        0 B/op   0 allocs/op
BenchmarkMessage_ForEach-12                   28254212     35.90 ns/op                        0 B/op   0 allocs/op
BenchmarkMessageIntegrity_AddTo-12             1000000   1179.00 ns/op      16.96 MB/s        0 B/op   0 allocs/op
BenchmarkMessageIntegrity_Check-12              975954   1219.00 ns/op      26.24 MB/s        0 B/op   0 allocs/op
BenchmarkMessage_Write-12                     41040598     30.40 ns/op     922.13 MB/s        0 B/op   0 allocs/op
BenchmarkMessageType_Value-12               1000000000      0.53 ns/op                        0 B/op   0 allocs/op
BenchmarkMessage_WriteTo-12                   94942935     11.30 ns/op                        0 B/op   0 allocs/op
BenchmarkMessage_ReadFrom-12                  43437718     29.30 ns/op     682.87 MB/s        0 B/op   0 allocs/op
BenchmarkMessage_ReadBytes-12                 74693397     15.90 ns/op    1257.42 MB/s        0 B/op   0 allocs/op
BenchmarkIsMessage-12                       1000000000      1.20 ns/op   16653.64 MB/s        0 B/op   0 allocs/op
BenchmarkMessage_NewTransactionID-12            521121   2450.00 ns/op                        0 B/op   0 allocs/op
BenchmarkMessageFull-12                        5389495    221.00 ns/op                        0 B/op   0 allocs/op
BenchmarkMessageFullHardcore-12               12715876     94.40 ns/op                        0 B/op   0 allocs/op
BenchmarkMessage_WriteHeader-12              100000000     11.60 ns/op                        0 B/op   0 allocs/op
BenchmarkMessage_CloneTo-12                   30199020     41.80 ns/op    1626.66 MB/s        0 B/op   0 allocs/op
BenchmarkMessage_AddTo-12                    415257625      2.97 ns/op                        0 B/op   0 allocs/op
BenchmarkDecode-12                            49573747     23.60 ns/op                        0 B/op   0 allocs/op
BenchmarkUsername_AddTo-12                    56282674     22.50 ns/op                        0 B/op   0 allocs/op
BenchmarkUsername_GetFrom-12                 100000000     10.10 ns/op                        0 B/op   0 allocs/op
BenchmarkNonce_AddTo-12                       39419097     35.80 ns/op                        0 B/op   0 allocs/op
BenchmarkNonce_AddTo_BadLength-12            196291666      6.04 ns/op                        0 B/op   0 allocs/op
BenchmarkNonce_GetFrom-12                    120857732      9.93 ns/op                        0 B/op   0 allocs/op
BenchmarkUnknownAttributes/AddTo-12           28881430     37.20 ns/op                        0 B/op   0 allocs/op
BenchmarkUnknownAttributes/GetFrom-12         64907534     19.80 ns/op                        0 B/op   0 allocs/op
BenchmarkXOR-12                               32868506     32.20 ns/op   31836.66 MB/s
BenchmarkXORSafe-12                            5185776    234.00 ns/op    4378.74 MB/s
BenchmarkXORFast-12                           30975679     32.50 ns/op   31525.28 MB/s
BenchmarkXORMappedAddress_AddTo-12            21518028     54.50 ns/op                        0 B/op   0 allocs/op
BenchmarkXORMappedAddress_GetFrom-12          35597667     34.40 ns/op                        0 B/op   0 allocs/op
ok      github.com/pion/stun   60.973s

Roadmap

The library is used as a part of our WebRTC implementation. Please refer to that roadmap to track our major milestones.

Community

Pion has an active community on the Slack.

Follow the Pion Twitter for project updates and important WebRTC news.

We are always looking to support your projects. Please reach out if you have something to build! If you need commercial support or don't want to use public methods you can contact us at [email protected]

Contributing

Check out the contributing wiki to join the group of amazing people making this project possible

License

MIT License - see LICENSE for full text

# Packages

No description provided by the author
Package main implement end-to-end tests.
Package stuntest contains helpers for testing STUN clients.

# Functions

Build wraps Message.Build method.
CheckOverflow returns ErrAttributeSizeOverflow if got is bigger that max.
CheckSize returns ErrAttrSizeInvalid if got is not equal to expected.
Decode decodes Message from data to m, returning error if any.
Dial connects to the address on the named network and then initializes Client on that connection, returning error if any.
DialURI connect to the STUN/TURN URI and then initializes Client on that connection, returning error if any.
FingerprintValue returns CRC-32 of b XOR-ed by 0x5354554e.
IsAttrSizeInvalid returns true if error means that attribute size is invalid.
IsAttrSizeOverflow returns true if error means that attribute size is too big.
IsMessage returns true if b looks like STUN message.
MustBuild wraps Build call and panics on error.
New returns *Message with pre-allocated Raw.
NewAgent initializes and returns new Agent with provided handler.
NewClient initializes new Client from provided options, starting internal goroutines and using default options fields if necessary.
NewLongTermIntegrity returns new MessageIntegrity with key for long-term credentials.
NewNonce returns new Nonce from string.
NewProtoType defines a procedure for creating a new ProtoType from a raw string naming the transport protocol type.
NewRealm returns Realm with provided value.
NewSchemeType defines a procedure for creating a new SchemeType from a raw string naming the scheme type.
NewShortTermIntegrity returns new MessageIntegrity with key for short-term credentials.
NewSoftware returns *Software from string.
NewTransactionID returns new random transaction ID using crypto/rand as source.
NewTransactionIDSetter returns new Setter that sets message transaction id to provided value.
NewType returns new message type with provided method and class.
NewUsername returns Username with provided value.
NoopHandler just discards any event.
ParseURI parses a STUN or TURN urls following the ABNF syntax described in https://tools.ietf.org/html/rfc7064 and https://tools.ietf.org/html/rfc7065 respectively.
WithAgent sets client STUN agent.
WithClock sets Clock of client, the source of current time.
WithCollector rests client timeout collector, the implementation of ticker which calls function on each tick.
WithHandler sets client handler which is called if Agent emits the Event with TransactionID that is not currently registered by Client.
WithNoConnClose prevents client from closing underlying connection when the Close() method is called.
WithNoRetransmit disables retransmissions and sets RTO to defaultMaxAttempts * defaultRTO which will be effectively time out if not set.
WithRTO sets client RTO as defined in STUN RFC.
WithTimeoutRate sets RTO timer minimum resolution.

# Constants

ALTERNATE-DOMAIN.
ALTERNATE-SERVER.
CACHE-TIMEOUT.
CHANGED-ADDRESS.
CHANGE-REQUEST.
CHANNEL-NUMBER.
CONNECTION-ID.
DATA.
DONT-FRAGMENT.
ERROR-CODE.
EVEN-PORT.
FINGERPRINT.
ICE-CONTROLLED.
ICE-CONTROLLING.
LIFETIME.
MAPPED-ADDRESS.
MESSAGE-INTEGRITY.
MESSAGE-INTEGRITY-SHA256.
NONCE.
Attributes from An Origin Attribute for the STUN Protocol.
OTHER-ADDRESS.
PADDING.
PASSWORD-ALGORITHM.
PASSWORD-ALGORITHMS.
PRIORITY.
REALM.
REQUESTED-ADDRESS-FAMILY.
REQUESTED-TRANSPORT.
RESERVATION-TOKEN.
RESPONSE-ORIGIN.
RESPONSE-PORT.
SOFTWARE.
SOURCE-ADDRESS.
UNKNOWN-ATTRIBUTES.
USE-CANDIDATE.
USERHASH.
USERNAME.
XOR-MAPPED-ADDRESS.
XOR-PEER-ADDRESS.
XOR-RELAYED-ADDRESS.
0b11.
0b01.
0b00.
0b10.
Address Family not Supported.
Allocation Mismatch.
Allocation Quota Reached.
Possible error codes.
Error codes from RFC 6062.
Error codes from RFC 6062.
Forbidden.
Insufficient Capacity.
Peer Address Family Mismatch.
Possible error codes.
Possible error codes.
Possible error codes.
Possible error codes.
DEPRECATED, use CodeUnauthorized.
Possible error codes.
Possible error codes.
Unsupported Transport Protocol.
Wrong Credentials.
IANA assigned ports for "stun" protocol.
IANA assigned ports for "stun" protocol.
Possible methods for STUN Message.
Possible methods for STUN Message.
Possible methods for STUN Message.
Methods from RFC 6062.
Methods from RFC 6062.
Methods from RFC 6062.
Possible methods for STUN Message.
Possible methods for STUN Message.
Possible methods for STUN Message.
Possible methods for STUN Message.
ProtoTypeTCP indicates the URL uses a TCP transport.
ProtoTypeUDP indicates the URL uses a UDP transport.
ProtoTypeUnknown indicates an unknown or unsupported protocol.
SchemeTypeSTUN indicates the URL represents a STUN server.
SchemeTypeSTUNS indicates the URL represents a STUNS (secure) server.
SchemeTypeTURN indicates the URL represents a TURN server.
SchemeTypeTURNS indicates the URL represents a TURNS (secure) server.
SchemeTypeUnknown indicates an unknown or unsupported scheme.
96 bit.

# Variables

nolint:gochecknoglobals.
nolint:gochecknoglobals.
nolint:gochecknoglobals.
ErrAgentClosed indicates that agent is in closed state and is unable to handle transactions.
ErrAttributeNotFound means that attribute with provided attribute type does not exist in message.
ErrAttributeSizeInvalid means that decoded attribute size is invalid.
ErrAttributeSizeOverflow means that decoded attribute size is too big.
ErrBadIPLength means that len(IP) is not net.{IPv6len,IPv4len}.
ErrBadUnknownAttrsSize means that UNKNOWN-ATTRIBUTES attribute value has invalid length.
ErrClientClosed indicates that client is closed.
ErrClientNotInitialized means that client connection or agent is nil.
ErrDecodeToNil occurs on Decode(data, nil) call.
ErrFingerprintBeforeIntegrity means that FINGERPRINT attribute is already in message, so MESSAGE-INTEGRITY attribute cannot be added.
ErrFingerprintMismatch means that computed fingerprint differs from expected.
ErrHost indicates malformed hostname is provided.
ErrIntegrityMismatch means that computed HMAC differs from expected.
ErrInvalidQuery indicates an malformed query is provided.
ErrNoConnection means that ClientOptions.Connection is nil.
ErrNoDefaultReason means that default reason for provided error code is not defined in RFC.
ErrPort indicates malformed port is provided.
ErrProtoType indicates an unsupported transport type was provided.
ErrSchemeType indicates the scheme type could not be parsed.
ErrSTUNQuery indicates query arguments are provided in a STUN URL.
ErrTransactionExists indicates that transaction with same id is already registered.
ErrTransactionNotExists indicates that agent failed to find transaction.
ErrTransactionStopped indicates that transaction was manually stopped.
ErrTransactionTimeOut indicates that transaction has reached deadline.
ErrUnexpectedHeaderEOF means that there were not enough bytes in m.Raw to read header.
ErrUnknownType indicates an error with Unknown info.
ErrUnsupportedURI is an error thrown if the user passes an unsupported STUN or TURN URI.
nolint:gochecknoglobals.
nolint:gochecknoglobals.

# Structs

Agent is low-level abstraction over transaction list that handles concurrency (all calls are goroutine-safe) and time outs (via Collect call).
AlternateServer represents ALTERNATE-SERVER attribute.
Client simulates "connection" to STUN server.
CloseErr indicates client close failure.
DecodeErr records an error and place when it is occurred.
DecodeErrPlace records a place where error is occurred.
DialConfig is used to pass configuration to DialURI().
ErrorCodeAttribute represents ERROR-CODE attribute.
Event is passed to Handler describing the transaction event.
FingerprintAttr represents FINGERPRINT attribute.
MappedAddress represents MAPPED-ADDRESS attribute.
Message represents a single STUN packet.
MessageType is STUN Message Type Field.
OtherAddress represents OTHER-ADDRESS attribute.
RawAttribute is a Type-Length-Value (TLV) object that can be added to a STUN message.
ResponseOrigin represents RESPONSE-ORIGIN attribute.
StopErr occurs when Client fails to stop transaction while processing error.
URI represents a STUN (rfc7064) or TURN (rfc7065) URI.
XORMappedAddress implements XOR-MAPPED-ADDRESS attribute.

# Interfaces

Interfaces that are implemented by message attributes, shorthands for them, or helpers for message fields as type or transaction id.
ClientAgent is Agent implementation that is used by Client to process transactions.
Clock abstracts the source of current time.
Collector calls function f with constant rate.
Connection wraps Reader, Writer and Closer interfaces.
Interfaces that are implemented by message attributes, shorthands for them, or helpers for message fields as type or transaction id.
Interfaces that are implemented by message attributes, shorthands for them, or helpers for message fields as type or transaction id.

# Type aliases

Attributes is list of message attributes.
AttrType is attribute type.
ClientOption sets some client option.
ErrorCode is code for ERROR-CODE attribute.
Handler handles state changes of transaction.
MessageClass is 8-bit representation of 2-bit class of STUN Message Class.
MessageIntegrity represents MESSAGE-INTEGRITY attribute.
Method is uint16 representation of 12-bit STUN method.
Nonce represents NONCE attribute.
ProtoType indicates the transport protocol type that is used in the ice.URL structure.
Realm represents REALM attribute.
SchemeType indicates the type of server used in the ice.URL structure.
Software is SOFTWARE attribute.
TextAttribute is helper for adding and getting text attributes.
UnknownAttributes represents UNKNOWN-ATTRIBUTES attribute.
Username represents USERNAME attribute.