ss7client

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

README

ss7-3eai-gateway-client

Go client and NATS wire contract for ss7-3eai-gateway, an SS7 signalling gateway (M3UA / SCCP / TCAP / MAP) that applications drive over NATS.

Licensed under the Apache License 2.0, separately from the gateway (AGPL-3.0-only), so an SMSC or any other application can link it under any licence.

go get github.com/3eAI-Labs/ss7-3eai-gateway-client

What it covers

The interface the gateway implements end to end — the MAP short-message path:

Operation Method Subjects
SendRoutingInfoForSM (MAP op 45) SendRoutingInfoForSM map.sri.request → map.sri.response
MT-ForwardSM (MAP op 44) MTForwardSM map.mt.sms.request → map.mt.sms.response
MO-ForwardSM (MAP op 46), received from a foreign MSC SubscribeMO map.mo.sms

The package also defines the Message JSON schema, parameter keys, status values and the gateway's failure codes — the contract for consumers in other languages.

Usage

nc, err := nats.Connect(natsURL)
if err != nil { /* ... */ }
defer nc.Close()

gw, err := ss7client.New(nc)
if err != nil { /* ... */ }
defer gw.Close()

sri, err := gw.SendRoutingInfoForSM(ctx, ss7client.SRIRequest{
	MSISDN:               "905321112233",
	ServiceCentreAddress: ss7client.E164("905001112233"),
})
if err != nil { /* *ss7client.GatewayError, ErrInvalidRequest, or a context error */ }

_, err = gw.MTForwardSM(ctx, ss7client.MTRequest{
	IMSI:                 sri.IMSI,
	NetworkNodeNumber:    ss7client.E164(sri.NetworkNodeNumber),
	ServiceCentreAddress: ss7client.E164("905001112233"),
	TPDU:                 smsDeliverTPDU, // 3GPP TS 23.040, opaque to the gateway
})

sub, err := gw.SubscribeMO("smsc", func(m *ss7client.Message) {
	// m.Sender: originating MSC, m.Recipient: SMSC address, m.PayloadData: SMS-SUBMIT TPDU
})

