LTE S1AP C++ Sample Code Using OSS ASN.1 Tools


This sample is provided as part of the OSS ASN.1 Tools trial and commercial shipments. The source code and related files are listed below for reference.

The sample demonstrates how to use the OSS ASN.1 Tools to process messages for the 3GPP LTE S1AP standard (TS 36.413 version 19.0.0).

It runs on Linux on x86-64 as an example and illustrates how to decode, inspect, and create LTE S1AP messages using the OSS ASN.1 Tools API.

The sample reads S1AP messages from .per files, decodes and prints them, and creates and encodes successful outcome messages.

A makefile is included for building and running the test program using the OSS ASN.1/C++ library.

To explore more samples (LTE RRC, 5G RRC, S1AP, X2AP, NGAP), visit the main Sample Code page.

Overview

This sample shows how to:

  • Initialize the OSS ASN.1/C++ runtime for the LTE S1AP schema.
  • Read a PER-encoded S1AP message from an input file.
  • Decode and print LTE S1AP messages.
  • Create and encode a response message.
  • Build and run the sample test program with a makefile on Linux.

Files in This Sample

The files listed below are included in the OSS ASN.1 Tools trial and commercial shipments and are used by this sample program:

File Description
README.TXT Instructions and sample overview.
*.asn ASN.1 source files that describe the 3GPP LTE S1AP protocol (TS 36.413), used with this program example.
S1AP-PDU_HandoverRequest_bin.per Valid PER-encoded S1AP message (HandoverRequest). It should pass testing.
ts1ap.cpp Simple C++ program that shows how to work with LTE S1AP protocol data. It reads input messages from files, decodes and prints them, and creates and encodes an S1AP message.
makefile Makefile that builds and runs the sample test.
makefile.rtoed Makefile that builds and runs the sample test using RTOED.
gui/ ASN.1 Studio project for viewing/compiling schema and generating sample data.

Build and Run Instructions

(Installation instructions for the OSS ASN.1 Tools are included in all trial and commercial shipments.)

To build and run this sample, install a trial or licensed version of the OSS ASN.1 Tools for C++.

1. Generate C++ source and header files (runtime-only shipments)

If your shipment is runtime-only, generate the .cpp and .h files by running:

make cross

This creates a samples/cross directory with:

  • the required .asn files
  • scripts to run the OSS ASN.1/C++ compiler (asn1cpl.sh or asn1cpl.bat)
2. Build and run the sample
make

This command compiles the sample C++ source, links it with the OSS ASN.1/C++ static library, and executes the test. To use another type of library in the shipment (such as a shared library), set the A makefile variable, for example:

make A=so
3. Clean up generated files
make clean
4. Other Platforms

Note: The C++ source code in this sample is platform-independent. Linux commands are shown as an example, but equivalent samples and build instructions are available for Windows, macOS, and other platforms. For help with platform-specific instructions, please contact OSS Support.

Code Listing: ts1ap.cpp

The following listing shows the main C++ source file for this sample test program, ts1ap.cpp. It demonstrates how to read PER-encoded LTE S1AP messages from files, decode and print them, and create and encode a response message using the OSS ASN.1 Tools API.

Show ts1ap.cpp source code
/*****************************************************************************/
/*  Copyright (C) 2025 OSS Nokalva, Inc.  All rights reserved.               */
/*****************************************************************************/
/* THIS FILE IS PROPRIETARY MATERIAL OF OSS NOKALVA, INC.                    */
/* AND MAY BE USED ONLY BY DIRECT LICENSEES OF OSS NOKALVA, INC.             */
/* THIS FILE MAY NOT BE DISTRIBUTED.                                         */
/* THIS COPYRIGHT STATEMENT MAY NOT BE REMOVED.                              */
/* THIS SAMPLE PROGRAM IS PROVIDED AS IS. THE SAMPLE PROGRAM AND ANY RESULTS */
/* OBTAINED FROM IT ARE PROVIDED WITHOUT ANY WARRANTIES OR REPRESENTATIONS,  */
/* EXPRESS, IMPLIED OR STATUTORY.                                            */
/*****************************************************************************/

/*
 * A demonstrative example for handling 3GPP LTE S1AP protocol data in ASN.1/C++
 */
#include <errno.h>
#include "s1ap.h"

/*
 * Auxiliary function to make output prettier.
 */
void printBorder()
{
    printf("-------------------------------------------------------\n");
}

char *filesDir; /* The directory where input files reside. It is set to the
		 * command line parameter if any and to the directory where
		 * the sample is started, otherwise.
		 */


/*
 * A simple class used to report non-ASN.1/C++ errors (such as a failure to
 * create a socket) to the application. You may use any alternative error
 * handling if you wish.
 */

class NonASN1Exception {
private:
    const char *message;	/* can contain C format specifications */
    const char *extra_data;	/* data handled by fmt. specifications (if any) */
    int errcode;
public:
    NonASN1Exception(const char *msg, int code = 0,
	    const char *extd = NULL);
    NonASN1Exception(const NonASN1Exception & that);
    const char *get_message() const;
    const char *get_extra_data() const;
    int get_errcode() const;
};

