v2

package
v0.7.5 Latest Latest
Warning

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

Go to latest
Published: May 5, 2020 License: MIT Imports: 15 Imported by: 0

README

v2: GTPv2 in Golang

Package v2 provides the simple and painless handling of GTPv2-C protocol in pure Golang.

Getting Started

Working examples are available in example directory, which might be the better instruction for developers.

Opening a connection
Client

Dial opens a connection between the specified peer by confirming the peer is alive by Echo Request/Response exchange. If you don't need Echo, see Server section.

// Note that the conn is not bound to raddr. to let a Conn to be able to communicate with multiple peers.
// Interface type is required here to let Conn know which is the local interface type.
conn, err := v2.Dial(ctx, laddr, raddr, v2.IFTypeS11MMEGTPC, 0)
if err != nil {
    // ...
}
Server

Retrieve Conn with NewConn, and ListenAndServe to start listening.

// Interface type is required here to let Conn know which is the local interface type.
srvConn := v2.NewConn(srvAddr, v2.IFTypeS11MMEGTPC, 0)
if err := srvConn.ListenAndServe(ctx); err != nil {
    // ...
}
Handling incoming messages

Prepare functions that comform to HandlerFunc, and register them to Conn with AddHandler. This should be done as soon as you get Conn not to miss the incoming messages.

HandlerFunc is to handle the incoming messages by message type. See example for how it is like.
Also consider using AddHandlers when you have many HandlerFuncs.

// write what you expect to do on receiving a message. Handlers should be added per message type.
// by default, Echo Request/Response and Version Not Supported Indication is handled automatically.
conn.AddHandler(
    // first param is the type of message. give number in uint8 or use v2.MsgTypeXXX.
    messages.MsgTypeCreateSessionResponse,
    // second param is the HandlerFunc to describe how you handle the message coming from peer.
    func(c *v2.Conn, senderAddr net.Addr, msg messages.Message) error {
        // Do what you want with CreateSessionResponse message here.
        // see examples directly for functional examples
    },
)
Manipulating sessions

With Conn, you can create, modify, delete GTPv2-C sessions and bearers with the built-in methods.

Session creation

CreateSession creates a Session, while storing values given as IEs and creating a default bearer. In the following call, for example, IMSI and TEID for S1-U eNB is stored in the created Session.

session, err := c.CreateSession(
    // put IEs required for your implementation here.
    // it is easier to use constructors in ies package.
    ies.NewIMSI("123451234567890"),
    
    // or, you can use ies.New() to create an IE without type-specific constructor.
    // put the type of IE, flags/instance, and payload as the parameters.
    ies.New(ies.ExtendedTraceInformation, 0x00, []byte{0xde, 0xad, 0xbe, 0xef}),
    
    // to set the instance to IE created with message-specific constructor, WithInstance()
    // may be your help.
    ies.NewIMSI("123451234567890").WithInstance(1), // no one wants to set instance to IMSI, though.

    // don't forget to contain the Sender F-TEID, as it is used to distinguish the incoming
    // messages by Conn.
    //
    // to be secure, TEID should be generated with random values, without conflicts in a Conn.
    // to achieve that, v2 provides NewFTEID() which returns F-TEID in *ies.IE.
    s11Conn.NewFTEID(v2.IFTypeS11MMEGTPC, mmeIP, ""),
)
if err != nil {
    // ...
}
Session deletion / Bearer modification

DeleteSession and ModifyBearer methods are provided to send each message as easy as possible. Unlike CreateSession, they don't manipulate the Session information automatically.

Opening a U-Plane connection

See v1/README.md.

Supported Features

The following Messages marked with "Yes" are currently available with their own useful constructors.

Even there are some missing Messages, you can create any kind of Message by using messages.NewGeneric().

Messages
ID Name Supported
0 (Spare/Reserved) -
1 Echo Request Yes
2 Echo Response Yes
3 Version Not Supported Indication Yes
4-16 (Spare/Reserved) -
17-24 (Spare/Reserved) -
25-31 (Spare/Reserved) -
32 Create Session Request Yes
33 Create Session Response Yes
34 Modify Bearer Request Yes
35 Modify Bearer Response Yes
36 Delete Session Request Yes
37 Delete Session Response Yes
38 Change Notification Request
39 Change Notification Response
40 Remote UE Report Notification
41 Remote UE Report Acknowledge
42-63 (Spare/Reserved) -
64 Modify Bearer Command Yes
65 Modify Bearer Failure Indication Yes
66 Delete Bearer Command Yes
67 Delete Bearer Failure Indication Yes
68 Bearer Resource Command
69 Bearer Resource Failure Indication
70 Downlink Data Notification Failure Indication
71 Trace Session Activation
72 Trace Session Deactivation
73 Stop Paging Indication Yes
74-94 (Spare/Reserved) -
95 Create Bearer Request Yes
96 Create Bearer Response Yes
97 Update Bearer Request
98 Update Bearer Response
99 Delete Bearer Request Yes
100 Delete Bearer Response Yes
101 Delete PDN Connection Set Request
102 Delete PDN Connection Set Response
103 PGW Downlink Triggering Notification
104 PGW Downlink Triggering Acknowledge
105-127 (Spare/Reserved) -
128 Identification Request
129 Identification Response
130 Context Request Yes
131 Context Response Yes
132 Context Acknowledge Yes
133 Forward Relocation Request
134 Forward Relocation Response
135 Forward Relocation Complete Notification
136 Forward Relocation Complete Acknowledge
137 Forward Access Context Notification
138 Forward Access Context Acknowledge
139 Relocation Cancel Request
140 Relocation Cancel Response
141 Configuration Transfer Tunnel
142-148 (Spare/Reserved) -
149 Detach Notification
150 Detach Acknowledge
151 CS Paging Indication
152 RAN Information Relay
153 Alert MME Notification
154 Alert MME Acknowledge
155 UE Activity Notification
156 UE Activity Acknowledge
157 ISR Status Indication
158 UE Registration Query Request
159 UE Registration Query Response
160 Create Forwarding Tunnel Request
161 Create Forwarding Tunnel Response
162 Suspend Notification
163 Suspend Acknowledge
164 Resume Notification
165 Resume Acknowledge
166 Create Indirect Data Forwarding Tunnel Request
167 Create Indirect Data Forwarding Tunnel Response
168 Delete Indirect Data Forwarding Tunnel Request
169 Delete Indirect Data Forwarding Tunnel Response
170 Release Access Bearers Request Yes
171 Release Access Bearers Response Yes
172-175 (Spare/Reserved) -
176 Downlink Data Notification
177 Downlink Data Notification Acknowledge
178 (Spare/Reserved) -
179 PGW Restart Notification
180 PGW Restart Notification Acknowledge
181-199 (Spare/Reserved) -
200 Update PDN Connection Set Request
201 Update PDN Connection Set Response
202-210 (Spare/Reserved) -
211 Modify Access Bearers Request Yes
212 Modify Access Bearers Response Yes
213-230 (Spare/Reserved) -
231 MBMS Session Start Request
232 MBMS Session Start Response
233 MBMS Session Update Request
234 MBMS Session Update Response
235 MBMS Session Stop Request
236 MBMS Session Stop Response
237-239 (Spare/Reserved) -
240-247 (Spare/Reserved) -
248-255 (Spare/Reserved) -
Information Elements

