blob: 262fbb11786595a8a98df06299a4cf330c8e1f75 [file] [log] [blame]
Harald Welte1f6a0352011-01-15 20:07:45 +01001% RFC 3331 MTP2 User Adaption Layer coding / decoding
2
3% (C) 2011 by Harald Welte <laforge@gnumonks.org>
4%
5% All Rights Reserved
6%
7% This program is free software; you can redistribute it and/or modify
8% it under the terms of the GNU Affero General Public License as
9% published by the Free Software Foundation; either version 3 of the
10% License, or (at your option) any later version.
11%
12% This program is distributed in the hope that it will be useful,
13% but WITHOUT ANY WARRANTY; without even the implied warranty of
14% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15% GNU General Public License for more details.
16%
17% You should have received a copy of the GNU Affero General Public License
18% along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20-module(m2ua_codec).
21-author('Harald Welte <laforge@gnumonks.org>').
22-include("m2ua.hrl").
23
24-export([parse_m2ua_msg/1, encode_m2ua_msg/1]).
25
26% parse a binary chunk of options into an options proplist
27parse_m2ua_opts(<<>>, OptList) ->
28 OptList;
29parse_m2ua_opts(OptBin, OptList) ->
30 <<Tag:16/big, LengthIncHdr:16/big, Remain/binary>> = OptBin,
31 Length = LengthIncHdr - 4,
32 <<Value:Length/binary, NextOpts/binary>> = Remain,
33 NewOpt = {Tag, {Length, Value}},
34 parse_m2ua_opts(NextOpts, [NewOpt|OptList]).
35
36% parse a single M2UA message
37parse_m2ua_msgt(_, _, _, Remain) ->
38 parse_m2ua_opts(Remain, []).
39
40% parse a M2UA message binary into a record
41parse_m2ua_msg(DataBin) when is_binary(DataBin) ->
42 <<1:8, 0:8, MsgClass:8, MsgType:8, MsgLen:32/big, Remain/binary>> = DataBin,
43 Parsed = parse_m2ua_msgt(MsgClass, MsgType, MsgLen, Remain),
44 {ok, #m2ua_msg{msg_class = MsgClass, msg_type = MsgType, parameters = Parsed}}.
45
46
47
48% encode a single option
49encode_m2ua_opt({OptNum, {DataBinLen, DataBin}}) when is_integer(OptNum) ->
50 LengthIncHdr = DataBinLen + 4,
51 <<OptNum:16/big, LengthIncHdr:16/big, DataBin/binary>>.
52
53% encode a list of options
54encode_m2ua_opts([], OptEnc) ->
55 list_to_binary(OptEnc);
56encode_m2ua_opts([CurOpt|OptPropList], OptEnc) ->
57 CurOptEnc = encode_m2ua_opt(CurOpt),
58 encode_m2ua_opts(OptPropList, list_to_binary([OptEnc, CurOptEnc])).
59
60
61% encode a particular message type
62encode_m2ua_msgt(MsgClass, MsgType, Params) ->
63 OptBin = encode_m2ua_opts(Params, <<>>),
64 MsgLenIncHdr = 4 + binary:byte_size(OptBin),
65 <<1:8, 0:8, MsgClass:8, MsgType:8, MsgLenIncHdr:32/big, OptBin/binary>>.
66
67% encode a message from record to binary
68encode_m2ua_msg(#m2ua_msg{msg_class = MsgClass, msg_type = MsgType, parameters = Params}) ->
69 encode_m2ua_msgt(MsgClass, MsgType, Params).