NonASN1Exception::NonASN1Exception(const char *msg, int code, const char *extd)
{
    message = msg;
    extra_data = extd;
    errcode = code;
}

NonASN1Exception::NonASN1Exception(const NonASN1Exception & that)
{
    message = that.message;
    errcode = that.errcode;
    extra_data = that.extra_data;
}

const char *NonASN1Exception::get_message() const
{
    return message;
}

const char *NonASN1Exception::get_extra_data() const
{
    return extra_data;
}

int NonASN1Exception::get_errcode() const
{
    return errcode;
}

/*
 * FUNCTION     printHexString() prints data (octet string) as a sequence of
 *              hexadecimal digits 'XXXX...'H
 *
 * PARAMETERS
 *    ctl       ASN.1/C++ control object
 *    value     reference to input data (OssString object)
 */
void printHexString(OssControl *ctl, const OssString &value)
{
    ctl->printHex(value.get_buffer(), value.length());
}

/*
 * FUNCTION     printHexBitString() prints data (bit string) as a sequence of
 *              hexadecimal digits 'XXXX...'H
 *
 * PARAMETERS
 *    ctl       ASN.1/C++ control object
 *    value     reference to input data (OssBitString object)
 */
void printHexBitString(OssControl *ctl, const OssBitString &value)
{
    ctl->printHex((const char *)value.get_buffer(), (value.length() + 7) / 8);
}

/*
 * FUNCTION     Helper function to open file in the specified directory.
 *
 * PARAMETERS
 *     directoryName    directory where fileName resides
 *     fileName         file to open
 *
 * RETURNS      pointer to file on success, NULL on failure
 */
FILE * openInputFile(char *directoryName, const char *fileName)
{
    char *path;
    FILE *fv;
    const char kPathSeparator =
#ifdef _WIN32
				'\\';
#else
				'/';
#endif

    if (directoryName) {
	size_t dLength = strlen(directoryName);

	if (NULL == (path = (char *)asn1Malloc(dLength + strlen(fileName) + 2))) {
	    return NULL;
	}

	memcpy(path, directoryName, dLength);
	if (path[dLength - 1] != kPathSeparator)
	    path[dLength++] = kPathSeparator;
	strcpy(path+dLength, fileName);
    } else {
	path = (char *) fileName;
    }

    if (!(fv = fopen(path, "rb"))) {
	printf("Failed to open the '%s' file. Restart the sample program using the file "
		"location as the input parameter.\n", path);
    }

    if (path != fileName)
	asn1Free(path);

    return fv;
}

/*
 * FUNCTION     readEncodingFromFile() reads serialized message from specified
 *              file
 *
 * PARAMETERS
 *    filename  name of file containing serialized message
 *
 * RETURNS      a pointer to a newly allocated EncodedBuffer object containing
 *              the encoding read from the file
 */
static EncodedBuffer *readEncodingFromFile(const char *filename)
{
    long length;
    FILE *in = NULL;
    unsigned char *data = NULL;
    EncodedBuffer *result = new EncodedBuffer();

    try {
	/* Open the file and determine its length */
	in = openInputFile(filesDir, filename);
	if (!in)
	    throw NonASN1Exception(strerror(errno), errno);
	if (fseek(in, 0, SEEK_END))
	    throw NonASN1Exception(strerror(errno), errno);
	length = ftell(in);
	if (length < 0)
	    throw NonASN1Exception(strerror(errno), errno);

	/*
	 * Allocate memory. We need to use asn1Malloc so we can later pass
	 * the ownership of the allocated memory to the EncodedBuffer object.
	 */
	data = (unsigned char *)asn1Malloc(length);
	if (!data)
	    throw NonASN1Exception("No memory", OUT_MEMORY);

	/* Read the file */
	rewind(in);
	if (length != (long)fread(data, 1, (size_t)length, in))
	    throw NonASN1Exception("Error reading the file", 0);
	fclose(in);

	/* Pass the read buffer to the EncodedBuffer */
	result->grab_buffer(length, (char *)data);
	return result;
    } catch (...) {
	if (in)
	    fclose(in);
	if (data)
	    asn1Free(data);
	delete result;
	throw;
    }
}

/* Names of Criticality values */
static const char *Criticalities[] = { "reject", "ignore", "notify" };

/* Names of HandoverType values */
static const char *HandoverTypes[] = {
	"intralte", "ltetoutran", "ltetogeran", "utrantolte", "gerantolte"
};

/*
 * FUNCTION     printProtocolExtensions() prints ProtocolExtensionContainer
 *              data.
 *
 * PARAMETERS
 *    ctl       OSS control variable
 *    ie_ext    reference to ProtocolExtensionContainer data to print
 *              (NULL is acceptable, in this case the function does nothing)
 *    indent    indentation
 */
