smpp

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2021 License: GPL-3.0 Imports: 7 Imported by: 1

README

Golang SMPP v3.4 Library

Overview

This is a golang library for SMPP v3.4 message generation and parsing.

Usage

The library is in the package smpp. There are two basic object types: smpp.Parameter and smpp.PDU. One may Encode a PDU object to an octet stream in network byte order, and may Decode an octet stream in network byte order into a PDU.

An SMPP v3.4 PDU has a header and one or more Parameters. Parameters are Mandatory or Optional. Mandatory Parameters are at fixed offsets in a PDU, based on the PDU type, and are either of fixed size, or are null terminated (or it is a short_message, which is treated specially, as described below). Optional Parameters are TLV (Tag/Length/Value) encoded. There are different constructors for different Paramter types:

p := smpp.NewFLParameter(value interface{})
p := smpp.NewCOctetStringParameter(value string)
p := smpp.NewOctetStringFromString(value string)
p := smpp.NewTLVParameter(tag uint16, value interface{})

NewFLParameter is for fixed length parameters, and the length and encoding is inferred from the value type, which may be uint8, uint16 or uint32. NetCOctetStringParameter is for C-Octet-Strings (which are null--that is, byte with a value of 0--terminated). OctetStringFromString produces an Octet-String (which is not null terminated) from a string. The only Parameter type that uses this is short_messsage, which must be preceded by an sm_length Parameter that provides the short_message length. NewTLVParameter generates an Optional Parameter. The Length of the TLV is inferred from type of value, which may be uint8, uint16, uint32, string or []byte.

None of the Parameter constructors return an error, so that they can be used inline with a PDU constructor. They will, however, return nil if something goes wrong.

To create a PDU:

pdu := smpp.NewPDU(id smpp.CommandIDType, status uint32, sequence uint32, mandatoryParams []*smpp.Parameter, optionalParams []*smpp.Parameter)

To decode an incoming byte stream (which must be a complete PDU):

pdu, err := smpp.DecodePDU(stream []byte)

Examples

There are examples in the examples/ directory.

Status

In pdu.go, the global variable pduTypeDefinition maps the Mandatory Parameters for each PDU type. Particularly, neither SubmitMulti nor SubmitMultiResp are implemented, and messages of this type will neither encode nor decode properly. It requires a bit of extra logic in the code to support these. Additionally, there are no unit tests for a subset of the message types, so their encode/decode methods are not thoroughly tested.

Documentation

Index

Constants

View Source
const (
	CommandGenericNack         = 0x80000000
	CommandBindReceiver        = 0x00000001
	CommandBindReceiverResp    = 0x80000001
	CommandBindTransmitter     = 0x00000002
	CommandBindTransmitterResp = 0x80000002
	CommandQuerySm             = 0x00000003
	CommandQuerySmResp         = 0x80000003
	CommandSubmitSm            = 0x00000004
	CommandSubmitSmResp        = 0x80000004
	CommandDeliverSm           = 0x00000005
	CommandDeliverSmResp       = 0x80000005
	CommandUnbind              = 0x00000006
	CommandUnbindResp          = 0x80000006
	CommandReplaceSm           = 0x00000007
	CommandReplaceSmResp       = 0x80000007
	CommandCancelSm            = 0x00000008
	CommandCancelSmResp        = 0x80000008
	CommandBindTransceiver     = 0x00000009
	CommandBindTransceiverResp = 0x80000009
	CommandOutbind             = 0x0000000B
	CommandEnquireLink         = 0x00000015
	CommandEnquireLinkResp     = 0x80000015
	CommandSubmitMulti         = 0x00000021
	CommandSubmitMultiResp     = 0x80000021
	CommandAlertNotification   = 0x00000102
	CommandDataSm              = 0x00000103
	CommandDataSmResp          = 0x80000103
)

These correspond to SMPP Message Type

Variables

This section is empty.

Functions

func CommandName

func CommandName(commandID CommandIDType) string

CommandName returns the string representation for a CommandID

func LengthOfNextPDU

func LengthOfNextPDU(stream []byte) uint32

LengthOfNextPDU reads a stream that should contain at least a fragment of an SMPP PDU. If the length of stream is less than 4, then return 0 (meaning length is not yet known)

Types

type BindInfo

type BindInfo struct {
	Type BindType
}

BindInfo contains information for a bind

type BindType

type BindType uint

BindType is an enumeration of Bind types