The following Information Elements marked with "Yes" are currently available with their own useful constructors.

Even there are some missing IEs, you can create any kind of IEs by using ies.New() function or by initializing ies.IE directly.

ID Name Supported
0 (Spare/Reserved) -
1 International Mobile Subscriber Identity (IMSI) Yes
2 Cause Yes
3 Recovery (Restart Counter) Yes
4-34 (Spare/Reserved) -
35-50 (Spare/Reserved) -
51 STN-SR
52-70 (Spare/Reserved) -
71 Access Point Name (APN) Yes
72 Aggregate Maximum Bit Rate (AMBR) Yes
73 EPS Bearer ID (EBI) Yes
74 IP Address Yes
75 Mobile Equipment Identity (MEI) Yes
76 MSISDN Yes
77 Indication Yes
78 Protocol Configuration Options (PCO) Yes
79 PDN Address Allocation (PAA) Yes
80 Bearer Level Quality of Service (Bearer QoS) Yes
81 Flow Quality of Service (Flow QoS) Yes
82 RAT Type Yes
83 Serving Network Yes
84 EPS Bearer Level Traffic Flow Template (Bearer TFT)
85 Traffic Aggregation Description (TAD)
86 User Location Information (ULI) Yes
87 Fully Qualified Tunnel Endpoint Identifier (F-TEID) Yes
88 TMSI Yes
89 Global CN-Id Yes
90 S103 PDN Data Forwarding Info (S103PDF) Yes
91 S1-U Data Forwarding Info (S1UDF) Yes
92 Delay Value Yes
93 Bearer Context Yes
94 Charging ID Yes
95 Charging Characteristics Yes
96 Trace Information
97 Bearer Flags Yes
98 (Spare/Reserved) -
99 PDN Type Yes
100 Procedure Transaction ID Yes
101 (Spare/Reserved) -
102 (Spare/Reserved) -
103 MM Context (GSM Key and Triplets)
104 MM Context (UMTS Key, Used Cipher and Quintuplets)
105 MM Context (GSM Key, Used Cipher and Quintuplets)
106 MM Context (UMTS Key and Quintuplets)
107 MM Context (EPS Security Context, Quadruplets and Quintuplets)
108 MM Context (UMTS Key, Quadruplets and Quintuplets)
109 PDN Connection
110 PDU Numbers
111 Packet TMSI Yes
112 P-TMSI Signature Yes
113 Hop Counter Yes
114 UE Time Zone Yes
115 Trace Reference Yes
116 Complete Request Message
117 GUTI Yes
118 F-Container
119 F-Cause
120 PLMN ID Yes
121 Target Identification
122 (Spare/Reserved) -
123 Packet Flow ID
124 RAB Context
125 Source RNC PDCP Context Info
126 Port Number Yes
127 APN Restriction Yes
128 Selection Mode Yes
129 Source Identification
130 (Spare/Reserved) -
131 Change Reporting Action
132 Fully Qualified PDN Connection Set Identifier (FQ-CSID) Yes
133 Channel Needed
134 eMLPP Priority
135 Node Type Yes
136 Fully Qualified Domain Name (FQDN) Yes
137 Transaction Identifier (TI)
138 MBMS Session Duration
139 MBMS Service Area
140 MBMS Session Identifier
141 MBMS Flow Identifier
142 MBMS IP Multicast Distribution
143 MBMS Distribution Acknowledge
144 RFSP Index
145 User CSG Information (UCI) Yes
146 CSG Information Reporting Action
147 CSG ID Yes
148 CSG Membership Indication (CMI) Yes
149 Service Indicator Yes
150 Detach Type Yes
151 Local Distinguished Name (LDN) Yes
152 Node Features
153 MBMS Time to Data Transfer
154 Throttling
155 Allocation/Retention Priority (ARP)
156 EPC Timer
157 Signalling Priority Indication
158 Temporary Mobile Group Identity (TMGI)
159 Additional MM context for SRVCC
160 Additional flags for SRVCC
161 (Spare/Reserved) -
162 MDT Configuration
163 Additional Protocol Configuration Options (APCO)
164 Absolute Time of MBMS Data Transfer
165 H(e)NB Information Reporting
166 IPv4 Configuration Parameters (IP4CP)
167 Change to Report Flags
168 Action Indication
169 TWAN Identifier
170 ULI Timestamp Yes
171 MBMS Flags
172 RAN/NAS Cause Yes
173 CN Operator Selection Entity
174 Trusted WLAN Mode Indication
175 Node Number
176 Node Identifier
177 Presence Reporting Area Action
178 Presence Reporting Area Information
179 TWAN Identifier Timestamp
180 Overload Control Information
181 Load Control Information
182 Metric
183 Sequence Number
184 APN and Relative Capacity
185 WLAN Offloadability Indication
186 Paging and Service Information
187 Integer Number
188 Millisecond Time Stamp
189 Monitoring Event Information
190 ECGI List
191 Remote UE Context
192 Remote User ID
193 Remote UE IP information
194 CIoT Optimizations Support Indication
195 SCEF PDN Connection
196 Header Compression Configuration
197 Extended Protocol Configuration Options (ePCO)
198 Serving PLMN Rate Control
199 Counter
200 Mapped UE Usage Type
201 Secondary RAT Usage Data Report
202 UP Function Selection Indication Flags
203 Maximum Packet Loss Rate
204 APN Rate Control Status
205 Extended Trace Information
206-253 (Spare/Reserved) -
254 (Spare/Reserved) -
255 Private Extension Yes