static void printProtocolExtensions(OssControl *ctl, Global_ENB_ID::iE_Extensions *ie_ext,
	int indent)
{
    int index;
    /*
     * Different messages use iE_Extensions fields, which all are binary compatible.
     * We intend to use this function for any protocol extension IE list.
     */
    Global_ENB_ID::iE_Extensions::component *ie;
    s1ap_PDU pdu;

    /* Return if there are no extensions */
    if (!ie_ext)
	return;

    printf("%*s%s includes the following IEs:\n", indent++, "", "iE-Extensions");
    /* Print each IE in the list */
    index = 1;
    for (OssIndex i = ie_ext->first(); i != OSS_NOINDEX; i = ie_ext->next(i)) {
	ie = ie_ext->at(i);

	printf("%*s#%d: id = %2u, criticality = %s\n", indent, "",
		index, ie->get_id(), Criticalities[ie->get_criticality()]);
	if (ie->get_extensionValue().has_decoded()) {
	    /* Extract the open type data */
	    ie->get_extensionValue().get_decoded(pdu);
	    /* Print it in a generic way, using ASN.1 value notation */
	    pdu.print(*ctl);
	} else
	    printf("PDU is not decoded\n");
	index++;
    }
}

/*
 * FUNCTION     printProtocolIEs() prints ProtocolIE-Container data.
 *
 * PARAMETERS
 *    ctl       OSS control variable
 *    ies       reference to ProtocolIE-Container data to print
 *    indent    indentation
 */
