pySim-prog.py: add support for MSISDN programming

This change implements programming of EF.MSISDN as per 3GPP TS 31.102,
sections 4.2.26 and 4.4.2.3, excluding the following fields:

  - Alpha Identifier (currently 'FF'O * 20),
  - Capability/Configuration1 Record Identifier ('FF'O),
  - Extension1 Record Identifier ('FF'O).

This feature is introduced exclusively for sysmoUSIM-SJS1.
Othere SIM card types need to be tested.

Change-Id: Ie033a0ffc3697ae562eaa7a241a0f6af6c2b0594
diff --git a/pySim/cards.py b/pySim/cards.py
index 802ad69..b4b5fdf 100644
--- a/pySim/cards.py
+++ b/pySim/cards.py
@@ -658,6 +658,17 @@
 			r = self._scc.select_file(['3f00', '7f10'])
 			data, sw = self._scc.update_record('6f42', 1, lpad(p['smsp'], 104), force_len=True)
 
+		# EF.MSISDN
+		# TODO: Alpha Identifier (currently 'ff'O * 20)
+		# TODO: Capability/Configuration1 Record Identifier
+		# TODO: Extension1 Record Identifier
+		if p.get('msisdn') is not None:
+			msisdn = enc_msisdn(p['msisdn'])
+			data = 'ff' * 20 + msisdn + 'ff' * 2
+
+			r = self._scc.select_file(['3f00', '7f10'])
+			data, sw = self._scc.update_record('6F40', 1, data, force_len=True)
+
 	def erase(self):
 		return
 
diff --git a/pySim/utils.py b/pySim/utils.py
index 12f66b9..8420b23 100644
--- a/pySim/utils.py
+++ b/pySim/utils.py
@@ -299,3 +299,29 @@
 		msisdn = '+' + msisdn
 
 	return (npi, ton, msisdn)
+
+def enc_msisdn(msisdn, npi=0x01, ton=0x03):
+	"""
+	Encode MSISDN as LHV so it can be stored to EF.MSISDN.
+	See 3GPP TS 31.102, section 4.2.26 and 4.4.2.3.
+
+	Default NPI / ToN values:
+	  - NPI: ISDN / telephony numbering plan (E.164 / E.163),
+	  - ToN: network specific or international number (if starts with '+').
+	"""
+
+	# Leading '+' indicates International Number
+	if msisdn[0] == '+':
+		msisdn = msisdn[1:]
+		ton = 0x01
+
+	# Append 'f' padding if number of digits is odd
+	if len(msisdn) % 2 > 0:
+		msisdn += 'f'
+
+	# BCD length also includes NPI/ToN header
+	bcd_len = len(msisdn) // 2 + 1
+	npi_ton = (npi & 0x0f) | ((ton & 0x07) << 4) | 0x80
+	bcd = rpad(swap_nibbles(msisdn), 10 * 2) # pad to 10 octets
+
+	return ('%02x' % bcd_len) + ('%02x' % npi_ton) + bcd