1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
|
% SM-TP (Short Message Transport Protocol) codec (as per 3GPP TS 23.040).
% Coding of some messages depends on type of the containing RPDU.
%
% (C) 2020 by Vadim Yanitskiy <axilirator@gmail.com>
%
% All Rights Reserved
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU Affero General Public License as
% published by the Free Software Foundation; either version 3 of the
% License, or (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU Affero General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
%
% Additional Permission under GNU AGPL version 3 section 7:
%
% If you modify this Program, or any covered work, by linking or
% combining it with runtime libraries of Erlang/OTP as released by
% Ericsson on http://www.erlang.org (or a modified version of these
% libraries), containing parts covered by the terms of the Erlang Public
% License (http://www.erlang.org/EPLICENSE), the licensors of this
% Program grant you additional permission to convey the resulting work
% without the need to license the runtime libraries of Erlang/OTP under
% the GNU Affero General Public License. Corresponding Source for a
% non-source form of such a combination shall include the source code
% for the parts of the runtime libraries of Erlang/OTP used as well as
% that of the covered work.
-module(sm_tp_codec).
-export([encode/2, decode/2]).
-ifdef(TEST).
-export([encode_tp_addr/2, decode_tp_addr/1]).
-export([encode_tp_scts/2, decode_tp_scts/1]).
-export([decode_tp_vp/2]).
-endif.
%% 9.2.3.1 "TP-Message-Type-Indicator (TP-MTI)"
-define(TP_MTI_SUBMIT, 02#01).
-define(TP_MTI_COMMAND, 02#10).
-define(TP_MTI_DELIVER, 02#00).
-define(TP_MTI_SUBMIT_REPORT, 02#01).
-define(TP_MTI_STATUS_REPORT, 02#10).
-define(TP_MTI_DELIVER_REPORT, 02#00).
%% 9.2.3.3 "TP-Validity-Period-Format (TP-VPF)"
-define(TP_VP_VPF_ABSENT, 02#00).
-define(TP_VP_VPF_RELATIVE, 02#10).
-define(TP_VP_VPF_ENHANCED, 02#01).
-define(TP_VP_VPF_ABSOLUTE, 02#11).
%% 9.2.3.12.3 "TP-Validity-Period (Enhanced format)" sub-types
-define(TP_VP_EVPF_ABSENT, 02#000).
-define(TP_VP_EVPF_RELATIVE, 02#001).
-define(TP_VP_EVPF_RELATIVE_SEC, 02#010).
-define(TP_VP_EVPF_RELATIVE_BCD, 02#011).
%% 9.2.2 TP-User-Data may contain up to 140 octets
%% (together with optional TP-User-Data-Header)
-define(TP_USER_DATA_MAX_LEN, 140).
-define(TP_USER_DATA_PADDING, 16#ff).
%% Encode TP-{Originating,Destination}-Address (see 9.2.3.7 and 9.2.3.8).
%% NOTE: The Addr is expected to be octet-aligned and encoded by the caller.
%% TODO: The maximum length of the full address field is 12 octets (see 9.1.2.5).
encode_tp_addr({NPI, ToN}, {AddrBitLen, Addr}) when is_binary(Addr) ->
%% QBitNum indicates number of useful nibbles (octet halves) in the Address
%% regardless of the indicated ToN (e.g. BCD number or alphanumeric),
%% excluding any nibbles containing only fill bits.
case {AddrBitLen div 4, AddrBitLen rem 4} of
{QBitEven, QBitRem} when QBitRem > 0 ->
AddrQBitLen = QBitEven + 1;
{QBitEven, 0} ->
AddrQBitLen = QBitEven
end,
%% As per 9.1.2.5, the 1st MSB of the 2nd octet shall be set high.
<<AddrQBitLen, 1:1, ToN:3, NPI:4, Addr/bytes>>.
%% Decode TP-{Originating,Destination}-Address (see 9.2.3.7 and 9.2.3.8).
%% NOTE: The returned Addr is octet-aligned and to be decoded by the caller.
decode_tp_addr(TPDU) when is_binary(TPDU) ->
%% QBitLen indicates number of useful nibbles (octet halves) in the Address
%% regardless of the indicated ToN (e.g. BCD number or alphanumeric),
%% excluding any nibbles containing only fill bits.
%% As per 9.1.2.5, the 1st MSB of the 2nd octet shall be set high.
<<QBitLen, 1:1, ToN:3, NPI:4, AddrRest/bytes>> = TPDU,
%% Full address field shall be octet-aligned, so there may be optional padding.
if
(QBitLen rem 2) =/= 0 ->
AddrByteLen = QBitLen div 2 + 1;
true ->
AddrByteLen = QBitLen div 2
end,
<<Addr:AddrByteLen/bytes, Rest/bytes>> = AddrRest,
{ok, {NPI, ToN}, {QBitLen * 4, Addr}, Rest}.
%% Encode TP-Service-Centre-Time-Stamp as per 9.2.3.11.
encode_tp_scts(current, TimeZone) ->
LocalTime = erlang:localtime(),
encode_tp_scts(LocalTime, TimeZone);
encode_tp_scts(LocalTime, {TZHour, TZMin}) when (TZMin rem 15) == 0 ->
%% Encoded timezone is in quarters of an hour (signed)
if
TZHour < 0 ->
AbsOffset = (TZHour * 60 * -1 + TZMin) div 15,
encode_tp_scts(LocalTime, 1, AbsOffset);
true ->
AbsOffset = (TZHour * 60 + TZMin) div 15,
encode_tp_scts(LocalTime, 0, AbsOffset)
end.
encode_tp_scts({{Year, Month, Day}, {Hour, Min, Sec}}, Minus, AbsOffset) ->
%% BCD-encode date and time as YY:MM:DD:hh:mm:ss.
DateTimeList = lists:map(
fun bcd_codec:encode_num/1,
[Year rem 100, Month, Day, Hour, Min, Sec]
),
DateTime = list_to_binary(DateTimeList),
%% BCD-encode the timezone offset.
N1 = AbsOffset div 10,
N2 = AbsOffset rem 10,
TZ = <<N2:4, Minus:1, N1:3>>,
<<DateTime/bytes, TZ/bytes>>.
%% Decode TP-Service-Centre-Time-Stamp as per 9.2.3.11.
decode_tp_scts(<<DateTime:6/bytes, N2:4, Minus:1, N1:3>>) ->
%% Decode BCD-coded date and time as YY:MM:DD:hh:mm:ss.
DateTimeList = lists:map(
fun bcd_codec:decode_num/1,
binary_to_list(DateTime)
),
[Year, Month, Day, Hour, Min, Sec] = DateTimeList,
%% Decode BCD-encoded (in quarters of an hour) timezone offset.
AbsOffset = (N1 * 10) + N2,
if
Minus == 1 ->
TZHour = -AbsOffset div 4;
true ->
TZHour = AbsOffset div 4
end,
TZMin = AbsOffset * 15 rem 60,
{ok, {{Year, Month, Day}, {Hour, Min, Sec}}, {TZHour, TZMin}}.
%% TP-Validity-Period is not present.
decode_tp_vp(?TP_VP_VPF_ABSENT, Rest) ->
{ok, omit, Rest};
%% 9.2.3.12.1 TP-Validity-Period (Relative format).
%% NOTE: Returned value is always in seconds.
decode_tp_vp(?TP_VP_VPF_RELATIVE, <<VP:8, Rest/bytes>>) ->
if
VP >= 0, VP =< 143 ->
Minutes = (VP + 1) * 5;
VP >= 144, VP =< 167 ->
%% 12 hours + (VP - 143) * 30 minutes
Minutes = 12 * 60 + (VP - 143) * 30;
VP >= 168, VP =< 196 ->
%% (VP - 166) days
Minutes = (VP - 166) * 24 * 60;
VP >= 197, VP =< 255 ->
%% (VP - 192) weeks
Minutes = (VP - 192) * 7 * 24 * 60
end,
{ok, {relative, Minutes * 60}, Rest};
%% 9.2.3.12.2 TP-Validity-Period (Absolute format).
%% The representation of time is identical to TP-Service-Centre-Time-Stamp.
decode_tp_vp(?TP_VP_VPF_ABSOLUTE, <<VP:7/bytes, Rest/bytes>>) ->
{ok, DateTime, TimeZone} = decode_tp_scts(VP),
{ok, {absolute, DateTime, TimeZone}, Rest};
%% 9.2.3.12.3 TP-Validity-Period (Enhanced format, no extensions).
decode_tp_vp(?TP_VP_VPF_ENHANCED, <<0:1, SingleShot:1, _:3, EVPF:3, VP:6/bytes, Rest/bytes>>) ->
case EVPF of
?TP_VP_EVPF_ABSENT ->
Result = omit;
?TP_VP_EVPF_RELATIVE ->
{ok, Result, _} = decode_tp_vp(?TP_VP_VPF_RELATIVE, VP);
?TP_VP_EVPF_RELATIVE_SEC ->
<<Seconds, _VPRest/bytes>> = VP,
Result = {relative, Seconds};
?TP_VP_EVPF_RELATIVE_BCD ->
<<Hh, Mm, Ss, _VPRest/bytes>> = VP,
Seconds =
bcd_codec:decode_num(Hh) * 60 * 60 +
bcd_codec:decode_num(Mm) * 60 +
bcd_codec:decode_num(Ss),
Result = {relative, Seconds};
_ ->
Result = reserved
end,
{ok, {enhanced, SingleShot, Result}, Rest};
decode_tp_vp(02#01, <<1:1, _/bits>>) ->
error({vpf_ext_not_supported});
decode_tp_vp(VPF, _) ->
error({unknown_vpf, VPF}).
%% Decode TP-User-Data and TP-User-Data-Header (if present).
%% Depending on DCS, TP-User-Data-Length can be in septets or octets.
decode_tp_ud(_UDHI, _DCS, TPDU) ->
%% TODO: actually decode UD-Header if present
%% NOTE: UDLen may indicate either the number of octets or septets
%% NOTE: UDHLen always in octets
<<_UDLen, UserData/bytes>> = TPDU,
{ok, {[], UserData}}.
%% 23.040 9.2.2.2
decode_submit(TPDU) ->
%% Header and TP-Message-Reference
<<RP:1, UDHI:1, SRR:1, VPF:2, RD:1, ?TP_MTI_SUBMIT:2, MR, Rest1/binary>> = TPDU,
%% TP-Destination-Address (variable size, odd units, padding)
{ok, DAType, DA, Rest2} = decode_tp_addr(Rest1),
%% TP-Protocol-Identifier and TP-Data-Coding-Scheme
<<PID, DCS, Rest3/binary>> = Rest2,
%% followed by optional TP-Validity-Period (depends on VPF)
{ok, VP, Rest4} = decode_tp_vp(VPF, Rest3),
%% Finally, TP-User-Data (and optional UD-Header)
{ok, UD} = decode_tp_ud(UDHI, DCS, Rest4),
{ok,
{sm_tp_submit, #{
reply_path_req => RP,
status_report_req => SRR,
reject_duplicates => RD,
tp_msg_ref => MR,
dest_addr => {DAType, DA},
pid => PID,
dcs => DCS,
valid_period => VP,
user_data => UD
}}}.
%% 23.040 9.2.2.4
decode_command(TPDU) ->
<<_:1, _UDHI:1, SRR:1, _:3, ?TP_MTI_COMMAND:2, MR, PID, CT, MN, Rest1/binary>> = TPDU,
%% TP-Destination-Address (variable size, odd units, padding)
{ok, DAType, DA, Rest2} = decode_tp_addr(Rest1),
%% TP-Command-Data and its length
<<CDLen, CommandData:CDLen/bytes>> = Rest2,
{ok,
{sm_tp_command, #{
status_report_req => SRR,
tp_msg_ref => MR,
pid => PID,
cmd_type => CT,
msg_number => MN,
dest_addr => {DAType, DA},
cmd_data => CommandData
}}}.
%% 23.040 9.2.2.2a (ii)
decode_submit_report_ack(TPDU) ->
%% NOTE: Extension bit (for PID) != 0 is not supported
<<_:1, UDHI:1, _:4, ?TP_MTI_SUBMIT_REPORT:2, 0:1, _:4, UDPres:1, DCSPres:1, PIDPres:1,
SCTS:7/bytes, Rest1/binary>> = TPDU,
%% PID, DCS fields are optional (presence defined by flags)
<<PID:PIDPres/unit:8, DCS:DCSPres/unit:8, Rest2/bytes>> = Rest1,
%% TP-User-Data is also optional
if
UDPres == 1, size(Rest2) > 0 ->
{ok, UD} = decode_tp_ud(UDHI, DCS, Rest2);
true ->
UD = omit
end,
%% TODO: further decode TP-Service-Centre-Time-Stamp
{ok,
{sm_tp_submit_report, #{
sc_time_stamp => SCTS,
pid => PID,
dcs => DCS,
user_data => UD
}}}.
%% 23.040 9.2.2.2a (i)
decode_submit_report_error(TPDU) ->
%% NOTE: Extension bit (for PID) != 0 is not supported
<<_:1, UDHI:1, _:4, ?TP_MTI_SUBMIT_REPORT:2, Cause, 0:1, _:4, UDPres:1, DCSPres:1, PIDPres:1,
SCTS:7/bytes, Rest1/binary>> = TPDU,
%% PID, DCS fields are optional (presence defined by flags)
<<PID:PIDPres/unit:8, DCS:DCSPres/unit:8, Rest2/bytes>> = Rest1,
%% TP-User-Data is also optional
if
UDPres == 1, size(Rest2) > 0 ->
{ok, UD} = decode_tp_ud(UDHI, DCS, Rest2);
true ->
UD = omit
end,
%% TODO: further decode TP-Service-Centre-Time-Stamp
{ok,
{sm_tp_submit_report, #{
sc_time_stamp => SCTS,
pid => PID,
dcs => DCS,
cause => Cause,
user_data => UD
}}}.
decode(RPMsgType, <<_:6, MTI:2, _/bits>> = TPDU) ->
case {RPMsgType, MTI} of
%% Mobile originated message submission
{sm_rp_mo_data, ?TP_MTI_SUBMIT} ->
%% MS -> MSC/SGSN: RP-DATA
decode_submit(TPDU);
{sm_rp_mo_data, ?TP_MTI_COMMAND} ->
%% MS -> MSC/SGSN: RP-DATA
decode_command(TPDU);
{sm_rp_mo_ack, ?TP_MTI_SUBMIT_REPORT} ->
%% MSC/SGSN -> MS: RP-ACK
decode_submit_report_ack(TPDU);
{sm_rp_mo_error, ?TP_MTI_SUBMIT_REPORT} ->
%% MSC/SGSN -> MS: RP-ERROR
decode_submit_report_error(TPDU);
_ ->
{error, unknown_msg}
end.
%% Encode TP-User-Data and TP-User-Data-Header(s) as per 9.2.3.24.
%% NOTE: UserData must be encoded by the caller itself.
encode_tp_ud(HdrList, UserData) ->
Hdrs = encode_tp_ud_hdrs(HdrList, <<>>),
HdrsLen = byte_size(Hdrs),
%% The maximum length of TP-User-Data (and optional headers) is 140 octets.
%% NOTE: byte_size() will round the size to octet boundary.
TotalLen = HdrsLen + byte_size(UserData),
if
TotalLen > ?TP_USER_DATA_MAX_LEN ->
error({sm_tp_ud, overflow, TotalLen});
true ->
%% TPDU must be octet-aligned
%% TODO: is there a more elegant way?
PadLen = byte_size(UserData) * 8 - bit_size(UserData),
UDEnc = <<Hdrs/bytes, UserData/bits, ?TP_USER_DATA_PADDING:PadLen>>,
{HdrsLen, UDEnc}
end.
encode_tp_ud_hdrs([{Type, Value} | Tail], Hdrs) ->
Length = byte_size(Value),
HdrTLV = <<Type:8, Length:8, Value/bytes>>,
encode_tp_ud_hdrs(Tail, <<Hdrs/bytes, HdrTLV/bytes>>);
encode_tp_ud_hdrs([], Hdrs) ->
Hdrs.
%% Calculate the number of septets or octets (depending on DCS)
%% in both TP-User-Data and TP-User-Data-Header(s).
calc_tp_udl(_DCS, HdrsLen, UserDataBitLen) ->
%% HACK! TODO: parse DCS as per 3GPP TS 23.038, section 4
if
(UserDataBitLen rem 8) > 0 ->
(HdrsLen * 8 div 7) + (UserDataBitLen div 7);
true ->
HdrsLen + UserDataBitLen div 8
end.
%% 23.040 9.2.2.1 "SMS-DELIVER type"
encode_deliver(Params) ->
#{
reply_path := RP,
status_report_ind := SRI,
loop_prevention := LP,
more_messages_to_send := MMS,
orig_addr := {OAType, OA},
pid := PID,
dcs := DCS,
date_time := DateTime,
timezone := TimeZone,
user_data := {HdrList, UserData}
} = Params,
%% TP-Originating-Address
OAEnc = encode_tp_addr(OAType, OA),
%% TP-Service-Centre-Time-Stamp
SCTS = encode_tp_scts(DateTime, TimeZone),
%% TP-User-Data and TP-User-Data-Header(s)
{HdrsLen, UDEnc} = encode_tp_ud(HdrList, UserData),
if
HdrsLen > 0 ->
UDHI = 1;
true ->
UDHI = 0
end,
%% TP-User-Data-Length (depends on DCS)
UDLen = calc_tp_udl(DCS, HdrsLen, bit_size(UserData)),
<<RP:1, UDHI:1, SRI:1, 0:1, LP:1, MMS:1, ?TP_MTI_DELIVER:2, OAEnc/bytes, PID, DCS, SCTS/bytes,
UDLen, UDEnc/bytes>>.
encode(RPMsgType, {TPMsgType, Params}) ->
case {RPMsgType, TPMsgType} of
%% Mobile terminated message delivery
{sm_rp_mt_data, sm_tp_deliver} ->
%% MSC/SGSN -> MS: RP-DATA
encode_deliver(Params);
{sm_rp_mt_data, sm_tp_status_report} ->
%% MSC/SGSN -> MS: RP-DATA
%% encode_status_report(Params);
ok;
{sm_rp_mt_ack, sm_tp_deliver_report} ->
%% MS -> MSC/SGSN: RP-ACK
%% encode_deliver_report_ack(Params);
ok;
{sm_rp_mt_error, sm_tp_deliver_report} ->
%% MS -> MSC/SGSN: RP-ERROR
%% encode_deliver_report_error(Params);
ok;
_ ->
{error, unknown_msg}
end.
|