void printProtocolIEs(OssControl *ctl, HandoverRequired::protocolIEs & ies,
	int indent)
{
    int index;		/* IE's ordinal number */
    HandoverRequired::protocolIEs::component *ie;
    OssString *rac;

    printf("%*s%s includes the following IEs:\n", indent++, "",
	    "protocolIEs");

    index = 1;
    /* For each IE in the SEQUENCE OF */
    for (OssIndex i = ies.first(); i != OSS_NOINDEX; i = ies.next(i)) {
	ie = ies.at(i);
	printf("\n%*s#%d: id = %2u, criticality = %s\n", indent, "",
		index, ie->get_id(), Criticalities[ie->get_criticality()]);

	indent++;
	index++;
	HandoverRequiredIEs_Value & iedata = ie->get_value();

	if (iedata.has_decoded()) {
	    /* If the IE's data are decoded */

	    /* Depending on the IE identifier */
	    switch (ie->get_id()) {
	    case id_MME_UE_S1AP_ID:
		{
		    /* id-MME-UE-S1AP-ID */
		    MME_UE_S1AP_ID *mme_id;

		    mme_id = iedata.get_MME_UE_S1AP_ID();
		    printf("%*svalue %s: %u\n", indent, "", "MME-UE-S1AP-ID",
			    *mme_id);
		}
		break;
	    case id_eNB_UE_S1AP_ID:
		{
		    /* id-eNB-UE-S1AP-ID */
		    ENB_UE_S1AP_ID *enb_id;

		    enb_id = iedata.get_ENB_UE_S1AP_ID();
		    printf("%*svalue %s: %u\n", indent, "", "ENB-UE-S1AP-ID",
			    *enb_id);
		}
		break;
	    case id_HandoverType:
		{
		    /* id-HandoverType */
		    HandoverType *htype;

		    htype = iedata.get_HandoverType();
		    printf("%*svalue %s: %s\n", indent, "", "HandoverType",
			    HandoverTypes[*htype]);
		}
		break;
	    case id_Cause:
		{
		    /* id-Cause */
		    Cause *cause;
		    CauseRadioNetwork *cause_rnw;
		    CauseTransport *cause_trans;
		    CauseNas *cause_nas;
		    CauseProtocol *cause_proto;
		    CauseMisc *cause_misc;

		    cause = iedata.get_Cause();
		    printf("%*svalue %s: ", indent, "", "Cause");
		    if ((cause_rnw = cause->get_radioNetwork())) {
			printf("%s : %d", "radioNetwork", *cause_rnw);
		    } else if ((cause_trans = cause->get_transport())) {
			printf("%s : %d", "transport", *cause_trans);
		    } else if ((cause_nas = cause->get_nas())) {
			printf("%s : %d", "nas", *cause_nas);
		    } else if ((cause_proto = cause->get_protocol())) {
			printf("%s : %d", "protocol", *cause_proto);
		    } else if ((cause_misc = cause->get_misc())) {
			printf("%s : %d", "misc", *cause_misc);
		    } else {
			printf("Unknown alternative no. %d", cause->get_selection());
		    }
		    printf("\n");
		}
		break;
	    case id_TargetID:
		{
		    /* id-TargetID */
		    TargetID *target_id;
		    TargeteNB_ID *target_enb_id;
		    TargetRNC_ID *target_rnc_id;
		    CGI *cgi;

		    target_id = iedata.get_TargetID();
		    printf("%*svalue %s: ", indent, "", "TargetID");
		    if ((target_enb_id = target_id->get_targeteNB_ID())) {
			/* If the targeteNB-ID alternative is chosen */
			printf( "%s :\n", "targeteNB-ID");
			/* global-ENB-ID */
			printf("%*s%s:\n", indent, "", "global-ENB-ID");
			indent++;
			/* pLMNidentity */
			printf("%*s%s: ", indent, "", "pLMNidentity");

			Global_ENB_ID & g_enb_id = target_enb_id->get_global_ENB_ID();
			PLMNidentity & plmn_id = g_enb_id.get_pLMNidentity();

			printHexString(ctl, plmn_id);
			/* eNB-ID */
			printf("%*s%s: ", indent, "", "eNB-ID");

			OssBitString *enb_id;
			if ((enb_id = g_enb_id.get_eNB_ID().get_macroENB_ID())) {
			    printf("%s: ", "macroENB-ID");
			    printHexBitString(ctl, *enb_id);
			} else if ((enb_id = g_enb_id.get_eNB_ID().get_homeENB_ID())) {
			    printf("%s: ", "homeENB-ID");
			    printHexBitString(ctl, *enb_id);
			} else {
			    printf("Unknown alternative no. %d",
				    g_enb_id.get_eNB_ID().get_selection());
			}
			printProtocolExtensions(ctl, g_enb_id.get_iE_Extensions(),
				indent);
			indent --;
            		/* selected-TAI */
            		printf("%*s%s:\n", indent, "", "selected-TAI");

			TAI & tai = target_enb_id->get_selected_TAI();

            		/* pLMNidentity */
			indent ++;
            		printf("%*s%s: ", indent, "", "pLMNidentity");
            		printHexString(ctl, tai.get_pLMNidentity());

            		/* tAC */
            		printf("%*s%s: ", indent, "", "tAC");
            		printHexString(ctl, tai.get_tAC());
			printProtocolExtensions(ctl, tai.get_iE_Extensions(),
				indent);
			indent --;
			printf("\n");
			/* iE_Extensions is optional */
			printProtocolExtensions(ctl, target_enb_id->get_iE_Extensions(),
				indent);
		    } else if ((target_rnc_id = target_id->get_targetRNC_ID())) {
			/* If the targetRNC-ID alternative is chosen */
			printf("%s :\n", "targetRNC-ID");
			/* lAI */
			LAI & lai = target_rnc_id->get_lAI();

			printf("%*s%s:\n", indent, "", "lAI");
			indent++;
			/* pLMNidentity */
			printf("%*s%s: ", indent, "", "pLMNidentity");
			printHexString(ctl, lai.get_pLMNidentity());
			/* lAC */
			printf("%*s%s: ", indent, "", "lAC");
			printHexString(ctl, lai.get_lAC());
			/* iE_Extensions is optional */
			printProtocolExtensions(ctl, lai.get_iE_Extensions(),
				indent);
			indent--;
			/* rAC is optional */

			rac = target_rnc_id->get_rAC();
			if (rac) {
			    printf("%*s%s: ", indent, "", "rAC");
			    printHexString(ctl, *rac);
			}
			/* rNC-ID */
			printf("%*s%s: %u", indent, "", "rNC-ID",
				target_rnc_id->get_rNC_ID());
			/* extendedRNC-ID is optional */
			printProtocolExtensions(ctl, target_rnc_id->get_iE_Extensions(),
				indent);
			printf("\n");
		    } else if ((cgi = target_id->get_cGI())) {
			/* If the cGI alternative is chosen */
			printf("%s :\n", "cGI");
			/* pLMNidentity */
			indent++;
			printf("%*s%s: ", indent, "", "pLMNidentity");
			printHexString(ctl, cgi->get_pLMNidentity());
			/* lAC */
			printf("%*s%s: ", indent, "", "lAC");
			printHexString(ctl, cgi->get_lAC());
			/* cI */
			printf("%*s%s: ", indent, "", "cI");
			printHexString(ctl, cgi->get_cI());

			rac = cgi->get_rAC();
			/* rAC is optional */
			if (rac) {
			    printf("%*s%s: ", indent, "", "rAC");
			    printHexString(ctl, *rac);
			}
		    } else {
			printf("Unknown alternative no. %d", target_id->get_selection());
		    }
		}
		break;
	    case id_Direct_Forwarding_Path_Availability:
		{
		    /* id-Direct-Forwarding-Path-Availability */
		    Direct_Forwarding_Path_Availability *dfpa;

		    dfpa = iedata.get_Direct_Forwarding_Path_Availability();
		    printf("%*svalue %s: %u\n", indent, "", "Direct-Forwarding-Path-Availability",
			    *dfpa);
		}
		break;
	    default:
		/* Any other IE is printed generically, using ASN.1 value notation */
		s1ap_PDU ie_pdu;

		printf("%*s", indent, "");
		iedata.get_decoded(ie_pdu);
		ie_pdu.print(*ctl);
		break;
	    }
	} else {
	    printf("PDU is not decoded\n");
	}
	indent--;
    }
}