Documentation

Overview

Package v2 provides the simple and painless handling of GTPv2-C protocol in pure Golang.

Please see README.md for detailed usage of the APIs provided by this package.

https://github.com/wmnsk/go-gtp/blob/master/v2/README.md

Index

Constants

View Source
const (
	GTPCPort = ":2123"
	GTPUPort = ":2152"
)

Registered UDP ports

View Source
const (
	IFTypeS1UeNodeBGTPU uint8 = iota
	IFTypeS1USGWGTPU
	IFTypeS12RNCGTPU
	IFTypeS12SGWGTPU
	IFTypeS5S8SGWGTPU
	IFTypeS5S8PGWGTPU
	IFTypeS5S8SGWGTPC
	IFTypeS5S8PGWGTPC
	IFTypeS5S8SGWPMIPv6
	IFTypeS5S8PGWPMIPv6
	IFTypeS11MMEGTPC
	IFTypeS11S4SGWGTPC
	IFTypeS10MMEGTPC
	IFTypeS3MMEGTPC
	IFTypeS3SGSNGTPC
	IFTypeS4SGSNGTPU
	IFTypeS4SGWGTPU
	IFTypeS4SGSNGTPC
	IFTypeS16SGSNGTPC
	IFTypeeNodeBGTPUForDL
	IFTypeeNodeBGTPUForUL
	IFTypeRNCGTPUForData
	IFTypeSGSNGTPUForData
	IFTypeSGWUPFGTPUForDL
	IFTypeSmMBMSGWGTPC
	IFTypeSnMBMSGWGTPC
	IFTypeSmMMEGTPC
	IFTypeSnSGSNGTPC
	IFTypeSGWGTPUForUL
	IFTypeSnSGSNGTPU
	IFTypeS2bePDGGTPC
	IFTypeS2bUePDGGTPU
	IFTypeS2bPGWGTPC
	IFTypeS2bUPGWGTPU
	IFTypeS2aTWANGTPU
	IFTypeS2aTWANGTPC
	IFTypeS2aPGWGTPC
	IFTypeS2aPGWGTPU
	IFTypeS11MMEGTPU
	IFTypeS11SGWGTPU
)

InterfaceType definitions.

View Source
const (
	APNRestrictionNoExistingContextsorRestriction uint8 = iota
	APNRestrictionPublic1
	APNRestrictionPublic2
	APNRestrictionPrivate1
	APNRestrictionPrivate2
)

APN Restriction definitions.

View Source
const (
	CauseLocalDetach                                   uint8 = 2
	CauseCompleteDetach                                uint8 = 3
	CauseRATChangedFrom3GPPToNon3GPP                   uint8 = 4
	CauseISRDeactivation                               uint8 = 5
	CauseErrorIndicationReceivedFromRNCeNodeBS4SGSNMME uint8 = 6
	CauseIMSIDetachOnly                                uint8 = 7
	CauseReactivationRequested                         uint8 = 8
	CausePDNReconnectionToThisAPNDisallowed            uint8 = 9
	CauseAccessChangedFromNon3GPPTo3GPP                uint8 = 10
	CausePDNConnectionInactivityTimerExpires           uint8 = 11
	CausePGWNotResponding                              uint8 = 12
	CauseNetworkFailure                                uint8 = 13
	CauseQoSParameterMismatch                          uint8 = 14

	CauseRequestAccepted                        uint8 = 16
	CauseRequestAcceptedPartially               uint8 = 17
	CauseNewPDNTypeDueToNetworkPreference       uint8 = 18
	CauseNewPDNTypeDueToSingleAddressBearerOnly uint8 = 19
	CauseContextNotFound                        uint8 = 64
	CauseInvalidMessageFormat                   uint8 = 65
	CauseVersionNotSupportedByNextPeer          uint8 = 66
	CauseInvalidLength                          uint8 = 67
	CauseServiceNotSupported                    uint8 = 68
	CauseMandatoryIEIncorrect                   uint8 = 69
	CauseMandatoryIEMissing                     uint8 = 70

	CauseSystemFailure                   uint8 = 72
	CauseNoResourcesAvailable            uint8 = 73
	CauseSemanticErrorInTheTFTOperation  uint8 = 74
	CauseSyntacticErrorInTheTFTOperation uint8 = 75
	CauseSemanticErrorsInPacketFilters   uint8 = 76
	CauseSyntacticErrorsInPacketFilters  uint8 = 77
	CauseMissingOrUnknownAPN             uint8 = 78

	CauseGREKeyNotFound                      uint8 = 80
	CauseRelocationFailure                   uint8 = 81
	CauseDeniedInRAT                         uint8 = 82
	CausePreferredPDNTypeNotSupported        uint8 = 83
	CauseAllDynamicAddressesAreOccupied      uint8 = 84
	CauseUEContextWithoutTFTAlreadyActivated uint8 = 85
	CauseProtocolTypeNotSupported            uint8 = 86
	CauseUENotResponding                     uint8 = 87
	CauseUERefuses                           uint8 = 88
	CauseServiceDenied                       uint8 = 89
	CauseUnableToPageUE                      uint8 = 90
	CauseNoMemoryAvailable                   uint8 = 91
	CauseUserAuthenticationFailed            uint8 = 92
	CauseAPNAccessDeniedNoSubscription       uint8 = 93
	CauseRequestRejectedReasonNotSpecified   uint8 = 94
	CausePTMSISignatureMismatch              uint8 = 95
	CauseIMSIIMEINotKnown                    uint8 = 96
	CauseSemanticErrorInTheTADOperation      uint8 = 97
	CauseSyntacticErrorInTheTADOperation     uint8 = 98

	CauseRemotePeerNotResponding                                                        uint8 = 100
	CauseCollisionWithNetworkInitiatedRequest                                           uint8 = 101
	CauseUnableToPageUEDueToSuspension                                                  uint8 = 102
	CauseConditionalIEMissing                                                           uint8 = 103
	CauseAPNRestrictionTypeIncompatibleWithCurrentlyActivePDNConnection                 uint8 = 104
	CauseInvalidOverallLengthOfTheTriggeredResponseMessageAndAPiggybackedInitialMessage uint8 = 105
	CauseDataForwardingNotSupported                                                     uint8 = 106
	CauseInvalidReplyFromRemotePeer                                                     uint8 = 107
	CauseFallbackToGTPv1                                                                uint8 = 108
	CauseInvalidPeer                                                                    uint8 = 109
	CauseTemporarilyRejectedDueToHandoverTAURAUProcedureInProgress                      uint8 = 110
	CauseModificationsNotLimitedToS1UBearers                                            uint8 = 111
	CauseRequestRejectedForAPMIPv6Reason                                                uint8 = 112
	CauseAPNCongestion                                                                  uint8 = 113
	CauseBearerHandlingNotSupported                                                     uint8 = 114
	CauseUEAlreadyReattached                                                            uint8 = 115
	CauseMultiplePDNConnectionsForAGivenAPNNotAllowed                                   uint8 = 116
	CauseTargetAccessRestrictedForTheSubscriber                                         uint8 = 117

	CauseMMESGSNRefusesDueToVPLMNPolicy              uint8 = 119
	CauseGTPCEntityCongestion                        uint8 = 120
	CauseLateOverlappingRequest                      uint8 = 121
	CauseTimedOutRequest                             uint8 = 122
	CauseUEIsTemporarilyNotReachableDueToPowerSaving uint8 = 123
	CauseRelocationFailureDueToNASMessageRedirection uint8 = 124
	CauseUENotAuthorisedByOCSOrExternalAAAServer     uint8 = 125
	CauseMultipleAccessesToAPDNConnectionNotAllowed  uint8 = 126
	CauseRequestRejectedDueToUECapability            uint8 = 127
	CauseS1UPathFailure                              uint8 = 128
)