Behaviour worth knowing

  • Correlation. Responses are broadcast on the response subject; every client instance receives every response and keeps only those carrying its own correlation IDs.

  • Failures. Every outcome comes back on the response subject as *GatewayError:

    • the peer answered with a MAP ReturnError → Status REMOTE_ERROR, Code the MAP error code (MAPErrAbsentSubscriberSM, MAPErrUnknownSubscriber, …), Message its name — the input to an SMSC's retry decision;
    • a TCAP Reject → REMOTE_ERROR with ErrCodeRemoteError;
    • the dialogue timed out or was aborted → TIMEOUT / ABORTED with a negative Code.

    Any status the client does not recognise is treated as a failure, never as success.

  • Deadlines. The gateway sends no response for a request it rejects before starting a dialogue. The client checks the fields the gateway requires before publishing, and bounds a request without a context deadline by DefaultTimeout (40s, longer than the gateway's default 30s TCAP dialogue timeout).

  • MO delivery is a plain NATS publish: an MO-ForwardSM published while no subscriber is connected is lost. Use a queue group to share the stream across instances.

Licence

Apache License 2.0. Copyright 2026 3eAI Labs Ltd. Contributions are accepted under the 3eAI Labs Contributor Licence Agreement; see CONTRIBUTING.md.

Documentation

Overview

Package ss7client is the NATS client for ss7-3eai-gateway: the subjects, the message schema and a typed request/response client for the MAP SMS path.

This module is licensed under the Apache License 2.0, separately from the gateway server (AGPL-3.0-only), so an SMSC or any other application can link it without taking on the server's licence. The dependency runs one way: the server imports this module for the wire contract, this module never imports the server.

Interface covered

Only the interface the gateway implements end to end is exposed:

Wire model

Every message is a JSON-encoded Message. Requests are published on a request subject; the gateway queue-subscribes, runs the MAP dialogue and publishes the outcome — result or failure — on the matching response subject with the request's correlation_id. Response subjects are broadcast: every client instance receives every response and keeps only its own, by correlation_id.

A request the gateway rejects before starting a dialogue (missing field, undecodable JSON) produces no response today; the caller only sees its own deadline. Client therefore validates the fields the gateway requires before publishing, and applies a default deadline when the context has none.

Index

Constants

View Source
const (
	// SubjectSRIRequest carries SRI-for-SM requests, application → gateway.
	SubjectSRIRequest = "map.sri.request"
	// SubjectSRIResponse carries SRI-for-SM results and failures, gateway → application.
	SubjectSRIResponse = "map.sri.response"
	// SubjectMTSMSRequest carries MT-Forward-SM requests, application → gateway.
	SubjectMTSMSRequest = "map.mt.sms.request"
	// SubjectMTSMSResponse carries MT-Forward-SM results and failures, gateway → application.
	SubjectMTSMSResponse = "map.mt.sms.response"
	// SubjectMOSMS carries MO-Forward-SM received from a foreign MSC, gateway → application.
	SubjectMOSMS = "map.mo.sms"
)

NATS subjects of the MAP SMS interface. The gateway queue-subscribes to the request subjects (queue group = its cluster name) and publishes on the response subjects.

View Source
const (
	// ParamServiceCentreAddress (request, SRI and MT): the SMSC address, as
	// a digit string or an [AddressString] object.
	ParamServiceCentreAddress = "service_centre_address"
	// ParamNetworkNodeNumber (request, MT): the serving MSC/VLR address
	// returned by SRI-for-SM, as a digit string or an [AddressString] object.
	ParamNetworkNodeNumber = "network_node_number"
	// ParamTPDUBase64 (request, MT): the TPDU as standard base64, an
	// alternative to Message.PayloadData.
	ParamTPDUBase64 = "tpdu_base64"
	// ParamVMSCAddress (response, SRI): digits of the network node number
	// returned by the HLR.
	ParamVMSCAddress = "vmsc_address"
)

Keys of Message.Parameters understood or produced by the gateway.

View Source
const (
	// StatusDelivered: MT-Forward-SM ended with a ReturnResult. A successful
	// SRI-for-SM response carries an empty status.
	StatusDelivered = "DELIVERED"
	// StatusTimeout: the gateway's TCAP dialogue timer expired.
	StatusTimeout = "TIMEOUT"
	// StatusAborted: the peer aborted the dialogue (TC-P-ABORT / TC-U-ABORT).
	StatusAborted = "ABORTED"
	// StatusRemoteError: the peer answered with a MAP ReturnError — ErrorCode
	// is the MAP error code (positive, see MAPErr*) and ErrorMessage its name —
	// or with a TCAP Reject / a ReturnError without a code — ErrorCode is
	// ErrCodeRemoteError.
	StatusRemoteError = "REMOTE_ERROR"
)

Values of Message.Status on response subjects.

View Source
const (
	ErrCodeTimeout      int32 = -1
	ErrCodeAborted      int32 = -2
	ErrCodeRemoteError  int32 = -3
	ErrCodeUnclassified int32 = -99
)

Gateway-private failure codes in Message.ErrorCode. They are negative so they never collide with MAP error codes (3GPP TS 29.002 MAP-ErrorCodes, positive).

View Source
const (
	MAPErrUnknownSubscriber         int32 = 1
	MAPErrUnidentifiedSubscriber    int32 = 5
	MAPErrAbsentSubscriberSM        int32 = 6
	MAPErrIllegalSubscriber         int32 = 9
	MAPErrTeleserviceNotProvisioned int32 = 11
	MAPErrIllegalEquipment          int32 = 12
	MAPErrCallBarred                int32 = 13
	MAPErrFacilityNotSupported      int32 = 21
	MAPErrSubscriberBusyForMTSMS    int32 = 31
	MAPErrSMDeliveryFailure         int32 = 32
	MAPErrSystemFailure             int32 = 34
	MAPErrDataMissing               int32 = 35
	MAPErrUnexpectedDataValue       int32 = 36
)

MAP error codes (3GPP TS 29.002, MAP-ErrorCodes) that SendRoutingInfoForSM and MT-ForwardSM can return, carried in Message.ErrorCode with StatusRemoteError. The gateway passes any code through; these are the ones an SMSC's retry logic normally distinguishes.

View Source
const DefaultTimeout = 40 * time.Second

DefaultTimeout bounds a request whose context has no deadline. It is longer than the gateway's default TCAP dialogue timeout (tcap.dialogue_timeout, 30s), so the gateway's own TIMEOUT response normally arrives first.

Variables

View Source
var (
	// ErrInvalidRequest wraps a request rejected before publishing because
	// a field the gateway requires is missing.
	ErrInvalidRequest = errors.New("ss7 client: invalid request")
	// ErrClosed is returned for requests made after, or pending at, Close.
	ErrClosed = errors.New("ss7 client: closed")
)

Functions

This section is empty.

Types

type AddressString

type AddressString struct {
	Digits        string `json:"digits"`
	Nature        uint8  `json:"nature"`
	NumberingPlan uint8  `json:"numbering_plan"`
}

AddressString is the object form of an address parameter. Nature and NumberingPlan are the TS 29.002 AddressString nature-of-address and numbering-plan indicators; a bare digit string in Parameters means international (4) / ISDN-E.164 (1).

func E164

func E164(digits string) AddressString

E164 returns an international ISDN/E.164 AddressString.

type Client

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

Client sends MAP SMS requests to the gateway and matches the responses by correlation ID. It is safe for concurrent use. It does not own the NATS connection: Close releases the client's subscriptions only.

func New

func New(nc *nats.Conn, opts ...Option) (*Client, error)

New subscribes to the response subjects and returns a ready Client.

func (*Client) Close

func (c *Client) Close() error

Close unsubscribes and fails every pending request with ErrClosed.

func (*Client) MTForwardSM

func (c *Client) MTForwardSM(ctx context.Context, req MTRequest) (*MTResult, error)

MTForwardSM delivers a short message to the serving MSC. On a gateway-reported failure it returns *GatewayError.

func (*Client) SendRoutingInfoForSM

func (c *Client) SendRoutingInfoForSM(ctx context.Context, req SRIRequest) (*SRIResult, error)

SendRoutingInfoForSM asks the subscriber's HLR where to deliver a short message. On a gateway-reported failure it returns *GatewayError.

func (*Client) SubscribeMO

func (c *Client) SubscribeMO(queue string, handle func(*Message)) (*nats.Subscription, error)

SubscribeMO delivers MO-Forward-SM messages the gateway received from foreign MSCs: Sender is the originating MSC address, Recipient the SMSC address, IMSI the originator when the network supplied it, PayloadData the SMS-SUBMIT TPDU. With a non-empty queue, instances sharing the queue name split the stream; with an empty queue every instance receives every message. The returned subscription is the caller's to unsubscribe.

MO is a plain NATS publish: a message published while no subscriber is connected is lost.

type Direction

type Direction string

Direction is relative to the SS7 network: Inbound goes into it (application → gateway), Outbound comes out of it (gateway → application).

const (
	DirectionInbound  Direction = "INBOUND"
	DirectionOutbound Direction = "OUTBOUND"
)

type GatewayError

type GatewayError struct {
	CorrelationID string
	Status        string // StatusTimeout, StatusAborted, ...
	Code          int32  // ErrCode* (negative) or a MAP error code (positive, MAPErr*)
	Message       string
	NodeID        string
}

GatewayError is a failure the gateway reported on a response subject.

func (*GatewayError) Error

func (e *GatewayError) Error() string

type MTRequest

type MTRequest struct {
	IMSI                 string        // required, from SRIResult.IMSI
	NetworkNodeNumber    AddressString // required, from SRIResult.NetworkNodeNumber
	ServiceCentreAddress AddressString // required
	TPDU                 []byte        // required, SMS-DELIVER TPDU (3GPP TS 23.040), opaque to the gateway
	// MSCPointCode overrides the destination point code. Zero routes on the
	// network node number GT alone.
	MSCPointCode uint32
}

MTRequest is a MAP MT-ForwardSM request (3GPP TS 29.002 §12.9).

type MTResult

type MTResult struct {
	Status string // StatusDelivered
	NodeID string
	Raw    *Message
}

MTResult is a successful MT-ForwardSM answer.

type Message

type Message struct {
	MessageID     string      `json:"message_id"`
	CorrelationID string      `json:"correlation_id,omitempty"`
	MessageType   MessageType `json:"message_type"`
	Direction     Direction   `json:"direction"`
	Timestamp     time.Time   `json:"timestamp"`

	// Addressing (E.164 digits).
	Sender    string `json:"sender,omitempty"`
	Recipient string `json:"recipient,omitempty"`
	IMSI      string `json:"imsi,omitempty"`
	MSISDN    string `json:"msisdn,omitempty"`

	// SS7 routing overrides. Zero/empty means "use the gateway's configuration".
	OPC         uint32 `json:"opc,omitempty"`
	DPC         uint32 `json:"dpc,omitempty"`
	SSN         uint8  `json:"ssn,omitempty"`
	GlobalTitle string `json:"global_title,omitempty"`

	Content     string                 `json:"content,omitempty"`
	PayloadData []byte                 `json:"payload_data,omitempty"` // base64 in JSON
	Parameters  map[string]interface{} `json:"parameters,omitempty"`

	ServiceKey uint32 `json:"service_key,omitempty"`
	EventType  string `json:"event_type,omitempty"`

	Status       string `json:"status,omitempty"`
	ErrorCode    int32  `json:"error_code,omitempty"`
	ErrorMessage string `json:"error_message,omitempty"`

	TraceID string `json:"trace_id,omitempty"`
	NodeID  string `json:"node_id,omitempty"` // gateway node that handled the dialogue
}

Message is the JSON document carried on every subject. Field names and JSON tags are the wire contract shared with non-Go consumers; changing one breaks them.

type MessageType

type MessageType string

MessageType identifies the operation a Message belongs to.

const (
	MsgTypeMAPSRI   MessageType = "MAP_SRI"
	MsgTypeMAPMTSMS MessageType = "MAP_MT_SMS"
	MsgTypeMAPMOSMS MessageType = "MAP_MO_SMS"
)

type Option

type Option func(*Client)

Option configures a Client.

func WithDecodeErrorHandler

func WithDecodeErrorHandler(f func(subject string, data []byte, err error)) Option

WithDecodeErrorHandler receives messages on the client's subscriptions that are not valid JSON Messages. Without it they are dropped.

func WithDefaultTimeout

func WithDefaultTimeout(d time.Duration) Option

WithDefaultTimeout replaces DefaultTimeout for requests without a deadline.

type SRIRequest

type SRIRequest struct {
	MSISDN               string        // required, E.164 digits
	ServiceCentreAddress AddressString // required
	// HLRGlobalTitle and HLRPointCode override the gateway's map.hlr_gt and
	// map.hlr_pc for this request. Leave empty to use the configuration.
	HLRGlobalTitle string
	HLRPointCode   uint32
}

SRIRequest is a MAP SendRoutingInfoForSM request (3GPP TS 29.002 §12.1).

type SRIResult

type SRIResult struct {
	IMSI string
	// NetworkNodeNumber is the serving MSC/VLR address digits; pass it to
	// MTRequest.NetworkNodeNumber.
	NetworkNodeNumber string
	NodeID            string // gateway node that ran the dialogue
	Raw               *Message
}

SRIResult is a successful SendRoutingInfoForSM answer.

Jump to

Keyboard shortcuts

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