gtpv1

package
v0.8.10 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2024 License: MIT Imports: 18 Imported by: 9

README

v1: GTPv1 in Golang

Package v1 provides simple and painless handling of GTPv1-C and GTPv1-U protocols in pure Golang.

Getting Started

This package is still under construction. The networking feature is only available for GTPv1-U. GTPv1-C feature would be available in the future.
See message and ie directory for what you can do with the current implementation.

Creating a PDP Context as a client

NOT IMPLEMENTED YET!

Waiting for a PDP Context to be created as a server

NOT IMPLEMENTED YET!

Opening a U-Plane connection

Retrieve UPlaneConn first, using DialUPlane (for client) or NewUPlaneConn (for server).

Client

DialUPlane sends Echo Request and returns UPlaneConn if it succeeds. If you don't need Echo, see Server section. As GTP is UDP-based connection, and there are no session management on UPlaneConn, the behavior of Dial and ListenAndServe is not quite different.

uConn, err := v1.Dial(ctx, laddr, raddr)
if err != nil {
	// ...
}
defer uConn.Close()
Server

Retrieve UPlaneConn with NewUPlaneConn, and ListenAndServe to start listening.

uConn := v1.NewUPlaneConn(laddr)
if err != nil {
	// ...
}
defer uConn.Close()

// This blocks, and returns an error when it's fatal.
if err := uConn.ListenAndServe(ctx); err != nil {
	// ...
}
Manupulating UPlaneConn

With UPlaneConn, you can add and delete tunnels, and manipulate device directly.

Using Linux Kernel GTP-U

Linux Kernel GTP-U is quite performant and easy to handle, but it requires root privilege, and of course it works only on Linux. So it is disabled by default. To get started, enable it first. Note that it cannot be disabled while the program is working.

if err := uConn.EnableKernelGTP("gtp0", v1.roleSGSN); err != nil {
	// ...
}

Then, when the bearer information is ready, use AddTunnel or AddTunnelOverride to add a tunnel.
The latter one deletes the existing tunnel with the same IP and/or incoming TEID before creating a tunnel, while the former fails if there's any duplication.

// add a tunnel by giving GTP peer's IP, subscriber's IP,
if err := uConn.AddTunnelOverride(
	net.ParseIP("10.10.10.10"), // GTP peer's IP
	net.ParseIP("1.1.1.1"),     // subscriber's IP
	0x55667788,                 // outgoing TEID
	0x11223344,                 // incoming TEID
); err != nil {
	// ...
}

When the tunnel is no longer necessary, use DelTunnelByITEI or DelTunnelByMSAddress to delete it.
Or, by Close-ing the UPlaneConn, all the tunnels associated will the cleared.

// delete a tunnel by giving an incoming TEID.
if err := uConn.DelTunnelByITEI(0x11223344); err != nil {
	// ...
}

// delete a tunnel by giving an IP address assigned to a subscriber.
if err := uConn.DelTunnelByMSAddress(net.ParseIP("1.1.1.1")); err != nil {
	// ...
}

The packets NOT forwarded by the Kernel can be handled automatically by giving a handler to UPlaneConn.
Handlers for T-PDU, Echo Request/Response, and Error Indication are registered by default, but you can override them using AddHandler.

uConn.AddHandler(message.MsgTypeEchoRequest, func(c v1.Conn, senderAddr net.Addr, msg message.Message) error {
	// do anything you want for Echo Request here.
	// errors returned here are passed to `errCh` that is given to UPlaneConn at the beginning.
	return nil
})

If the tunnel with appropriate IP or TEID is not found for a T-PDU packet, Kernel sends it to userland. You can manipulate it with ReadFromGTP.

buf := make([]byte, 1500)

// the 3rd returned value is TEID in GTPv1-U Header.
n, raddr, teid, err := uConn.ReadFromGTP(buf)
if err != nil {
	// ...
}

fmt.Printf("%x", buf[:n]) // prints only the payload, no GTP header included.

Also, you can send any payload by using WriteToGTP. It writes the given payload with GTP header to the specified addr over UPlaneConn.

// first return value is the number of bytes written.
if _, err := uConn.WriteToGTP(teid, payload, addr); err != nil {
	// ...
}
Using userland GTP-U

Note: package v1 does provide the encapsulation/decapsulation and some networking features, but it does NOT provide routing of the decapsulated packets, nor capturing IP layer and above on the specified interface. This is because such kind of operations cannot be done without platform-specific codes.

You can use to ReadFromGTP read the packets coming into uConn. This does not work for the packets which are handled by RelayTo.

buf := make([]byte, 1500)
n, raddr, teid, err := uConn.ReadFromGTP(buf)
if err != nil {
	// ...
}

fmt.Printf("%x", buf[:n]) // prints the payload encapsulated in the GTP header.

Also, you can send any payload by using WriteToGTP. It writes the given payload with GTP header to the specified addr over UPlaneConn.