Cause definitions.

View Source
const (
	CMINonCSG uint8 = iota
	CMICSG
)

CSG Membership Indication definitions.

View Source
const (
	DetachTypePS uint8
	DetachTypeCombinedPSCS
)

Detach Type definitions.

View Source
const (
	NodeIDIPv4 uint8 = iota
	NodeIDIPv6
	NodeIDOther
)

Node-ID Type definitions.

View Source
const (
	NodeTypeSGSN uint8 = iota
	NodeTypeMME
)

Node Type definitions.

View Source
const (
	ProtoIDLCP  uint16 = 0xc021
	ProtoIDPAP  uint16 = 0xc023
	ProtoIDCHAP uint16 = 0xc223
	ProtoIDIPCP uint16 = 0x8021
)

Protocol ID definitions. For more identifiers, see RFC 3232.

View Source
const (
	ContIDPCSCFIPv6AddressRequest uint16
	ContIDIMCNSubsystemSignalingFlag
	ContIDDNSServerIPv6AddressRequest
	ContIDNotSupported
	ContIDMSSupportofNetworkRequestedBearerControlIndicator

	ContIDDSMIPv6HomeAgentAddressRequest
	ContIDDSMIPv6HomeNetworkPrefixRequest
	ContIDDSMIPv6IPv4HomeAgentAddressRequest
	ContIDIPaddressAllocationViaNASSignalling
	ContIDIPv4addressAllocationViaDHCPv4
	ContIDPCSCFIPv4AddressRequest
	ContIDDNSServerIPv4AddressRequest
	ContIDMSISDNRequest
	ContIDIFOMSupportRequest
	ContIDIPv4LinkMTURequest
	ContIDMSSupportOfLocalAddressInTFTIndicator
	ContIDPCSCFReselectionSupport
	ContIDNBIFOMRequestIndicator
	ContIDNBIFOMMode
	ContIDNonIPLinkMTURequest
	ContIDAPNRateControlSupportIndicator
	ContID3GPPPSDataOffUEstatus
	ContIDReliableDataServiceRequestIndicator
	ContIDAdditionalAPNRateControlForExceptionDataSupportIndicator
	ContIDPDUSessionID

	ContIDEthernetFramePayloadMTURequest
	ContIDUnstructuredLinkMTURequest
	ContID5GSMCauseValue
)

Container ID definitions.

View Source
const (
	PDNTypeIPv4 uint8
	PDNTypeIPv6
	PDNTypeIPv4v6
	PDNTypeNonIP
)

PDN Type definitions.

View Source
const (
	ProtoTypeS1APCause uint8
	ProtoTypeEMMCause
	ProtoTypeESMCause
	ProtoTypeDiameterCause
	ProtoTypeIKEv2Cause
)

Protocol Type definitions.

View Source
const (
	CauseType uint8 = iota
	CauseTypeRadioNetworkLayer
	CauseTypeTransportLayer
	CauseTypeNAS
	CauseTypeProtocol
	CauseTypeMiscellaneous
)

Cause Type definitions.

View Source
const (
	RATTypeUTRAN uint8
	RATTypeGERAN
	RATTypeWLAN
	RATTypeGAN
	RATTypeHSPAEvolution
	RATTypeEUTRAN
	RATTypeVirtual
	RATTypeEUTRANNBIoT
	RATTypeLTEM
	RATTypeNR
)