const (
	TransceiverBind BindType = iota
	ReceiverBind
	TransmitterBind
)

These are the possible bind types

type CommandIDType

type CommandIDType uint32

CommandIDType is an enumeration of defined Command IDs

func CommandIDFromString

func CommandIDFromString(commandName string) (CommandIDType, bool)

CommandIDFromString takes a command string name and returns the corresponding CommandIDType. The boolean is set to true if the commandName is understand; otherwise it is false, and the returned value for CommandIDType is undefined

type ESME

type ESME struct {
}

ESME represents an ESME, which initiates connection to one or more SMSCs

func (*ESME) BindToPeer

func (esme *ESME) BindToPeer(peer *Peer, bind BindInfo) error

BindToPeer establishes a bind with a remote peer to which a transport connection is already completed

func (*ESME) ConnectToPeer

func (esme *ESME) ConnectToPeer(remoteAddr net.IP, remotePort uint16) (peer *Peer, err error)

ConnectToPeer connects a transport (TCP) to a remote peer

func (*ESME) SendMessageToPeer

func (esme *ESME) SendMessageToPeer(peer *Peer, pdu *PDU) error

SendMessageToPeer sends a message to a bound peer

func (*ESME) StartListenLoop

func (esme *ESME) StartListenLoop()

StartListenLoop should be run in a goroutine, and listens for incoming messages from peers

type JSONDocument

type JSONDocument struct {
	Messages []JSONMessage `json:"messages"`
}

JSONDocument describes the SMPP JSON document structure

func UnmarshallJSON

func UnmarshallJSON(data []byte) (*JSONDocument, error)

UnmarshallJSON treats 'data' as a stream of characters in a JSON struct, and attempts to convert them into a JSONMessage

type JSONMandatoryParameterMap

type JSONMandatoryParameterMap struct {
	AddrTon              uint8  `json:"addr_ton"`
	AddrNpi              uint8  `json:"addr_npi"`
	AddressRange         string `json:"address_range"`
	DataCoding           uint8  `json:"data_coding"`
	DestinationAddr      string `json:"destination_addr"`
	DestinationAddrNpi   uint8  `json:"destination_addr_npi"`
	DestinationAddrTon   uint8  `json:"destination_addr_ton"`
	EsmClass             uint8  `json:"esm_class"`
	InterfaceVersion     uint8  `json:"interface_version"`
	Password             string `json:"password"`
	MessageID            string `json:"message_id"`
	PriorityFlag         uint8  `json:"priority_flag"`
	ProtocolID           uint8  `json:"protocol_id"`
	RegisteredDelivery   uint8  `json:"registered_delivery"`
	ReplaceIfPresentFlag uint8  `json:"replace_if_present_flag"`
	ScheduleDeliveryTime string `json:"schedule_delivery_time"`
	ServiceType          string `json:"service_type"`
	ShortMessage         string `json:"short_message"`
	SmDefaultMsgID       uint8  `json:"sm_default_msg_id"`
	SmLength             uint8  `json:"sm_length"`
	SourceAddrNpi        uint8  `json:"source_addr_npi"`
	SourceAddrTon        uint8  `json:"source_addr_ton"`
	SourceAddr           string `json:"source_addr"`
	SystemID             string `json:"system_id"`
	SystemType           string `json:"system_type"`
	ValidityPeriod       string `json:"validity_period"`
}

JSONMandatoryParameterMap describes the layout of the SMPP JSON file mandatory_parameters field

type JSONMessage

type JSONMessage struct {
	CommandID           uint32                    `json:"command_id"`
	SequenceNumber      uint32                    `json:"sequence_number"`
	CommandStatus       uint32                    `json:"command_status"`
	EncodedLength       uint32                    `json:"encoded_length"`
	MandatoryParameters JSONMandatoryParameterMap `json:"mandatory_parameters"`
	OptionalParameters  JSONOptionalParameterMap  `json:"optional_parameters"`
}

JSONMessage describes the SMPP JSON message structure

type JSONOptionalParameterMap