// first return value is the number of bytes written.
if _, err := uConn.WriteToGTP(teid, payload, addr); err != nil {
	// ...
}

Especially or SGSN/S-GW-ish nodes(=have multiple GTP tunnels and its raison d'être is just to forward traffic right to left/left to right) we provide a method to swap TEID and forward T-PDU packets automatically and efficiently.
By using RelayTo, the UPlaneConn automatically handles the T-PDU packet in background with the least cost. Note that it's performed on the userland and thus it's not so performant.

// this is the example for S-GW that completed establishing a session and ready to forward U-Plane packets.
s1uConn.RelayTo(s5uConn, s1usgwTEID, s5uBearer.OutgoingTEID, s5uBearer.RemoteAddress)
s5uConn.RelayTo(s1uConn, s5usgwTEID, s1uBearer.OutgoingTEID, s1uBearer.RemoteAddress)
Handling Extension Headers

AddExtensionHeaders adds ExtensionHeader(s) to the Header of a Message, set the E flag, and checks if the types given are consistent (error will be returned if not).

msg := message.NewTPDU(0x11223344, []byte{0xde, 0xad, 0xbe, 0xef})
if err := msg.AddExtensionHeaders(
	// We don't support construction of the specific type of an ExtensionHeader.
	// The second parameter should be the serialized bytes of contents.
	message.NewExtensionHeader(
		message.ExtHeaderTypeUDPPort,
		[]byte{0x22, 0xb8},
		message.ExtHeaderTypePDUSessionContainer,
	),
	message.NewExtensionHeader(
		message.ExtHeaderTypePDUSessionContainer,
		[]byte{0x00, 0xc2},
		message.ExtHeaderTypeNoMoreExtensionHeaders,
	),
); err != nil {
	// ...
}

ExtensionHeaders decoded or added are stored in ExtensionHeaders field in the Header, which can be accessed like this.

// no need to write msg.Header.ExtensionHeaders, as the Header is embedded in messages.
for _, eh := range msg.ExtensionHeaders {
	log.Println(eh.Type)     // ExtensionHeader type has its own Type while it's not actually included in a packet. 
	log.Println(eh.Content)  // We do not support decoding of each type of content yet. Decode them on your own.
	log.Println(eh.NextType) // Don't sort the slice - it ruins the packet, or even cause a panic.
}

When you are directly manipulating a Header for some reason, WithExtensionHeaders would help you simplify your operation. Be sure not to call it on a Message, as it returns *Header, not a Message interface.

header := message.NewHeader(
	0x30, // no need to set E flag here - With... method will do that instead.
	message.MsgTypeEchoRequest,
	0xdeadbeef,
	0x00,
	[]byte{0xde, 0xad, 0xbe, 0xef},
).WithExtensionHeaders(
	message.NewExtensionHeader(
		message.ExtHeaderTypeUDPPort,
		[]byte{0x22, 0xb8},
		message.ExtHeaderTypePDUSessionContainer,
	),
	message.NewExtensionHeader(
		message.ExtHeaderTypePDUSessionContainer,
		[]byte{0x00, 0xc2},
		message.ExtHeaderTypeNoMoreExtensionHeaders,
	),
)

Supported Features

Messages

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 message.NewGeneric.

ID Name Supported
0 (Spare/Reserved) -
1 Echo Request Yes
2 Echo Response Yes
3 Version Not Supported Yes
4 Node Alive Request
5 Node Alive Response
6 Redirection Request
7 Redirection Response
8-15 (Spare/Reserved) -
16 Create PDP Context Request Yes
17 Create PDP Context Response Yes
18 Update PDP Context Request Yes
19 Update PDP Context Response Yes
20 Delete PDP Context Request Yes
21 Delete PDP Context Response Yes
22 Initiate PDP Context Activation Request
23 Initiate PDP Context Activation Response
24-25 (Spare/Reserved) -
26 Error Indication Yes
27 PDU Notification Request
28 PDU Notification Response
29 PDU Notification Reject Request
30 PDU Notification Reject Response
31 Supported Extension Headers Notification Yes
32 Send Routeing Information for GPRS Request
33 Send Routeing Information for GPRS Response
34 Failure Report Request
35 Failure Report Response
36 Note MS GPRS Present Request
37 Note MS GPRS Present Response
38-47 (Spare/Reserved) -
48 Identification Request
49 Identification Response
50 SGSN Context Request
51 SGSN Context Response
52 SGSN Context Acknowledge
53 Forward Relocation Request
54 Forward Relocation Response
55 Forward Relocation Complete
56 Relocation Cancel Request
57 Relocation Cancel Response
58 Forward SRNS Context
59 Forward Relocation Complete Acknowledge
60 Forward SRNS Context Acknowledge
61 UE Registration Query Request
62 UE Registration Query Response
63-69 (Spare/Reserved) -
70 RAN Information Relay
71-95 (Spare/Reserved) -
96 MBMS Notification Request
97 MBMS Notification Response
98 MBMS Notification Reject Request
99 MBMS Notification Reject Response
100 Create MBMS Context Request
101 Create MBMS Context Response
102 Update MBMS Context Request
103 Update MBMS Context Response
104 Delete MBMS Context Request
105 Delete MBMS Context Response
106 - 111 (Spare/Reserved) -
112 MBMS Registration Request
113 MBMS Registration Response
114 MBMS De-Registration Request
115 MBMS De-Registration Response
116 MBMS Session Start Request
117 MBMS Session Start Response
118 MBMS Session Stop Request
119 MBMS Session Stop Response
120 MBMS Session Update Request
121 MBMS Session Update Response
122-127 (Spare/Reserved) -
128 MS Info Change Notification Request
129 MS Info Change Notification Response
130-239 (Spare/Reserved) -
240 Data Record Transfer Request
241 Data Record Transfer Response
242-253 (Spare/Reserved) -
254 End Marker
255 G-PDU Yes
Information Elements

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

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

ID Name Supported
0 (Spare/Reserved) -
1 Cause Yes
2 IMSI Yes
3 Routeing Area Identity Yes
4 Temporary Logical Link Identity
5 Packet TMSI Yes
6 (Spare/Reserved) -
7 (Spare/Reserved) -
8 Reordering Required Yes
9 Authentication Triplet Yes
10 (Spare/Reserved) -
11 MAP Cause Yes
12 P-TMSI Signature Yes
13 MS Validated Yes
14 Recovery Yes
15 Selection Mode Yes
16 TEID Data I Yes
17 TEID C-Plane Yes
18 TEID Data II Yes
19 Teardown Indication Yes
20 NSAPI Yes
21 RANAP Cause Yes
22 RAB Context
23 Radio Priority SMS
24 Radio Priority
25 Packet Flow ID
26 Charging Characteristics
27 Trace Reference
28 Trace Type
29 MS Not Reachable Reason
30-126 (Spare/Reserved) -
127 Charging ID Yes
128 End User Address Yes
129 MM Context
130 PDP Context
131 Access Point Name Yes
132 Protocol Configuration Options Yes
133 GSN Address Yes
134 MSISDN Yes
135 QoS Profile
136 Authentication Quintuplet Yes
137 Traffic Flow Template
138 Target Identification
139 UTRAN Transparent Container
140 RAB Setup Information
141 Extension Header Type List Yes
142 Trigger Id
143 OMC Identity
144 RAN Transparent Container
145 PDP Context Prioritization
146 Additional RAB Setup Information
147 SGSN Number
148 Common Flags Yes
149 APN Restriction Yes
150 Radio Priority LCS
151 RAT Type Yes
152 User Location Information Yes
153 MS Time Zone Yes
154 IMEISV Yes
155 CAMEL Charging Information Container
156 MBMS UE Context
157 Temporary Mobile Group Identity
158 RIM Routing Address
159 MBMS Protocol Configuration Options
160 MBMS Service Area
161 Source RNC PDCP Context Info
162 Additional Trace Info
163 Hop Counter
164 Selected PLMN Id
165 MBMS Session Identifier
166 MBMS 2G/3G Indicator
167 Enhanced NSAPI
168 MBMS Session Duration
169 Additional MBMS Trace Info
170 MBMS Session Repetition Number
171 MBMS Time To Data Transfer
172 (Spare/Reserved) -
173 BSS Container
174 Cell Identification
175 PDU Numbers
176 BSS GP Cause
177 Required MBMS Bearer Capabilities
178 RIM Routing Address Discriminator
179 List of Setup PFCs
180 PS Handover XID Parameters
181 MS Info Change Reporting Action
182 Direct Tunnel Flags
183 Correlation Id
184 Bearer Control Mode
185 MBMS Flow Identifier
186 MBMS IP Multicast Distribution
187 MBMS Distribution Acknowledgement
188 Reliable InterRAT Handover Info
189 RFSP Index
190 Fully Qualified Domain Name
191 Evolved Allocation Retention Priority I
192 Evolved Allocation Retention Priority II
193 Extended Common Flags Yes
194 User CSG Information
195 CSG Information Reporting Action
196 CSG ID
197 CSG Membership Indication
198 Aggregate Maximum Bit Rate
199 UE Network Capability
200 UE-AMBR
201 APN-AMBR with NSAPI
202 GGSN Back-Off Time
203 Signalling Priority Indication
204 Signalling Priority Indication with NSAPI
205 Higher Bitrates than 16Mbps Flag
206 (Spare/Reserved) -
207 Additional MM Context for SRVCC
208 Additional Flags for SRVCC
209 STN-SR
210 C-MSISDN
211 Extended RANAP Cause
212 eNodeB ID
213 Selection Mode with NSAPI
214 ULI Timestamp Yes
215 LHN Id with NSAPI
216 CN Operator Selection Entity
217 UE Usage Type
218 Extended Common Flags II Yes
219 Node Identifier
220 CIoT Optimizations Support Indication
221 SCEF PDN Connection
222 IOV Updates Counter
223-237 (Spare/Reserved) -
238 Special IE Type for IE Type Extension
239-250 (Spare/Reserved) -
251 Charging Gateway Address
252-254 (Spare/Reserved) -
255 Private Extension

Documentation

Overview

Package gtpv1 provides simple and painless handling of GTPv1-C and GTPv1-U 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/gtpv1/README.md

Index

Constants

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

Registered UDP ports

View Source
const (
	ReqCauseRequestIMSI uint8 = iota
	ReqCauseRequestIMEI
	ReqCauseRequestIMSIAndIMEI
	ReqCauseNoIdentityNeeded
	ReqCauseMSRefuses
	ReqCauseMSIsNotGPRSResponding
	ReqCauseReactivationRequested
	ReqCausePDPAddressInactivityTimerExpires
	ReqCauseNetworkFailure
	ReqCauseQoSParameterMismatch
)

Cause definitions.

View Source
const (
	ResCauseRequestAccepted uint8 = iota + 128
	ResCauseNewPDPTypeDueToNetworkPreference
	ResCauseNewPDPTypeDueToSingleAddressBearerOnly
)

Cause definitions.

View Source
const (
	ResCauseNonExistent uint8 = iota + 192
	ResCauseInvalidMessageFormat
	ResCauseIMSIIMEINotKnown
	ResCauseMSIsGPRSDetached
	ResCauseMSIsNotGPRSResponding
	ResCauseMSRefuses
	ResCauseVersionNotSupported
	ResCauseNoResourcesAvailable
	ResCauseServiceNotSupported
	ResCauseMandatoryIEIncorrect
	ResCauseMandatoryIEMissing
	ResCauseOptionalIEIncorrect
	ResCauseSystemFailure
	ResCauseRoamingRestriction
	ResCausePTMSISignatureMismatch
	ResCauseGPRSConnectionSuspended
	ResCauseAuthenticationFailure
	ResCauseUserAuthenticationFailed
	ResCauseContextNotFound
	ResCauseAllDynamicPDPAddressesAreOccupied
	ResCauseNoMemoryIsAvailable
	ResCauseRelocationFailure
	ResCauseUnknownMandatoryExtensionHeader
	ResCauseSemanticErrorInTheTFTOperation
	ResCauseSyntacticErrorInTheTFTOperation
	ResCauseSemanticErrorsInPacketFilter
	ResCauseSyntacticErrorsInPacketFilter
	ResCauseMissingOrUnknownAPN
	ResCauseUnknownPDPAddressOrPDPType
	ResCausePDPContextWithoutTFTAlreadyActivated
	ResCauseAPNAccessDeniedNoSubscription
	ResCauseAPNRestrictionTypeIncompatibilityWithCurrentlyActivePDPContexts
	ResCauseMSMBMSCapabilitiesInsufficient
	ResCauseInvalidCorrelationID
	ResCauseMBMSBearerContextSuperseded
	ResCauseBearerControlModeViolation
	ResCauseCollisionWithNetworkInitiatedRequest
	ResCauseAPNCongestion
	ResCauseBearerHandlingNotSupported
	ResCauseTargetAccessRestrictedForTheSubscriber
	ResCauseUEIsTemporarilyNotReachableDueToPowerSaving
	ResCauseRelocationFailureDueToNASMessageRedirection
)

Cause definitions.

View Source
const (
	SelectionModeMSorNetworkProvidedAPNSubscribedVerified uint8 = iota | 0xf0
	SelectionModeMSProvidedAPNSubscriptionNotVerified
	SelectionModeNetworkProvidedAPNSubscriptionNotVerified
)

SelectionMode definitions.

View Source
const (
	PDPTypeETSI uint8 = iota | 0xf0
	PDPTypeIETF
)

PDP Type Organization 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 (
	RatTypeUTRAN uint8
	RatTypeGERAN
	RatTypeWLAN
	RatTypeGAN
	RatTypeHSPAEvolution
	RatTypeEUTRAN
)

RATType definitions.

View Source
const (
	LocTypeCGI uint8 = iota
	LocTypeSAI
	LocTypeRAI
)

UserLocationInformation GeographicLocationType definitions.

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

APN Restriction definitions.

View Source
const (
	MAPCauseUnknownSubscriber uint8
	MAPCauseUnknownBaseStation
	MAPCauseUnknownMSC
	MAPCauseSecureTransportError
	MAPCauseUnidentifiedSubscriber
	MAPCauseAbsentSubscriberSM
	MAPCauseUnknownEquipment
	MAPCauseRoamingNotAllowed
	MAPCauseIllegalSubscriber
	MAPCauseBearerServiceNotProvisioned
	MAPCauseTeleserviceNotProvisioned
	MAPCauseIllegalEquipment
	MAPCauseCallBarred
	MAPCauseForwardingViolation
	MAPCauseCUGReject
	MAPCauseIllegalSSOperation
	MAPCauseSSErrorStatus
	MAPCauseSSNotAvailable
	MAPCauseSSSubscriptionViolatio
	MAPCauseSSIncompatibility
	MAPCauseFacilityNotSupported
	MAPCauseOngoingGroupCall
	MAPCauseInvalidTargetBaseStation
	MAPCauseNoRadioResourceAvailable
	MAPCauseNoHandoverNumberAvailable
	MAPCauseSubsequentHandoverFailure
	MAPCauseAbsentSubscriber
	MAPCauseIncompatibleTerminal
	MAPCauseShortTermDenial
	MAPCauseLongTermDenial
	MAPCauseSubscriberBusyForMTSMS
	MAPCauseSMDeliveryFailure
	MAPCauseMessageWaitingListFull
	MAPCauseSystemFailure
	MAPCauseDataMissing
	MAPCauseUnexpectedDataValue
	MAPCausePWRegistrationFailure
	MAPCauseNegativePWCheck
	MAPCauseNoRoamingNumberAvailable
	MAPCauseTracingBufferFull

	MAPCauseTargetCellOutsideGroupCallArea
	MAPCauseNumberOfPWAttemptsViolation
	MAPCauseNumberChanged
	MAPCauseBusySubscriber
	MAPCauseNoSubscriberReply
	MAPCauseForwardingFailed
	MAPCauseORNotAllowed
	MAPCauseATINotAllowed
	MAPCauseNoGroupCallNumberAvailable
	MAPCauseResourceLimitation
	MAPCauseUnauthorizedRequestingNetwork
	MAPCauseUnauthorizedLCSClient
	MAPCausePositionMethodFailure

	MAPCauseUnknownOrUnreachableLCSClient
	MAPCauseMMEventNotSupported
	MAPCauseATSINotAllowed
	MAPCauseATMNotAllowed
	MAPCauseInformationNotAvailabl

	MAPCauseUnknownAlphabe
	MAPCauseUSSDBusy
)

MAP Cause definitions.

View Source
const (
	RABPreempted uint8
	RANAPCauseTrelocoverallExpiry
	RANAPCauseTrelocprepExpiry
	RANAPCauseTreloccompleteExpiry
	RANAPCauseTqueuingExpiry
	RANAPCauseRelocationTriggered
	RANAPCauseTRELOCallocExpiry
	RANAPCauseUnableToEstablishDuringRelocation
	RANAPCauseUnknownTargetRNC
	RANAPCauseRelocationCancelled
	RANAPCauseSuccessfulRelocation
	RANAPCauseRequestedCipheringIntegrityProtectionAlgorithmsNotSupported
	RANAPCauseChangeOfCipheringIntegrityProtectionIsNotSupported
	RANAPCauseFailureInTheRadioInterfaceProcedure
	RANAPCauseReleaseDueToUTRANGeneratedReason
	RANAPCauseUserInactivity
	RANAPCauseTimeCriticalRelocation
	RANAPCauseRequestedTrafficClassNotAvailable
	RANAPCauseInvalidRABParametersValue
	RANAPCauseRequestedMaximumBitRateNotAvailable
	RANAPCauseRequestedGuaranteedBitRateNotAvailable
	RANAPCauseRequestedTransferDelayNotAchievable
	RANAPCauseInvalidRABParametersCombination
	RANAPCauseConditionViolationForSDUParameters
	RANAPCauseConditionViolationForTrafficHandlingPriority
	RANAPCauseConditionViolationForGuaranteedBitRate
	RANAPCauseUserPlaneVersionsNotSupported
	RANAPCauseIuUPFailure
	RANAPCauseRelocationFailureInTargetCNRNCOrTargetSystem
	RANAPCauseInvalidRABID
	RANAPCauseNoRemainingRAB
	RANAPCauseInteractionWithOtherProcedure
	RANAPCauseRequestedMaximumBitRateForDLNotAvailable
	RANAPCauseRequestedMaximumBitRateForULNotAvailable
	RANAPCauseRequestedGuaranteedBitRateForDLNotAvailable
	RANAPCauseRequestedGuaranteedBitRateForULNotAvailable
	RANAPCauseRepeatedIntegrityCheckingFailure
	RANAPCauseRequestedReportTypeNotSupported
	RANAPCauseRequestSuperseded
	RANAPCauseReleaseDueToUEWenRatedSignallingConnectionRelease
	RANAPCauseResourceOptimisationRelocation
	RANAPCauseRequestedInformationNotAvailable
	RANAPCauseRelocationDesirableForRadioReasons
	RANAPCauseRelocationNotSupportedInTargetRNCOrTargetSystem
	RANAPCauseDirectedRetry
	RANAPCauseRadioConnectionWithUELost
	RANAPCauseRNCUnableToEstablishAllRFCs
	RANAPCauseDecipheringKeysNotAvailable
	RANAPCauseDedicatedAssistanceDataNotAvailable
	RANAPCauseRelocationTargetNotAllowed
	RANAPCauseLocationReportingCongestion
	RANAPCauseReduceLoadInServingCell
	RANAPCauseNoRadioResourcesAvailableInTargetCell
	RANAPCauseGERANIuModeFailure
	RANAPCauseAccessRestrictedDueToSharedNetworks
	RANAPCauseIncomingRelocationNotSupportedDueTodPUESBINEFeature
	RANAPCauseTrafficLoadInTheTargetCellHigherThanInTheSourceCell
	RANAPCauseMBMSNoMulticastServiceForThisUE
	RANAPCauseMBMSUnknownUEID
	RANAPCauseSuccessfulMBMSSessionStartNoDataBearerNecessary
	RANAPCauseMBMSSupersededDueToNNSF
	RANAPCauseMBMSUELinkingAlreadyDone
	RANAPCauseMBMSUEDeLinkingFailureNoExistingUELinking
	RANAPCauseTMGIUnknown
	RANAPCauseSignallingTransportResourceFailure
	RANAPCauseIuTransportConnectionFailedToEstablish

	RANAPCauseUserRestrictionStartIndication
	RANAPCauseUserRestrictionEndIndication
	RANAPCauseNormalRelease

	RANAPCauseTransferSyntaxError
	RANAPCauseSemanticError
	RANAPCauseMessageNotCompatibleWithReceiverState
	RANAPCauseAbstractSyntaxErrorReject
	RANAPCauseAbstractSyntaxErrorIgnoreAndNotify
	RANAPCauseAbstractSyntaxErrorFalselyConstructedMessage

	RANAPCauseOAMIntervention
	RANAPCauseNoResourceAvailable
	RANAPCauseUnspecifiedFailure
	RANAPCauseNetworkOptimisation
)

RANAP Cause definitions.

View Source
const (
	ConfigProtocolPPPWithIP uint8 = 0
)

Configuration Protocol definitions.

Variables

View Source
var (
	// ErrUnexpectedType indicates that the type of incoming message is not expected.
	ErrUnexpectedType = errors.New("got unexpected type of message")

	// ErrInvalidConnection indicates that the connection type(C-Plane or U-Plane) is
	// not the expected one.
	ErrInvalidConnection = errors.New("got invalid connection type")

	// ErrConnNotOpened indicates that some operation is failed due to the status of
	// Conn is not valid.
	ErrConnNotOpened = errors.New("connection is not opened")
)

Functions

func Decapsulate

func Decapsulate(b []byte) (uint32, []byte, error)

Decapsulate decapsulates given bytes and returns TEID and Payload.

func DecapsulateWithExtensionHeader added in v0.8.8

func DecapsulateWithExtensionHeader(b []byte) (uint32, []byte, []*message.ExtensionHeader, error)

DecapsulateWithExtensionHeader decapsulates given bytes and returns TEID, Payload, and Extension Headers. It is always safe to use this even if there may be no Extension Headers.

func DisableLogging

func DisableLogging()

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

func EnableLogging

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 Encapsulate

func Encapsulate(teid uint32, payload []byte) *message.TPDU

Encapsulate encapsulates given payload with GTPv1-U Header and returns message.TPDU.

func EncapsulateWithExtensionHeader added in v0.8.8

func EncapsulateWithExtensionHeader(teid uint32, payload []byte, extHdrs ...*message.ExtensionHeader) *message.TPDU

EncapsulateWithExtensionHeader encapsulates given payload and Extension Headers with GTPv1-U Header and returns message.TPDU.

func SetLogger

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 Conn

type Conn interface {
	net.PacketConn
	AddHandler(uint8, HandlerFunc)
	RespondTo(net.Addr, message.Message, message.Message) error
	Restarts() uint8
}

Conn is an abstraction of both GTPv1-C and GTPv1-U Conn.

type ErrorIndicatedError

type ErrorIndicatedError struct {
	TEID uint32
	Peer string
}

ErrorIndicatedError indicates that Error Indication message is received on U-Plane Connection.

func (*ErrorIndicatedError) Error

func (e *ErrorIndicatedError) Error() string

type HandlerFunc

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

HandlerFunc is a handler for specific GTPv1 message.

type HandlerNotFoundError added in v0.7.11

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 message.

func (*HandlerNotFoundError) Error added in v0.7.11

func (e *HandlerNotFoundError) Error() string

Error returns violating message type to handle.

type KernelGTP added in v0.7.14

type KernelGTP struct {
	Link *netlink.GTP
	// contains filtered or unexported fields
}

KernelGTP consists of the Linux Kernel GTP-U related objects.

type Relay deprecated

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

Relay is to relay packets between two UPlaneConn.

Deprecated: Use UPlaneConn.RelayTo() instead.

func NewRelay deprecated

func NewRelay(leftConn, rightConn *UPlaneConn) *Relay

NewRelay creates a new Relay.

Deprecated: Use UPlaneConn.RelayTo() instead.

func (*Relay) AddPeer deprecated

func (r *Relay) AddPeer(teidIn, teidOut uint32, raddr net.Addr)

AddPeer adds a peer information with the TEID contained in the incoming meesage.

Deprecated: Use UPlaneConn.RelayTo() instead.

func (*Relay) Close deprecated

func (r *Relay) Close() error

Close closes Relay. It does not close the UPlaneConn given at first.

Deprecated: Use UPlaneConn.RelayTo() instead.

func (*Relay) Run deprecated

func (r *Relay) Run()

Run starts listening on both UPlaneConn. Until peer information is registered by AddPeer(), it just drops packets.

Deprecated: Use UPlaneConn.RelayTo() instead.

type Role

type Role int

Role is a role for Kernel GTP-U.

const (
	RoleGGSN Role = iota
	RoleSGSN
)

Role definitions.

type UPlaneConn

type UPlaneConn struct {

	// for Linux kernel GTP with netlink
	KernelGTP
	// contains filtered or unexported fields
}

UPlaneConn represents a U-Plane Connection of GTPv1.

func DialUPlane

func DialUPlane(ctx context.Context, laddr, raddr net.Addr) (*UPlaneConn, error)

DialUPlane sends Echo Request to raddr to check if the endpoint is alive and returns UPlaneConn.

func NewUPlaneConn

func NewUPlaneConn(laddr net.Addr) *UPlaneConn

NewUPlaneConn creates a new UPlaneConn used for server. On client side, use DialUPlane instead.

func (*UPlaneConn) AddHandler

func (u *UPlaneConn) AddHandler(msgType uint8, fn HandlerFunc)

AddHandler adds a message handler to *UPlaneConn.

By adding HandlerFuncs, *UPlaneConn (and *Session, *Bearer created by the *UPlaneConn) will handle the specified type of message with it's paired HandlerFunc when receiving. Messages without registered handlers are just ignored and discarded and the user will get ErrNoHandlersFound error.

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

HandlerFuncs for EchoResponse and ErrorIndication are registered by default. These HandlerFuncs can be overwritten by specifying message.MsgTypeEchoResponse and/or message.MsgTypeErrorIndication as msgType parameter.

func (*UPlaneConn) AddHandlers

func (u *UPlaneConn) AddHandlers(funcs map[uint8]HandlerFunc)

AddHandlers adds multiple handler funcs at a time.

See AddHandler for detailed usage.

func (*UPlaneConn) AddTunnel

func (u *UPlaneConn) AddTunnel(peerIP, msIP net.IP, otei, itei uint32) error

AddTunnel adds a GTP-U tunnel with Linux Kernel GTP-U via netlink.

func (*UPlaneConn) AddTunnelOverride

func (u *UPlaneConn) AddTunnelOverride(peerIP, msIP net.IP, otei, itei uint32) error

AddTunnelOverride adds a GTP-U tunnel with Linux Kernel GTP-U via netlink. If there is already an existing tunnel that has the same msIP and/or incoming TEID, this deletes it before adding the tunnel.

func (*UPlaneConn) Close

func (u *UPlaneConn) Close() error

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

func (*UPlaneConn) CloseRelay

func (u *UPlaneConn) CloseRelay(teidIn uint32) error

CloseRelay stops relaying T-PDU from a conn to conn.

func (*UPlaneConn) DelTunnelByITEI

func (u *UPlaneConn) DelTunnelByITEI(itei uint32) error

DelTunnelByITEI deletes a Linux Kernel GTP-U tunnel specified with the incoming TEID.

func (*UPlaneConn) DelTunnelByMSAddress

func (u *UPlaneConn) DelTunnelByMSAddress(msIP net.IP) error

DelTunnelByMSAddress deletes a Linux Kernel GTP-U tunnel specified with the subscriber's IP.

func (*UPlaneConn) DisableErrorIndication added in v0.7.7

func (u *UPlaneConn) DisableErrorIndication()

DisableErrorIndication makes default T-PDU handler stop responding with Error Indication in case of receiving T-PDU with unknown TEID.

When disabled, it passes the unhandled T-PDU to user who calls ReadFromGTP instead.

func (*UPlaneConn) EchoRequest

func (u *UPlaneConn) EchoRequest(raddr net.Addr) error

EchoRequest sends a EchoRequest.

func (*UPlaneConn) EchoResponse

func (u *UPlaneConn) EchoResponse(raddr net.Addr) error

EchoResponse sends a EchoResponse.

func (*UPlaneConn) EnableErrorIndication added in v0.7.7

func (u *UPlaneConn) EnableErrorIndication()

EnableErrorIndication re-enables automatic sending of Error Indication to unknown messages, which is enabled by default.

See also: DisableErrorIndication.

func (*UPlaneConn) EnableKernelGTP

func (u *UPlaneConn) EnableKernelGTP(devname string, role Role) error

EnableKernelGTP enables Linux Kernel GTP-U. Note that this removes all the existing userland tunnels, and cannot be disabled while the program is working (at least at this moment).

Using Kernel GTP-U is much more performant than userland, but requires root privilege. After enabled, users should add tunnels by AddTunnel func, and also add appropriate routing entries. For handling downlink traffic on P-GW, for example;

ip route add <UE's IP> dev <devname> table <table ID> ip rule add from <SGi side of I/F> lookup <table ID>

This let the traffic from SGi side of network I/F to be forwarded to GTP device, and if the UE's IP is known to Kernel GTP-U(by AddTunnel), it is encapsulated and forwarded to the peer(S-GW, in this case).

Please see the examples/gw-tester for how each node handles routing from the program.

func (*UPlaneConn) ErrorIndication

func (u *UPlaneConn) ErrorIndication(raddr net.Addr, received message.Message) error

ErrorIndication just sends ErrorIndication message.

func (*UPlaneConn) ListenAndServe

func (u *UPlaneConn) ListenAndServe(ctx context.Context) error

ListenAndServe creates a new GTPv2-C *Conn and start serving. This blocks, and returns error only if it face the fatal one. Non-fatal errors are logged with logger. See SetLogger/EnableLogger/DisableLogger for handling of those logs.

func (*UPlaneConn) LocalAddr

func (u *UPlaneConn) LocalAddr() net.Addr

LocalAddr returns the local network address.

func (*UPlaneConn) NewFTEID

func (u *UPlaneConn) NewFTEID(ifType uint8, v4, v6 string) (fteidIE *v2ie.IE)

NewFTEID creates a new GTPv2 F-TEID with random TEID value that is unique within UPlaneConn. 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 for non-local interface type, such as the ones that are used in U-Plane. For local interface, use (*Conn).NewSenderFTEID instead.

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 (*UPlaneConn) ReadFrom

func (u *UPlaneConn) 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.

Note that valid GTP-U packets handled by Kernel can NOT be retrieved by this.

func (*UPlaneConn) ReadFromGTP

func (u *UPlaneConn) ReadFromGTP(p []byte) (n int, addr net.Addr, teid uint32, err error)

ReadFromGTP reads a packet from the connection, copying the payload without GTP header into p. It returns the number of bytes copied into p, the return address that was on the packet, TEID in the GTP header.

Note that valid GTP-U packets handled by Kernel can NOT be retrieved by this.

func (*UPlaneConn) RelayTo

func (u *UPlaneConn) RelayTo(c *UPlaneConn, teidIn, teidOut uint32, raddr net.Addr) error

RelayTo relays T-PDU type of packet to peer node(specified by raddr) from the UPlaneConn given.

By using this, owner of UPlaneConn won't be able to Read and Write the packets that has teidIn.

func (*UPlaneConn) RespondTo

func (u *UPlaneConn) RespondTo(raddr net.Addr, received, toBeSent message.Message) error

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

This is to make it easier to handle SequenceNumber.

func (*UPlaneConn) Restarts

func (u *UPlaneConn) Restarts() uint8

Restarts returns the number of restarts in uint8.

func (*UPlaneConn) SetDeadline

func (u *UPlaneConn) 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 (*UPlaneConn) SetReadDeadline

func (u *UPlaneConn) 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 (*UPlaneConn) SetWriteDeadline

func (u *UPlaneConn) 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 (*UPlaneConn) WriteTo

func (u *UPlaneConn) 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.

func (*UPlaneConn) WriteToGTP

func (u *UPlaneConn) WriteToGTP(teid uint32, p []byte, addr net.Addr) (n int, err error)

WriteToGTP writes a packet with TEID and payload to addr.

func (*UPlaneConn) WriteToWithDSCPECN added in v0.8.2

func (u *UPlaneConn) WriteToWithDSCPECN(p []byte, addr net.Addr, dscpecn int) (n int, err error)

WriteToWithDSCPECN writes a packet with payload p to addr using the given DSCP/ECN value. WriteToWithDSCPECN 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.

Directories

Path Synopsis
Package ie provides encoding/decoding feature of GTPv1 Information Elements.
Package ie provides encoding/decoding feature of GTPv1 Information Elements.
Package message provides encoding/decoding feature of GTPv1 protocol.
Package message provides encoding/decoding feature of GTPv1 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