RAT Type definitions.

View Source
const (
	SelectionModeMSorNetworkProvidedAPNSubscribedVerified uint8 = iota
	SelectionModeMSProvidedAPNSubscriptionNotVerified
	SelectionModeNetworkProvidedAPNSubscriptionNotVerified
)

SelectionMode definitions.

View Source
const (
	ServiceIndCSCall uint8
	ServiceIndSMS
)

Service Indicator definitions.

View Source
const (
	AccessModeClosed uint8 = iota
	AccessModeHybrid
)

Access Mode definitions.

View Source
const (
	DaylightSavingNoAdjustment uint8 = iota
	DaylightSavingPlusOneHour
	DaylightSavingPlusTwoHours
)

Daylight Saving Time definitions.

View Source
const (
	ConfigProtocolPPPWithIP uint8 = 0
)

Configuration Protocol definitions.

Variables

View Source
var (
	// ErrTEIDNotFound indicates that TEID is not registered for the interface specified.
	ErrTEIDNotFound = errors.New("no TEID found")

	// ErrTimeout indicates that a handler failed to complete its work due to the
	// absence of messages expected to come from another endpoint.
	ErrTimeout = errors.New("timed out")
)

Functions

func DisableLogging added in v0.6.1

func DisableLogging()

DisableLogging disables the logging from the package. Logging is enabled by default.

func EnableLogging added in v0.6.1

func EnableLogging(l *log.Logger)

EnableLogging enables the logging from the package. If l is nil, it uses default logger provided by the package. Logging is enabled by default.

See also: SetLogger.

func PassMessageTo

func PassMessageTo(s *Session, msg messages.Message, timeout time.Duration) error

PassMessageTo passes the message (typically "triggerred message") to the session expecting to receive it.

If the message queue of s is full, it waits for certain period of time specified by timeout. It discards the msg and returns error if expired. The default queue size of a Session is 1000 and it cannot be configured in the current implementation.

func SetLogger added in v0.6.1

func SetLogger(l *log.Logger)

SetLogger replaces the standard logger with arbitrary *log.Logger.

This package prints just informational logs from goroutines working background that might help developers test the program but can be ignored safely. More important ones that needs any action by caller would be returned as errors.

Types

type Bearer

type Bearer struct {
	EBI               uint8
	SubscriberIP, APN string
	ChargingID        uint32
	*QoSProfile
	// contains filtered or unexported fields
}

Bearer represents a GTPv2 bearer.

func NewBearer

func NewBearer(ebi uint8, apn string, qos *QoSProfile) *Bearer

NewBearer creates a new Bearer.

func (*Bearer) IncomingTEID

func (b *Bearer) IncomingTEID() uint32

IncomingTEID returns the incoming TEID associated with Bearer.

func (*Bearer) OutgoingTEID

func (b *Bearer) OutgoingTEID() uint32

OutgoingTEID returns the outgoing TEID associated with Bearer.

func (*Bearer) RemoteAddress

func (b *Bearer) RemoteAddress() net.Addr

RemoteAddress returns the remote address associated with Bearer.

func (*Bearer) SetIncomingTEID

func (b *Bearer) SetIncomingTEID(teid uint32)

SetIncomingTEID sets the incoming TEID associated with Bearer.

func (*Bearer) SetOutgoingTEID

func (b *Bearer) SetOutgoingTEID(teid uint32)

SetOutgoingTEID sets the outgoing TEID associated with Bearer.

func (*Bearer) SetRemoteAddress

func (b *Bearer) SetRemoteAddress(raddr net.Addr)

SetRemoteAddress sets the remote address associated with Bearer.

type BearerNotFoundError added in v0.6.0

type BearerNotFoundError struct {
	IMSI string
}

BearerNotFoundError indicates that no Bearer found by lookup methods.

func (*BearerNotFoundError) Error added in v0.6.0

func (e *BearerNotFoundError) Error() string

x Error returns message with IMSI associated with Bearer if available.

type CauseNotOKError added in v0.6.0

type CauseNotOKError struct {
	MsgType string
	Cause   uint8
	Msg     string
}

CauseNotOKError indicates that the value in Cause IE is not OK.

func (*CauseNotOKError) Error added in v0.6.0

func (e *CauseNotOKError) Error() string

x Error returns error cause with message.

type Conn

type Conn struct {

	// RestartCounter is the RestartCounter value in Recovery IE, which represents how many
	// times the GTPv2-C endpoint is restarted.
	RestartCounter uint8
	// contains filtered or unexported fields
}

Conn represents a GTPv2-C connection.

Conn provides the automatic handling of message by adding handlers to it with AddHandler(s). See AddHandler for detailed usage.

Conn also provides the functions to manage Sessions/Bearers that works over the connection(=between a node to another). See the docs of CreateSession, AddSession, DeleteSession methods for details.

func Dial

func Dial(ctx context.Context, laddr, raddr net.Addr, localIfType, counter uint8) (*Conn, error)

Dial sends Echo Request to raddr to check if the endpoint is alive and returns Conn.

It does not bind the raddr to the underlying connection, which enables a Conn to send to/receive from multiple peers with single laddr.

If Echo exchange is unnecessary, use NewConn and ListenAndServe instead.

func NewConn

func NewConn(laddr net.Addr, localIfType, counter uint8) *Conn

NewConn creates a new Conn used for server. On client side, use Dial instead.

func (*Conn) AddHandler

func (c *Conn) AddHandler(msgType uint8, fn HandlerFunc)

AddHandler adds a message handler to Conn.

By adding HandlerFunc, Conn(and Session, Bearer created over the Conn) will handle the specified type of message with it's paired HandlerFunc when receiving. Messages without registered handlers are just ignored and logged.

This should be performed just after creating Conn, otherwise the user cannot retrieve any values, which is in most cases vital to continue working as a node, from the incoming messages.

The error returned from handler is just logged. Any important due should be done inside the HandlerFunc before returning. This behavior might change in the future.

