package
0.8.11
Repository: https://github.com/wmnsk/go-gtp.git
Documentation: pkg.go.dev

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

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

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.

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

# Packages

Package ie provides encoding/decoding feature of GTPv1 Information Elements.
Package message provides encoding/decoding feature of GTPv1 protocol.
Package testutils is an internal package to be used for unit tests.

# Functions

Decapsulate decapsulates given bytes and returns TEID and Payload.
DecapsulateWithExtensionHeader decapsulates given bytes and returns TEID, Payload, and Extension Headers.
DialUPlane sends Echo Request to raddr to check if the endpoint is alive and returns UPlaneConn.
DisableLogging disables the logging from the package.
EnableLogging enables the logging from the package.
Encapsulate encapsulates given payload with GTPv1-U Header and returns message.TPDU.
EncapsulateWithExtensionHeader encapsulates given payload and Extension Headers with GTPv1-U Header and returns message.TPDU.
NewRelay creates a new Relay.
NewUPlaneConn creates a new UPlaneConn used for server.
SetLogger replaces the standard logger with arbitrary *log.Logger.

# Constants

APN Restriction definitions.
APN Restriction definitions.
APN Restriction definitions.
APN Restriction definitions.
APN Restriction definitions.
Configuration Protocol definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Container ID definitions.
Registered UDP ports.
Registered UDP ports.
UserLocationInformation GeographicLocationType definitions.
UserLocationInformation GeographicLocationType definitions.
UserLocationInformation GeographicLocationType definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
MAP Cause definitions.
PDP Type Organization definitions.
PDP Type Organization definitions.
Protocol ID definitions.
Protocol ID definitions.
Protocol ID definitions.
Protocol ID definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RANAP Cause definitions.
RATType definitions.
RATType definitions.
RATType definitions.
RATType definitions.
RATType definitions.
RATType definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Cause definitions.
Role definitions.
Role definitions.
SelectionMode definitions.
SelectionMode definitions.
SelectionMode definitions.

# Variables

ErrConnNotOpened indicates that some operation is failed due to the status of Conn is not valid.
ErrInvalidConnection indicates that the connection type(C-Plane or U-Plane) is not the expected one.
ErrUnexpectedType indicates that the type of incoming message is not expected.

# Structs

ErrorIndicatedError indicates that Error Indication message is received on U-Plane Connection.
HandlerNotFoundError indicates that the handler func is not registered in *Conn for the incoming GTPv2 message.
KernelGTP consists of the Linux Kernel GTP-U related objects.
Relay is to relay packets between two UPlaneConn.
UPlaneConn represents a U-Plane Connection of GTPv1.

# Interfaces

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

# Type aliases

HandlerFunc is a handler for specific GTPv1 message.
Role is a role for Kernel GTP-U.