/*
 * FUNCTION     printHandoverRequiredMsg() prints an S1AP PDU which contains
 *              a HandoverRequired message.
 *
 * PARAMETERS
 *    ctl       OSS control variable
 *    request   a pointer to the S1AP PDU to print (assuming it contains a
 *              HandoverRequired message)
 */
void printHandoverRequiredMsg(OssControl *ctl, S1AP_PDU *request)
{
    InitiatingMessage *initmsg;
    HandoverRequired *hr;

    printf("\nGet message information\n");
    printBorder();

    initmsg = request->get_initiatingMessage();
    if (!initmsg) {
	/* If the message is not an InitiatingMessage */
	printf("Unexpected message id = %d\n", request->get_selection());
	throw NonASN1Exception("Unsupported message type", -1, NULL);
    }

    hr = initmsg->get_value().get_HandoverRequired();
    if (!hr) {
	/* If the message is not a HandoverRequired */
	printf("Unexpected message id = %d\n", initmsg->get_procedureCode());
	throw NonASN1Exception("Unsupported message type", -1, NULL);
    }

    printProtocolIEs(ctl, hr->get_protocolIEs(), 0);
}

/*
 * FUNCTION     createSuccessResponse() creates an S1AP successful outcome
 *              message for a given HandoverRequired request.
 *
 * PARAMETERS
 *    ctl       OSS control object
 *    request   input message (request)
 *    response  pointer to the variable that is to hold the resulting
 *              successful outcome message created by the function
 */
void createSuccessResponse(OssControl *ctl, S1AP_PDU *request,
	S1AP_PDU **response)
{
    InitiatingMessage *initmsg;
    HandoverRequired *hr;
    S1AP_PDU *resp;

    printf("\nCreate response\n");
    printBorder();

    initmsg = request->get_initiatingMessage();
    if (!initmsg) {
	/* If the message is not an InitiatingMessage */
	printf("Unexpected message id = %d\n", request->get_selection());
	throw NonASN1Exception("Unsupported message type", -1, NULL);
    }

    hr = initmsg->get_value().get_HandoverRequired();
    if (!hr) {
	/* If the message is not a HandoverRequired */
	printf("Unexpected message id = %d\n", initmsg->get_procedureCode());
	throw NonASN1Exception("Unsupported message type", -1, NULL);
    }

    /* Create a response message object */
    resp = new S1AP_PDU();

    /* Fill it */
    try {
	SuccessfulOutcome outcome_msg;
	HandoverCommand hc;
	HandoverRequired::protocolIEs &req_ies = hr->get_protocolIEs();
	HandoverRequired::protocolIEs::component *req_ie;
	HandoverCommand::protocolIEs &resp_ies = hc.get_protocolIEs();
	/*
	 * We are filling the response IE list starting from beginning.
	 * However, the OssList class has no function to append a new
	 * component to its tail (it cannot be done efiiciently because
	 * of its single-linked list representation). So, we save an OssList
	 * iterator pointing to the last component of the response IE list.
	 */
	OssIndex resp_tail = OSS_NOINDEX;

	/*
	 * Create successful outcome message from initiating message. Copy
	 * some IEs from input to output.
	 */
	for (OssIndex i = req_ies.first(); i != OSS_NOINDEX;
		i = req_ies.next(i)) {
	    req_ie = req_ies.at(i);
	    if (req_ie->get_id() == id_eNB_UE_S1AP_ID ||
		    req_ie->get_id() == id_MME_UE_S1AP_ID ||
		    req_ie->get_id() == id_HandoverType) {
		/* Copy the IE from the request to the response */
		resp_tail = resp_ies.insert_after(resp_tail,
			*(HandoverCommand::protocolIEs::component *)req_ie);
	    }
	}

	/* Add E-RABList IE to outcome message */
	HandoverCommand::protocolIEs::component resp_ie;
	E_RABList rablist;
	E_RABList::component rablist_comp;
	Cause cause;

	cause.set_radioNetwork(x2_handover_triggered);

	E_RABItem rabitem(13, cause);

	rablist_comp.set_id(id_E_RABItem);
	rablist_comp.set_criticality(ignore);
	rablist_comp.get_value().set_E_RABItem(rabitem);
	rablist.prepend(rablist_comp);

	resp_ie.set_id(id_E_RABtoReleaseListHOCmd);
	resp_ie.set_criticality(ignore);
	resp_ie.get_value().set_E_RABList(rablist);
	resp_tail = resp_ies.insert_after(resp_tail, resp_ie);

	/* Add Target-ToSource-TransparentContainer IE to outcome message */
	Target_ToSource_TransparentContainer tc(1, "\x55");

	resp_ie.set_id(id_Target_ToSource_TransparentContainer);
	resp_ie.set_criticality(reject);
	resp_ie.get_value().set_Target_ToSource_TransparentContainer(tc);
	resp_tail = resp_ies.insert_after(resp_tail, resp_ie);

	/* Construct a response message from the IE list */
	outcome_msg.set_procedureCode(initmsg->get_procedureCode());
	outcome_msg.set_criticality(reject);
	outcome_msg.get_value().set_HandoverCommand(hc);
	resp->set_successfulOutcome(outcome_msg);
	*response = resp;
    } catch (...) {
	/* Cleanup */
	delete resp;
	throw;
    }
}