HandlerFunc for EchoResponse and VersionNotSupportedIndication are registered by default. These HandlerFunc can be overridden by specifying messages.MsgTypeEchoResponse and/or messages.MsgTypeVersionNotSupportedIndication as msgType parameter.

func (*Conn) AddHandlers

func (c *Conn) AddHandlers(funcs map[uint8]HandlerFunc)

AddHandlers adds multiple handler funcs at a time, using a map. The key of the map is message type of the GTPv2-C messages. You can use MsgTypeFooBar constants defined in this package as well as any raw uint8 values.

See AddHandler for how the given handlers behave.

func (*Conn) BearerCount added in v0.2.0

func (c *Conn) BearerCount() int

BearerCount returns the number of bearers registered in Conn.

This may have some impact on performance in case of large number of Session and Bearer exist.

func (*Conn) Close

func (c *Conn) Close() error

Close closes the connection. Any blocked Read or Write operations will be unblocked and return errors.

func (*Conn) CreateSession

func (c *Conn) CreateSession(raddr net.Addr, ie ...*ies.IE) (*Session, uint32, error)

CreateSession sends a CreateSessionRequest and stores information given with IE in the Session returned.

After using this method, users don't need to call AddSession with the session returned.

By creating a Session with this method, the values in IEs given, such as TEID in F-TEID are stored with "best effort". See the source code to see what kind information is handled automatically in this method.

Also, a Bearer named "default" is also created to be used as default bearer. The default bearer can be retrieved by using GetDefaultBearer() or LookupBearerByName("default").

Note that this method doesn't care IEs given are sufficient or not, as the required IE varies much depending on the context in which the Create Session Request is used. In other words, any kind of IE can be put on the Create Session Request message using this method.

func (*Conn) DecSequence added in v0.3.1

func (c *Conn) DecSequence() uint32

DecSequence decrements the SequenceNumber associated with Conn.

func (*Conn) DeleteBearer added in v0.2.0

func (c *Conn) DeleteBearer(teid uint32, sess *Session, ie ...*ies.IE) (uint32, error)

DeleteBearer sends a DeleteBearerRequest TEID and with IEs given.

func (*Conn) DeleteSession

func (c *Conn) DeleteSession(teid uint32, sess *Session, ie ...*ies.IE) (uint32, error)

DeleteSession sends a DeleteSessionRequest with TEID and IEs given.

func (*Conn) DisableValidation

func (c *Conn) DisableValidation()

DisableValidation turns off automatic validation of incoming messages. It is not recommended to use this except the node is in debugging mode.

See EnableValidation for what are validated.

func (*Conn) EchoRequest

func (c *Conn) EchoRequest(raddr net.Addr) (uint32, error)

EchoRequest sends a EchoRequest.

func (*Conn) EchoResponse

func (c *Conn) EchoResponse(raddr net.Addr, req messages.Message) error

EchoResponse sends a EchoResponse in response to the EchoRequest.

func (*Conn) EnableValidation

func (c *Conn) EnableValidation()

EnableValidation turns on automatic validation of incoming messages. This is expected to be used only after DisableValidation() is used, as the validation is enabled by default.

Conn checks if;

GTP Version is 2
TEID is known to Conn

Even the validation is failed, it does not return error to user. Instead, it just logs and discards the packets so that the HandlerFunc won't get the invalid message. Extra validations should be done in HandlerFunc.

func (*Conn) GetIMSIByTEID

func (c *Conn) GetIMSIByTEID(teid uint32, peer net.Addr) (string, error)

GetIMSIByTEID returns IMSI associated with TEID and the peer node.

func (*Conn) GetSessionByIMSI

func (c *Conn) GetSessionByIMSI(imsi string) (*Session, error)

GetSessionByIMSI returns Session looked up by IMSI.

func (*Conn) GetSessionByTEID

func (c *Conn) GetSessionByTEID(teid uint32, peer net.Addr) (*Session, error)

GetSessionByTEID returns Session looked up by TEID and sender of the message.

func (*Conn) IncSequence added in v0.3.1

func (c *Conn) IncSequence() uint32

IncSequence increments the SequenceNumber associated with Conn.

func (*Conn) ListenAndServe added in v0.7.0

func (c *Conn) ListenAndServe(ctx context.Context) error

ListenAndServe creates a new GTPv2-C Conn and start serving background.

func (*Conn) LocalAddr

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

LocalAddr returns the local network address.

func (*Conn) ModifyBearer

func (c *Conn) ModifyBearer(teid uint32, sess *Session, ie ...*ies.IE) (uint32, error)

ModifyBearer sends a ModifyBearerRequest with TEID and IEs given..

func (*Conn) NewSenderFTEID added in v0.7.3

func (c *Conn) NewSenderFTEID(v4, v6 string) (fteidIE *ies.IE)

NewSenderFTEID creates a new F-TEID with random TEID value that is unique within Conn. To ensure the uniqueness, don't create in the other way if you once use this method. This is meant to be used for creating F-TEID IE only for local interface type that is specified at the creation of Conn.

Note that in the case there's a lot of Session on the Conn, it may take a long time to find a new unique value.

TODO: optimize performance...

func (*Conn) ParseCreateSession added in v0.7.4

func (c *Conn) ParseCreateSession(raddr net.Addr, ie ...*ies.IE) (*Session, error)

ParseCreateSession iterates through the ies and returns a session

func (*Conn) ReadFrom

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

ReadFrom reads a packet from the connection, copying the payload into p. It returns the number of bytes copied into p and the return address that was on the packet. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered. Callers should always process the n > 0 bytes returned before considering the error err. ReadFrom can be made to time out and return an Error with Timeout() == true after a fixed time limit; see SetDeadline and SetReadDeadline.

func (*Conn) RegisterSession added in v0.7.3

func (c *Conn) RegisterSession(itei uint32, session *Session)

RegisterSession registers session to Conn with its incoming TEID to distinguish which session the incoming messages are for.

Incoming TEID(itei) should be the one with it's local interface type. e.g., if the Conn is used for S-GW on S11 I/F, itei should be the one with interface type=IFTypeS11S4SGWGTPC.