type JSONOptionalParameterMap struct {
	SCInterfaceVersion       uint32 `yaml:"SC_interface_version"`
	AdditionalStatusInfoText uint32 `yaml:"additional_status_info_text"`
	AlertOnMessageDelivery   uint32 `yaml:"alert_on_message_delivery"`
	CallbackNum              uint32 `yaml:"callback_num"`
	CallbackNumAtag          uint32 `yaml:"callback_num_atag"`
	CallbackNumPresInd       uint32 `yaml:"callback_num_pres_ind"`
	DeliveryFailureReason    uint32 `yaml:"delivery_failure_reason"`
	DestAddrSubunit          uint32 `yaml:"dest_addr_subunit"`
	DestBearerType           uint32 `yaml:"dest_bearer_type"`
	DestNetworkType          uint32 `yaml:"dest_network_type"`
	DestSubaddress           uint32 `yaml:"dest_subaddress"`
	DestTelematicsID         uint32 `yaml:"dest_telematics_id"`
	DestinationPort          uint32 `yaml:"destination_port"`
	DisplayTime              uint32 `yaml:"display_time"`
	DpfResult                uint32 `yaml:"dpf_result"`
	ItsReplyType             uint32 `yaml:"its_reply_type"`
	ItsSessionInfo           uint32 `yaml:"its_session_info"`
	LanguageIndicator        uint32 `yaml:"language_indicator"`
	MessagePayload           uint32 `yaml:"message_payload"`
	MessageState             uint32 `yaml:"message_state"`
	MoreMessagesToSend       uint32 `yaml:"more_messages_to_send"`
	MsAvailabilityStatus     uint32 `yaml:"ms_availability_status"`
	MsMsgWaitFacilities      uint32 `yaml:"ms_msg_wait_facilities"`
	MsValidity               uint32 `yaml:"ms_validity"`
	NetworkErrorCode         uint32 `yaml:"network_error_code"`
	NumberOfMessages         uint32 `yaml:"number_of_messages"`
	PayloadType              uint32 `yaml:"payload_type"`
	PrivacyIndicator         uint32 `yaml:"privacy_indicator"`
	QosTimeToLive            uint32 `yaml:"qos_time_to_live"`
	ReceiptedMessageID       uint32 `yaml:"receipted_message_id"`
	SarMsgRefNum             uint32 `yaml:"sar_msg_ref_num"`
	SarSegmentSeqnum         uint32 `yaml:"sar_segment_seqnum"`
	SarTotalSegments         uint32 `yaml:"sar_total_segments"`
	SetDpf                   uint32 `yaml:"set_dpf"`
	SmsSignal                uint32 `yaml:"sms_signal"`
	SourceAddrSubunit        uint32 `yaml:"source_addr_subunit"`
	SourceBearerType         uint32 `yaml:"source_bearer_type"`
	SourceNetworkType        uint32 `yaml:"source_network_type"`
	SourcePort               uint32 `yaml:"source_port"`
	SourceSubaddress         uint32 `yaml:"source_subaddress"`
	SourceTelematicsID       uint32 `yaml:"source_telematics_id"`
	UserMessageReference     uint32 `yaml:"user_message_reference"`
	UserResponseCode         uint32 `yaml:"user_response_code"`
	UssdServiceOp            uint32 `yaml:"ussd_service_op"`
}

JSONOptionalParameterMap describes the layout of the SMPP JSON file optional_parameters field

type NetworkStreamReader

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

NetworkStreamReader provides a mechanism for reading PDUs from an incoming TCP stream connection, breaking the stream into PDUs

func NewNetworkStreamReader

func NewNetworkStreamReader(fromConnection net.Conn) *NetworkStreamReader

NewNetworkStreamReader creates a NetworkStreamReader that operates on the identified connection

func (*NetworkStreamReader) AttachedConnectionIsClosed

func (reader *NetworkStreamReader) AttachedConnectionIsClosed() bool

AttachedConnectionIsClosed returns true if the underlying TCP connection has closed, which is determined during a Read() read operation

func (*NetworkStreamReader) ExtractNextPDUs

func (reader *NetworkStreamReader) ExtractNextPDUs() ([]*PDU, error)

ExtractNextPDUs repeatedly reads from the TCP stream until there is at least one PDU. It returns the set of extracted PDUs, and like Read(), stores any remaining data for subsequent calls

func (*NetworkStreamReader) Read

func (reader *NetworkStreamReader) Read() ([]*PDU, error)

Read performs a read of the associated TCP stream and attempts to extract one or more PDUs from the stream. If there are data left over after extracting zero or more PDUs, those data are saved, and subsequent Read values are appended to those data

type PDU

type PDU struct {
	CommandLength       uint32
	CommandID           CommandIDType
	CommandStatus       uint32
	SequenceNumber      uint32
	MandatoryParameters []*Parameter
	OptionalParameters  []*Parameter
}

PDU is a PDU for