/*
 * FUNCTION     testS1AP() is used to test S1AP message, the input serialized
 *              pdu is deserialized and printed, then an outcome message
 *              is created, printed and encoded.
 *
 * PARAMETERS
 *    ctl       OSS control object
 *    filename  name of file containing serialized message
 */
static void testS1AP(OssControl *ctl, const char *filename)
{
    EncodedBuffer *encoded_request;
    EncodedBuffer encoded_response;
    S1AP_PDU_PDU pdu;
    S1AP_PDU *request, *response;

    printf("======================================================"
	    "======================\n");
    printf("Read encoding from file: %s\n\n", filename);
    /* Read serialized message from file */
    encoded_request = readEncodingFromFile(filename);
    try {
	printf("Deserialize request\n");
	printBorder();

	/* Decode the input message */
	pdu.decode(*ctl, *encoded_request);

	/* Free memory allocated for encoded message */
	delete encoded_request;
	encoded_request = NULL;

	/* Print the input message in the decoded form */
	printf("\nDeserialized request\n");
	printBorder();
	pdu.print(*ctl);

	/* Access components of the message */
	request = pdu.get_data();
	printHandoverRequiredMsg(ctl, request);

	/* Create successful outcome message */
	createSuccessResponse(ctl, request, &response);

	/* Free the decoded input message */
	pdu.free_data(*ctl);

	/* Print the response message */
	pdu.set_data(*response);
	pdu.print(*ctl);

	/* Serialize response */
	printf("\nSerialize response\n");
	pdu.encode(*ctl, encoded_response);
	printf("Serialized response (%lu bytes):\n",
		encoded_response.get_length());
	printBorder();
	encoded_response.print_hex(*ctl);
	printf("\n");

	/* Free memory allocated for outcome message */
	delete response;
    } catch (...) {
	/* Cleanup in case of a possible error */
	delete encoded_request;
	throw;
    }
}

/*
 * Main application routine
 */
int main(int argc, char *argv[])
{
    int retcode;
    filesDir = argc > 1 ? argv[1] : (char *) ".";

    try {
	s1ap_Control ctl;

	/* Set the encoding rules and encoding/decoding flags */
	ctl.setEncodingRules(OSS_PER_ALIGNED);
	ctl.setEncodingFlags(AUTOMATIC_ENCDEC);
	ctl.setDecodingFlags(AUTOMATIC_ENCDEC);
	ctl.setDebugFlags(PRINT_ERROR_MESSAGES | PRINT_DECODING_DETAILS |
		PRINT_ENCODING_DETAILS);

	testS1AP(&ctl, "S1AP-PDU_HandoverRequest_bin.per");
	retcode = 0;
    } catch (ASN1RuntimeException &exc) {
        retcode = exc.get_code();
	printf("An error occurred: code = %d.\n", retcode);
    } catch (NonASN1Exception &exc) {
	printf("NonASN1Exception: ");
	retcode = exc.get_errcode();
	printf(exc.get_message(), exc.get_extra_data(), retcode);
        printf("\n");
        if (!retcode)
	    retcode = -1;
    } catch (...) {
	printf("An unexpected exception occurred.\n");
	retcode =  -1;
    }
    if (!retcode)
	printf("Testing successful.\n");

    return retcode;
}

Expected Output (Excerpt)

This is the expected output when running the sample:

Encoding response message...
Encoding successful.

ASN.1 Schema Excerpt (s1ap.asn)

Show excerpt from s1ap.asn
-- Excerpt from s1ap.asn 3GPP TS 36.413 V19.0.0 (2025-09) 

-- Elementary Procedure definitions
--
-- **************************************************************

S1AP-PDU-Descriptions  { 
itu-t (0) identified-organization (4) etsi (0) mobileDomain (0) 
eps-Access (21) modules (3) s1ap (1) version1 (1) s1ap-PDU-Descriptions (0)}

DEFINITIONS AUTOMATIC TAGS ::= 

BEGIN

-- **************************************************************
--
-- IE parameter types from other modules.
--
-- **************************************************************

IMPORTS
	Criticality,
	ProcedureCode