func (*Conn) RemoveSession

func (c *Conn) RemoveSession(session *Session)

RemoveSession removes a session registered in a Conn.

func (*Conn) RemoveSessionByIMSI added in v0.6.1

func (c *Conn) RemoveSessionByIMSI(imsi string)

RemoveSessionByIMSI removes a session looked up by IMSI.

Use RemoveSession instead if you already have the Session in your hand.

func (*Conn) RespondTo

func (c *Conn) RespondTo(raddr net.Addr, received, toBeSent messages.Message) error

RespondTo sends a message(specified with "toBeSent" param) in response to a message (specified with "received" param).

This exists to make it easier to handle SequenceNumber.

func (*Conn) SendMessageTo added in v0.3.1

func (c *Conn) SendMessageTo(msg messages.Message, addr net.Addr) (uint32, error)

SendMessageTo sends a message to addr. Unlike WriteTo, it sets the Sequence Number properly and returns the one used in the message.

func (*Conn) SequenceNumber added in v0.3.1

func (c *Conn) SequenceNumber() uint32

SequenceNumber returns the current(=last used) SequenceNumber associated with Conn.

func (*Conn) SessionCount added in v0.2.0

func (c *Conn) SessionCount() int

SessionCount returns the number of sessions registered in Conn.

This may have some impact on performance in case of large number of Session exists.

func (*Conn) Sessions

func (c *Conn) Sessions() []*Session

Bearers returns all the bearers registered in Session.

func (*Conn) SetDeadline

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

SetDeadline sets the read and write deadlines associated with the connection. It is equivalent to calling both SetReadDeadline and SetWriteDeadline.

A deadline is an absolute time after which I/O operations fail with a timeout (see type Error) instead of blocking. The deadline applies to all future and pending I/O, not just the immediately following call to Read or Write. After a deadline has been exceeded, the connection can be refreshed by setting a deadline in the future.

An idle timeout can be implemented by repeatedly extending the deadline after successful Read or Write calls.

A zero value for t means I/O operations will not time out.

func (*Conn) SetReadDeadline

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

SetReadDeadline sets the deadline for future Read calls and any currently-blocked Read call. A zero value for t means Read will not time out.

func (*Conn) SetWriteDeadline

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

SetWriteDeadline sets the deadline for future Write calls and any currently-blocked Write call. Even if write times out, it may return n > 0, indicating that some of the data was successfully written. A zero value for t means Write will not time out.

func (*Conn) VersionNotSupportedIndication

func (c *Conn) VersionNotSupportedIndication(raddr net.Addr, req messages.Message) error

VersionNotSupportedIndication sends VersionNotSupportedIndication message in response to any kind of message.Message.

func (*Conn) WriteTo

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

WriteTo writes a packet with payload p to addr. WriteTo can be made to time out and return an Error with Timeout() == true after a fixed time limit; see SetDeadline and SetWriteDeadline. On packet-oriented connections, write timeouts are rare.

type HandlerFunc

type HandlerFunc func(c *Conn, senderAddr net.Addr, msg messages.Message) error

HandlerFunc is a handler for specific GTPv2-C message.

type HandlerNotFoundError added in v0.6.0

type HandlerNotFoundError struct {
	MsgType string
}

HandlerNotFoundError indicates that the handler func is not registered in *Conn for the incoming GTPv2 message. In usual cases this error should not be taken as fatal, as the other endpoint can make your program stop working just by sending unregistered messages.

func (*HandlerNotFoundError) Error added in v0.6.0

func (e *HandlerNotFoundError) Error() string

x Error returns violating message type to handle.

type InvalidSequenceError added in v0.6.0

type InvalidSequenceError struct {
	Seq uint32
}

InvalidSequenceError indicates that the Sequence Number is invalid.

func (*InvalidSequenceError) Error added in v0.6.0

func (e *InvalidSequenceError) Error() string

x Error returns violating Sequence Number.

type InvalidSessionError added in v0.6.0

type InvalidSessionError struct {
	IMSI string
}

InvalidSessionError indicates that something went wrong with Session.

func (*InvalidSessionError) Error added in v0.6.0

func (e *InvalidSessionError) Error() string

x Error returns message with IMSI associated with Session if available.

type InvalidTEIDError added in v0.6.0

type InvalidTEIDError struct {
	TEID uint32
}

InvalidTEIDError indicates that the TEID value is different from expected one or not registered in TEIDMap.

func (*InvalidTEIDError) Error added in v0.6.0

func (e *InvalidTEIDError) Error() string

x Error returns violating TEID.

type InvalidVersionError added in v0.6.0

type InvalidVersionError struct {
	Version int
}

InvalidVersionError indicates that the version of the message specified by the user is not acceptable for the receiver.

func (*InvalidVersionError) Error added in v0.6.0

func (e *InvalidVersionError) Error() string

x Error returns violationg version.

type Location

type Location struct {
	MCC, MNC               string
	RATType                uint8
	LAC, CI, SAI, RAI, TAI uint16
	ECI, MeNBI, EMeNBI     uint32
}

Location is a subscriber's location.

type QoSProfile

type QoSProfile struct {
	PCI, PVI bool
	PL, QCI  uint8
	// Max bit rate for Uplink and Donwlink
	MBRUL, MBRDL uint64
	// Guaranteed bit rate for Uplink and Donwlink
	GBRUL, GBRDL uint64
}

QoSProfile represents a QoS-related information that belongs to a Bearer.

type RequiredIEMissingError added in v0.6.0

type RequiredIEMissingError struct {
	Type uint8
}

RequiredIEMissingError indicates that the IE required is missing.

func (*RequiredIEMissingError) Error added in v0.6.0

func (e *RequiredIEMissingError) Error() string

x Error returns error with missing IE type.

type RequiredParameterMissingError added in v0.6.0

type RequiredParameterMissingError struct {
	Name, Msg string
}

RequiredParameterMissingError indicates that no Bearer found by lookup methods.