func ConvertJSONToPDUs

func ConvertJSONToPDUs(jsonMessages []*JSONMessage) ([]*PDU, error)

ConvertJSONToPDUs creates PDUs from well-formed JSONMessage objects

func DecodePDU

func DecodePDU(stream []byte) (*PDU, error)

DecodePDU accepts a byte stream in network byte order, and attempts to convert it to a PDU object

func NewPDU

func NewPDU(id CommandIDType, status uint32, sequence uint32, mandatoryParams []*Parameter, optionalParams []*Parameter) *PDU

NewPDU creates a new PDU object

func (*PDU) CommandName

func (pdu *PDU) CommandName() string

CommandName returns the string name for this PDU's CommandID

func (*PDU) ComputeLength

func (pdu *PDU) ComputeLength() uint32

ComputeLength computes the enocde length of the PDU and returns it

func (*PDU) Encode

func (pdu *PDU) Encode() ([]byte, error)

Encode converts the 'pdu' object into a byte stream appropriate for network transmission

func (*PDU) IsRequest

func (pdu *PDU) IsRequest() bool

IsRequest returns true if the Command is in the request range (i.e., top-order bit is not set); otherwise it returns false

type PDUDefinition

type PDUDefinition struct {
	Type                CommandIDType
	MinLength           uint32
	MandatoryParameters []string
}

PDUDefinition describes a PDU. It contains the set of mandatory Parameters and the minimum length (including the header and the mandatory Parameters).

type Parameter

type Parameter struct {
	Type         ParameterType
	EncodeLength uint32
	Value        interface{}
}

Parameter is mandatory or optional parameter. If the type is TypeTLV then Value is an instance of TLV

func NewCOctetStringParameter

func NewCOctetStringParameter(value string) *Parameter

NewCOctetStringParameter creates a Parameter where the value is a C-Octet String (a null terminated string). It is up to the caller to pass a correct value if Decimal or Hex is required. The passed string must contain only ASCII, or this won't work the way you expect.

func NewFLParameter

func NewFLParameter(value interface{}) *Parameter

NewFLParameter creates a Parameter where the length is fixed by the type (e.g., TypeUint32). The stored Type will be introspected from the type of 'value'

func NewOctetStringFromString

func NewOctetStringFromString(value string) *Parameter

NewOctetStringFromString creates a Parameter of type OctetString (not null terminated) from a string.

func NewTLVParameter

func NewTLVParameter(tag uint16, value interface{}) *Parameter

NewTLVParameter creates a new Parameter with the provided tag. The length is introspected from the value, which may be a uint8, a uint16, a uint32, a string, or a []byte.

func (*Parameter) Encode

func (param *Parameter) Encode() []byte

Encode converts the 'param' object into a byte stream appropriate for network transmission

type ParameterDefinition

type ParameterDefinition struct {
	Name      string
	Type      ParameterType
	MaxLength uint16
	TagID     uint16
}

ParameterDefinition provides attributes for a Parameter. MaxLength will be set to the fixed length for fixed length types (e.g., TypeUint32). If there is no MaxLength for a variable sized type (e.g., TypeASCII), then MaxLength will be set to zero. TagID is set only if the type is TypeTLV; otherwise it is zero.

type ParameterType

type ParameterType uint32

ParameterType is an enumeration of parameter types

const (
	// TypeUint8 encoded as single byte, unsigned 8-bit integer
	TypeUint8 ParameterType = iota
	// TypeUint16 encoded as two bytes, unsigned 16-bit integer
	TypeUint16
	// TypeUint32 encoded as four bytes, unsigned 32-bit integer
	TypeUint32
	// TypeCOctetString encoded as variable length field of bytes, must be NULL (0) terminated
	TypeCOctetString
	// TypeOctetString encoded as variable length field of bytes
	TypeOctetString
	// TypeTLV encodes as octet string
	TypeTLV
)

type Peer

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

Peer represents a peer for an SMPP entity (an ESME or SMSC)

func NewPeerWithConnection

func NewPeerWithConnection(c *net.TCPConn) *Peer

NewPeerWithConnection instantiates a Peer object, providing it with an already created connection. This can be useful if you wish to use local binds for a Peer connection

type TLV

type TLV struct {
	Tag     uint16
	VLength uint16
	Value   interface{}
}

TLV represents the value in a Parameter struct for TLV type Parameters

Directories

Path Synopsis
_examples

Jump to

Keyboard shortcuts

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