FROM S1AP-CommonDataTypes

	CellTrafficTrace,
	DeactivateTrace,
	DownlinkUEAssociatedLPPaTransport,
	DownlinkNASTransport,
	DownlinkNonUEAssociatedLPPaTransport,
	DownlinkS1cdma2000tunnelling,
	ENBDirectInformationTransfer,
	ENBStatusTransfer,
	ENBConfigurationUpdate,
	ENBConfigurationUpdateAcknowledge,
	ENBConfigurationUpdateFailure,
	ErrorIndication,
	HandoverCancel,
	HandoverCancelAcknowledge,
	HandoverCommand,
	HandoverFailure,
	HandoverNotify,
	HandoverPreparationFailure,
	HandoverRequest,
	HandoverRequestAcknowledge,
	HandoverRequired,
	InitialContextSetupFailure,
	InitialContextSetupRequest,
	InitialContextSetupResponse,
	InitialUEMessage,
	KillRequest,
	KillResponse,
	LocationReportingControl,
	LocationReportingFailureIndication,
	LocationReport,
	MMEConfigurationUpdate,
	MMEConfigurationUpdateAcknowledge,
	MMEConfigurationUpdateFailure,
	MMEDirectInformationTransfer,
	MMEStatusTransfer,
	NASNonDeliveryIndication,
	OverloadStart,
	OverloadStop,
	Paging,
	PathSwitchRequest,
	PathSwitchRequestAcknowledge,
	PathSwitchRequestFailure,	
	PrivateMessage,
	Reset,
	ResetAcknowledge,
	S1SetupFailure,
	S1SetupRequest,
	S1SetupResponse,
	E-RABModifyRequest,
	E-RABModifyResponse,
	E-RABModificationIndication,
	E-RABModificationConfirm,
	E-RABReleaseCommand,
	E-RABReleaseResponse,
	E-RABReleaseIndication,
	E-RABSetupRequest,
	E-RABSetupResponse,
	TraceFailureIndication,
	TraceStart,
	UECapabilityInfoIndication,
	UEContextModificationFailure,
	UEContextModificationRequest,
	UEContextModificationResponse,
	UEContextReleaseCommand,
	UEContextReleaseComplete,
	UEContextReleaseRequest,
	UERadioCapabilityMatchRequest,
	UERadioCapabilityMatchResponse,
	UplinkUEAssociatedLPPaTransport,
	UplinkNASTransport,
	UplinkNonUEAssociatedLPPaTransport,
	UplinkS1cdma2000tunnelling,
	WriteReplaceWarningRequest,
	WriteReplaceWarningResponse,
	ENBConfigurationTransfer,
	MMEConfigurationTransfer,
	PWSRestartIndication,
	UEContextModificationIndication,
	UEContextModificationConfirm,
	RerouteNASRequest,
	PWSFailureIndication,
	UEContextSuspendRequest,
	UEContextSuspendResponse,
	UEContextResumeRequest,
	UEContextResumeResponse,
	UEContextResumeFailure,
	ConnectionEstablishmentIndication,
	NASDeliveryIndication,
	RetrieveUEInformation,
	UEInformationTransfer,
	ENBCPRelocationIndication,
	MMECPRelocationIndication,
	SecondaryRATDataUsageReport,
	UERadioCapabilityIDMappingRequest,
	UERadioCapabilityIDMappingResponse,
	HandoverSuccess,
	ENBEarlyStatusTransfer,
	MMEEarlyStatusTransfer,
	S1RemovalFailure,
	S1RemovalRequest,
	S1RemovalResponse



FROM S1AP-PDU-Contents
	
	id-CellTrafficTrace,
	id-DeactivateTrace,
	id-downlinkUEAssociatedLPPaTransport,
	id-downlinkNASTransport,
	id-downlinkNonUEAssociatedLPPaTransport,
	id-DownlinkS1cdma2000tunnelling,
	id-eNBStatusTransfer,
	id-ErrorIndication,
	id-HandoverCancel,
	id-HandoverNotification,
	id-HandoverPreparation,
	id-HandoverResourceAllocation,
	id-InitialContextSetup,
	id-initialUEMessage,
	id-ENBConfigurationUpdate,
	id-Kill,
	id-LocationReportingControl,
	id-LocationReportingFailureIndication,
	id-LocationReport,
	id-eNBDirectInformationTransfer,
	id-MMEConfigurationUpdate,
	id-MMEDirectInformationTransfer,
	id-MMEStatusTransfer,
	id-NASNonDeliveryIndication,
	id-OverloadStart,
	id-OverloadStop,
	id-Paging,
	id-PathSwitchRequest,
	id-PrivateMessage,
	id-Reset,
	id-S1Setup,
	id-E-RABModify,
	id-E-RABModificationIndication,
	id-E-RABRelease,
	id-E-RABReleaseIndication,
	id-E-RABSetup,
	id-TraceFailureIndication,
	id-TraceStart,
	id-UECapabilityInfoIndication,
	id-UEContextModification,
	id-UEContextRelease,
	id-UEContextReleaseRequest,
	id-UERadioCapabilityMatch,
	id-uplinkUEAssociatedLPPaTransport,
	id-uplinkNASTransport,
	id-uplinkNonUEAssociatedLPPaTransport,
	id-UplinkS1cdma2000tunnelling,
	id-WriteReplaceWarning,
	id-eNBConfigurationTransfer,
	id-MMEConfigurationTransfer,
	id-PWSRestartIndication,
	id-UEContextModificationIndication,
	id-RerouteNASRequest,
	id-PWSFailureIndication,
	id-UEContextSuspend,
	id-UEContextResume,
	id-ConnectionEstablishmentIndication,
	id-NASDeliveryIndication,
	id-RetrieveUEInformation,
	id-UEInformationTransfer,
	id-eNBCPRelocationIndication,
	id-MMECPRelocationIndication,
	id-SecondaryRATDataUsageReport,
	id-UERadioCapabilityIDMapping,
	id-HandoverSuccess,
	id-eNBEarlyStatusTransfer,
	id-MMEEarlyStatusTransfer,
	id-S1Removal



