Initial commit
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..f6d517a
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,3 @@
+.rebar3/
+ebin/
+_build/
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..14e2f77
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,373 @@
+Mozilla Public License Version 2.0
+==================================
+
+1. Definitions
+--------------
+
+1.1. "Contributor"
+    means each individual or legal entity that creates, contributes to
+    the creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+    means the combination of the Contributions of others (if any) used
+    by a Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+    means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+    means Source Code Form to which the initial Contributor has attached
+    the notice in Exhibit A, the Executable Form of such Source Code
+    Form, and Modifications of such Source Code Form, in each case
+    including portions thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+    means
+
+    (a) that the initial Contributor has attached the notice described
+        in Exhibit B to the Covered Software; or
+
+    (b) that the Covered Software was made available under the terms of
+        version 1.1 or earlier of the License, but not also under the
+        terms of a Secondary License.
+
+1.6. "Executable Form"
+    means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+    means a work that combines Covered Software with other material, in 
+    a separate file or files, that is not Covered Software.
+
+1.8. "License"
+    means this document.
+
+1.9. "Licensable"
+    means having the right to grant, to the maximum extent possible,
+    whether at the time of the initial grant or subsequently, any and
+    all of the rights conveyed by this License.
+
+1.10. "Modifications"
+    means any of the following:
+
+    (a) any file in Source Code Form that results from an addition to,
+        deletion from, or modification of the contents of Covered
+        Software; or
+
+    (b) any new file in Source Code Form that contains any Covered
+        Software.
+
+1.11. "Patent Claims" of a Contributor
+    means any patent claim(s), including without limitation, method,
+    process, and apparatus claims, in any patent Licensable by such
+    Contributor that would be infringed, but for the grant of the
+    License, by the making, using, selling, offering for sale, having
+    made, import, or transfer of either its Contributions or its
+    Contributor Version.
+
+1.12. "Secondary License"
+    means either the GNU General Public License, Version 2.0, the GNU
+    Lesser General Public License, Version 2.1, the GNU Affero General
+    Public License, Version 3.0, or any later versions of those
+    licenses.
+
+1.13. "Source Code Form"
+    means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+    means an individual or a legal entity exercising rights under this
+    License. For legal entities, "You" includes any entity that
+    controls, is controlled by, or is under common control with You. For
+    purposes of this definition, "control" means (a) the power, direct
+    or indirect, to cause the direction or management of such entity,
+    whether by contract or otherwise, or (b) ownership of more than
+    fifty percent (50%) of the outstanding shares or beneficial
+    ownership of such entity.
+
+2. License Grants and Conditions
+--------------------------------
+
+2.1. Grants
+
+Each Contributor hereby grants You a world-wide, royalty-free,
+non-exclusive license:
+
+(a) under intellectual property rights (other than patent or trademark)
+    Licensable by such Contributor to use, reproduce, make available,
+    modify, display, perform, distribute, and otherwise exploit its
+    Contributions, either on an unmodified basis, with Modifications, or
+    as part of a Larger Work; and
+
+(b) under Patent Claims of such Contributor to make, use, sell, offer
+    for sale, have made, import, and otherwise transfer either its
+    Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+The licenses granted in Section 2.1 with respect to any Contribution
+become effective for each Contribution on the date the Contributor first
+distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+The licenses granted in this Section 2 are the only rights granted under
+this License. No additional rights or licenses will be implied from the
+distribution or licensing of Covered Software under this License.
+Notwithstanding Section 2.1(b) above, no patent license is granted by a
+Contributor:
+
+(a) for any code that a Contributor has removed from Covered Software;
+    or
+
+(b) for infringements caused by: (i) Your and any other third party's
+    modifications of Covered Software, or (ii) the combination of its
+    Contributions with other software (except as part of its Contributor
+    Version); or
+
+(c) under Patent Claims infringed by Covered Software in the absence of
+    its Contributions.
+
+This License does not grant any rights in the trademarks, service marks,
+or logos of any Contributor (except as may be necessary to comply with
+the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+No Contributor makes additional grants as a result of Your choice to
+distribute the Covered Software under a subsequent version of this
+License (see Section 10.2) or under the terms of a Secondary License (if
+permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+Each Contributor represents that the Contributor believes its
+Contributions are its original creation(s) or it has sufficient rights
+to grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+This License is not intended to limit any rights You have under
+applicable copyright doctrines of fair use, fair dealing, or other
+equivalents.
+
+2.7. Conditions
+
+Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
+in Section 2.1.
+
+3. Responsibilities
+-------------------
+
+3.1. Distribution of Source Form
+
+All distribution of Covered Software in Source Code Form, including any
+Modifications that You create or to which You contribute, must be under
+the terms of this License. You must inform recipients that the Source
+Code Form of the Covered Software is governed by the terms of this
+License, and how they can obtain a copy of this License. You may not
+attempt to alter or restrict the recipients' rights in the Source Code
+Form.
+
+3.2. Distribution of Executable Form
+
+If You distribute Covered Software in Executable Form then:
+
+(a) such Covered Software must also be made available in Source Code
+    Form, as described in Section 3.1, and You must inform recipients of
+    the Executable Form how they can obtain a copy of such Source Code
+    Form by reasonable means in a timely manner, at a charge no more
+    than the cost of distribution to the recipient; and
+
+(b) You may distribute such Executable Form under the terms of this
+    License, or sublicense it under different terms, provided that the
+    license for the Executable Form does not attempt to limit or alter
+    the recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+You may create and distribute a Larger Work under terms of Your choice,
+provided that You also comply with the requirements of this License for
+the Covered Software. If the Larger Work is a combination of Covered
+Software with a work governed by one or more Secondary Licenses, and the
+Covered Software is not Incompatible With Secondary Licenses, this
+License permits You to additionally distribute such Covered Software
+under the terms of such Secondary License(s), so that the recipient of
+the Larger Work may, at their option, further distribute the Covered
+Software under the terms of either this License or such Secondary
+License(s).
+
+3.4. Notices
+
+You may not remove or alter the substance of any license notices
+(including copyright notices, patent notices, disclaimers of warranty,
+or limitations of liability) contained within the Source Code Form of
+the Covered Software, except that You may alter any license notices to
+the extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+You may choose to offer, and to charge a fee for, warranty, support,
+indemnity or liability obligations to one or more recipients of Covered
+Software. However, You may do so only on Your own behalf, and not on
+behalf of any Contributor. You must make it absolutely clear that any
+such warranty, support, indemnity, or liability obligation is offered by
+You alone, and You hereby agree to indemnify every Contributor for any
+liability incurred by such Contributor as a result of warranty, support,
+indemnity or liability terms You offer. You may include additional
+disclaimers of warranty and limitations of liability specific to any
+jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+---------------------------------------------------
+
+If it is impossible for You to comply with any of the terms of this
+License with respect to some or all of the Covered Software due to
+statute, judicial order, or regulation then You must: (a) comply with
+the terms of this License to the maximum extent possible; and (b)
+describe the limitations and the code they affect. Such description must
+be placed in a text file included with all distributions of the Covered
+Software under this License. Except to the extent prohibited by statute
+or regulation, such description must be sufficiently detailed for a
+recipient of ordinary skill to be able to understand it.
+
+5. Termination
+--------------
+
+5.1. The rights granted under this License will terminate automatically
+if You fail to comply with any of its terms. However, if You become
+compliant, then the rights granted under this License from a particular
+Contributor are reinstated (a) provisionally, unless and until such
+Contributor explicitly and finally terminates Your grants, and (b) on an
+ongoing basis, if such Contributor fails to notify You of the
+non-compliance by some reasonable means prior to 60 days after You have
+come back into compliance. Moreover, Your grants from a particular
+Contributor are reinstated on an ongoing basis if such Contributor
+notifies You of the non-compliance by some reasonable means, this is the
+first time You have received notice of non-compliance with this License
+from such Contributor, and You become compliant prior to 30 days after
+Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+infringement claim (excluding declaratory judgment actions,
+counter-claims, and cross-claims) alleging that a Contributor Version
+directly or indirectly infringes any patent, then the rights granted to
+You by any and all Contributors for the Covered Software under Section
+2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all
+end user license agreements (excluding distributors and resellers) which
+have been validly granted by You or Your distributors under this License
+prior to termination shall survive termination.
+
+************************************************************************
+*                                                                      *
+*  6. Disclaimer of Warranty                                           *
+*  -------------------------                                           *
+*                                                                      *
+*  Covered Software is provided under this License on an "as is"       *
+*  basis, without warranty of any kind, either expressed, implied, or  *
+*  statutory, including, without limitation, warranties that the       *
+*  Covered Software is free of defects, merchantable, fit for a        *
+*  particular purpose or non-infringing. The entire risk as to the     *
+*  quality and performance of the Covered Software is with You.        *
+*  Should any Covered Software prove defective in any respect, You     *
+*  (not any Contributor) assume the cost of any necessary servicing,   *
+*  repair, or correction. This disclaimer of warranty constitutes an   *
+*  essential part of this License. No use of any Covered Software is   *
+*  authorized under this License except under this disclaimer.         *
+*                                                                      *
+************************************************************************
+
+************************************************************************
+*                                                                      *
+*  7. Limitation of Liability                                          *
+*  --------------------------                                          *
+*                                                                      *
+*  Under no circumstances and under no legal theory, whether tort      *
+*  (including negligence), contract, or otherwise, shall any           *
+*  Contributor, or anyone who distributes Covered Software as          *
+*  permitted above, be liable to You for any direct, indirect,         *
+*  special, incidental, or consequential damages of any character      *
+*  including, without limitation, damages for lost profits, loss of    *
+*  goodwill, work stoppage, computer failure or malfunction, or any    *
+*  and all other commercial damages or losses, even if such party      *
+*  shall have been informed of the possibility of such damages. This   *
+*  limitation of liability shall not apply to liability for death or   *
+*  personal injury resulting from such party's negligence to the       *
+*  extent applicable law prohibits such limitation. Some               *
+*  jurisdictions do not allow the exclusion or limitation of           *
+*  incidental or consequential damages, so this exclusion and          *
+*  limitation may not apply to You.                                    *
+*                                                                      *
+************************************************************************
+
+8. Litigation
+-------------
+
+Any litigation relating to this License may be brought only in the
+courts of a jurisdiction where the defendant maintains its principal
+place of business and such litigation shall be governed by laws of that
+jurisdiction, without reference to its conflict-of-law provisions.
+Nothing in this Section shall prevent a party's ability to bring
+cross-claims or counter-claims.
+
+9. Miscellaneous
+----------------
+
+This License represents the complete agreement concerning the subject
+matter hereof. If any provision of this License is held to be
+unenforceable, such provision shall be reformed only to the extent
+necessary to make it enforceable. Any law or regulation which provides
+that the language of a contract shall be construed against the drafter
+shall not be used to construe this License against a Contributor.
+
+10. Versions of the License
+---------------------------
+
+10.1. New Versions
+
+Mozilla Foundation is the license steward. Except as provided in Section
+10.3, no one other than the license steward has the right to modify or
+publish new versions of this License. Each version will be given a
+distinguishing version number.
+
+10.2. Effect of New Versions
+
+You may distribute the Covered Software under the terms of the version
+of the License under which You originally received the Covered Software,
+or under the terms of any subsequent version published by the license
+steward.
+
+10.3. Modified Versions
+
+If you create software not governed by this License, and you want to
+create a new license for such software, you may create and use a
+modified version of this License if you rename the license and remove
+any references to the name of the license steward (except to note that
+such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+Licenses
+
+If You choose to distribute Source Code Form that is Incompatible With
+Secondary Licenses under the terms of this version of the License, the
+notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+-------------------------------------------
+
+  This Source Code Form is subject to the terms of the Mozilla Public
+  License, v. 2.0. If a copy of the MPL was not distributed with this
+  file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular
+file, then You may include the notice in a location (such as a LICENSE
+file in a relevant directory) where a recipient would be likely to look
+for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+---------------------------------------------------------
+
+  This Source Code Form is "Incompatible With Secondary Licenses", as
+  defined by the Mozilla Public License, v. 2.0.
diff --git a/include/gsup_protocol.hrl b/include/gsup_protocol.hrl
new file mode 100644
index 0000000..15d5718
--- /dev/null
+++ b/include/gsup_protocol.hrl
@@ -0,0 +1,173 @@
+% This Source Code Form is subject to the terms of the Mozilla Public
+% License, v. 2.0. If a copy of the MPL was not distributed with this
+% file, You can obtain one at https://mozilla.org/MPL/2.0/.
+% (C) 2019 Andrey Velikiy <agreat22@gmail.com>
+% (C) 2019 Fairwaves (edited) 
+
+-ifndef(GSUP_PROTOCOL).
+-define(GSUP_PROTOCOL, true).
+
+-type 'GSUPMessageType'() :: location_upd_req
+                  | location_upd_err
+                  | location_upd_res
+                  | send_auth_info_req
+                  | send_auth_info_err
+                  | send_auth_info_res
+                  | auth_failure_report
+                  | purge_ms_req
+                  | purge_ms_err
+                  | purge_ms_res
+                  | insert_sub_data_req
+                  | insert_sub_data_err
+                  | insert_sub_data_res
+                  | delete_sub_data_req
+                  | delete_sub_data_err
+                  | delete_sub_data_res
+                  | location_cancellation_req
+                  | location_cancellation_err
+                  | location_cancellation_res
+                  | ss_req
+                  | ss_err
+                  | ss_res
+                  | mo_forward_req
+                  | mo_forward_err
+                  | mo_forward_res
+                  | mt_forward_req
+                  | mt_forward_err
+                  | mt_forward_res
+                  | ready_for_sm_req
+                  | ready_for_sm_err
+                  | ready_for_sm_res
+                  | check_imei_req
+                  | check_imei_err
+                  | check_imei_res.
+
+-type 'GSUPMessage'() :: #{
+  message_type := 'GSUPMessageType'(),
+  imsi := binary(),
+  cause => integer(),
+  auth_tuples => [#{
+    rand := binary(),
+    sres := binary(),
+    kc := binary(),
+    ik => binary(),
+    ck => binary(),
+    autn => binary(),
+    res => binary()
+  }] | [],
+  pdp_info_complete => true,
+  pdp_info_list => [#{
+    pdp_context_id => integer(),
+    pdp_type => integer(),
+    access_point_name => binary(),
+    quality_of_service => binary(),
+    pdp_charging => integer()
+  }],
+  cancellation_type => integer(),
+  freeze_p_tmsi => true,  
+  msisdn => binary(),
+  hlr_number => binary(),
+  pdp_context_id => [integer()],
+  pdp_charging => integer(),
+  rand => binary(),
+  auts => binary(),
+  cn_domain => integer(),
+  session_id => integer(),
+  session_state => integer(),
+  ss_info => binary(),
+  sm_rp_mr => integer(),
+  sm_rp_da => binary(),
+  sm_rp_oa => binary(),
+  sm_rp_ui => binary(),
+  sm_rp_cause => integer(),
+  sm_rp_mms => integer(),
+  sm_alert_reason => integer(),
+  imei => binary(),
+  imei_check_result => integer()
+}.
+
+-define(SESSION_STATE_BEGIN, 1).
+-define(SESSION_STATE_CONTINUE, 2).
+-define(SESSION_STATE_END, 3).
+
+-define(IMSI, 16#01).
+-define(CAUSE, 16#02).
+-define(AUTH_TUPLE, 16#03).
+-define(PDP_INFO_COMPLETE, 16#04).
+-define(PDP_INFO, 16#05).
+-define(CANCELLATION_TYPE, 16#06).
+-define(FREEZE_P_TMSI, 16#07).
+-define(MSISDN, 16#08).
+-define(HLR_NUMBER, 16#09).
+-define(PDP_CONTEXT_ID, 16#10).
+-define(PDP_TYPE, 16#11).
+-define(ACCESS_POINT_NAME, 16#12).
+-define(QUALITY_OF_SERVICE, 16#13).
+-define(PDP_CHARGING, 16#14).
+-define(RAND, 16#20).
+-define(SRES, 16#21).
+-define(KC, 16#22).
+-define(IK, 16#23).
+-define(CK, 16#24).
+-define(AUTN, 16#25).
+-define(AUTS, 16#26).
+-define(RES, 16#27).
+-define(CN_DOMAIN, 16#28).
+-define(SESSION_ID, 16#30).
+-define(SESSION_STATE, 16#31).
+-define(SS_INFO, 16#35).
+-define(SM_RP_MR, 16#40).
+-define(SM_RP_DA, 16#41).
+-define(SM_RP_OA, 16#42).
+-define(SM_RP_UI, 16#43).
+-define(SM_RP_CAUSE, 16#44).
+-define(SM_RP_MMS, 16#45).
+-define(SM_ALERT_REASON, 16#46).
+-define(IMEI, 16#50).
+-define(IMEI_CHECK_RESULT, 16#51).
+
+-define(MANDATORY_DEFAULT, [imsi, message_type]).
+
+-define (GSUP_MESSAGES(), #{
+  16#04 => #{message_type => location_upd_req, mandatory => [], optional => [cn_domain]},
+  16#05 => #{message_type => location_upd_err, mandatory => [cause]},
+  16#06 => #{message_type => location_upd_res, mandatory => [], optional => [msisdn, hlr_number, pdp_info_complete, pdp_info_list]},
+  16#08 => #{message_type => send_auth_info_req, mandatory => [], optional => [cn_domain, auts, rand]},
+  16#09 => #{message_type => send_auth_info_err, mandatory => [cause]},
+  16#0a => #{message_type => send_auth_info_res, mandatory => [], optional => [auth_tuples]},
+  16#0b => #{message_type => auth_failure_report, mandatory => [], optional => [cn_domain]},
+  16#0c => #{message_type => purge_ms_req, mandatory => [hlr_number], optional => [cn_domain]},
+  16#0d => #{message_type => purge_ms_err, mandatory => [cause]},
+  16#0e => #{message_type => purge_ms_res, mandatory => [freeze_p_tmsi]},
+  16#10 => #{message_type => insert_sub_data_req, mandatory => [pdp_info_complete], optional => [cn_domain, msisdn, hlr_number, pdp_info_list, pdp_charging]},
+  16#11 => #{message_type => insert_sub_data_err, mandatory => [cause]},
+  16#12 => #{message_type => insert_sub_data_res, mandatory => []},
+  16#14 => #{message_type => delete_sub_data_req, mandatory => [], optional => [cn_domain, pdp_context_id]},
+  16#15 => #{message_type => delete_sub_data_err, mandatory => [cause]},
+  16#16 => #{message_type => delete_sub_data_res, mandatory => []},
+  16#1c => #{message_type => location_cancellation_req, mandatory => [], optional => [cn_domain, cancellation_type]},
+  16#1d => #{message_type => location_cancellation_err, mandatory => [cause]},
+  16#1e => #{message_type => location_cancellation_res, mandatory => [], optional => [cn_domain]},
+  16#20 => #{message_type => ss_req, mandatory => [session_id, session_state], optional => [ss_info]},
+  16#21 => #{message_type => ss_err, mandatory => [session_id, session_state, cause]},
+  16#22 => #{message_type => ss_res, mandatory => [session_id, session_state], optional => [ss_info]},
+  16#24 => #{message_type => mo_forward_req, mandatory => [sm_rp_mr, sm_rp_da, sm_rp_oa, sm_rp_ui]},
+  16#25 => #{message_type => mo_forward_err, mandatory => [sm_rp_mr, sm_rp_cause], optional => [sm_rp_ui]},
+  16#26 => #{message_type => mo_forward_res, mandatory => [sm_rp_mr]},
+  16#28 => #{message_type => mt_forward_req, mandatory => [sm_rp_mr, sm_rp_da, sm_rp_oa, sm_rp_ui], optional => [sm_rp_mms]},
+  16#29 => #{message_type => mt_forward_err, mandatory => [sm_rp_mr, sm_rp_cause], optional => [sm_rp_ui]},
+  16#2a => #{message_type => mt_forward_res, mandatory => [sm_rp_mr]},
+  16#2c => #{message_type => ready_for_sm_req, mandatory => [sm_rp_mr, sm_alert_reason]},
+  16#2d => #{message_type => ready_for_sm_err, mandatory => [sm_rp_mr, sm_sm_rp_cause], optional => [sm_rp_ui]},
+  16#2e => #{message_type => ready_for_sm_res, mandatory => [sm_rp_mr]},
+  16#30 => #{message_type => check_imei_req, mandatory => [imei]},
+  16#31 => #{message_type => check_imei_err, mandatory => [cause]},
+  16#32 => #{message_type => check_imei_res, mandatory => [imei_check_result]}
+}).
+
+-define(AUTH_TUPLE_MANDATORY, [rand, sres, kc]).
+-define(AUTH_TUPLE_OPTIONAL, [ik, ck, autn, res]).
+-define(PDP_INFO_MANDATORY, []).
+-define(PDP_INFO_OPTIONAL, [pdp_context_id, pdp_type, access_point_name, quality_of_service, pdp_charging]).
+
+-endif.
diff --git a/include/ipa.hrl b/include/ipa.hrl
new file mode 100644
index 0000000..95808d4
--- /dev/null
+++ b/include/ipa.hrl
@@ -0,0 +1,19 @@
+% This Source Code Form is subject to the terms of the Mozilla Public
+% License, v. 2.0. If a copy of the MPL was not distributed with this
+% file, You can obtain one at https://mozilla.org/MPL/2.0/.
+% (C) 2019 Andrey Velikiy <agreat22@gmail.com>
+% (C) 2019 Fairwaves (edited) 
+
+-ifndef(IPA).
+-define(IPA, true).
+
+-define(IPAC_PROTO_OSMO, 16#ee).
+-define(IPAC_PROTO_EXT_GSUP, 16#05).
+-define(IPAC_PROTO_IPACCESS, 16#fe).
+-define(IPAC_MSGT_PING, 0).
+-define(IPAC_MSGT_PONG, 1).
+-define(IPAC_MSGT_ID_GET, 4).
+-define(IPAC_MSGT_ID_RESP, 5).
+-define(IPAC_MSGT_ID_ACK, 6).
+
+-endif.
diff --git a/rebar.config b/rebar.config
new file mode 100644
index 0000000..4aa32ed
--- /dev/null
+++ b/rebar.config
@@ -0,0 +1,19 @@
+%% -*- erlang -*-
+
+{minimum_otp_vsn, "21"}.
+
+{erl_opts, [
+    warn_unused_vars,
+    debug_info
+]}.
+
+{xref_checks, [
+    undefined_function_calls,
+    undefined_functions,
+    locals_not_used,
+    deprecated_function_calls,
+    deprecated_functions
+]}.
+
+{deps, [
+]}.
diff --git a/rebar.lock b/rebar.lock
new file mode 100644
index 0000000..57afcca
--- /dev/null
+++ b/rebar.lock
@@ -0,0 +1 @@
+[].
diff --git a/src/gsup_protocol.erl b/src/gsup_protocol.erl
new file mode 100644
index 0000000..26c1211
--- /dev/null
+++ b/src/gsup_protocol.erl
@@ -0,0 +1,519 @@
+% This Source Code Form is subject to the terms of the Mozilla Public
+% License, v. 2.0. If a copy of the MPL was not distributed with this
+% file, You can obtain one at https://mozilla.org/MPL/2.0/.
+% (C) 2019 Andrey Velikiy <agreat22@gmail.com>
+% (C) 2019 Fairwaves (edited) 
+
+-module(gsup_protocol).
+
+-include ("gsup_protocol.hrl").
+-include ("ipa.hrl").
+
+-export([decode/1, encode/1, decode_bcd/1, encode_bcd/1]).
+-export_type(['GSUPMessage'/0, 'GSUPMessageType'/0]).
+
+-define (CHECK_SIZE(IE, Len, Value),
+  Value >= 0 andalso Value < (1 bsl (Len * 8)) orelse error({ie_value_length_mismatch, IE, Value})
+  ).
+
+-define (CHECK_LEN(IE, Len, Min, Max),
+  Len >= Min andalso Len =< Max orelse error({ie_length_mismatch, IE, Len})
+  ).
+
+-ifdef (TEST).
+-export ([encode_ie/2, decode_ie/2]).
+-endif.
+
+-spec decode(binary()) -> 'GSUPMessage'() | no_return().
+decode(<<MsgType, Tail/binary>>) ->
+  case ?GSUP_MESSAGES() of
+    #{MsgType := #{message_type := MsgTypeAtom, mandatory := Mandatory0}} ->
+      GSUPMessage = decode_ie(Tail, #{message_type => MsgTypeAtom}),
+      Mandatory = Mandatory0 ++ ?MANDATORY_DEFAULT,
+      case maps:size(maps:with(Mandatory, GSUPMessage)) == length(Mandatory) of
+        true -> GSUPMessage;
+        false -> error({mandatory_ie_missing, MsgTypeAtom, Mandatory -- maps:keys(GSUPMessage)})
+      end;
+    _ -> 
+      error({unknown_gsup_msg_type, MsgType})
+  end.
+
+decode_ie(<<>>, Map) -> Map;
+
+decode_ie(<<?IMSI, Len, IMSI:Len/binary, Tail/binary>>, Map) ->
+  ?CHECK_LEN(imsi, Len, 0, 8),
+  decode_ie(Tail, Map#{imsi => decode_bcd(IMSI, <<>>)});
+
+decode_ie(<<?CAUSE, Len, Cause:Len/unit:8, Tail/binary>>, Map) ->
+  ?CHECK_LEN(cause, Len, 1, 1),
+  decode_ie(Tail, Map#{cause => Cause});
+
+decode_ie(<<?AUTH_TUPLE, Len, AuthTuple0:Len/binary, Tail/binary>>, Map) ->
+  List = maps:get(auth_tuples, Map, []),
+  ?CHECK_LEN(auth_tuples, length(List) + 1, 1, 5),
+  AuthTuple = decode_auth_tuple(AuthTuple0, #{}),
+  check_auth_tuple(AuthTuple) orelse error({bad_auth_tuple, AuthTuple}),
+  decode_ie(Tail, Map#{auth_tuples => List ++ [AuthTuple]});
+
+decode_ie(<<?PDP_INFO_COMPLETE, Len, _:Len/binary, Tail/binary>>, Map) ->
+  ?CHECK_LEN(pdp_info_complete, Len, 0, 0),
+  decode_ie(Tail, Map#{pdp_info_complete => true});
+
+decode_ie(<<?PDP_INFO, Len, PDPInfo0:Len/binary, Tail/binary>>, Map) ->
+  List = maps:get(pdp_info_list, Map, []),
+  ?CHECK_LEN(pdp_info_list, length(List) + 1, 1, 10),
+  PDPInfo = decode_pdp_info(PDPInfo0, #{}),
+  check_pdp_info(PDPInfo) orelse error({bad_pdp_info, PDPInfo}),
+  decode_ie(Tail, Map#{pdp_info_list => List ++ [PDPInfo]});
+
+decode_ie(<<?CANCELLATION_TYPE, Len, CancellationType:Len/unit:8, Tail/binary>>, Map) ->
+  ?CHECK_LEN(cancellation_type, Len, 1, 1),
+  decode_ie(Tail, Map#{cancellation_type => CancellationType});
+
+decode_ie(<<?FREEZE_P_TMSI, Len, _:Len/binary, Tail/binary>>, Map) ->
+  ?CHECK_LEN(freeze_p_tmsi, Len, 0, 0),
+  decode_ie(Tail, Map#{freeze_p_tmsi => true});
+
+decode_ie(<<?MSISDN, Len, MSISDN:Len/binary, Tail/binary>>, Map) ->
+  ?CHECK_LEN(msisdn, Len, 0, 8),
+  decode_ie(Tail, Map#{msisdn => MSISDN});
+
+decode_ie(<<?HLR_NUMBER, Len, HLRNumber:Len/binary, Tail/binary>>, Map) ->
+  ?CHECK_LEN(hlr_number, Len, 0, 8),
+  decode_ie(Tail, Map#{hlr_number => HLRNumber});
+
+decode_ie(<<?PDP_CONTEXT_ID, Len, PDPContextId:Len/unit:8, Tail/binary>>, Map) ->
+  ?CHECK_LEN(pdp_context_id, Len, 1, 1),
+  List = maps:get(pdp_context_id, Map, []),
+  ?CHECK_LEN(pdp_context_id_list, length(List) + 1, 1, 10),
+  decode_ie(Tail, Map#{pdp_context_id => List ++ [PDPContextId]});
+
+decode_ie(<<?PDP_CHARGING, Len, PDPCharging:Len/unit:8, Tail/binary>>, Map) ->
+  ?CHECK_LEN(pdp_charging, Len, 2, 2),
+  decode_ie(Tail, Map#{pdp_charging => PDPCharging});
+
+decode_ie(<<?RAND, Len, Rand:Len/unit:8, Tail/binary>>, Map) ->
+  ?CHECK_LEN(rand, Len, 16, 16),
+  decode_ie(Tail, Map#{rand => Rand});
+
+decode_ie(<<?AUTS, Len, AUTS:Len/unit:8, Tail/binary>>, Map) ->
+  ?CHECK_LEN(auts, Len, 14, 14),
+  decode_ie(Tail, Map#{auts => AUTS});
+
+decode_ie(<<?CN_DOMAIN, Len, CN_Domain:Len/unit:8, Tail/binary>>, Map) ->
+  ?CHECK_LEN(cn_domain, Len, 1, 1),
+  decode_ie(Tail, Map#{cn_domain => CN_Domain});
+
+decode_ie(<<?SESSION_ID, Len, SesID:Len/unit:8, Tail/binary>>, Map) ->
+  ?CHECK_LEN(session_id, Len, 4, 4),
+  decode_ie(Tail, Map#{session_id => SesID});
+
+decode_ie(<<?SESSION_STATE, Len, SesState:Len/unit:8, Tail/binary>>, Map) ->
+  ?CHECK_LEN(session_state, Len, 1, 1),
+  decode_ie(Tail, Map#{session_state => SesState});
+
+decode_ie(<<?SS_INFO, Len, SesInfo:Len/binary, Tail/binary>>, Map) ->
+  decode_ie(Tail, Map#{ss_info => SesInfo});
+
+decode_ie(<<?SM_RP_MR, Len, MsgRef:Len/unit:8, Tail/binary>>, Map) ->
+  ?CHECK_LEN(sm_rp_mr, Len, 1, 1),
+  decode_ie(Tail, Map#{sm_rp_mr => MsgRef});
+
+decode_ie(<<?SM_RP_DA, Len, DA:Len/binary, Tail/binary>>, Map) ->
+  decode_ie(Tail, Map#{sm_rp_da => DA});
+
+decode_ie(<<?SM_RP_OA, Len, OA:Len/binary, Tail/binary>>, Map) ->
+  decode_ie(Tail, Map#{sm_rp_oa => OA});
+
+decode_ie(<<?SM_RP_UI, Len, MessageBody:Len/binary, Tail/binary>>, Map) ->
+  decode_ie(Tail, Map#{sm_rp_ui => MessageBody});
+
+decode_ie(<<?SM_RP_CAUSE, Len, RPCause:Len/unit:8, Tail/binary>>, Map) ->
+  ?CHECK_LEN(sm_rp_cause, Len, 1, 1),
+  decode_ie(Tail, Map#{sm_rp_cause => RPCause});
+
+decode_ie(<<?SM_RP_MMS, Len, RPMMS:Len/unit:8, Tail/binary>>, Map) ->
+  ?CHECK_LEN(sm_rp_mms, Len, 1, 1),
+  decode_ie(Tail, Map#{sm_rp_mms => RPMMS});
+
+decode_ie(<<?SM_ALERT_REASON, Len, AlertReason:Len/unit:8, Tail/binary>>, Map) ->
+  decode_ie(Tail, Map#{sm_alert_reason => AlertReason});
+
+decode_ie(<<?IMEI, Len, IMEI:Len/binary, Tail/binary>>, Map) ->
+  ?CHECK_LEN(imei, Len, 9, 9),
+  decode_ie(Tail, Map#{imei => IMEI});
+
+decode_ie(<<?IMEI_CHECK_RESULT, Len, IMEIResult:Len/unit:8, Tail/binary>>, Map) ->
+  ?CHECK_LEN(imei_check_result, Len, 1, 1),
+  decode_ie(Tail, Map#{imei_check_result => IMEIResult});
+
+decode_ie(<<_, Len, _:Len/binary, Tail/binary>>, Map) -> %% skip unknown IE
+  decode_ie(Tail, Map);
+
+decode_ie(X, Map) ->
+  error({cannot_decode_ie, X, Map}).
+
+-spec decode_bcd(binary()) -> binary().
+decode_bcd(BCDNumber) -> decode_bcd(BCDNumber, <<>>).
+
+decode_bcd(<<>>, Number) -> Number;
+
+decode_bcd(<<A:4, B:4, Tail/binary>>, Number) when A < 15, B < 15 ->
+  decode_bcd(Tail, <<Number/binary, (decode_nibble(B)), (decode_nibble(A))>>);
+
+decode_bcd(<<_:4, B:4, _Tail/binary>>, Number) when B < 15 ->
+  <<Number/binary, (decode_nibble(B))>>.
+
+decode_nibble(0) -> $0;
+decode_nibble(1) -> $1;
+decode_nibble(2) -> $2;
+decode_nibble(3) -> $3;
+decode_nibble(4) -> $4;
+decode_nibble(5) -> $5;
+decode_nibble(6) -> $6;
+decode_nibble(7) -> $7;
+decode_nibble(8) -> $8;
+decode_nibble(9) -> $9;
+decode_nibble(10) -> $*;
+decode_nibble(11) -> $#;
+decode_nibble(12) -> $a;
+decode_nibble(13) -> $b;
+decode_nibble(14) -> $c.
+
+decode_auth_tuple(<<?RAND, Len, Rand:Len/binary, Tail/binary>>, Map) ->
+  ?CHECK_LEN(rand, Len, 16, 16),
+  decode_auth_tuple(Tail, Map#{rand => Rand});
+
+decode_auth_tuple(<<?SRES, Len, SRES:Len/binary, Tail/binary>>, Map) ->
+  ?CHECK_LEN(sres, Len, 4, 4),
+  decode_auth_tuple(Tail, Map#{sres => SRES});
+
+decode_auth_tuple(<<?KC, Len, KC:Len/binary, Tail/binary>>, Map) ->
+  ?CHECK_LEN(kc, Len, 8, 8),
+  decode_auth_tuple(Tail, Map#{kc => KC});
+
+decode_auth_tuple(<<?IK, Len, IK:Len/binary, Tail/binary>>, Map) ->
+  ?CHECK_LEN(ik, Len, 16, 16),
+  decode_auth_tuple(Tail, Map#{ik => IK});
+
+decode_auth_tuple(<<?CK, Len, CK:Len/binary, Tail/binary>>, Map) ->
+  ?CHECK_LEN(ck, Len, 16, 16),
+  decode_auth_tuple(Tail, Map#{ck => CK});
+
+decode_auth_tuple(<<?AUTN, Len, AUTN:Len/binary, Tail/binary>>, Map) ->
+  ?CHECK_LEN(autn, Len, 16, 16),
+  decode_auth_tuple(Tail, Map#{autn => AUTN});
+
+decode_auth_tuple(<<?RES, Len, Res:Len/binary, Tail/binary>>, Map) ->
+  ?CHECK_LEN(res, Len, 0, 16),
+  decode_auth_tuple(Tail, Map#{res => Res});
+
+decode_auth_tuple(<<>>, Map) -> Map.
+
+decode_pdp_info(<<?PDP_CONTEXT_ID, Len, PDPContextId:Len/unit:8, Tail/binary>>, Map) ->
+  ?CHECK_LEN(pdp_context_id, Len, 1, 1),
+  decode_pdp_info(Tail, Map#{pdp_context_id => PDPContextId});
+
+decode_pdp_info(<<?PDP_TYPE, Len, PDPType:Len/unit:8, Tail/binary>>, Map) ->
+  ?CHECK_LEN(pdp_type, Len, 2, 2),
+  decode_pdp_info(Tail, Map#{pdp_type => PDPType});
+
+decode_pdp_info(<<?ACCESS_POINT_NAME, Len, APN:Len/binary, Tail/binary>>, Map) ->
+  ?CHECK_LEN(access_point_name, Len, 1, 100),
+  decode_pdp_info(Tail, Map#{access_point_name => APN});
+
+decode_pdp_info(<<?QUALITY_OF_SERVICE, Len, QOS:Len/binary, Tail/binary>>, Map) ->
+  ?CHECK_LEN(quality_of_service, Len, 1, 20),
+  decode_pdp_info(Tail, Map#{quality_of_service => QOS});
+
+decode_pdp_info(<<?PDP_CHARGING, Len, PDPCharging:Len/unit:8, Tail/binary>>, Map) ->
+  ?CHECK_LEN(pdp_charging, Len, 2, 2),
+  decode_pdp_info(Tail, Map#{pdp_charging => PDPCharging});
+
+decode_pdp_info(<<>>, Map) -> Map.
+
+-spec encode('GSUPMessage'()) -> binary() | no_return().
+encode(GSUPMessage = #{message_type := MsgTypeAtom}) when is_atom(MsgTypeAtom) ->
+  F = fun
+    (MsgType_, #{message_type := MsgTypeAtom_}, undefined) when MsgTypeAtom_ == MsgTypeAtom -> MsgType_;
+    (_, _, Acc) -> Acc
+  end,
+  case maps:fold(F, undefined, ?GSUP_MESSAGES()) of
+    undefined -> error({unknown_message_type, MsgTypeAtom}), MsgType = undefined;
+    MsgType when is_integer(MsgType) -> ok
+  end,
+  encode(MsgType, GSUPMessage).
+
+encode(MsgType, GSUPMessage) when is_integer(MsgType), is_map(GSUPMessage), MsgType >=0, MsgType =< 255 ->
+  case ?GSUP_MESSAGES() of
+    #{MsgType := #{message_type := MsgTypeAtom, mandatory := Mandatory0} = Map} ->
+      Mandatory = Mandatory0 ++ ?MANDATORY_DEFAULT,
+      Possible = Mandatory ++ maps:get(optional, Map, []),
+      case {maps:size(maps:with(Mandatory, GSUPMessage)) == length(Mandatory),
+            maps:size(maps:without(Possible, GSUPMessage)) == 0} of
+        {true, true} -> 
+          Tail = encode_ie(GSUPMessage, <<>>),
+          <<MsgType, Tail/binary>>;
+        {false, _} -> error({mandatory_ie_missing, MsgTypeAtom, Mandatory -- maps:keys(GSUPMessage)});
+        {_, false} -> error({ie_not_expected, MsgTypeAtom, maps:keys(GSUPMessage) -- Possible})
+      end;
+    _ -> 
+      error({unknown_gsup_msg_type, MsgType})
+  end.
+
+encode_ie(#{imsi := Value0} = GSUPMessage, Head) ->
+  Value = encode_bcd(Value0, <<>>),
+  Len = size(Value),
+  ?CHECK_LEN(imsi, Len, 0, 8),
+  encode_ie(maps:without([imsi], GSUPMessage), <<Head/binary, ?IMSI, Len, Value/binary>>);
+
+encode_ie(#{cause := Value} = GSUPMessage, Head) ->
+  Len = 1,
+  ?CHECK_SIZE(cause, Len, Value),
+  encode_ie(maps:without([cause], GSUPMessage), <<Head/binary, ?CAUSE, Len, Value:Len/unit:8>>);
+
+encode_ie(#{auth_tuples := Tuples0} = GSUPMessage, Head) ->
+  ?CHECK_LEN(auth_tuples, length(Tuples0), 0, 5),
+  Tuples = <<
+    begin
+      check_auth_tuple(Tuple) orelse error({bad_auth_tuple, Tuple}),
+      Value = encode_auth_tuple(Tuple, <<>>),
+      Len = size(Value),
+      <<?AUTH_TUPLE, Len, Value/binary>>
+    end || Tuple <- Tuples0>>,
+  encode_ie(maps:without([auth_tuples], GSUPMessage), <<Head/binary, Tuples/binary>>);
+
+encode_ie(#{pdp_info_complete := true} = GSUPMessage, Head) ->
+  encode_ie(maps:without([pdp_info_complete], GSUPMessage), <<Head/binary, ?PDP_INFO_COMPLETE, 0>>);
+
+encode_ie(#{pdp_info_complete := _} = _GSUPMessage, _Head) ->
+  error(pdp_info_complete_must_be_true);
+
+encode_ie(#{pdp_info_list := PDPInfoList0} = GSUPMessage, Head) -> %% PDPInfo
+  ?CHECK_LEN(pdp_info_list, length(PDPInfoList0), 0, 10),
+  PDPInfoList = <<
+    begin
+      check_pdp_info(PDPInfo) orelse error({bad_pdp_info, PDPInfo}),
+      Value = encode_pdp_info(PDPInfo, <<>>),
+      Len = size(Value),
+      <<?PDP_INFO, Len, Value/binary>>
+    end || PDPInfo <- PDPInfoList0>>,
+  encode_ie(maps:without([pdp_info_list], GSUPMessage), <<Head/binary, PDPInfoList/binary>>);
+
+encode_ie(#{cancellation_type := Value} = GSUPMessage, Head) ->
+  Len = 1,
+  ?CHECK_SIZE(cancellation_type, Len, Value),
+  encode_ie(maps:without([cancellation_type], GSUPMessage), <<Head/binary, ?CANCELLATION_TYPE, Len, Value:Len/unit:8>>);
+
+encode_ie(#{freeze_p_tmsi := true} = GSUPMessage, Head) ->
+  encode_ie(maps:without([freeze_p_tmsi], GSUPMessage), <<Head/binary, ?FREEZE_P_TMSI, 0>>);
+
+encode_ie(#{freeze_p_tmsi := _} = _GSUPMessage, _Head) ->
+  error(freeze_p_tmsi_must_be_true);
+
+encode_ie(#{msisdn := Value} = GSUPMessage, Head) ->
+  Len = size(Value),
+  ?CHECK_LEN(msisdn, Len, 0, 8),
+  encode_ie(maps:without([msisdn], GSUPMessage), <<Head/binary, ?MSISDN, Len, Value/binary>>);
+
+encode_ie(#{hlr_number := Value} = GSUPMessage, Head) ->
+  Len = size(Value),
+  ?CHECK_LEN(hlr_number, Len, 0, 8),
+  encode_ie(maps:without([hlr_number], GSUPMessage), <<Head/binary, ?HLR_NUMBER, Len, Value/binary>>);
+
+encode_ie(#{pdp_context_id := PDPCIdList0} = GSUPMessage, Head) ->
+  Len = 1,
+  PDPCIdList = <<
+    begin
+      ?CHECK_SIZE(pdp_context_id, Len, Value),
+      <<?PDP_CONTEXT_ID, Len, Value:Len/unit:8>>
+    end || Value <- PDPCIdList0>>,
+  encode_ie(maps:without([pdp_context_id], GSUPMessage), <<Head/binary, PDPCIdList/binary>>);
+
+encode_ie(#{pdp_charging := Value} = GSUPMessage, Head) ->
+  Len = 2,
+  ?CHECK_SIZE(pdp_charging, Len, Value),
+  encode_ie(maps:without([pdp_charging], GSUPMessage), <<Head/binary, ?PDP_CHARGING, Len, Value:Len/unit:8>>);
+
+encode_ie(#{rand := Value} = GSUPMessage, Head) ->
+  Len = 16,
+  ?CHECK_LEN(rand, size(Value), Len, Len),
+  encode_ie(maps:without([rand], GSUPMessage), <<Head/binary, ?RAND, Len, Value:Len/unit:8>>);
+
+encode_ie(#{auts := Value} = GSUPMessage, Head) ->
+  Len = 14,
+  ?CHECK_LEN(auts, size(Value), Len, Len),
+  encode_ie(maps:without([auts], GSUPMessage), <<Head/binary, ?AUTS, Len, Value:Len/unit:8>>);
+
+encode_ie(#{cn_domain := Value} = GSUPMessage, Head) ->
+  Len = 1,
+  ?CHECK_SIZE(cn_domain, Len, Value),
+  encode_ie(maps:without([cn_domain], GSUPMessage), <<Head/binary, ?CN_DOMAIN, Len, Value:Len/unit:8>>);
+
+encode_ie(#{session_id := Value} = GSUPMessage, Head) ->
+  Len = 4,
+  ?CHECK_SIZE(session_id, Len, Value),
+  encode_ie(maps:without([session_id], GSUPMessage), <<Head/binary, ?SESSION_ID, Len, Value:Len/unit:8>>);
+
+encode_ie(#{session_state := Value} = GSUPMessage, Head) ->
+  Len = 1,
+  ?CHECK_SIZE(session_state, Len, Value),
+  encode_ie(maps:without([session_state], GSUPMessage), <<Head/binary, ?SESSION_STATE, Len, Value:Len/unit:8>>);
+
+encode_ie(#{ss_info := Value} = GSUPMessage, Head) ->
+  Len = size(Value),
+  encode_ie(maps:without([ss_info], GSUPMessage), <<Head/binary, ?SS_INFO, Len, Value/binary>>);
+
+encode_ie(#{sm_rp_mr := Value} = GSUPMessage, Head) ->
+  Len = 1,
+  ?CHECK_SIZE(sm_rp_mr, Len, Value),
+  encode_ie(maps:without([sm_rp_mr], GSUPMessage), <<Head/binary, ?SM_RP_MR, Len, Value:Len/unit:8>>);
+
+encode_ie(#{sm_rp_da := Value} = GSUPMessage, Head) ->
+  Len = size(Value),
+  encode_ie(maps:without([sm_rp_da], GSUPMessage), <<Head/binary, ?SM_RP_DA, Len, Value/binary>>);
+
+encode_ie(#{sm_rp_oa := Value} = GSUPMessage, Head) ->
+  Len = size(Value),
+  encode_ie(maps:without([sm_rp_oa], GSUPMessage), <<Head/binary, ?SM_RP_OA, Len, Value/binary>>);
+
+encode_ie(#{sm_rp_ui := Value} = GSUPMessage, Head) ->
+  Len = size(Value),
+  encode_ie(maps:without([sm_rp_ui], GSUPMessage), <<Head/binary, ?SM_RP_UI, Len, Value/binary>>);
+
+encode_ie(#{sm_rp_cause := Value} = GSUPMessage, Head) ->
+  Len = 1,
+  ?CHECK_SIZE(sm_rp_cause, Len, Value),
+  encode_ie(maps:without([sm_rp_cause], GSUPMessage), <<Head/binary, ?SM_RP_CAUSE, Len, Value:Len/unit:8>>);
+
+encode_ie(#{sm_rp_mms := Value} = GSUPMessage, Head) ->
+  Len = 1,
+  ?CHECK_SIZE(sm_rp_mms, Len, Value),
+  encode_ie(maps:without([sm_rp_mms], GSUPMessage), <<Head/binary, ?SM_RP_MMS, Len, Value:Len/unit:8>>);
+
+encode_ie(#{sm_alert_reason := Value} = GSUPMessage, Head) ->
+  Len = 1,
+  ?CHECK_SIZE(sm_alert_reason, Len, Value),
+  encode_ie(maps:without([sm_alert_reason], GSUPMessage), <<Head/binary, ?SM_ALERT_REASON, Len, Value:Len/unit:8>>);
+
+encode_ie(#{imei := Value} = GSUPMessage, Head) ->
+  Len = size(Value),
+  encode_ie(maps:without([imei], GSUPMessage), <<Head/binary, ?IMEI, Len, Value/binary>>);
+
+encode_ie(#{imei_check_result := Value} = GSUPMessage, Head) ->
+  Len = 1,
+  ?CHECK_SIZE(imei_check_result, Len, Value),
+  encode_ie(maps:without([imei_check_result], GSUPMessage), <<Head/binary, ?IMEI_CHECK_RESULT, Len, Value:Len/unit:8>>);
+
+encode_ie(_, Head) -> Head.
+
+encode_bcd(BCDNumber) -> encode_bcd(BCDNumber, <<>>).
+
+encode_bcd(<<A, B, Tail/binary>>, BCDNumber) ->
+  encode_bcd(Tail, <<BCDNumber/binary, (encode_nibble(B)):4, (encode_nibble(A)):4>>);
+
+encode_bcd(<<A>>, BCDNumber) ->
+  <<BCDNumber/binary, 16#f:4, (encode_nibble(A)):4>>;
+
+encode_bcd(<<>>, BCDNumber) ->
+  BCDNumber.
+
+encode_nibble($0) -> 0;
+encode_nibble($1) -> 1;
+encode_nibble($2) -> 2;
+encode_nibble($3) -> 3;
+encode_nibble($4) -> 4;
+encode_nibble($5) -> 5;
+encode_nibble($6) -> 6;
+encode_nibble($7) -> 7;
+encode_nibble($8) -> 8;
+encode_nibble($9) -> 9;
+encode_nibble($*) -> 10;
+encode_nibble($#) -> 11;
+encode_nibble($a) -> 12;
+encode_nibble($b) -> 13;
+encode_nibble($c) -> 14;
+encode_nibble($A) -> 12;
+encode_nibble($B) -> 13;
+encode_nibble($C) -> 14;
+encode_nibble(X) -> error({bad_bcd_character, X}).
+
+check_auth_tuple(AuthTuple) ->
+  Mandatory = ?AUTH_TUPLE_MANDATORY,
+  Possible = Mandatory ++ ?AUTH_TUPLE_OPTIONAL,
+  (maps:size(maps:with(Mandatory, AuthTuple)) == length(Mandatory))
+    orelse error({mandatory_ie_missing, auth_tuples, Mandatory -- maps:keys(AuthTuple)}),
+  (maps:size(maps:without(Possible, AuthTuple)) == 0)
+    orelse error({ie_not_expected, auth_tuples, maps:keys(AuthTuple) -- Possible}).
+
+check_pdp_info(PDPInfo) ->
+  Mandatory = ?PDP_INFO_MANDATORY,
+  Possible = Mandatory ++ ?PDP_INFO_OPTIONAL,
+  (maps:size(maps:with(Mandatory, PDPInfo)) == length(Mandatory))
+    orelse error({mandatory_ie_missing, pdp_info_list, Mandatory -- maps:keys(PDPInfo)}),
+  (maps:size(maps:without(Possible, PDPInfo)) == 0)
+    orelse error({ie_not_expected, pdp_info_list, maps:keys(PDPInfo) -- Possible}).
+
+encode_auth_tuple(#{rand := Value} = Map, Head) ->
+  Len = 16,
+  ?CHECK_LEN(rand, size(Value), Len, Len),
+  encode_auth_tuple(maps:without([rand], Map), <<Head/binary, ?RAND, Len, Value:Len/binary>>);
+
+encode_auth_tuple(#{sres := Value} = Map, Head) ->
+  Len = 4,
+  ?CHECK_LEN(sres, size(Value), Len, Len),
+  encode_auth_tuple(maps:without([sres], Map), <<Head/binary, ?SRES, Len, Value:Len/binary>>);
+
+encode_auth_tuple(#{kc := Value} = Map, Head) ->
+  Len = 8,
+  ?CHECK_LEN(kc, size(Value), Len, Len),
+  encode_auth_tuple(maps:without([kc], Map), <<Head/binary, ?KC, Len, Value:Len/binary>>);
+
+encode_auth_tuple(#{ik := Value} = Map, Head) ->
+  Len = 16,
+  ?CHECK_LEN(ik, size(Value), Len, Len),
+  encode_auth_tuple(maps:without([ik], Map), <<Head/binary, ?IK, Len, Value:Len/binary>>);
+
+encode_auth_tuple(#{ck := Value} = Map, Head) ->
+  Len = 16,
+  ?CHECK_LEN(ck, size(Value), Len, Len),
+  encode_auth_tuple(maps:without([ck], Map), <<Head/binary, ?CK, Len, Value:Len/binary>>);
+
+encode_auth_tuple(#{autn := Value} = Map, Head) ->
+  Len = 16,
+  ?CHECK_LEN(autn, size(Value), Len, Len),
+  encode_auth_tuple(maps:without([autn], Map), <<Head/binary, ?AUTN, Len, Value:Len/binary>>);
+
+encode_auth_tuple(#{res := Value} = Map, Head) ->
+  Len = size(Value),
+  ?CHECK_LEN(res, size(Value), Len, Len),
+  encode_auth_tuple(maps:without([res], Map), <<Head/binary, ?RES, Len, Value/binary>>);
+
+encode_auth_tuple(#{}, Head) -> Head.
+
+encode_pdp_info(#{pdp_context_id := Value} = Map, Head) ->
+  Len = 1,
+  ?CHECK_SIZE(pdp_context_id, Len, Value),
+  encode_pdp_info(maps:without([pdp_context_id], Map), <<Head/binary, ?PDP_CONTEXT_ID, Len, Value:Len/unit:8>>);
+
+encode_pdp_info(#{pdp_type := Value} = Map, Head) ->
+  Len = 2,
+  ?CHECK_SIZE(pdp_type, Len, Value),
+  encode_pdp_info(maps:without([pdp_type], Map), <<Head/binary, ?PDP_TYPE, Len, Value:Len/unit:8>>);
+
+encode_pdp_info(#{access_point_name := Value} = Map, Head) ->
+  Len = size(Value),
+  ?CHECK_LEN(access_point_name, Len, 1, 100),
+  encode_pdp_info(maps:without([access_point_name], Map), <<Head/binary, ?ACCESS_POINT_NAME, Len, Value/binary>>);
+
+encode_pdp_info(#{quality_of_service := Value} = Map, Head) ->
+  Len = size(Value),
+  ?CHECK_LEN(quality_of_service, Len, 1, 20),
+  encode_pdp_info(maps:without([quality_of_service], Map), <<Head/binary, ?QUALITY_OF_SERVICE, Len, Value/binary>>);
+
+encode_pdp_info(#{pdp_charging := Value} = Map, Head) ->
+  Len = 2,
+  ?CHECK_SIZE(pdp_charging, Len, Value),
+  encode_pdp_info(maps:without([pdp_charging], Map), <<Head/binary, ?PDP_CHARGING, Len, Value:Len/unit:8>>);
+
+encode_pdp_info(#{}, Head) -> Head.
diff --git a/src/ipa.erl b/src/ipa.erl
new file mode 100644
index 0000000..479860e
--- /dev/null
+++ b/src/ipa.erl
@@ -0,0 +1,40 @@
+% This Source Code Form is subject to the terms of the Mozilla Public
+% License, v. 2.0. If a copy of the MPL was not distributed with this
+% file, You can obtain one at https://mozilla.org/MPL/2.0/.
+% (C) 2019 Andrey Velikiy <agreat22@gmail.com>
+% (C) 2019 Fairwaves (edited) 
+
+-module(ipa).
+
+-include ("ipa.hrl").
+
+-export ([decode/1, encode/1]).
+
+-spec decode(binary()) -> {ok, binary()} | {reply, ping | resp | ack, binary(), binary()} | {more_data, binary()} | {error, term()}.
+decode(<<1:16, ?IPAC_PROTO_IPACCESS, ?IPAC_MSGT_PING, Rest/binary>>) ->
+  {reply, ping, <<1:16, ?IPAC_PROTO_IPACCESS, ?IPAC_MSGT_PONG>>, Rest};
+
+decode(<<1:16, ?IPAC_PROTO_IPACCESS, ?IPAC_MSGT_ID_RESP, Rest/binary>>) ->
+  {reply, resp, <<1:16, ?IPAC_PROTO_IPACCESS, ?IPAC_MSGT_ID_ACK>>, Rest};
+
+decode(<<1:16, ?IPAC_PROTO_IPACCESS, ?IPAC_MSGT_ID_ACK, Rest/binary>>) ->
+  {reply, ack, <<1:16, ?IPAC_PROTO_IPACCESS, ?IPAC_MSGT_ID_GET>>, Rest};
+
+decode(<<PSize:16, ?IPAC_PROTO_OSMO, Packet:PSize/binary, Rest/binary>>) ->
+  case Packet of
+    <<?IPAC_PROTO_EXT_GSUP, Packet1/binary>> ->
+      {ok, {Packet1, Rest}};
+    <<X, _/binary>> ->
+      {error, {bad_protocol_extension, X}}
+  end;
+
+decode(<<_PSize:16, X, _/binary>>) when X /= ?IPAC_PROTO_OSMO ->
+  {error, {bad_stream_id, X}};
+
+decode(Rest) ->
+  {more_data, Rest}.
+
+-spec encode(binary()) -> binary().
+encode(Packet) ->
+  Len = size(Packet) + 1,
+  <<Len:16, ?IPAC_PROTO_OSMO, ?IPAC_PROTO_EXT_GSUP, Packet/binary>>.
diff --git a/src/osmo_gsup.app.src b/src/osmo_gsup.app.src
new file mode 100644
index 0000000..cf9f18b
--- /dev/null
+++ b/src/osmo_gsup.app.src
@@ -0,0 +1,9 @@
+{application, osmo_gsup, [
+  {description, "OSMOCOM GSUP library"},
+  {vsn, "0.1.1"},
+  {registered, []},
+  {applications, [
+    kernel,
+    stdlib
+  ]}
+]}.
diff --git a/test/gsup_encode_decode_test.erl b/test/gsup_encode_decode_test.erl
new file mode 100644
index 0000000..52806e8
--- /dev/null
+++ b/test/gsup_encode_decode_test.erl
@@ -0,0 +1,75 @@
+% This Source Code Form is subject to the terms of the Mozilla Public
+% License, v. 2.0. If a copy of the MPL was not distributed with this
+% file, You can obtain one at https://mozilla.org/MPL/2.0/.
+% (C) 2019 Andrey Velikiy <agreat22@gmail.com>
+% (C) 2019 Fairwaves (edited) 
+
+-module (gsup_encode_decode_test).
+
+-include_lib("eunit/include/eunit.hrl").
+
+-define(BINARY_ISD_REQUEST_BAD, <<16,1,8,98,66,130,119,116,88,81,242,5,7,16,1,1,18,2,1,42,8,7,6,148,97,49,100,96,33,40,1,1>>).
+-define(BINARY_ISD_REQUEST, <<0,35,238,5, 16,1,8,98,66,130,119,116,88,81,242,4,0,5,7,16,1,1,18,2,1,42,8,7,6,148,97,49,100,96,33,40,1,1>>).
+-define(MAP_ISD_REQUEST, #{cn_domain => 1,imsi => <<"262428774785152">>,message_type => insert_sub_data_req,msisdn => <<6,148,97,49,100,96,33>>,pdp_info_list => [#{access_point_name => <<1,42>>,pdp_context_id => 1}], pdp_info_complete => true}).
+
+-define(BINARY_MO_FORWARD_REQUEST, <<0,44,238,5, 36,1,8,98,66,2,0,0,0,128,248,64,1,66,65,5,3,0,137,103,245,66,8,2,6,148,33,3,0,0,136,67,10,5,35,5,0,33,67,245,0,0,0>>).
+-define(MAP_MO_FORWARD_REQUEST, #{imsi => <<"262420000000088">>,message_type => mo_forward_req,sm_rp_da => <<3,0,137,103,245>>,sm_rp_mr => 66,sm_rp_oa => <<2,6,148,33,3,0,0,136>>,sm_rp_ui => <<5,35,5,0,33,67,245,0,0,0>>}).
+
+-define(BINARY_SS_REQUEST, <<0,44,238,5, 32,1,8,98,66,2,0,0,0,64,246,48,4,32,0,0,1,49,1,1,53,21,161,19,2,1,5,2,1,59,48,11,4,1,15,4,6,170,81,12,6,27,1>>).
+-define(MAP_SS_REQUEST, #{imsi => <<"262420000000046">>,message_type => ss_req,session_id => 536870913,session_state => 1,ss_info => <<161,19,2,1,5,2,1,59,48,11,4,1,15,4,6,170,81,12,6,27,1>>}).
+
+-define(BINARY_SAI_RESULT,<<0,192,238,5, 10,1,8,98,66,2,80,118,115,7,240,3,34,32,16,139,144,41,228,197,232,161,115,52,229,66,150,129,111,14,163,33,4,154,221,96,95,34,8,214,95,14,186,82,93,186,131,3,34,32,16,98,45,225,235,92,202,105,88,14,17,66,100,38,60,70,60,33,4,125,216,104,213,34,8,92,188,236,132,7,137,137,207,3,34,32,16,247,184,92,22,164,154,219,122,73,61,217,228,64,22,207,229,33,4,12,236,133,61,34,8,2,247,249,165,41,173,134,71,3,34,32,16,115,152,209,15,231,72,227,254,143,199,185,130,91,206,171,41,33,4,236,133,225,34,34,8,67,180,13,145,7,174,211,12,3,34,32,16,251,173,219,197,60,132,202,24,53,87,236,186,86,175,231,59,33,4,61,86,38,102,34,8,224,104,249,198,53,145,182,54>>).
+-define(MAP_SAI_RESULT, #{auth_tuples => [
+    #{kc => <<15447081440312670851:8/unit:8>>,rand => <<185511231865796904634040334886313594531:16/unit:8>>,sres => <<2598199391:4/unit:8>>},
+    #{kc => <<6682475998917265871:8/unit:8>>,rand => <<130502579135052156657755432460855559740:16/unit:8>>,sres => <<2111334613:4/unit:8>>},
+    #{kc => <<213913995087545927:8/unit:8>>,rand => <<329276565356490492799345768940241866725:16/unit:8>>,sres => <<216827197:4/unit:8>>},
+    #{kc => <<4878539212899406604:8/unit:8>>,rand => <<153654688921371376697326139997978274601:16/unit:8>>,sres => <<3968196898:4/unit:8>>},
+    #{kc => <<16170449091771348534:8/unit:8>>,rand => <<334538951772921257466553732075468351291:16/unit:8>>,sres => <<1029056102:4/unit:8>>}
+  ],imsi => <<"262420056737700">>,message_type => send_auth_info_res}).
+
+isd_request_test() ->
+  {ok, {Pkt, <<>>}} = ipa:decode(?BINARY_ISD_REQUEST),
+  Map = gsup_protocol:decode(Pkt),
+  ?assertEqual(?MAP_ISD_REQUEST, Map),
+  Bin = ipa:encode(gsup_protocol:encode(Map)),
+  ?assertEqual(?BINARY_ISD_REQUEST, Bin).
+
+mo_forward_request_test() ->
+  {ok, {Pkt, <<>>}} = ipa:decode(?BINARY_MO_FORWARD_REQUEST),
+  Map = gsup_protocol:decode(Pkt),
+  ?assertEqual(?MAP_MO_FORWARD_REQUEST, Map),
+  Bin = ipa:encode(gsup_protocol:encode(Map)),
+  ?assertEqual(?BINARY_MO_FORWARD_REQUEST, Bin).
+
+ss_request_test() ->
+  {ok, {Pkt, <<>>}} = ipa:decode(?BINARY_SS_REQUEST),
+  Map = gsup_protocol:decode(Pkt),
+  ?assertEqual(?MAP_SS_REQUEST, Map),
+  Bin = ipa:encode(gsup_protocol:encode(Map)),
+  ?assertEqual(?BINARY_SS_REQUEST, Bin).
+
+sai_result_test() ->
+  {ok, {Pkt, <<>>}} = ipa:decode(?BINARY_SAI_RESULT),
+  Map = gsup_protocol:decode(Pkt),
+  ?assertEqual(?MAP_SAI_RESULT, Map),
+  Bin = ipa:encode(gsup_protocol:encode(Map)),
+  ?assertEqual(?BINARY_SAI_RESULT, Bin).
+
+missing_params_test() ->
+  ?assertError({mandatory_ie_missing,insert_sub_data_req,[pdp_info_complete]}, gsup_protocol:decode(?BINARY_ISD_REQUEST_BAD)),
+  ?assertError({mandatory_ie_missing,mo_forward_req,[sm_rp_mr,sm_rp_da,sm_rp_oa,sm_rp_ui]}, gsup_protocol:encode(#{message_type => mo_forward_req, imsi => <<"123456">>})).
+
+excess_params_test() ->
+  ?assertError({ie_not_expected,location_upd_err,[pdp_info_complete]}, gsup_protocol:encode(#{message_type => location_upd_err,imsi => <<"1234">>,cause => 1,pdp_info_complete => <<>>})).
+
+ie_size_test() ->
+  ?assertEqual(#{cause => 255}, gsup_protocol:decode_ie(<<2,1,255>>, #{})),
+  ?assertError({ie_length_mismatch,cause,2}, gsup_protocol:decode_ie(<<2,2,0,0>>, #{})),
+
+  ?assertError({ie_value_length_mismatch,cause,-1}, gsup_protocol:encode_ie(#{cause => -1}, <<>>)),
+  ?assertEqual(<<2,1,255>>, gsup_protocol:encode_ie(#{cause => 255}, <<>>)),
+  ?assertError({ie_value_length_mismatch,cause,256}, gsup_protocol:encode_ie(#{cause => 256}, <<>>)),
+  ?assertEqual(<<20,2,255,255>>, gsup_protocol:encode_ie(#{pdp_charging => 16#ffff}, <<>>)),
+  ?assertError({ie_value_length_mismatch,pdp_charging,16#10000}, gsup_protocol:encode_ie(#{pdp_charging => 16#10000}, <<>>)),
+  ?assertEqual(<<48,4,255,255,255,255>>, gsup_protocol:encode_ie(#{session_id => 16#ffffffff}, <<>>)),
+  ?assertError({ie_value_length_mismatch,session_id,16#100000000}, gsup_protocol:encode_ie(#{session_id => 16#100000000}, <<>>)).