func (*RequiredParameterMissingError) Error added in v0.6.0

x Error returns missing parameter with message.

type Session

type Session struct {

	// Subscriber is a Subscriber associated with Session.
	*Subscriber
	// contains filtered or unexported fields
}

Session is a GTPv2 Session.

func NewSession

func NewSession(peerAddr net.Addr, sub *Subscriber) *Session

NewSession creates a new Session with subscriber information.

This is expected to be used by server-like nodes. Otherwise, use CreateSession(), which sends Create Session Request and returns a new Session.

func (*Session) Activate

func (s *Session) Activate() error

Activate marks a Session active.

func (*Session) AddBearer

func (s *Session) AddBearer(name string, br *Bearer)

AddBearer adds a Bearer to Session with arbitrary name given.

In the single-bearer environment it is not used, as a bearer named "default" is always available after created a Session.

func (*Session) AddTEID

func (s *Session) AddTEID(ifType uint8, teid uint32)

AddTEID adds TEID to session with InterfaceType.

This is used to keep TEIDs of any interface types that may be used later, including the ones that are assigned to U-Plane.

For incoming TEID of local interface type, (*Conn).RegisterSession does that instead of users but it is safe to call it.

func (*Session) BearerCount added in v0.2.0

func (s *Session) BearerCount() int

BearerCount returns the number of bearers registered in Session.

func (*Session) Bearers added in v0.4.0

func (s *Session) Bearers() []*Bearer

Bearers returns all the bearers registered in Session.

func (*Session) Deactivate

func (s *Session) Deactivate() error

Deactivate marks a Session inactive.

func (*Session) GetDefaultBearer

func (s *Session) GetDefaultBearer() *Bearer

GetDefaultBearer returns the default bearer.

func (*Session) GetTEID

func (s *Session) GetTEID(ifType uint8) (uint32, error)

GetTEID returns TEID associated with InterfaceType given.

func (*Session) IsActive

func (s *Session) IsActive() bool

IsActive reports whether a Session is active or not.

func (*Session) LookupBearerByEBI

func (s *Session) LookupBearerByEBI(ebi uint8) (*Bearer, error)

LookupBearerByEBI looks up Bearer registered in Session by EBI.

func (*Session) LookupBearerByName

func (s *Session) LookupBearerByName(name string) (*Bearer, error)

LookupBearerByName looks up Bearer registered in Session by name.

func (*Session) LookupBearerNameByEBI added in v0.2.0

func (s *Session) LookupBearerNameByEBI(ebi uint8) (string, error)

LookupBearerNameByEBI looks up name of Bearer by EBI and returns its name.

func (*Session) LookupEBIByName

func (s *Session) LookupEBIByName(name string) uint8

LookupEBIByName returns EBI associated with name.

If no EBI found, it returns 0(=invalid value for EBI).

func (*Session) LookupEBIByTEID

func (s *Session) LookupEBIByTEID(teid uint32) uint8

LookupEBIByTEID returns EBI associated with TEID.

If no EBI found, it returns 0(=invalid value for EBI).

func (*Session) PeerAddr

func (s *Session) PeerAddr() net.Addr

PeerAddr returns the address of the peer node associated with Session.

func (*Session) RemoveBearer

func (s *Session) RemoveBearer(name string)

RemoveBearer removes a Bearer looked up by name.

func (*Session) RemoveBearerByEBI added in v0.2.0

func (s *Session) RemoveBearerByEBI(ebi uint8)

RemoveBearerByEBI removes a Bearer looked up by name.

func (*Session) SetDefaultBearer

func (s *Session) SetDefaultBearer(bearer *Bearer)

SetDefaultBearer sets given bearer as the default bearer.

func (*Session) UpdatePeerAddr added in v0.6.1

func (s *Session) UpdatePeerAddr(peer net.Addr)

UpdatePeerAddr updates the address of the peer node associated with Session.

func (*Session) WaitMessage

func (s *Session) WaitMessage(seq uint32, timeout time.Duration) (messages.Message, error)

WaitMessage waits for a message to come from other Session.

It waits for certain period of time specified by timeout, and returns the message if seq matches the SequenceNumber of message. Otherwise it returns error immediately.

type Subscriber

type Subscriber struct {
	IMSI, MSISDN, IMEI string
	*Location
}

Subscriber is a subscriber that belongs to a GTPv2 session.

type UnexpectedIEError added in v0.6.0

type UnexpectedIEError struct {
	IEType uint8
}

UnexpectedIEError indicates that the type of incoming message is not expected.

func (*UnexpectedIEError) Error added in v0.6.0

func (e *UnexpectedIEError) Error() string

x Error returns violating message type.

type UnexpectedTypeError added in v0.6.0

type UnexpectedTypeError struct {
	Msg messages.Message
}

UnexpectedTypeError indicates that the type of incoming message is not expected.

func (*UnexpectedTypeError) Error added in v0.6.0

func (e *UnexpectedTypeError) Error() string

x Error returns violating message type.

type UnknownAPNError added in v0.6.0

type UnknownAPNError struct {
	APN string
}

UnknownAPNError indicates that the APN is different from expected one.

func (*UnknownAPNError) Error added in v0.6.0

func (e *UnknownAPNError) Error() string

x Error returns violating APN.

type UnknownIMSIError added in v0.6.0

type UnknownIMSIError struct {
	IMSI string
}

UnknownIMSIError indicates that the IMSI is different from expected one.

func (*UnknownIMSIError) Error added in v0.6.0

func (e *UnknownIMSIError) Error() string

x Error returns violating IMSI.

Directories

Path Synopsis
Package ies provides encoding/decoding feature of GTPv2 Information Elements.
Package ies provides encoding/decoding feature of GTPv2 Information Elements.
Package messages provides encoding/decoding feature of GTPv2 protocol.
Package messages provides encoding/decoding feature of GTPv2 protocol.
Package testutils is an internal package to be used for unit tests.
Package testutils is an internal package to be used for unit tests.

Jump to

Keyboard shortcuts

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