FROM S1AP-Constants;


-- **************************************************************
--
-- Interface Elementary Procedure Class
--
-- **************************************************************

S1AP-ELEMENTARY-PROCEDURE ::= CLASS {
	&InitiatingMessage				,
	&SuccessfulOutcome							OPTIONAL,
	&UnsuccessfulOutcome						OPTIONAL,
	&procedureCode				ProcedureCode 	UNIQUE,
	&criticality				Criticality 	DEFAULT ignore
}
WITH SYNTAX {
	INITIATING MESSAGE			&InitiatingMessage
	[SUCCESSFUL OUTCOME			&SuccessfulOutcome]
	[UNSUCCESSFUL OUTCOME		&UnsuccessfulOutcome]
	PROCEDURE CODE				&procedureCode
	[CRITICALITY				&criticality]
}

-- **************************************************************
--
-- Interface PDU Definition
--
-- **************************************************************

S1AP-PDU ::= CHOICE {
	initiatingMessage	InitiatingMessage,
	successfulOutcome	SuccessfulOutcome,
	unsuccessfulOutcome	UnsuccessfulOutcome,
	...
}

InitiatingMessage ::= SEQUENCE {
	procedureCode	S1AP-ELEMENTARY-PROCEDURE.&procedureCode		({S1AP-ELEMENTARY-PROCEDURES}),
	criticality		S1AP-ELEMENTARY-PROCEDURE.&criticality			({S1AP-ELEMENTARY-PROCEDURES}{@procedureCode}),
	value			S1AP-ELEMENTARY-PROCEDURE.&InitiatingMessage	({S1AP-ELEMENTARY-PROCEDURES}{@procedureCode})
}

SuccessfulOutcome ::= SEQUENCE {
	procedureCode	S1AP-ELEMENTARY-PROCEDURE.&procedureCode		({S1AP-ELEMENTARY-PROCEDURES}),
	criticality		S1AP-ELEMENTARY-PROCEDURE.&criticality			({S1AP-ELEMENTARY-PROCEDURES}{@procedureCode}),
	value			S1AP-ELEMENTARY-PROCEDURE.&SuccessfulOutcome	({S1AP-ELEMENTARY-PROCEDURES}{@procedureCode})
}

UnsuccessfulOutcome ::= SEQUENCE {
	procedureCode	S1AP-ELEMENTARY-PROCEDURE.&procedureCode		({S1AP-ELEMENTARY-PROCEDURES}),
	criticality		S1AP-ELEMENTARY-PROCEDURE.&criticality			({S1AP-ELEMENTARY-PROCEDURES}{@procedureCode}),
	value			S1AP-ELEMENTARY-PROCEDURE.&UnsuccessfulOutcome	({S1AP-ELEMENTARY-PROCEDURES}{@procedureCode})
}

-- **************************************************************
--
-- Interface Elementary Procedure List
--
-- **************************************************************

S1AP-ELEMENTARY-PROCEDURES S1AP-ELEMENTARY-PROCEDURE ::= {
	S1AP-ELEMENTARY-PROCEDURES-CLASS-1			|
	S1AP-ELEMENTARY-PROCEDURES-CLASS-2,	
	...
}

Using ASN.1 Studio (Optional)

The gui/ subdirectory contains an ASN.1 Studio project for this sample. With ASN.1 Studio you can:

  • Open the LTE S1AP ASN.1 modules.
  • Generate code from the ASN.1 schema.
  • Create and edit sample encoded LTE S1AP messages.
  • Export projects to gmake makefiles.

Related Samples

Disclaimer

This sample is provided solely for illustration purposes, for example to demonstrate usage of the OSS ASN.1 Tools API with 3GPP LTE S1AP messages. It does not represent a complete application. To build and run this sample, you must use a trial or licensed version of the appropriate OSS ASN.1 Tools. The copyright and license statements included in each source file remain fully applicable.

Need Help?

If you have questions about using this sample, contact OSS Nokalva Support.

See Also