aboutsummaryrefslogtreecommitdiffstats
path: root/lib/diameter
diff options
context:
space:
mode:
Diffstat (limited to 'lib/diameter')
-rwxr-xr-xlib/diameter/bin/diameterc32
-rw-r--r--lib/diameter/doc/src/Makefile4
-rw-r--r--lib/diameter/doc/src/book.xml4
-rw-r--r--lib/diameter/doc/src/diameter.xml441
-rw-r--r--lib/diameter/doc/src/diameter_app.xml6
-rw-r--r--lib/diameter/doc/src/diameter_codec.xml10
-rw-r--r--lib/diameter/doc/src/diameter_dict.xml17
-rw-r--r--lib/diameter/doc/src/diameter_examples.xml4
-rw-r--r--lib/diameter/doc/src/diameter_intro.xml6
-rw-r--r--lib/diameter/doc/src/diameter_make.xml116
-rw-r--r--lib/diameter/doc/src/diameter_sctp.xml40
-rw-r--r--lib/diameter/doc/src/diameter_soc.xml2
-rw-r--r--lib/diameter/doc/src/diameter_soc_rfc6733.xml6
-rw-r--r--lib/diameter/doc/src/diameter_tcp.xml2
-rw-r--r--lib/diameter/doc/src/diameter_transport.xml2
-rw-r--r--lib/diameter/doc/src/diameter_using.xml2
-rw-r--r--lib/diameter/doc/src/diameterc.xml (renamed from lib/diameter/doc/src/diameter_compile.xml)8
-rw-r--r--lib/diameter/doc/src/files.mk2
-rw-r--r--lib/diameter/doc/src/notes.xml1009
-rw-r--r--lib/diameter/doc/src/ref_man.xml6
-rw-r--r--lib/diameter/doc/src/seealso.ent13
-rw-r--r--lib/diameter/doc/src/user_man.xml4
-rw-r--r--lib/diameter/doc/standard/rfc7068.txt1627
-rw-r--r--lib/diameter/doc/standard/rfc7075.txt563
-rw-r--r--lib/diameter/examples/code/GNUmakefile4
-rw-r--r--lib/diameter/examples/code/client.erl53
-rw-r--r--lib/diameter/examples/code/client_cb.erl14
-rw-r--r--lib/diameter/examples/code/node.erl174
-rw-r--r--lib/diameter/examples/code/peer.erl150
-rw-r--r--lib/diameter/examples/code/redirect_cb.erl8
-rw-r--r--lib/diameter/examples/code/relay.erl43
-rw-r--r--lib/diameter/examples/code/relay_cb.erl8
-rw-r--r--lib/diameter/examples/code/server.erl46
-rw-r--r--lib/diameter/examples/code/server_cb.erl55
-rw-r--r--lib/diameter/examples/dict/.gitignore2
-rw-r--r--lib/diameter/examples/dict/GNUmakefile60
-rw-r--r--lib/diameter/examples/dict/depend.sed43
-rw-r--r--lib/diameter/examples/dict/rfc4004_mip.dia4
-rw-r--r--lib/diameter/examples/dict/rfc4005_nas.dia4
-rw-r--r--lib/diameter/examples/dict/rfc4006_cc.dia4
-rw-r--r--lib/diameter/examples/dict/rfc4072_eap.dia4
-rw-r--r--lib/diameter/examples/dict/rfc4590_digest.dia2
-rw-r--r--lib/diameter/examples/dict/rfc4740_sip.dia4
-rw-r--r--lib/diameter/include/diameter.hrl11
-rw-r--r--lib/diameter/include/diameter_gen.hrl423
-rw-r--r--lib/diameter/src/Makefile24
-rw-r--r--lib/diameter/src/app.sed40
-rw-r--r--lib/diameter/src/base/diameter.erl14
-rw-r--r--lib/diameter/src/base/diameter_capx.erl59
-rw-r--r--lib/diameter/src/base/diameter_codec.erl339
-rw-r--r--lib/diameter/src/base/diameter_config.erl57
-rw-r--r--lib/diameter/src/base/diameter_lib.erl114
-rw-r--r--lib/diameter/src/base/diameter_peer.erl41
-rw-r--r--lib/diameter/src/base/diameter_peer_fsm.erl508
-rw-r--r--lib/diameter/src/base/diameter_reg.erl6
-rw-r--r--lib/diameter/src/base/diameter_service.erl859
-rw-r--r--lib/diameter/src/base/diameter_service_sup.erl4
-rw-r--r--lib/diameter/src/base/diameter_stats.erl19
-rw-r--r--lib/diameter/src/base/diameter_sup.erl4
-rw-r--r--lib/diameter/src/base/diameter_sync.erl2
-rw-r--r--lib/diameter/src/base/diameter_traffic.erl688
-rw-r--r--lib/diameter/src/base/diameter_types.erl273
-rw-r--r--lib/diameter/src/base/diameter_watchdog.erl254
-rw-r--r--lib/diameter/src/compiler/diameter_codegen.erl579
-rw-r--r--lib/diameter/src/compiler/diameter_dict_util.erl51
-rw-r--r--lib/diameter/src/compiler/diameter_forms.hrl6
-rw-r--r--lib/diameter/src/compiler/diameter_make.erl257
-rw-r--r--lib/diameter/src/diameter.app.src26
-rw-r--r--lib/diameter/src/diameter.appup.src106
-rw-r--r--lib/diameter/src/info/diameter_dbg.erl (renamed from lib/diameter/src/base/diameter_dbg.erl)167
-rw-r--r--lib/diameter/src/info/diameter_info.erl (renamed from lib/diameter/src/base/diameter_info.erl)19
-rw-r--r--lib/diameter/src/modules.mk14
-rw-r--r--lib/diameter/src/transport/diameter_sctp.erl317
-rw-r--r--lib/diameter/src/transport/diameter_tcp.erl37
-rw-r--r--lib/diameter/src/transport/diameter_transport_sup.erl4
-rw-r--r--lib/diameter/test/diameter_3xxx_SUITE.erl200
-rw-r--r--lib/diameter/test/diameter_app_SUITE.erl143
-rw-r--r--lib/diameter/test/diameter_capx_SUITE.erl6
-rw-r--r--lib/diameter/test/diameter_codec_SUITE.erl188
-rw-r--r--lib/diameter/test/diameter_codec_test.erl188
-rw-r--r--lib/diameter/test/diameter_compiler_SUITE.erl194
-rw-r--r--lib/diameter/test/diameter_config_SUITE.erl26
-rw-r--r--lib/diameter/test/diameter_ct.erl2
-rw-r--r--lib/diameter/test/diameter_dpr_SUITE.erl44
-rw-r--r--lib/diameter/test/diameter_event_SUITE.erl35
-rw-r--r--lib/diameter/test/diameter_examples_SUITE.erl87
-rw-r--r--lib/diameter/test/diameter_failover_SUITE.erl8
-rw-r--r--lib/diameter/test/diameter_gen_sctp_SUITE.erl33
-rw-r--r--lib/diameter/test/diameter_gen_tcp_SUITE.erl67
-rw-r--r--lib/diameter/test/diameter_pool_SUITE.erl133
-rw-r--r--lib/diameter/test/diameter_relay_SUITE.erl159
-rw-r--r--lib/diameter/test/diameter_stats_SUITE.erl6
-rw-r--r--lib/diameter/test/diameter_tls_SUITE.erl18
-rw-r--r--lib/diameter/test/diameter_traffic_SUITE.erl496
-rw-r--r--lib/diameter/test/diameter_transport_SUITE.erl103
-rw-r--r--lib/diameter/test/diameter_util.erl63
-rw-r--r--lib/diameter/test/diameter_watchdog_SUITE.erl10
-rw-r--r--lib/diameter/test/modules.mk4
-rw-r--r--lib/diameter/vsn.mk6
99 files changed, 9449 insertions, 2700 deletions
diff --git a/lib/diameter/bin/diameterc b/lib/diameter/bin/diameterc
index 2f5834d359..2c9a8f555c 100755
--- a/lib/diameter/bin/diameterc
+++ b/lib/diameter/bin/diameterc
@@ -4,7 +4,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2014. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -50,13 +50,10 @@ usage() ->
" -i dir = set an include directory for inherited beams~n"
" -E = no .erl output~n"
" -H = no .hrl output~n"
- " -d = write intermediate files (.spec and .forms)~n",
+ " -d = write intermediate files (.D and .F)~n",
[?MODULE]).
main(Args) ->
- %% Add the ebin directory relative to the script path.
- BinDir = filename:dirname(escript:script_name()),
- code:add_path(filename:join([BinDir, "..", "ebin"])),
halt(gen(Args)).
gen(Args) ->
@@ -72,15 +69,12 @@ gen(Args) ->
1
end.
-compile(#argv{file = File, options = Opts} = A) ->
- try diameter_dict_util:parse({path, File}, Opts) of
- {ok, Spec} ->
- maybe_output(A, Spec, Opts, spec), %% the spec file
- maybe_output(A, Spec, Opts, erl), %% the erl file
- maybe_output(A, Spec, Opts, hrl), %% The hrl file
+compile(#argv{file = File, options = Opts, output = Out}) ->
+ try diameter_make:codec({path, File}, Opts ++ Out) of
+ ok ->
0;
{error, Reason} ->
- error_msg(diameter_dict_util:format_error(Reason), []),
+ error_msg(diameter_make:format_error(Reason), []),
1
catch
error: Reason ->
@@ -88,10 +82,6 @@ compile(#argv{file = File, options = Opts} = A) ->
2
end.
-maybe_output(#argv{file = File, output = Output}, Spec, Opts, Mode) ->
- lists:member(Mode, Output)
- andalso diameter_codegen:from_dict(File, Spec, Opts, Mode).
-
error_msg({Fmt, Args}) ->
error_msg(Fmt, Args).
@@ -119,8 +109,9 @@ arg(["-o", Dir | Args], #argv{options = Opts} = A) ->
true = dir_exists(Dir),
arg(Args, A#argv{options = [{outdir, Dir} | Opts]});
-arg(["-i", Dir | Args], #argv{options = Opts} = A) ->
- arg(Args, A#argv{options = Opts ++ [{include, Dir}]});
+arg(["-i", Dir | Args], #argv{} = A) ->
+ code:add_patha(Dir), %% Set path here instead of passing an include
+ arg(Args, A); %% option so it's set before calling diameter_make.
arg(["--name", Name | Args], #argv{options = Opts} = A) ->
arg(Args, A#argv{options = [{name, Name} | Opts]});
@@ -137,9 +128,8 @@ arg(["-E" | Args], #argv{output = Output} = A) ->
arg(["-H" | Args], #argv{output = Output} = A) ->
arg(Args, A#argv{output = lists:delete(hrl, Output)});
-arg(["-d" | Args], #argv{options = Opts, output = Output} = A) ->
- arg(Args, A#argv{options = [debug | Opts],
- output = [spec | Output]});
+arg(["-d" | Args], #argv{output = Output} = A) ->
+ arg(Args, A#argv{output = [parse, forms | Output -- [parse, forms]]});
arg([[$- = M, C, H | T] | Args], A) %% clustered options
when C /= $i, C /= $o, C /= $- ->
diff --git a/lib/diameter/doc/src/Makefile b/lib/diameter/doc/src/Makefile
index bd2b6b103a..229812fd08 100644
--- a/lib/diameter/doc/src/Makefile
+++ b/lib/diameter/doc/src/Makefile
@@ -82,6 +82,7 @@ gifs: $(GIF_FILES:%=$(HTMLDIR)/%)
man: $(MAN1_FILES) $(MAN3_FILES) $(MAN4_FILES)
$(INDEX_TARGET): $(INDEX_SRC) $(APP_FILE)
+ $(gen_verbose) \
sed -e 's/%VSN%/$(VSN)/; \
s/%ERLANG_SITE%/www\.erlang\.se\//; \
s/%UP_ONE_LEVEL%/..\/..\/..\/doc\/index.html/; \
@@ -140,7 +141,10 @@ release_spec:
depend.mk: depend.sed Makefile seealso.ent \
$(XML_REF_FILES) $(XML_CHAPTER_FILES)
+ $(gen_verbose)
+ $(V_at) \
sed -f seehere.sed seealso.ent > seehere.ent
+ $(V_at) \
(for f in $(XML_REF_FILES) $(XML_CHAPTER_FILES); do \
sed -f $< $$f | sed "s@%FILE%@`basename $$f .xml`@g"; \
done) \
diff --git a/lib/diameter/doc/src/book.xml b/lib/diameter/doc/src/book.xml
index 960296528b..7b606c84d0 100644
--- a/lib/diameter/doc/src/book.xml
+++ b/lib/diameter/doc/src/book.xml
@@ -1,11 +1,11 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE book SYSTEM "book.dtd">
<book xmlns:xi="http://www.w3.org/2001/XInclude">
<header titlestyle="normal">
<copyright>
-<year>2011</year>
+<year>2011</year><year>2013</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/diameter/doc/src/diameter.xml b/lib/diameter/doc/src/diameter.xml
index db19fbb271..dbbbb01138 100644
--- a/lib/diameter/doc/src/diameter.xml
+++ b/lib/diameter/doc/src/diameter.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd" [
<!ENTITY spawn_opt
'<seealso marker="erts:erlang#spawn_opt-2">erlang:spawn_opt/2</seealso>'>
@@ -20,7 +20,8 @@
<header>
<copyright>
-<year>2011</year><year>2013</year>
+<year>2011</year>
+<year>2015</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -110,7 +111,7 @@ Defined in &dict_data_types;.</p>
<tag><c>application_alias() = term()</c></tag>
<item>
<p>
-A name identifying a Diameter application in
+Name identifying a Diameter application in
service configuration.
Passed to &call; when sending requests
defined by the application.</p>
@@ -128,9 +129,9 @@ ExtraArgs = list()
</pre>
<p>
-A module implementing the callback interface defined in &man_app;,
+Module implementing the callback interface defined in &man_app;,
along with any
-extra arguments to be appended to those documented for the interface.
+extra arguments to be appended to those documented.
Note that extra arguments specific to an outgoing request can be
specified to &call;, in which case
those are are appended to any module-specific extra arguments.</p>
@@ -138,7 +139,7 @@ those are are appended to any module-specific extra arguments.</p>
<p>
Specifying a <c>#diameter_callback{}</c> record allows individual
functions to be configured in place of the usual &man_app; callbacks.
-See that module for details.</p>
+See <c>diameter_callback.erl</c> for details.</p>
<marker id="application_opt"/>
</item>
@@ -155,7 +156,7 @@ Has one the following types.</p>
<tag><c>{alias, &application_alias;}</c></tag>
<item>
<p>
-An unique identifier for the application in the scope of the
+Unique identifier for the application in the scope of the
service.
Defaults to the value of the <c>dictionary</c> option if
unspecified.</p>
@@ -164,16 +165,16 @@ unspecified.</p>
<tag><c>{dictionary, atom()}</c></tag>
<item>
<p>
-The name of an encode/decode module for the Diameter
+Name of an encode/decode module for the Diameter
messages defined by the application.
-These modules are generated from a specification file whose format is
-documented in &man_dict;.</p>
+These modules are generated from files whose format is documented in
+&man_dict;.</p>
</item>
<tag><c>{module, &application_module;}</c></tag>
<item>
<p>
-The callback module with which messages of the Diameter application are
+Callback module in which messages of the Diameter application are
handled.
See &man_app; for the required interface and semantics.</p>
</item>
@@ -181,7 +182,7 @@ See &man_app; for the required interface and semantics.</p>
<tag><c>{state, term()}</c></tag>
<item>
<p>
-The initial callback state.
+Initial callback state.
The prevailing state is passed to some
&man_app;
callbacks, which can then return a new state.
@@ -191,25 +192,24 @@ Defaults to the value of the <c>alias</c> option if unspecified.</p>
<tag><c>{call_mutates_state, true|false}</c></tag>
<item>
<p>
-Specifies whether or not the &app_pick_peer;
+Whether or not the &app_pick_peer;
application callback can modify the application state.
Defaults to <c>false</c> if unspecified.</p>
-<note>
+<warning>
<p>
-&app_pick_peer; callbacks
-are serialized when these are allowed to modify state, which is a
-potential performance bottleneck.
+&app_pick_peer; callbacks are serialized when this option is <c>true</c>,
+which is a potential performance bottleneck.
A simple Diameter client may suffer no ill effects from using mutable
state but a server or agent that responds to incoming request should
probably avoid it.</p>
-</note>
+</warning>
</item>
<tag><c>{answer_errors, callback|report|discard}</c></tag>
<item>
<p>
-Determines the manner in which incoming answer messages containing
+Manner in which incoming answer messages containing
decode errors are handled.</p>
<p>
@@ -227,14 +227,14 @@ question is as if a callback had taken place and returned
<c>{error, failure}</c>.</p>
<p>
-Defaults to <c>report</c> if unspecified.</p>
+Defaults to <c>discard</c> if unspecified.</p>
</item>
<tag><c>{request_errors, answer_3xxx|answer|callback}</c></tag>
<item>
<p>
-Determines the manner in which incoming requests are handled when an
-error other than 3007, DIAMETER_APPLICATION_UNSUPPORTED (which cannot
+Manner in which incoming requests are handled when an
+error other than 3007 (DIAMETER_APPLICATION_UNSUPPORTED, which cannot
be associated with an application callback module), is detected.</p>
<p>
@@ -244,7 +244,8 @@ If <c>answer</c> then even 5xxx errors are answered without a
callback unless the connection in question has configured the RFC 3588
common dictionary as noted below.
If <c>callback</c> then a &app_handle_request; callback always takes
-place and the return value determines the answer sent to the peer.</p>
+place and its return value determines the answer sent to the peer, if
+any.</p>
<p>
Defaults to <c>answer_3xxx</c> if unspecified.</p>
@@ -252,13 +253,14 @@ Defaults to <c>answer_3xxx</c> if unspecified.</p>
<note>
<p>
Answers sent by diameter set the E-bit in the Diameter Header.
-Since RFC 3588 allowed only 3xxx result codes in an
+Since RFC 3588 allows only 3xxx result codes in an
<c>answer-message</c>, <c>answer</c> has the same semantics as
-<c>answer_3xxx</c> if the peer connection in question has configured
-the RFC 3588 common dictionary, <c>diameter_gen_base_rfc3588</c>.
-RFC 6733 allows both 3xxx and 5xxx result codes in an
-<c>answer-message</c> so a connection configured with the RFC 6733
-common dictionary, <c>diameter_gen_base_rfc6733</c>, does
+<c>answer_3xxx</c> when the transport in question has
+been configured with <c>diameter_gen_base_rfc3588</c> as its common
+dictionary.
+Since RFC 6733 allows both 3xxx and 5xxx result codes in an
+<c>answer-message</c>, a transport with
+<c>diameter_gen_base_rfc6733</c> as its common dictionary does
distinguish between <c>answer_3xxx</c> and <c>answer</c>.</p>
</note>
</item>
@@ -291,9 +293,8 @@ Multiple options append to the argument list.</p>
<tag><c>{filter, &peer_filter;}</c></tag>
<item>
<p>
-A filter to apply to the list of available peers before passing them to
-the &app_pick_peer;
-callback for the application in question.
+Filter to apply to the list of available peers before passing it to
+the &app_pick_peer; callback for the application in question.
Multiple options are equivalent a single <c>all</c> filter on the
corresponding list of filters.
Defaults to <c>none</c>.</p>
@@ -302,7 +303,7 @@ Defaults to <c>none</c>.</p>
<tag><c>{timeout, &dict_Unsigned32;}</c></tag>
<item>
<p>
-The number of milliseconds after which the request should
+Number of milliseconds after which the request should
timeout.
Defaults to 5000.</p>
</item>
@@ -310,9 +311,9 @@ Defaults to 5000.</p>
<tag><c>detach</c></tag>
<item>
<p>
-Causes &call; to return <c>ok</c> as
+Cause &call; to return <c>ok</c> as
soon as the request in
-question has been encoded instead of waiting for and returning
+question has been encoded, instead of waiting for and returning
the result from a subsequent &app_handle_answer; or
&app_handle_error; callback.</p>
</item>
@@ -331,8 +332,8 @@ An invalid option will cause &call; to fail.</p>
<p>
AVP values sent in outgoing CER or CEA messages during capabilities
exchange.
-Can be configured both on a service and a transport, values specified
-on the latter taking precedence over any specified on the former.
+Can be configured both on a service and a transport, values
+on the latter taking precedence.
Has one of the following types.</p>
<taglist>
@@ -355,10 +356,10 @@ question communicates an address list as described in
<tag><c>{'Origin-State-Id', &dict_Unsigned32;}</c></tag>
<item>
<p>
-Origin-State-Id is optional but will be included in outgoing messages
-sent by diameter itself: CER/CEA, DWR/DWA and DPR/DPA.
+Origin-State-Id is optional but, if configured, will be included in
+outgoing CER/CEA and DWR/DWA messages.
Setting a value of <c>0</c> (zero) is equivalent to not setting a
-value as documented in &the_rfc;.
+value, as documented in &the_rfc;.
The function &origin_state_id;
can be used as to retrieve a value that is computed when the diameter
application is started.</p>
@@ -370,8 +371,8 @@ application is started.</p>
<item>
<p>
Inband-Security-Id defaults to the empty list, which is equivalent to a
-list containing only 0 (= NO_INBAND_SECURITY).
-If 1 (= TLS) is specified then TLS is selected if the CER/CEA received
+list containing only 0 (NO_INBAND_SECURITY).
+If 1 (TLS) is specified then TLS is selected if the CER/CEA received
from the peer offers it.</p>
</item>
@@ -426,7 +427,7 @@ configuration passed to &start_service; or &add_transport;.</p>
<tag><c>peer_filter() = term()</c></tag>
<item>
<p>
-A filter passed to &call; in order to select candidate peers for a
+Filter passed to &call; in order to select candidate peers for a
&app_pick_peer; callback.
Has one of the following types.</p>
@@ -437,38 +438,38 @@ Has one of the following types.</p>
<p>
Matches any peer.
This is a convenience that provides a filter equivalent to no
-filter at all.</p>
+filter.</p>
</item>
<tag><c>host</c></tag>
<item>
<p>
-Matches only those peers whose <c>Origin-Host</c> has the same value
-as <c>Destination-Host</c> in the outgoing request in question,
+Matches only those peers whose Origin-Host has the same value
+as Destination-Host in the outgoing request in question,
or any peer if the request does not contain
-a <c>Destination-Host</c> AVP.</p>
+a Destination-Host AVP.</p>
</item>
<tag><c>realm</c></tag>
<item>
<p>
-Matches only those peers whose <c>Origin-Realm</c> has the same value
-as <c>Destination-Realm</c> in the outgoing request in question,
+Matches only those peers whose Origin-Realm has the same value
+as Destination-Realm in the outgoing request in question,
or any peer if the request does not contain
-a <c>Destination-Realm</c> AVP.</p>
+a Destination-Realm AVP.</p>
</item>
<tag><c>{host, any|&dict_DiameterIdentity;}</c></tag>
<item>
<p>
-Matches only those peers whose <c>Origin-Host</c> has the
+Matches only those peers whose Origin-Host has the
specified value, or all peers if the atom <c>any</c>.</p>
</item>
-<tag><c>{realm, any|&dict_DiameterIdentity;</c></tag>
+<tag><c>{realm, any|&dict_DiameterIdentity;}</c></tag>
<item>
<p>
-Matches only those peers whose <c>Origin-Realm</c> has the
+Matches only those peers whose Origin-Realm has the
specified value, or all peers if the atom <c>any</c>.</p>
</item>
@@ -477,7 +478,8 @@ specified value, or all peers if the atom <c>any</c>.</p>
<p>
Matches only those peers for which the specified
<c>&evaluable;</c> returns
-<c>true</c> on the connection's <c>diameter_caps</c> record.
+<c>true</c> when applied to the connection's <c>diameter_caps</c>
+record.
Any other return value or exception is equivalent to <c>false</c>.</p>
</item>
@@ -497,7 +499,23 @@ Matches only those peers matched by each filter in the specified list.</p>
<item>
<p>
Matches only those peers matched by at least one filter in the
-specified list.</p>
+specified list.
+The resulting list will be in match order, peers matching the
+first filter of the list sorting before those matched by the second,
+and so on.</p>
+</item>
+
+<tag><c>{first, [&peer_filter;]}</c></tag>
+<item>
+<p>
+Like <c>any</c>, but stops at the first filter for which there are
+matches, which can be much more efficient when there are many peers.
+For example, the following filter causes only peers best matching
+both the host and realm filters to be presented.</p>
+
+<pre>
+{first, [{all, [host, realm]}, realm]}
+</pre>
</item>
</taglist>
@@ -508,10 +526,10 @@ that matches no peer.</p>
<note>
<p>
-The <c>host</c> and <c>realm</c> filters examine the
-outgoing request as passed to &call;,
-assuming that this is a record- or list-valued <c>&codec_message;</c>,
-and that the message contains at most one of each AVP.
+The <c>host</c> and <c>realm</c> filters cause the Destination-Host
+and Destination-Realm AVPs to be extracted from the
+outgoing request, assuming it to be a record- or list-valued
+<c>&codec_message;</c>, and assuming at most one of each AVP.
If this is not the case then the <c>{host|realm, &dict_DiameterIdentity;}</c>
filters must be used to achieve the desired result.
An empty <c>&dict_DiameterIdentity;</c>
@@ -555,7 +573,7 @@ Can have one of the following types.</p>
<p>
The service is being started or stopped.
No event precedes a <c>start</c> event.
-No event follows a <c>stop</c> event and this event
+No event follows a <c>stop</c> event, and this event
implies the termination of all transport processes.</p>
</item>
@@ -575,16 +593,15 @@ The RFC 3539 watchdog state machine has
transitioned into (<c>up</c>) or out of (<c>down</c>) the OKAY
state.
If a <c>#diameter_packet{}</c> is present in an <c>up</c> event
-then there has been a capabilties exchange on a newly established
-transport connection and the record contains the received CER or CEA.
-Otherwise a connection has reestablished without the loss or
-connectivity.</p>
+then there has been a capabilities exchange on a newly established
+transport connection and the record contains the received CER or
+CEA.</p>
<p>
Note that a single <c>up</c> or <c>down</c> event for a given peer
corresponds to multiple &app_peer_up; or &app_peer_down;
callbacks, one for each of the Diameter applications negotiated during
-capablilities exchange.
+capabilities exchange.
That is, the event communicates connectivity with the
peer as a whole while the callbacks communicate connectivity with
respect to individual Diameter applications.</p>
@@ -599,7 +616,7 @@ Opts = [&transport_opt;]
<p>
A connecting transport is attempting to establish/reestablish a
-transport connection with a peer following &reconnect_timer; or
+transport connection with a peer following &connect_timer; or
&watchdog_timer; expiry.</p>
</item>
@@ -627,10 +644,10 @@ CB = &evaluable;
</pre>
<p>
-An incoming CER has been answered with the indicated result code or
+An incoming CER has been answered with the indicated result code, or
discarded.
-<c>Caps</c> contains pairs of values for the local node and remote
-peer.
+<c>Caps</c> contains pairs of values, for the local node and remote
+peer respectively.
<c>Pkt</c> contains the CER in question.
In the case of rejection by a capabilities callback, the tuple
contains the rejecting callback.</p>
@@ -647,7 +664,7 @@ Pkt = #diameter_packet{}
<p>
An incoming CER contained errors and has been answered with the
indicated result code.
-<c>Caps</c> contains only values for the local node.
+<c>Caps</c> contains values for the local node only.
<c>Pkt</c> contains the CER in question.</p>
</item>
@@ -661,7 +678,7 @@ connection establishment.</p>
<tag><c>{'CEA', Result, Caps, Pkt}</c></tag>
<item>
<pre>
-Result = integer() | atom() | {capabilities_cb, CB, ResultCode|discard}
+Result = ResultCode | atom() | {capabilities_cb, CB, ResultCode|discard}
Caps = #diameter_caps{}
Pkt = #diameter_packet{}
ResultCode = integer()
@@ -729,7 +746,7 @@ info fields of forms other than the above.</p>
<tag><c>service_name() = term()</c></tag>
<item>
<p>
-The name of a service as passed to &start_service; and with which the
+Name of a service as passed to &start_service; and with which the
service is identified.
There can be at most one service with a given name on a given node.
Note that &make_ref;
@@ -741,7 +758,7 @@ can be used to generate a service name that is somewhat unique.</p>
<tag><c>service_opt()</c></tag>
<item>
<p>
-An option passed to &start_service;.
+Option passed to &start_service;.
Can be any <c>&capability;</c> as well as the following.</p>
<taglist>
@@ -749,12 +766,12 @@ Can be any <c>&capability;</c> as well as the following.</p>
<tag><c>{application, [&application_opt;]}</c></tag>
<item>
<p>
-Defines a Diameter application supported by the service.</p>
+A Diameter application supported by the service.</p>
<p>
A service must configure one tuple for each Diameter
application it intends to support.
-For an outgoing Diameter request, the relevant <c>&application_alias;</c> is
+For an outgoing request, the relevant <c>&application_alias;</c> is
passed to &call;, while for an
incoming request the application identifier in the message
header determines the application, the identifier being specified in
@@ -765,11 +782,24 @@ the application's &dictionary; file.</p>
The capabilities advertised by a node must match its configured
applications. In particular, <c>application</c> configuration must
be matched by corresponding &capability; configuration, of
-Application-Id AVP's in particular.</p>
+*-Application-Id AVPs in particular.</p>
</warning>
</item>
+<marker id="incoming_maxlen"/>
+<tag><c>{incoming_maxlen, 0..16777215}</c></tag>
+<item>
+<p>
+Bound on the expected size of incoming Diameter messages.
+Messages larger than the specified number of bytes are discarded.</p>
+
+<p>
+Defaults to <c>16777215</c>, the maximum value of the 24-bit Message
+Length field in a Diameter Header.</p>
+
+</item>
+
<tag><c>{restrict_connections, false
| node
| nodes
@@ -777,11 +807,12 @@ Application-Id AVP's in particular.</p>
| evaluable()}</c></tag>
<item>
<p>
-Specifies the degree to which the service allows multiple transport
-connections to the same peer.</p>
+The degree to which the service allows multiple transport
+connections to the same peer, as identified by its Origin-Host
+at capabilities exchange.</p>
<p>
-If type <c>[node()]</c> then a connection is rejected if another already
+If <c>[node()]</c> then a connection is rejected if another already
exists on any of the specified nodes.
Types <c>false</c>, <c>node</c>, <c>nodes</c> and
&evaluable; are equivalent to
@@ -802,9 +833,9 @@ Defaults to <c>nodes</c>.</p>
<tag><c>{sequence, {H,N} | &evaluable;}</c></tag>
<item>
<p>
-Specifies a constant value <c>H</c> for the topmost <c>32-N</c> bits of
-of 32-bit End-to-End and Hop-by-Hop identifiers generated
-by the service, either explicity or as a return value of a function
+A constant value <c>H</c> for the topmost <c>32-N</c> bits of
+of 32-bit End-to-End and Hop-by-Hop Identifiers generated
+by the service, either explicitly or as a return value of a function
to be evaluated at &start_service;.
In particular, an identifier <c>Id</c> is mapped to a new identifier
as follows.</p>
@@ -812,11 +843,11 @@ as follows.</p>
(H bsl N) bor (Id band ((1 bsl N) - 1))
</pre>
<p>
-Note that &the_rfc; requires that End-to-End identifiers remain unique
+Note that &the_rfc; requires that End-to-End Identifiers remain unique
for a period of at least 4 minutes and that this and the call rate
-places a lower bound on the appropriate values of <c>N</c>:
-at a rate of <c>R</c> requests per second an <c>N</c>-bit counter
-traverses all of its values in <c>(1 bsl N) div (R*60)</c> minutes so
+places a lower bound on appropriate values of <c>N</c>:
+at a rate of <c>R</c> requests per second, an <c>N</c>-bit counter
+traverses all of its values in <c>(1 bsl N) div (R*60)</c> minutes, so
the bound is <c>4*R*60 =&lt; 1 bsl N</c>.</p>
<p><c>N</c> must lie in the range <c>0..32</c> and <c>H</c> must be a
@@ -829,7 +860,7 @@ Defaults to <c>{0,32}</c>.</p>
<p>
Multiple Erlang nodes implementing the same Diameter node should
be configured with different sequence masks to ensure that each node
-uses a unique range of End-to-End and Hop-by-Hop identifiers for
+uses a unique range of End-to-End and Hop-by-Hop Identifiers for
outgoing requests.</p>
</warning>
</item>
@@ -837,7 +868,7 @@ outgoing requests.</p>
<tag><c>{share_peers, boolean() | [node()] | evaluable()}</c></tag>
<item>
<p>
-Specifies nodes to which peer connections established on the local
+Nodes to which peer connections established on the local
Erlang node are communicated.
Shared peers become available in the remote candidates list passed to
&app_pick_peer; callbacks on remote nodes whose services are
@@ -852,7 +883,7 @@ by the specified function, evaluated whenever a peer connection
becomes available or a remote service requests information about local
connections.
The value <c>true</c> is equivalent to <c>fun &nodes;</c>.
-The value <c>node()</c> in a node list is ignored, so a collection of
+The value <c>node()</c> in a list is ignored, so a collection of
services can all be configured to share with the same list of
nodes.</p>
@@ -876,7 +907,7 @@ of a single Diameter node across multiple Erlang nodes.</p>
<tag><c>{spawn_opt, [term()]}</c></tag>
<item>
<p>
-An options list passed to &spawn_opt; when spawning a process for an
+Options list passed to &spawn_opt; when spawning a process for an
incoming Diameter request, unless the transport in question
specifies another value.
Options <c>monitor</c> and <c>link</c> are ignored.</p>
@@ -885,10 +916,77 @@ Options <c>monitor</c> and <c>link</c> are ignored.</p>
Defaults to the empty list.</p>
</item>
+<marker id="strict_mbit"/>
+<tag><c>{strict_mbit, boolean()}</c></tag>
+<item>
+<p>
+Whether or not to regard an AVP setting the M-bit as erroneous when
+the command grammar in question does not explicitly allow the AVP.
+If <c>true</c> then such AVPs are regarded as 5001 errors,
+DIAMETER_AVP_UNSUPPORTED.
+If <c>false</c> then the M-bit is ignored and policing
+it becomes the receiver's responsibility.</p>
+
+<p>
+Defaults to <c>true</c>.</p>
+
+<warning>
+<p>
+RFC 6733 is unclear about the semantics of the M-bit.
+One the one hand, the CCF specification in section 3.2 documents AVP
+in a command grammar as meaning <b>any</b> arbitrary AVP; on the
+other hand, 1.3.4 states that AVPs setting the M-bit cannot be added
+to an existing command: the modified command must instead be
+placed in a new Diameter application.</p>
+<p>
+The reason for the latter is presumably interoperability:
+allowing arbitrary AVPs setting the M-bit in a command makes its
+interpretation implementation-dependent, since there's no
+guarantee that all implementations will understand the same set of
+arbitrary AVPs in the context of a given command.
+However, interpreting <c>AVP</c> in a command grammar as <b>any</b>
+AVP, regardless of M-bit, renders 1.3.4 meaningless, since the receiver
+can simply ignore any AVP it thinks isn't relevant, regardless of the
+sender's intent.</p>
+<p>
+Beware of confusing mandatory in the sense of the M-bit with mandatory
+in the sense of the command grammar.
+The former is a semantic requirement: that the receiver understand the
+semantics of the AVP in the context in question.
+The latter is a syntactic requirement: whether or not the AVP must
+occur in the message in question.</p>
+</warning>
+
+</item>
+
+<marker id="string_decode"/>
+<tag><c>{string_decode, boolean()}</c></tag>
+<item>
+<p>
+Whether or not to decode AVPs of type &dict_OctetString; and its
+derived types &dict_DiameterIdentity;, &dict_DiameterURI;,
+&dict_IPFilterRule;, &dict_QoSFilterRule;, and &dict_UTF8String;.
+If <c>true</c> then AVPs of these types are decoded to string().
+If <c>false</c> then values are retained as binary().</p>
+
+<p>
+Defaults to <c>true</c>.</p>
+
+<warning>
+<p>
+This option should be set to <c>false</c>
+since a sufficiently malicious peer can otherwise cause large amounts
+of memory to be consumed when decoded Diameter messages are passed
+between processes.
+The default value is for backwards compatibility.</p>
+</warning>
+
+</item>
+
<tag><c>{use_shared_peers, boolean() | [node()] | evaluable()}</c></tag>
<item>
<p>
-Specifies nodes from which communicated peers are made available in
+Nodes from which communicated peers are made available in
the remote candidates list of &app_pick_peer; callbacks.</p>
<p>
@@ -899,7 +997,7 @@ If <c>evaluable()</c> then only peers returned by the specified
function are used, evaluated whenever a remote service communicates
information about an available peer connection.
The value <c>true</c> is equivalent to <c>fun &nodes;</c>.
-The value <c>node()</c> in a node list is ignored.</p>
+The value <c>node()</c> in a list is ignored.</p>
<p>
Defaults to <c>false</c>.</p>
@@ -928,7 +1026,7 @@ each node from which requests are sent.</p>
<tag><c>transport_opt()</c></tag>
<item>
<p>
-An option passed to &add_transport;.
+Option passed to &add_transport;.
Has one of the following types.</p>
<taglist>
@@ -936,8 +1034,7 @@ Has one of the following types.</p>
<tag><c>{applications, [&application_alias;]}</c></tag>
<item>
<p>
-The list of Diameter applications to which the transport should be
-restricted.
+Diameter applications to which the transport should be restricted.
Defaults to all applications configured on the service in question.
Applications not configured on the service in question are ignored.</p>
@@ -946,7 +1043,7 @@ Applications not configured on the service in question are ignored.</p>
The capabilities advertised by a node must match its configured
applications.
In particular, setting <c>applications</c> on a transport typically
-implies having to set matching Application-Id AVP's in a
+implies having to set matching *-Application-Id AVPs in a
&capabilities; tuple.</p>
</warning>
@@ -956,7 +1053,7 @@ implies having to set matching Application-Id AVP's in a
<tag><c>{capabilities, [&capability;]}</c></tag>
<item>
<p>
-AVP's used to construct outgoing CER/CEA messages.
+AVPs used to construct outgoing CER/CEA messages.
Values take precedence over any specified on the service in
question.</p>
@@ -970,7 +1067,7 @@ TLS is desired over TCP as implemented by &man_tcp;.</p>
<tag><c>{capabilities_cb, &evaluable;}</c></tag>
<item>
<p>
-A callback invoked upon reception of CER/CEA during capabilities
+Callback invoked upon reception of CER/CEA during capabilities
exchange in order to ask whether or not the connection should
be accepted.
Applied to the <c>&transport_ref;</c> and
@@ -1018,32 +1115,61 @@ case the corresponding callbacks are applied until either all return
<tag><c>{capx_timeout, &dict_Unsigned32;}</c></tag>
<item>
<p>
-The number of milliseconds after which a transport process having an
+Number of milliseconds after which a transport process having an
established transport connection will be terminated if the expected
capabilities exchange message (CER or CEA) is not received from the peer.
-For a connecting transport, the timing of reconnection attempts is
-governed by &watchdog_timer; or &reconnect_timer; expiry.
+For a connecting transport, the timing of connection attempts is
+governed by &connect_timer; or &watchdog_timer; expiry.
For a listening transport, the peer determines the timing.</p>
<p>
Defaults to 10000.</p>
</item>
+<marker id="connect_timer"/>
+<tag><c>{connect_timer, Tc}</c></tag>
+<item>
+<pre>
+Tc = &dict_Unsigned32;
+</pre>
+
+<p>
+For a connecting transport, the &the_rfc; Tc timer, in milliseconds.
+This timer determines the frequency with which a transport
+attempts to establish an initial connection with its peer
+following transport configuration.
+Once an initial connection has been
+established, &watchdog_timer; determines the frequency of
+reconnection attempts, as required by RFC 3539.</p>
+
+<p>
+For a listening transport, the timer specifies the time after which a
+previously connected peer will be forgotten: a connection after this time is
+regarded as an initial connection rather than reestablishment,
+causing the RFC 3539 state machine to pass to state OKAY rather than
+REOPEN.
+Note that these semantics are not governed by the RFC and
+that a listening transport's &connect_timer; should be greater
+than its peer's Tw plus jitter.</p>
+
+<p>
+Defaults to 30000 for a connecting transport and 60000 for a listening
+transport.</p>
+</item>
+
<marker id="disconnect_cb"/>
<tag><c>{disconnect_cb, &evaluable;}</c></tag>
<item>
<p>
-A callback invoked prior to terminating the transport process of a
+Callback invoked prior to terminating the transport process of a
transport connection having watchdog state <c>OKAY</c>.
-Applied to <c>Reason=transport|service|application</c> and the
-<c>&transport_ref;</c> and
-<c>&app_peer;</c>
-in question, <c>Reason</c> indicating whether the diameter
-application is being stopped, the service in question is being stopped
-at &stop_service; or
-the transport in question is being removed at &remove_transport;,
-respectively.</p>
+Applied to <c>application|service|transport</c> and the
+<c>&transport_ref;</c> and <c>&app_peer;</c> in question:
+<c>application</c> indicates that the diameter application is
+being stopped, <c>service</c> that the service in question is being
+stopped by &stop_service;, and <c>transport</c> that the transport in
+question is being removed by &remove_transport;.</p>
<p>
The return value can have one of the following types.</p>
@@ -1052,7 +1178,7 @@ The return value can have one of the following types.</p>
<tag><c>{dpr, [option()]}</c></tag>
<item>
<p>
-Causes Disconnect-Peer-Request to be sent to the peer, the transport
+Send Disconnect-Peer-Request to the peer, the transport
process being terminated following reception of
Disconnect-Peer-Answer or timeout.
An <c>option()</c> can be one of the following.</p>
@@ -1061,7 +1187,7 @@ An <c>option()</c> can be one of the following.</p>
<tag><c>{cause, 0|rebooting|1|busy|2|goaway}</c></tag>
<item>
<p>
-The Disconnect-Cause to send, <c>REBOOTING</c>, <c>BUSY</c> and
+Disconnect-Cause to send, <c>REBOOTING</c>, <c>BUSY</c> and
<c>DO_NOT_WANT_TO_TALK_TO_YOU</c> respectively.
Defaults to <c>rebooting</c> for <c>Reason=service|application</c> and
<c>goaway</c> for <c>Reason=transport</c>.</p>
@@ -1070,9 +1196,9 @@ Defaults to <c>rebooting</c> for <c>Reason=service|application</c> and
<tag><c>{timeout, &dict_Unsigned32;}</c></tag>
<item>
<p>
-The number of milliseconds after which the transport process is
+Number of milliseconds after which the transport process is
terminated if DPA has not been received.
-Defaults to 1000.</p>
+Defaults to the value of &dpa_timeout;.</p>
</item>
</taglist>
</item>
@@ -1086,7 +1212,7 @@ Equivalent to <c>{dpr, []}</c>.</p>
<tag><c>close</c></tag>
<item>
<p>
-Causes the transport process to be terminated without
+Terminate the transport process without
Disconnect-Peer-Request being sent to the peer.</p>
</item>
@@ -1109,11 +1235,34 @@ configured them.</p>
Defaults to a single callback returning <c>dpr</c>.</p>
</item>
+<marker id="dpa_timeout"/>
+<tag><c>{dpa_timeout, &dict_Unsigned32;}</c></tag>
+<item>
+<p>
+Number of milliseconds after which a transport connection is
+terminated following an outgoing DPR if DPA is not received.</p>
+
+<p>
+Defaults to 1000.</p>
+</item>
+
+<marker id="dpr_timeout"/>
+<tag><c>{dpr_timeout, &dict_Unsigned32;}</c></tag>
+<item>
+<p>
+Number of milliseconds after which a transport connection is
+terminated following an incoming DPR if the peer does not close the
+connection.</p>
+
+<p>
+Defaults to 5000.</p>
+</item>
+
<marker id="length_errors"/>
<tag><c>{length_errors, exit|handle|discard}</c></tag>
<item>
<p>
-Specifies how to deal with errors in the Message Length field of the
+How to deal with errors in the Message Length field of the
Diameter Header in an incoming message.
An error in this context is that the length is not at least 20 bytes
(the length of a Header), is not a multiple of 4 (a valid length) or
@@ -1121,9 +1270,7 @@ is not the length of the message in question, as received over the
transport interface documented in &man_transport;.</p>
<p>
-If <c>exit</c> then a warning report is emitted and the parent of the
-transport process in question exits, which causes the transport
-process itself to exit as described in &man_transport;.
+If <c>exit</c> then the transport process in question exits.
If <c>handle</c> then the message is processed as usual, a resulting
&app_handle_request; or &app_handle_answer; callback (if one takes
place) indicating the <c>5015</c> error (DIAMETER_INVALID_MESSAGE_LENGTH).
@@ -1145,41 +1292,26 @@ See &man_tcp; for the behaviour of that module.</p>
</note>
</item>
-<marker id="reconnect_timer"/>
-<tag><c>{reconnect_timer, Tc}</c></tag>
+<tag><c>{pool_size, pos_integer()}</c></tag>
<item>
-<pre>
-Tc = &dict_Unsigned32;
-</pre>
-
-<p>
-For a connecting transport, the &the_rfc; Tc timer, in milliseconds.
-Note that this timer determines the frequency with which a transport
-will attempt to establish a connection with its peer only <em>before</em>
-an initial connection is established: once there is an initial
-connection it's &watchdog_timer; that determines the
-frequency of reconnection attempts, as required by RFC 3539.</p>
-
<p>
-For a listening transport, the timer specifies the time after which a
-previously connected peer will be forgotten: a connection after this time is
-regarded as an initial connection rather than a reestablishment,
-causing the RFC 3539 state machine to pass to state OKAY rather than
-REOPEN.
-Note that these semantics are not governed by the RFC and
-that a listening transport's &reconnect_timer; should be greater
-than its peer's Tw plus jitter.</p>
+Number of transport processes to start.
+For a listening transport, determines the size of the pool of
+accepting transport processes, a larger number being desirable for
+processing multiple concurrent peer connection attempts.
+For a connecting transport, determines the number of connections to
+the peer in question that will be attempted to be establshed:
+the &service_opt;: <c>restrict_connections</c> should also be
+configured on the service in question to allow multiple connections to
+the same peer.</p>
-<p>
-Defaults to 30000 for a connecting transport and 60000 for a listening
-transport.</p>
</item>
<marker id="spawn_opt"/>
<tag><c>{spawn_opt, [term()]}</c></tag>
<item>
<p>
-An options list passed to &spawn_opt; when spawning a process for an
+Options passed to &spawn_opt; when spawning a process for an
incoming Diameter request.
Options <c>monitor</c> and <c>link</c> are ignored.</p>
@@ -1192,7 +1324,7 @@ Defaults to the list configured on the service if not specified.</p>
<tag><c>{transport_config, term(), &dict_Unsigned32; | infinity}</c></tag>
<item>
<p>
-A term passed as the third argument to the &transport_start; function of
+Term passed as the third argument to the &transport_start; function of
the relevant &transport_module; in order to
start a transport process.
Defaults to the empty list if unspecified.</p>
@@ -1220,7 +1352,7 @@ To listen on both SCTP and TCP, define one transport for each.</p>
<tag><c>{transport_module, atom()}</c></tag>
<item>
<p>
-A module implementing a transport process as defined in &man_transport;.
+Module implementing a transport process as defined in &man_transport;.
Defaults to <c>diameter_tcp</c> if unspecified.</p>
<p>
@@ -1240,7 +1372,7 @@ corresponding timeout (see below) or all fail.</p>
<tag><c>{watchdog_config, [{okay|suspect, non_neg_integer()}]}</c></tag>
<item>
<p>
-Specifies configuration that alters the behaviour of the watchdog
+Configuration that alters the behaviour of the watchdog
state machine.
On key <c>okay</c>, the non-negative number of answered DWR
messages before transitioning from REOPEN to OKAY.
@@ -1295,7 +1427,7 @@ in predicate functions passed to &remove_transport;.</p>
<tag><c>transport_ref() = reference()</c></tag>
<item>
<p>
-An reference returned by &add_transport; that
+Reference returned by &add_transport; that
identifies the configuration.</p>
</item>
@@ -1661,7 +1793,7 @@ R_Flag}</c>.</p>
Note that <c>watchdog</c>, <c>peer</c>, <c>apps</c>, <c>caps</c>
and <c>port</c> entries depend on connectivity
with the peer and may not be present.
-Note also that the <c>statistics</c> entry presents values acuumulated
+Note also that the <c>statistics</c> entry presents values accumulated
during the lifetime of the transport configuration.</p>
<p>
@@ -1724,6 +1856,15 @@ connection might look as follows.</p>
The information presented here is as in the <c>connect</c> case except
that the client connections are grouped under an <c>accept</c> tuple.</p>
+<p>
+Whether or not the &transport_opt; <c>pool_size</c> has been
+configured affects the format
+of the listing in the case of a connecting transport, since a value
+greater than 1 implies multiple transport processes for the same
+<c>&transport_ref;</c>, as in the listening case.
+The format in this case is similar to the listening case, with a
+<c>pool</c> tuple in place of an <c>accept</c> tuple.</p>
+
</item>
<tag><c>connections</c></tag>
diff --git a/lib/diameter/doc/src/diameter_app.xml b/lib/diameter/doc/src/diameter_app.xml
index e6c9cc9a90..67c430c40a 100644
--- a/lib/diameter/doc/src/diameter_app.xml
+++ b/lib/diameter/doc/src/diameter_app.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd" [
<!ENTITY message '<seealso marker="#message">message()</seealso>'>
<!ENTITY dict
@@ -308,7 +308,7 @@ The return value <c>{Peer, NewState}</c> is only allowed if
the Diameter application in question was configured with the
&mod_application_opt; <c>{call_mutates_state, true}</c>.
Otherwise, the <c>State</c> argument is always
-the intial value as configured on the application, not any subsequent
+the initial value as configured on the application, not any subsequent
value returned by a &peer_up;
or &peer_down; callback.</p>
</warning>
@@ -565,7 +565,7 @@ Equivalent to</p>
</pre>
<p>
where <c>Avps</c> sets the Origin-Host, Origin-Realm, the specified
-Result-Code and (if the request contained one) Session-Id AVP's, and
+Result-Code and (if the request contained one) Session-Id AVPs, and
possibly Failed-AVP as described below.</p>
<p>
diff --git a/lib/diameter/doc/src/diameter_codec.xml b/lib/diameter/doc/src/diameter_codec.xml
index 4a77d5435b..308a56fab7 100644
--- a/lib/diameter/doc/src/diameter_codec.xml
+++ b/lib/diameter/doc/src/diameter_codec.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd" [
<!ENTITY records
'<seealso marker="diameter_dict#MESSAGE_RECORDS">diameter_dict(4)</seealso>'>
@@ -13,7 +13,7 @@
<erlref>
<header>
<copyright>
-<year>2012</year>
+<year>2012</year><year>2013</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -73,7 +73,7 @@ are defined in diameter.hrl, which can be included as follows.</p>
</pre>
<p>
-Application-specific records are definied in the hrl
+Application-specific records are defined in the hrl
files resulting from dictionary file compilation.</p>
</description>
@@ -122,7 +122,7 @@ Fields have the following types.</p>
<item>
<p>
Values in the AVP header, corresponding to AVP Code, the M flag, P
-flags and Vendor-ID respectivelty.
+flags and Vendor-ID respectively.
A Vendor-ID other than <c>undefined</c> implies a set V flag.</p>
</item>
@@ -222,7 +222,7 @@ header.</p>
<tag><c>is_retransmitted = boolean()</c></tag>
<item>
<p>
-Values correspoding to the R(equest), P(roxiable), E(rror)
+Values corresponding to the R(equest), P(roxiable), E(rror)
and T(Potentially re-transmitted message) flags of the Diameter
header.</p>
</item>
diff --git a/lib/diameter/doc/src/diameter_dict.xml b/lib/diameter/doc/src/diameter_dict.xml
index 4fcde495b3..5cf1b174a0 100644
--- a/lib/diameter/doc/src/diameter_dict.xml
+++ b/lib/diameter/doc/src/diameter_dict.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE erlref SYSTEM "fileref.dtd" [
<!ENTITY format
'<seealso marker="#FILE_FORMAT">FILE FORMAT</seealso>'>
@@ -431,7 +431,7 @@ equivalent to specifying it with <c>@avp_vendor_id</c>.</p>
Defines values of AVP Name having type Enumerated.
Section content consists of names and corresponding integer values.
Integer values can be prefixed with 0x to be interpreted as
-hexidecimal.</p>
+hexadecimal.</p>
<p>
Note that the AVP in question can be defined in an inherited
@@ -529,6 +529,11 @@ answer record and passed to a &app_handle_request;
callback upon reception of an incoming request.</p>
<p>
+In cases in which there is a choice between string() and binary() types
+for OctetString() and derived types, the representation is determined
+by the value of &mod_string_decode;.</p>
+
+<p>
<em>Basic AVP Data Formats</em></p>
<marker id="OctetString"/>
@@ -541,7 +546,7 @@ callback upon reception of an incoming request.</p>
<marker id="Grouped"/>
<pre>
-OctetString() = [0..255]
+OctetString() = string() | binary()
Integer32() = -2147483647..2147483647
Integer64() = -9223372036854775807..9223372036854775807
Unsigned32() = 0..4294967295
@@ -603,13 +608,15 @@ and <c>{{2104,2,26},{9,42,23}}</c> (both inclusive) can be encoded.</p>
<marker id="UTF8String"/>
<pre>
-UTF8String() = [integer()]
+UTF8String() = [integer()] | binary()
</pre>
<p>
List elements are the UTF-8 encodings of the individual characters
in the string.
-Invalid codepoints will result in encode/decode failure.</p>
+Invalid codepoints will result in encode/decode failure.
+On encode, a UTF8String() can be specified as a binary, or as a nested
+list of binaries and codepoints.</p>
<marker id="DiameterIdentity"/>
<pre>
diff --git a/lib/diameter/doc/src/diameter_examples.xml b/lib/diameter/doc/src/diameter_examples.xml
index 1fd7755695..7808d64b8d 100644
--- a/lib/diameter/doc/src/diameter_examples.xml
+++ b/lib/diameter/doc/src/diameter_examples.xml
@@ -1,11 +1,11 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">
<chapter>
<header>
<copyright>
-<year>2011</year><year>2012</year>
+<year>2011</year><year>2013</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
diff --git a/lib/diameter/doc/src/diameter_intro.xml b/lib/diameter/doc/src/diameter_intro.xml
index 288ebc0c7c..93293f2d8e 100644
--- a/lib/diameter/doc/src/diameter_intro.xml
+++ b/lib/diameter/doc/src/diameter_intro.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd" [
<!ENTITY % also SYSTEM "seealso.ent">
%also;
@@ -40,7 +40,7 @@ under the License.
The diameter application is an implementation of the Diameter protocol
as defined by &the_rfc;.
It supports arbitrary Diameter applications by way of a
-<em>dictionary</em> interface that allows messages and AVP's to be
+<em>dictionary</em> interface that allows messages and AVPs to be
defined and input into diameter as configuration.
It has support for all roles defined in the RFC: client, server and
agent.
@@ -69,7 +69,7 @@ interface</seealso>.</p>
<p>
While a service typically implements a single Diameter node (as
identified by an Origin-Host AVP), transports can themselves be
-associated with capabilities AVP's so that a single service can be
+associated with capabilities AVPs so that a single service can be
used to implement more than one Diameter node.</p>
<p>
diff --git a/lib/diameter/doc/src/diameter_make.xml b/lib/diameter/doc/src/diameter_make.xml
index ec71251be1..0c7e6b794d 100644
--- a/lib/diameter/doc/src/diameter_make.xml
+++ b/lib/diameter/doc/src/diameter_make.xml
@@ -1,5 +1,7 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd" [
+ <!ENTITY compile_forms2
+ '<seealso marker="compiler:compile#forms-2">compile:forms/2</seealso>'>
<!ENTITY filename
'<seealso marker="kernel:file#type-name">file:name()</seealso>'>
<!ENTITY dictionary
@@ -14,7 +16,7 @@
<header>
<copyright>
<year>2012</year>
-<year>2013</year>
+<year>2014</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -50,8 +52,8 @@ under the License.
<p>
The function &codec; is used to compile a diameter
&dictionary; into Erlang source.
-The resulting source implements the interface diameter required
-to encode and decode the dictionary's messages and AVP's.</p>
+The resulting source implements the interface diameter requires
+to encode and decode the dictionary's messages and AVPs.</p>
<p>
The utility &man_compile; provides an alternate compilation
@@ -64,16 +66,47 @@ interface.</p>
<funcs>
<func>
-<name>codec(Path::string(), [Opt]) -> ok | {error, Reason}</name>
+<name>codec(File :: iolist() | binary(), [Opt]) -> ok
+ | {ok, [Out]}
+ | {error, Reason}</name>
<fsummary>Compile a dictionary file into Erlang source.</fsummary>
<desc>
<p>
-Compile a single dictionary file to Erlang source.
-<c>Opt</c> can have the following types.</p>
+Compile a single dictionary file.
+The input <c>File</c> can be either a path or a literal dictionary,
+the occurrence of newline (ascii NL) or carriage return (ascii CR)
+identifying the latter.
+<c>Opt</c> determines the format of the results and whether they are
+written to file or returned, and can have the following types.</p>
<taglist>
+<tag><c>parse | forms | erl | hrl</c></tag>
+<item>
+<p>
+Specifies an output format.
+Whether the output is returned or written to file depends on whether
+or not option <c>return</c> is specified.
+When written to file, the resulting file(s) will have extensions
+<c>.D</c>, <c>.F</c>, <c>.erl</c>, and <c>.hrl</c>
+respectively, basenames defaulting to <c>dictionary</c> if the input
+dictionary is literal and does not specify <c>&dict_name;</c>.
+When returned, results are in the order of the corresponding format
+options.
+Format options default to <c>erl</c> and <c>hrl</c> (in this order) if
+unspecified.</p>
+
+<p>
+The <c>parse</c> format is an internal representation that can be
+passed to &flatten; and &format;, while the <c>forms</c> format can be
+passed to &compile_forms2;.
+The <c>erl</c> and <c>hrl</c> formats are returned as
+iolists.</p>
+<!-- That codec/2 can take the parsed format is undocumented, and
+ options name and inherits have no effect in this case. -->
+</item>
+
<tag><c>{include, string()}</c></tag>
<item>
<p>
@@ -90,7 +123,15 @@ Multiple <c>include</c> options can be specified.</p>
<item>
<p>
Write generated source to the specified directory.
-Defaults to the current working directory.</p>
+Defaults to the current working directory.
+Has no effect if option <c>return</c> is specified.</p>
+</item>
+
+<tag><c>return</c></tag>
+<item>
+<p>
+Return results in a <c>{ok, [Out]}</c> tuple instead of writing to
+file and returning <c>ok</c>.</p>
</item>
<tag><c>{name|prefix, string()}</c></tag>
@@ -108,7 +149,7 @@ Transform the input dictionary before compilation, appending
<c>&dict_inherits;</c> of the specified string.</p>
<p>
-Two forms of <c>@inherits</c> have special meaning:</p>
+Two forms have special meaning:</p>
<pre>
{inherits, "-"}
@@ -127,6 +168,57 @@ Multiple <c>inherits</c> options can be specified.</p>
</taglist>
+<p>
+Note that a dictionary's <c>&dict_name;</c>, together with the
+<c>outdir</c> option, determine the output paths when the
+<c>return</c> option is not specified.
+The <c>&dict_name;</c> of a literal input dictionary defaults to
+<c>dictionary</c>.</p>
+
+<p>
+A returned error reason can be converted into a readable string using
+&format_error;.</p>
+
+</desc>
+</func>
+
+<!-- ===================================================================== -->
+
+<func>
+<name>format(Parsed) -> iolist()</name>
+<fsummary>Format a parsed dictionary.</fsummary>
+<desc>
+<p>
+Turns a parsed dictionary, as returned by &codec;, back into the
+dictionary format.</p>
+</desc>
+</func>
+
+<!-- ===================================================================== -->
+
+<func>
+<name>flatten(Parsed) -> term()</name>
+<fsummary>Flatten a parsed dictionary.</fsummary>
+<desc>
+
+<p>
+Reconstitute a parsed dictionary, as returned by &codec;, without
+using <c>&dict_inherits;</c>.
+That is, construct an equivalent dictionary in which all AVP's are
+definined in the dictionary itself.
+The return value is also a parsed dictionary.</p>
+</desc>
+</func>
+
+<!-- ===================================================================== -->
+
+<func>
+<name>format_error(Reason) -> string()</name>
+<fsummary>Turn an error reason into a readable string.</fsummary>
+<desc>
+
+<p>
+Turn an error reason returned by &codec; into a readable string.</p>
</desc>
</func>
@@ -138,11 +230,7 @@ Multiple <c>inherits</c> options can be specified.</p>
<title>BUGS</title>
<p>
-All options are string-valued.
-In particular, it is not currently possible to specify
-an &dict_inherits; module as an atom(), or a path as an arbitrary
-&filename;</p>
-
+Unrecognized options are silently ignored.</p>
</section>
<!-- ===================================================================== -->
diff --git a/lib/diameter/doc/src/diameter_sctp.xml b/lib/diameter/doc/src/diameter_sctp.xml
index 5fe14b1ef6..6302cb1435 100644
--- a/lib/diameter/doc/src/diameter_sctp.xml
+++ b/lib/diameter/doc/src/diameter_sctp.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd" [
<!ENTITY gen_sctp '<seealso marker="kernel:gen_sctp">gen_sctp(3)</seealso>'>
<!ENTITY gen_sctp_open1
@@ -15,7 +15,8 @@
<erlref>
<header>
<copyright>
-<year>2011</year><year>2013</year>
+<year>2011</year>
+<year>2014</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -90,7 +91,7 @@ Options <c>raddr</c> and <c>rport</c> specify the remote address
and port for a connecting transport and not valid for a listening
transport: the former is required while latter defaults to 3868 if
unspecified.
-Mupltiple <c>raddr</c> options can be specified, in which case the
+Multiple <c>raddr</c> options can be specified, in which case the
connecting transport in question attempts each in sequence until
an association is established.</p>
@@ -113,7 +114,7 @@ and port respectively.</p>
<p>
Multiple <c>ip</c> options can be specified for a multihomed peer.
If none are specified then the values of <c>Host-IP-Address</c>
-in the <c>#diameter_service{}</c> record are used.
+in the <c>diameter_service</c> record are used.
(In particular, one of these must be specified.)
Option <c>port</c> defaults to 3868 for a listening transport and 0 for a
connecting transport.</p>
@@ -131,25 +132,18 @@ the buffer size.</p>
</warning>
<p>
-diameter_sctp uses the <c>transport_data</c> field of
-the <c>#diameter_packet{}</c> record to communicate the stream on which an
-inbound message has been received, or on which an outbound message
-should be sent: the value will be of the form <c>{stream, Id}</c>
-on an inbound message passed to a &app_handle_request; or
-&app_handle_answer; callback.
-For an outbound message, either <c>undefined</c> (explicitly or
-by receiving the outbound message as a <c>binary()</c>) or a tuple
-should be set in the return value of &app_handle_request;
-(typically by retaining the value passed into this function)
-or &app_prepare_request;.
-The value <c>undefined</c> uses a "next outbound stream" id and
-increments this modulo the total number outbound streams.
-That is, successive values of <c>undefined</c> cycle through all
-outbound streams.</p>
-
-<!-- TODO: Some way of getting at the number of available outbound -->
-<!-- streams. -->
-
+The <c>transport_data</c> field of record <c>diameter_packet</c>
+is used to communicate the stream on which an inbound message
+has been received, or on which an outbound message should be sent.
+The value will be of the form <c>{stream, Id}</c> for an inbound
+message passed to a &app_handle_request; or &app_handle_answer;
+callback.
+For an outbound message, <c>{outstream, Id}</c> in the return value of
+&app_handle_request; or &app_prepare_retransmit; sets the outbound
+stream, the stream id being interpreted modulo the number of outbound
+streams.
+Any other value, or not setting a value, causes successive such sends
+to cycle though all outbound streams.</p>
</desc>
</func>
diff --git a/lib/diameter/doc/src/diameter_soc.xml b/lib/diameter/doc/src/diameter_soc.xml
index 4f5419122f..d9159f84b5 100644
--- a/lib/diameter/doc/src/diameter_soc.xml
+++ b/lib/diameter/doc/src/diameter_soc.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd" [
<!ENTITY % also SYSTEM "seealso.ent" >
%also;
diff --git a/lib/diameter/doc/src/diameter_soc_rfc6733.xml b/lib/diameter/doc/src/diameter_soc_rfc6733.xml
index 8d85569650..34ec902632 100644
--- a/lib/diameter/doc/src/diameter_soc_rfc6733.xml
+++ b/lib/diameter/doc/src/diameter_soc_rfc6733.xml
@@ -1,9 +1,9 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="utf-8" ?>
<!--
<copyright>
-<year>2013</year>
+<year>2013</year><year>2013</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
@@ -1272,7 +1272,7 @@ during capabilities exchange.)</p>
<p>
The frequency of reconnection attempts is configured with the
-&mod_transport_opt; <c>reconnect_timer</c> and
+&mod_transport_opt; <c>connect_timer</c> and
<c>watchdog_timer</c>.</p>
<pre>
diff --git a/lib/diameter/doc/src/diameter_tcp.xml b/lib/diameter/doc/src/diameter_tcp.xml
index ce4d6cfd0f..f6bbe7dd23 100644
--- a/lib/diameter/doc/src/diameter_tcp.xml
+++ b/lib/diameter/doc/src/diameter_tcp.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd" [
<!ENTITY start '<seealso marker="#start-3">start/3</seealso>'>
<!ENTITY gen_tcp_connect3
diff --git a/lib/diameter/doc/src/diameter_transport.xml b/lib/diameter/doc/src/diameter_transport.xml
index 9161bd1f48..1618d05c47 100644
--- a/lib/diameter/doc/src/diameter_transport.xml
+++ b/lib/diameter/doc/src/diameter_transport.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd" [
<!ENTITY message '<seealso marker="#message">message()</seealso>'>
<!ENTITY MESSAGES '<seealso marker="#MESSAGES">MESSAGES</seealso>'>
diff --git a/lib/diameter/doc/src/diameter_using.xml b/lib/diameter/doc/src/diameter_using.xml
index c487d94a16..4427d29c3c 100644
--- a/lib/diameter/doc/src/diameter_using.xml
+++ b/lib/diameter/doc/src/diameter_using.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">
<chapter>
diff --git a/lib/diameter/doc/src/diameter_compile.xml b/lib/diameter/doc/src/diameterc.xml
index 6630019e5c..5bffe9a771 100644
--- a/lib/diameter/doc/src/diameter_compile.xml
+++ b/lib/diameter/doc/src/diameterc.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="iso-8859-1" ?>
+<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE comref SYSTEM "comref.dtd" [
<!ENTITY dictionary
'<seealso marker="diameter_dict">dictionary file</seealso>'>
@@ -29,7 +29,7 @@ supplied.
<docno></docno>
<date></date>
<rev></rev>
-<file>diameter_compile.xml</file>
+<file>diameterc.xml</file>
</header>
<com>diameterc</com>
@@ -41,7 +41,7 @@ supplied.
The diameterc utility is used to compile a diameter
&dictionary; into Erlang source.
The resulting source implements the interface diameter required
-to encode and decode the dictionary's messages and AVP's.</p>
+to encode and decode the dictionary's messages and AVPs.</p>
<p>
The module &man_make; provides an alternate compilation interface.</p>
@@ -83,7 +83,7 @@ Defaults to the current working directory.</p>
<tag><![CDATA[-H]]></tag>
<item>
<p>
-Supress erl and hrl generation, respectively.</p>
+Suppress erl and hrl generation, respectively.</p>
</item>
<tag><![CDATA[--name <name>]]></tag>
diff --git a/lib/diameter/doc/src/files.mk b/lib/diameter/doc/src/files.mk
index 510786a7fb..6e8b1f9068 100644
--- a/lib/diameter/doc/src/files.mk
+++ b/lib/diameter/doc/src/files.mk
@@ -21,7 +21,7 @@ XML_APPLICATION_FILES = \
ref_man.xml
XML_REF1_FILES = \
- diameter_compile.xml
+ diameterc.xml
XML_REF3_FILES = \
diameter.xml \
diff --git a/lib/diameter/doc/src/notes.xml b/lib/diameter/doc/src/notes.xml
index e750b56f1e..638b6e24b6 100644
--- a/lib/diameter/doc/src/notes.xml
+++ b/lib/diameter/doc/src/notes.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd" [
<!ENTITY % also SYSTEM "seealso.ent" >
<!ENTITY % here SYSTEM "seehere.ent" >
@@ -11,7 +11,7 @@
<header>
<copyright>
<year>2011</year>
-<year>2013</year>
+<year>2014</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -42,6 +42,1011 @@ first.</p>
<!-- ===================================================================== -->
+<section><title>diameter 1.9.2.4</title>
+
+ <section><title>Fixed Bugs and Malfunctions</title>
+ <list>
+ <item>
+ <p>
+ Fix handling of shared peer connections in watchdog state
+ SUSPECT.</p>
+ <p>
+ A peer connection shared from a remote node was regarded
+ as being up for the lifetime of the connection, ignoring
+ watchdog transitions into state SUSPECT.</p>
+ <p>
+ Own Id: OTP-13342</p>
+ </item>
+ </list>
+ </section>
+
+
+ <section><title>Improvements and New Features</title>
+ <list>
+ <item>
+ <p>
+ no</p>
+ <p>
+ Own Id: OTP-13385</p>
+ </item>
+ </list>
+ </section>
+
+</section>
+
+<section><title>diameter 1.9.2.3</title>
+
+ <section><title>Fixed Bugs and Malfunctions</title>
+ <list>
+ <item>
+ <p>
+ Make peer handling more efficient.</p>
+ <p>
+ Inefficient lookup and manipulation of peer lists could
+ result in poor performance when many outgoing requests
+ were sent simultaneously, or when many peers connected
+ simultaneously. Filtering peer lists on realm/host is now
+ also more efficient in many cases.</p>
+ <p>
+ Own Id: OTP-13164</p>
+ </item>
+ </list>
+ </section>
+
+</section>
+
+<section><title>diameter 1.9.2.2</title>
+
+ <section><title>Fixed Bugs and Malfunctions</title>
+ <list>
+ <item>
+ <p>
+ Fix diameter_watchdog function clause.</p>
+ <p>
+ OTP-12912 introduced an error with accepting transports
+ setting <c>{restrict_connections, false}</c>, causing
+ processes to fail when peer connections were terminated.</p>
+ <p>
+ Own Id: OTP-12969</p>
+ </item>
+ <item>
+ <p>
+ Fix request table leaks</p>
+ <p>
+ The End-to-End and Hop-by-Hop identifiers of outgoing
+ Diameter requests are stored in a table in order for the
+ caller to be located when the corresponding answer
+ message is received. Entries were orphaned if the handler
+ was terminated by an exit signal as a consequence of
+ actions taken by callback functions, or if callbacks
+ modified identifiers in retransmission cases.</p>
+ <p>
+ Own Id: OTP-13137</p>
+ </item>
+ </list>
+ </section>
+
+
+ <section><title>Improvements and New Features</title>
+ <list>
+ <item>
+ <p>
+ Add service_opt() strict_mbit.</p>
+ <p>
+ There are differing opinions on whether or not reception
+ of an arbitrary AVP setting the M-bit is an error. The
+ default interpretation is strict: if a command grammar
+ doesn't explicitly allow an AVP setting the M-bit then
+ reception of such an AVP is regarded as an error. Setting
+ <c>{strict_mbit, false}</c> disables this check.</p>
+ <p>
+ Own Id: OTP-12947</p>
+ </item>
+ </list>
+ </section>
+
+</section>
+
+<section><title>diameter 1.9.2.1</title>
+
+ <section><title>Fixed Bugs and Malfunctions</title>
+ <list>
+ <item>
+ <p>
+ Don't report 5005 (DIAMETER_AVP_MISSING) errors
+ unnecessarily.</p>
+ <p>
+ An AVP whose decode failed was reported as missing,
+ despite having been reported with another error as a
+ consequence of the failure.</p>
+ <p>
+ Own Id: OTP-12871</p>
+ </item>
+ <item>
+ <p>
+ Fix relay encode of nested, Grouped AVPs.</p>
+ <p>
+ A fault in OTP-12475 caused encode to fail if the first
+ AVP in a Grouped AVP was itself Grouped.</p>
+ <p>
+ Own Id: OTP-12879 Aux Id: OTP-12475 </p>
+ </item>
+ <item>
+ <p>
+ Improve decode performance.</p>
+ <p>
+ The time required to decode a message increased
+ quadratically with the number of AVPs in the worst case,
+ leading to extremely long execution times.</p>
+ <p>
+ Own Id: OTP-12891</p>
+ </item>
+ <item>
+ <p>
+ Match acceptable peer addresses case insensitively.</p>
+ <p>
+ Regular expressions passed in an 'accept' tuple to
+ diameter_tcp or diameter_sctp inappropriately matched
+ case.</p>
+ <p>
+ Own Id: OTP-12902</p>
+ </item>
+ <item>
+ <p>
+ Improve watchdog and statistics performance.</p>
+ <p>
+ Inefficient use of timers contributed to poor performance
+ at high load, as did ordering of the table statistics are
+ written to.</p>
+ <p>
+ Own Id: OTP-12912</p>
+ </item>
+ <item>
+ <p>
+ Fix start order of alternate transports.</p>
+ <p>
+ A transport configured with diameter:add_transport/2 can
+ be passed multiple transport_module/transport_config
+ tuples in order to specify alternate configuration,
+ modules being attempted in order until one succeeds. This
+ is primarily for the connecting case; for example, to
+ allow a transport to be configured to first attempt
+ connection over SCTP, and then TCP in case SCTP fails.
+ Multiple module tuples can be paired with a single config
+ tuple, but in this case the start order was reversed
+ relative to the order in which the modules were specifed.</p>
+ <p>
+ Own Id: OTP-12929</p>
+ </item>
+ <item>
+ <p>
+ Fix decode of Grouped AVPs containing errors.</p>
+ <p>
+ RFC 6733 says this of Failed-AVP in 7.5:</p>
+ <p>
+ <taglist><item><p><c> In the case where the offending AVP
+ is embedded within a Grouped AVP, the Failed-AVP MAY
+ contain the grouped AVP, which in turn contains the
+ single offending AVP. The same method MAY be employed if
+ the grouped AVP itself is embedded in yet another grouped
+ AVP and so on. In this case, the Failed-AVP MAY contain
+ the grouped AVP hierarchy up to the single offending AVP.
+ This enables the recipient to detect the location of the
+ offending AVP when embedded in a
+ group.</c></p></item></taglist></p>
+ <p>
+ It says this of DIAMETER_INVALID_AVP_LENGTH in 7.1.5:</p>
+ <p>
+ <taglist><item><p><c> The request contained an AVP with
+ an invalid length. A Diameter message indicating this
+ error MUST include the offending AVPs within a Failed-AVP
+ AVP. In cases where the erroneous AVP length value
+ exceeds the message length or is less than the minimum
+ AVP header length, it is sufficient to include the
+ offending AVP header and a zero filled payload of the
+ minimum required length for the payloads data type. If
+ the AVP is a Grouped AVP, the Grouped AVP header with an
+ empty payload would be sufficient to indicate the
+ offending AVP. In the case where the offending AVP header
+ cannot be fully decoded when the AVP length is less than
+ the minimum AVP header length, it is sufficient to
+ include an offending AVP header that is formulated by
+ padding the incomplete AVP header with zero up to the
+ minimum AVP header length.</c></p></item></taglist></p>
+ <p>
+ The AVPs placed in the errors field of a diameter_packet
+ record are intended to be appropriate for inclusion in a
+ Failed-AVP, but neither of the above paragraphs has been
+ followed in the Grouped case: the entire faulty AVP
+ (non-faulty components and all) has been included. This
+ made it difficult to identify the actual faulty AVP in
+ all but simple cases.</p>
+ <p>
+ The decode is now adapted to the RFC, and implements the
+ suggested single faulty AVP, nested in as many Grouped
+ containers as required.</p>
+ <p>
+ Own Id: OTP-12930</p>
+ </item>
+ </list>
+ </section>
+
+</section>
+
+<section><title>diameter 1.9.2</title>
+
+ <section><title>Fixed Bugs and Malfunctions</title>
+ <list>
+ <item>
+ <p>
+ Fix broken relay counters.</p>
+ <p>
+ OTP-12654 in OTP 17.5.3 broke counters in the case of
+ answer messages received in the relay application.
+ Counters were accumulated as unknown messages or
+ no_result_code instead of as relayed messages on the
+ intended Result-Code and 'Experimental-Result' tuples.</p>
+ <p>
+ Own Id: OTP-12741</p>
+ </item>
+ <item>
+ <p>
+ Fix diameter_sctp listener race.</p>
+ <p>
+ An oversight in OTP-12428 made it possible to start a
+ transport process that could not establish associations.</p>
+ <p>
+ Own Id: OTP-12744</p>
+ </item>
+ </list>
+ </section>
+
+</section>
+
+<section><title>diameter 1.9.1</title>
+
+ <section><title>Known Bugs and Problems</title>
+ <list>
+ <item>
+ <p>
+ Don't leave extra bit in decoded AVP data.</p>
+ <p>
+ OTP-12074 in OTP 17.3 missed one case: a length error on
+ a trailing AVP unknown to the dictionary in question.</p>
+ <p>
+ Own Id: OTP-12642</p>
+ </item>
+ <item>
+ <p>
+ Don't confuse Result-Code and Experimental-Result</p>
+ <p>
+ The errors field of a decoded diameter_packet record was
+ populated with a Result-Code AVP when an
+ Experimental-Result containing a 3xxx Result-Code was
+ received in an answer not setting the E-bit. The correct
+ AVP is now extracted from the incoming message.</p>
+ <p>
+ Own Id: OTP-12654</p>
+ </item>
+ <item>
+ <p>
+ Don't count on unknown Application Id.</p>
+ <p>
+ OTP-11721 in OTP 17.1 missed the case of an Application
+ Id not agreeing with that of the dictionary in question,
+ causing counters to be accumulated on keys containing the
+ unknown id.</p>
+ <p>
+ Own Id: OTP-12701</p>
+ </item>
+ </list>
+ </section>
+
+</section>
+
+<section><title>diameter 1.9</title>
+
+ <section><title>Fixed Bugs and Malfunctions</title>
+ <list>
+ <item>
+ <p>
+ Don't discard outgoing answers unnecessarily.</p>
+ <p>
+ Answers missing a Result-Code AVP or setting an E-bit
+ inappropriately were discarded even if encode was
+ successful.</p>
+ <p>
+ Own Id: OTP-11492</p>
+ </item>
+ <item>
+ <p>
+ Increase supervision timeouts.</p>
+ <p>
+ At diameter application shutdown, DPR could be omitted on
+ open peer connections because of short supervision
+ timeouts.</p>
+ <p>
+ Own Id: OTP-12412</p>
+ </item>
+ <item>
+ <p>
+ Fix retransmission of messages sent as header/avps list.</p>
+ <p>
+ Extracting End-to-End and Hop-by-Hop Identifiers resulted
+ in a function clause error, resulting in a handle_error
+ callback.</p>
+ <p>
+ Own Id: OTP-12415</p>
+ </item>
+ <item>
+ <p>
+ Fix diameter_avp decode of Grouped AVPs having decode
+ errors.</p>
+ <p>
+ Components of such an AVP were not extracted, causing it
+ to be represented by a single diameter_avp record instead
+ of the intended list.</p>
+ <p>
+ Dictionary files must be recompiled for the fix to have
+ effect.</p>
+ <p>
+ Own Id: OTP-12475</p>
+ </item>
+ <item>
+ <p>
+ Fix ordering of AVPs in relayed messages.</p>
+ <p>
+ The order was reversed relative to the received order,
+ with a Route-Record AVP prepended.</p>
+ <p>
+ Thanks to Andrzej Trawiński.</p>
+ <p>
+ Own Id: OTP-12551</p>
+ </item>
+ <item>
+ <p>
+ Fix issues with DiameterURI encode/decode.</p>
+ <p>
+ RFC 6773 changed the default port and transport, but the
+ RFC 3588 defaults were used even if the RFC 6733 common
+ dictionary was in use. The RFC 3588 defaults are now only
+ used when the common dictionary is
+ diameter_gen_base_rfc3588.</p>
+ <p>
+ Both RFC 3588 and 6733 disallow
+ transport=udp;protocol=diameter. Encode of the
+ combination now fails.</p>
+ <p>
+ Decode of ports numbers outside the range 0-65535 and
+ fully qualified domain names longer than 255 octets now
+ fails.</p>
+ <p>
+ Note that RFC 3588 is obsolete, and that there is a
+ diameter_gen_base_rfc6733. The change in defaults is a
+ potential interoperability problem when moving to RFC
+ 6733 with peers that do not send all URI components. The
+ fact that 6733 allows 5xxx result codes in answer
+ messages setting the E-bit, which RFC 3588 doesn't, is
+ another.</p>
+ <p>
+ Own Id: OTP-12589</p>
+ </item>
+ </list>
+ </section>
+
+
+ <section><title>Improvements and New Features</title>
+ <list>
+ <item>
+ <p>
+ Add service_opt() string_decode.</p>
+ <p>
+ To disable the decode of potentially large binaries to
+ string. This prevents large strings from being copied
+ when incoming Diameter messages are passed between
+ processes, a vulnerability that can lead to memory being
+ exhausted given sufficiently malicious peers.</p>
+ <p>
+ The value is a boolean(), true being the default for
+ backwards compatibility. Setting false causes both
+ diameter_caps records and decoded messages to contain
+ binary() in relevant places that previously had string():
+ diameter_app(3) callbacks need to be prepared for the
+ change.</p>
+ <p>
+ The Diameter types affected are OctetString and the
+ derived types UTF8String, DiameterIdentity, DiameterURI,
+ IPFilterRule, and QoSFilterRule. Time and Address are
+ unaffected.</p>
+ <p>
+ Own Id: OTP-11952</p>
+ </item>
+ <item>
+ <p>
+ Add transport_opt() pool_size.</p>
+ <p>
+ To allow for pools of accepting transport processes,
+ which can better service multiple simultaneous peer
+ connections. The option can also be used with connecting
+ transports, to establish multiple connections to the same
+ peer without having to configure multiple transports.</p>
+ <p>
+ Own Id: OTP-12428</p>
+ </item>
+ <item>
+ <p>
+ Allow DPR to be sent with diameter:call/4.</p>
+ <p>
+ It has been possible to send, but the answer was regarded
+ as unsolicited and discarded. DPA now causes the
+ transport process in question to be terminated, as for
+ DPR that diameter itself sends.</p>
+ <p>
+ Own Id: OTP-12542</p>
+ </item>
+ <item>
+ <p>
+ Discard requests after DPR.</p>
+ <p>
+ RFC 6733 is imprecise, but the tone is that messages
+ received after DPR are an exception to be dealt with only
+ because of the possibility of unordered delivery over
+ SCTP. As a consequence, and because a request following
+ DPR is unlikely to be answered due to the impending loss
+ of the peer connection, discard outgoing requests
+ following an outgoing or incoming DPR. Incoming requests
+ are also discarded, with the exception of DPR itself.
+ Answers are sent and received as usual.</p>
+ <p>
+ Own Id: OTP-12543</p>
+ </item>
+ <item>
+ <p>
+ Add transport_opt() dpr_timeout.</p>
+ <p>
+ To cause a peer connection to be closed following an
+ outgoing DPA when the peer fails to do so. It is the
+ recipient of DPA that should close the connection
+ according to RFC 6733.</p>
+ <p>
+ Own Id: OTP-12609</p>
+ </item>
+ <item>
+ <p>
+ Add service_opt() incoming_maxlen.</p>
+ <p>
+ To bound the expected size of incoming Diameter messages.
+ Messages larger than the specified number of bytes are
+ discarded, to prevent a malicious peer from generating
+ excessive load.</p>
+ <p>
+ Own Id: OTP-12628</p>
+ </item>
+ </list>
+ </section>
+
+</section>
+
+<section><title>diameter 1.8</title>
+
+ <section><title>Fixed Bugs and Malfunctions</title>
+ <list>
+ <item>
+ <p>
+ Fix remote diameter_request table leak.</p>
+ <p>
+ An outgoing request whose pick_peer callback selected a
+ transport on another node resulted in an orphaned table
+ entry on that node.</p>
+ <p>
+ Own Id: OTP-12196</p>
+ </item>
+ <item>
+ <p>
+ Fix handling of 3xxx Result-Code without E-bit.</p>
+ <p>
+ OTP-12233 broke the population of the errors field of the
+ diameter_packet record when an incoming request with an
+ E-bit/Result-Code mismatch was detected, causing a
+ 4-tuple to be inserted as Result-Code in a diameter_avp
+ record.</p>
+ <p>
+ Own Id: OTP-12233</p>
+ </item>
+ <item>
+ <p>
+ Fix ignored connect timer.</p>
+ <p>
+ There are two timers governing the establishment of peer
+ connections: connect_timer and watchdog_timer. The former
+ is the RFC 6733 Tc timer, and is used at initial
+ connection establishment. The latter is RFC 3539 TwInit,
+ and is used for connection reestablishment. A connecting
+ transport erroneously used watchdog_timer in both cases.</p>
+ <p>
+ Own Id: OTP-12281 Aux Id: seq12728 </p>
+ </item>
+ </list>
+ </section>
+
+
+ <section><title>Improvements and New Features</title>
+ <list>
+ <item>
+ <p>
+ Order candidate peers in pick_peer callbacks.</p>
+ <p>
+ The order of candidate peers presented to a
+ diameter_app(3) pick_peer callback has previously not
+ been documented, but there are use cases that are
+ simplified by an ordering. The order is now determined by
+ the filter.</p>
+ <p>
+ Own Id: OTP-12308</p>
+ </item>
+ </list>
+ </section>
+
+</section>
+
+<section><title>diameter 1.7.1</title>
+
+ <section><title>Fixed Bugs and Malfunctions</title>
+ <list>
+ <item>
+ <p>
+ Don't leave extra bit in decoded AVP data.</p>
+ <p>
+ An extra bit could be communicated in the data field of a
+ diameter_avp record in the case of length errors. Of no
+ consequence for code using the record encoding of
+ Diameter messages, but code examining diameter_avp
+ records would see this bit.</p>
+ <p>
+ Dictionary files must be recompiled for the fix to have
+ effect.</p>
+ <p>
+ Own Id: OTP-12074</p>
+ </item>
+ <item>
+ <p>
+ Fix counting of outgoing requests and answers setting the
+ E-bit.</p>
+ <p>
+ OTP-11721 broke these counters for all outgoing requests
+ except DWR, and caused answers setting the E-bit to be
+ counted as unknown messages.</p>
+ <p>
+ Own Id: OTP-12080</p>
+ </item>
+ <item>
+ <p>
+ Fix Failed-AVP decode.</p>
+ <p>
+ The best-effort decode only worked for AVPs in the common
+ dictionary, not for those in the dictionary of the
+ application identified in the Diameter Header of the
+ answer message in question.</p>
+ <p>
+ Failed-AVP in an answer decoded with the RFC 3588 common
+ dictionary (diameter_gen_base_rfc3588) was regarded as an
+ error. The RFC 6733 dictionary was unaffected.</p>
+ <p>
+ Dictionary files must be recompiled for the fix to have
+ effect.</p>
+ <p>
+ Own Id: OTP-12094</p>
+ </item>
+ </list>
+ </section>
+
+</section>
+
+<section><title>diameter 1.7</title>
+
+ <section><title>Fixed Bugs and Malfunctions</title>
+ <list>
+ <item>
+ <p>
+ Improve robustness.</p>
+ <p>
+ Counters returned by diameter:service_info/2 now only
+ count messages known to the dictionary in question, so
+ that an attacker cannot cause arbitrarily many counters
+ to be created.</p>
+ <p>
+ Messages to the Erlang log have been minimized, and those
+ related to traffic have been removed entirely since an
+ attacker could cause a node to be logged to death.
+ Consequently, the default answer_errors configuration has
+ been changed from report to discard. A service needs to
+ be restarted for the change in default to take effect.</p>
+ <p>
+ Own Id: OTP-11721</p>
+ </item>
+ <item>
+ <p>
+ Fix request table leak.</p>
+ <p>
+ Outgoing Diameter requests are stored in a table until an
+ answer is received or times out. Calling
+ diameter:stop_service/1 before this took place would
+ orphan the entries, resulting in a memory leak.</p>
+ <p>
+ Own Id: OTP-11893</p>
+ </item>
+ <item>
+ <p>
+ Fix broken SCTP transport.</p>
+ <p>
+ OTP-11593 caused the sending of answer messages over SCTP
+ to fail.</p>
+ <p>
+ Own Id: OTP-11901 Aux Id: OTP-11593 </p>
+ </item>
+ <item>
+ <p>
+ Fix watchdog process leak.</p>
+ <p>
+ A failed capabilities exchange on a listening transport
+ would orphan a process, causing a memory leak.</p>
+ <p>
+ Own Id: OTP-11934</p>
+ </item>
+ <item>
+ <p>
+ Fix incorrect handling of incoming DPR.</p>
+ <p>
+ In the case of a listening transport, a reconnection by a
+ peer following DPR could transition the watchdog state to
+ REOPEN instead of OKAY.</p>
+ <p>
+ Own Id: OTP-11938</p>
+ </item>
+ <item>
+ <p>
+ Fix handling of AVP length errors on unknown AVPs.</p>
+ <p>
+ An AVP (Header) length that pointed past the end of the
+ message was not flagged as a 5014 error in this case.
+ Moreover, encoding such an AVP in the Failed-AVP of an
+ answer message as a consequence of other errors (eg.
+ M-bit, resulting in 5001) failed if the AVP contained a
+ complete header.</p>
+ <p>
+ Dictionary files must be recompiled for the fix to have
+ effect.</p>
+ <p>
+ Own Id: OTP-11946</p>
+ </item>
+ <item>
+ <p>
+ Fix broken check in dictionary compilation.</p>
+ <p>
+ That an AVP specified in the content of a @codecs or
+ @custom_types section was undefined went undetected,
+ causing compilation to fail when attempting to lookup the
+ AVP's type.</p>
+ <p>
+ Own Id: OTP-11958</p>
+ </item>
+ </list>
+ </section>
+
+
+ <section><title>Improvements and New Features</title>
+ <list>
+ <item>
+ <p>
+ Add result code counters for CEA, DWA, and DPA.</p>
+ <p>
+ In addition to the existing result code counters on other
+ answer messages.</p>
+ <p>
+ Own Id: OTP-11891</p>
+ </item>
+ <item>
+ <p>
+ Add best-effort decode of AVPs within Failed-AVP.</p>
+ <p>
+ OTP-11007 disabled the decode of AVPs in Failed-AVP since
+ errors could cause the decode of Failed-AVP itself to
+ fail. Component AVPs are now decoded if possible,
+ otherwise not. AVPs of type Grouped are decoded as much
+ as possible, as deeply as possible.</p>
+ <p>
+ Dictionary files must be recompiled for the fix to have
+ effect.</p>
+ <p>
+ Own Id: OTP-11936 Aux Id: OTP-11007 </p>
+ </item>
+ <item>
+ <p>
+ Add counters for encode errors in outgoing Diameter
+ messages.</p>
+ <p>
+ In addition to the existing counters on decode errors.
+ The latter now count independently of result codes in
+ answer messages since decode errors do not preclude the
+ presence of a result code.</p>
+ <p>
+ Own Id: OTP-11937</p>
+ </item>
+ </list>
+ </section>
+
+</section>
+
+<section><title>diameter 1.6</title>
+
+ <section><title>Fixed Bugs and Malfunctions</title>
+ <list>
+ <item>
+ <p>
+ Add missing check at dictionary compilation.</p>
+ <p>
+ In particular, that an AVP defined as having type Grouped
+ in an @avp_types section has a corresponding definition
+ in a @grouped section.</p>
+ <p>
+ Own Id: OTP-11561</p>
+ </item>
+ <item>
+ <p>
+ Correct documentation on the setting of Origin-State-Id</p>
+ <p>
+ It was incorrectly stated that the AVP would be set in an
+ outgoing DPR/DPA.</p>
+ <p>
+ Own Id: OTP-11583</p>
+ </item>
+ <item>
+ <p>
+ Change interface for communicating outbound stream id to
+ diameter_sctp</p>
+ <p>
+ The module uses the transport_data field of record
+ diameter_packet to communicate the stream on which the an
+ incoming message is received and on which an outgoing
+ message should be sent, the previous interface being that
+ both are communicated as a tuple of the form {stream,
+ Id}. However, since diameter retains the value of an
+ incoming request's transport_data unless the
+ corresponding answer message specifies otherwise, the
+ behaviour in this case is to send an answer on the
+ outbound stream with the same identifier as the that of
+ the inbound stream on which the request was received. If
+ the inbound stream id is greater than or equal to the
+ number of outbound streams then this is guaranteed to
+ fail, causing the transport process in question to
+ terminate. There is no relationship between inbound and
+ outbound stream identifiers so diameter_sctp's imposition
+ of one is simply wrong.</p>
+ <p>
+ Outbound stream ids are now communicated with a different
+ tuple: {outstream, Id}, interpreted modulo the number of
+ outbound streams. Thus, retention of an inbound request's
+ transport_data has no effect on the selection of an
+ outbound stream.</p>
+ <p>
+ The change in interface is not strictly backwards
+ compatible because of the new atom for the outbound
+ stream. However, as there is currently no documented way
+ of obtaining the available number of outbound streams for
+ a peer connection, there is no way for a client to have
+ known the range of ids from which it could reliably have
+ chosen with the previous interface, so any setting of the
+ outbound stream has probably been unintentional. Not
+ explicitly specifying an outbound stream now results in a
+ round-robin selection.</p>
+ <p>
+ Thanks to Sharmila Pillai for reporting the problem.</p>
+ <p>
+ *** POTENTIAL INCOMPATIBILITY ***</p>
+ <p>
+ Own Id: OTP-11593</p>
+ </item>
+ <item>
+ <p>
+ Fix unicode path failure in diameter_make:codec/2.</p>
+ <p>
+ A dictionary path containing a unicode codepoint > 255
+ caused the function to fail.</p>
+ <p>
+ Own Id: OTP-11655</p>
+ </item>
+ <item>
+ <p>
+ Fix 'accept' config to diameter_sctp.</p>
+ <p>
+ OTP-10893 added support for {accept, Match} tuples to
+ specify addresses or regexps that should be matched
+ against peer addresses to decide whether or not a newly
+ established association should be retained, but this
+ hasn't been functional in the SCTP case because of
+ missing support in inet(3).</p>
+ <p>
+ The display of both local and peer addresses in
+ diameter:service_info/2 output has also been corrected.</p>
+ <p>
+ Own Id: OTP-11661 Aux Id: OTP-10229 </p>
+ </item>
+ <item>
+ <p>
+ Be lenient with the M-bit in Grouped AVPs.</p>
+ <p>
+ RFC 6733 says this, in 4.4:</p>
+ <p>
+ <taglist><item><p><c>Receivers of a Grouped AVP that does
+ not have the 'M' (mandatory) bit set and one or more of
+ the encapsulated AVPs within the group has the 'M'
+ (mandatory) bit set MAY simply be ignored if the Grouped
+ AVP itself is unrecognized. The rule applies even if the
+ encapsulated AVP with its 'M' (mandatory) bit set is
+ further encapsulated within other sub-groups, i.e., other
+ Grouped AVPs embedded within the Grouped
+ AVP.</c></p></item></taglist></p>
+ <p>
+ The first sentence is mangled but take it to mean this:</p>
+ <p>
+ <taglist><item><p><c>An unrecognized AVP of type Grouped
+ that does not set the 'M' bit MAY be ignored even if one
+ of its encapsulated AVPs sets the 'M'
+ bit.</c></p></item></taglist></p>
+ <p>
+ This is a bit of a non-statement since if the AVP is
+ unrecognized then its type is unknown. We therefore don't
+ know that its data bytes contain encapsulated AVPs, so
+ can't but ignore any of those that set the M-bit. Doing
+ anything else when the type *is* known would be
+ inconsistent.</p>
+ <p>
+ OTP-11087 (R16B03) caused the M-bit on any unrecognized
+ AVP to be regarded as an error, unrecognized being taken
+ to mean "not explicitly defined as a member of its
+ container". (That is, an AVP that can't be packed into a
+ dedicated record field, which is slightly stronger than
+ "not defined".) This fixed the original intention for
+ top-level AVPs but broke the required leniency for
+ Grouped AVPs whose type is known. This leniency is now
+ restored.</p>
+ <p>
+ Note that dictionary files need to be recompiled for the
+ change to have effect.</p>
+ <p>
+ Thanks to Rory McKeown for reporting the problem.</p>
+ <p>
+ Own Id: OTP-11675 Aux Id: OTP-11087 </p>
+ </item>
+ <item>
+ <p>
+ Fix pick_peer case clause failure.</p>
+ <p>
+ In the case of {call_mutates_state, true} configuration
+ on the service in question, any peer selection that
+ failed to select a peer resulted in a case clause
+ failure. This was noticed in the case of a peer failover
+ in which an alternate peer wasn't available.</p>
+ <p>
+ Own Id: OTP-11789</p>
+ </item>
+ </list>
+ </section>
+
+</section>
+
+<section><title>diameter 1.5</title>
+
+ <section><title>Improvements and New Features</title>
+ <list>
+ <item>
+ <p>
+ Rename reconnect_timer to connect_timer.</p>
+ <p>
+ The former is still accepted for backwards compatibility,
+ but the name is misleading given the semantics of the
+ timer.</p>
+ <p>
+ Own Id: OTP-11168</p>
+ </item>
+ <item>
+ <p>
+ Extend diameter_make(3).</p>
+ <p>
+ Dictionaries can now be compiled from strings, not just
+ filesystem paths, and results can be returned instead of
+ written to the filesystem.</p>
+ <p>
+ Own Id: OTP-11348</p>
+ </item>
+ <item>
+ <p>
+ Remove hardcoding of diameter_base as @prefix on
+ dictionaries for application id 0.</p>
+ <p>
+ Own Id: OTP-11361</p>
+ </item>
+ </list>
+ </section>
+
+</section>
+
+<section><title>diameter 1.4.4</title>
+
+ <section><title>Fixed Bugs and Malfunctions</title>
+ <list>
+ <item>
+ <p>
+ Fix setting of End-to-End and Hop-by-Hop Identifiers in
+ outgoing DWA.</p>
+ <p>
+ Broken by OTP-11184, which caused the identifiers to be
+ set anew, discarding the values from the incoming DWR.</p>
+ <p>
+ Own Id: OTP-11367</p>
+ </item>
+ <item>
+ <p>
+ Fix handling of 5014, DIAMETER_INVALID_AVP_LENGTH.</p>
+ <p>
+ The error was detected as 5004,
+ DIAMETER_INVALID_AVP_VALUE, for some Diameter types, in
+ which case an AVP length that pointed past the end of a
+ message resulted in encode failure.</p>
+ <p>
+ Own Id: OTP-11395</p>
+ </item>
+ </list>
+ </section>
+
+</section>
+
+<section><title>diameter 1.4.3</title>
+
+ <section><title>Fixed Bugs and Malfunctions</title>
+ <list>
+ <item>
+ <p>
+ Fix UTF8String encode.</p>
+ <p>
+ Encode now accepts any nested list of codepoints and
+ binaries. A list containing a binary was previously
+ misinterpreted and the documentation was incomplete.</p>
+ <p>
+ Own Id: OTP-11172</p>
+ </item>
+ <item>
+ <p>
+ Ensure DWR isn't sent immediately after DWA.</p>
+ <p>
+ This was possible if the timing was unfortunate. An
+ incoming DWR now properly resets the watchdog timer.</p>
+ <p>
+ Own Id: OTP-11184</p>
+ </item>
+ <item>
+ <p>
+ Fix faulty encode of Failed-AVP</p>
+ <p>
+ Reception of a CER, DWR or DPR that has decode failures
+ caused encode of the corresponding answer message to
+ fail.</p>
+ <p>
+ Own Id: OTP-11293</p>
+ </item>
+ <item>
+ <p>
+ Fix broken service_opt() spawn_opt.</p>
+ <p>
+ The option was ignored.</p>
+ <p>
+ Own Id: OTP-11299</p>
+ </item>
+ </list>
+ </section>
+
+</section>
+
<section><title>diameter 1.4.2</title>
<section><title>Fixed Bugs and Malfunctions</title>
diff --git a/lib/diameter/doc/src/ref_man.xml b/lib/diameter/doc/src/ref_man.xml
index 4b99fe716d..62ba02b0b5 100644
--- a/lib/diameter/doc/src/ref_man.xml
+++ b/lib/diameter/doc/src/ref_man.xml
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE application SYSTEM "application.dtd">
<application xmlns:xi="http://www.w3.org/2001/XInclude">
@@ -6,7 +6,7 @@
<header>
<copyright>
<year>2011</year>
-<year>2012</year>
+<year>2013</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
@@ -39,7 +39,7 @@ applications on top of the Diameter protocol. </p>
</description>
<xi:include href="diameter.xml"/>
-<xi:include href="diameter_compile.xml"/>
+<xi:include href="diameterc.xml"/>
<xi:include href="diameter_app.xml"/>
<xi:include href="diameter_codec.xml"/>
<xi:include href="diameter_dict.xml"/>
diff --git a/lib/diameter/doc/src/seealso.ent b/lib/diameter/doc/src/seealso.ent
index 76b9823f79..4e205ffad7 100644
--- a/lib/diameter/doc/src/seealso.ent
+++ b/lib/diameter/doc/src/seealso.ent
@@ -4,7 +4,7 @@
%CopyrightBegin%
-Copyright Ericsson AB 2012-2013. All Rights Reserved.
+Copyright Ericsson AB 2012-2015. All Rights Reserved.
The contents of this file are subject to the Erlang Public License,
Version 1.1, (the "License"); you may not use this file except in
@@ -64,11 +64,14 @@ significant.
<!ENTITY capabilities_cb '<seealso marker="#capabilities_cb">capabilities_cb</seealso>'>
<!ENTITY capx_timeout '<seealso marker="#capx_timeout">capx_timeout</seealso>'>
<!ENTITY disconnect_cb '<seealso marker="#disconnect_cb">disconnect_cb</seealso>'>
+<!ENTITY dpa_timeout '<seealso marker="#dpa_timeout">dpa_timeout</seealso>'>
<!ENTITY transport_config '<seealso marker="#transport_config">transport_config</seealso>'>
<!ENTITY transport_module '<seealso marker="#transport_module">transport_module</seealso>'>
-<!ENTITY reconnect_timer '<seealso marker="#reconnect_timer">reconnect_timer</seealso>'>
+<!ENTITY connect_timer '<seealso marker="#connect_timer">connect_timer</seealso>'>
<!ENTITY watchdog_timer '<seealso marker="#watchdog_timer">watchdog_timer</seealso>'>
+<!ENTITY mod_string_decode '<seealso marker="diameter#service_opt">diameter:service_opt()</seealso> <seealso marker="diameter#string_decode">string_decode</seealso>'>
+
<!-- diameter_app -->
<!ENTITY app_handle_answer '<seealso marker="diameter_app#Mod:handle_answer-4">handle_answer/4</seealso>'>
@@ -102,6 +105,9 @@ significant.
<!ENTITY dict_Address '<seealso marker="diameter_dict#DATA_TYPES">Address()</seealso>'>
<!ENTITY dict_DiameterIdentity '<seealso marker="diameter_dict#DATA_TYPES">DiameterIdentity()</seealso>'>
+<!ENTITY dict_DiameterURI '<seealso marker="diameter_dict#DATA_TYPES">DiameterURI()</seealso>'>
+<!ENTITY dict_IPFilterRule '<seealso marker="diameter_dict#DATA_TYPES">IPFilterRule()</seealso>'>
+<!ENTITY dict_QoSFilterRule '<seealso marker="diameter_dict#DATA_TYPES">QoSFilterRule()</seealso>'>
<!ENTITY dict_Grouped '<seealso marker="diameter_dict#DATA_TYPES">Grouped()</seealso>'>
<!ENTITY dict_OctetString '<seealso marker="diameter_dict#DATA_TYPES">OctetString()</seealso>'>
<!ENTITY dict_Time '<seealso marker="diameter_dict#DATA_TYPES">Time()</seealso>'>
@@ -115,6 +121,9 @@ significant.
<!-- diameter_make -->
<!ENTITY make_codec '<seealso marker="diameter_make#codec-2">diameter_make:codec/2</seealso>'>
+<!ENTITY make_format '<seealso marker="diameter_make#format-1">diameter_make:format/1</seealso>'>
+<!ENTITY make_flatten '<seealso marker="diameter_make#flatten-1">diameter_make:flatten/1</seealso>'>
+<!ENTITY make_format_error '<seealso marker="diameter_make#format_error-1">diameter_make:format_error/1</seealso>'>
<!-- diameter_transport -->
diff --git a/lib/diameter/doc/src/user_man.xml b/lib/diameter/doc/src/user_man.xml
index a6416c7e23..f915fa5a66 100644
--- a/lib/diameter/doc/src/user_man.xml
+++ b/lib/diameter/doc/src/user_man.xml
@@ -1,11 +1,11 @@
-<?xml version="1.0" encoding="latin1" ?>
+<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE part SYSTEM "part.dtd">
<part xmlns:xi="http://www.w3.org/2001/XInclude">
<header>
<copyright>
-<year>2011</year>
+<year>2011</year><year>2013</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
diff --git a/lib/diameter/doc/standard/rfc7068.txt b/lib/diameter/doc/standard/rfc7068.txt
new file mode 100644
index 0000000000..70fc24fab0
--- /dev/null
+++ b/lib/diameter/doc/standard/rfc7068.txt
@@ -0,0 +1,1627 @@
+
+
+
+
+
+
+Internet Engineering Task Force (IETF) E. McMurry
+Request for Comments: 7068 B. Campbell
+Category: Informational Oracle
+ISSN: 2070-1721 November 2013
+
+
+ Diameter Overload Control Requirements
+
+Abstract
+
+ When a Diameter server or agent becomes overloaded, it needs to be
+ able to gracefully reduce its load, typically by advising clients to
+ reduce traffic for some period of time. Otherwise, it must continue
+ to expend resources parsing and responding to Diameter messages,
+ possibly resulting in a progressively severe overload condition. The
+ existing Diameter mechanisms are not sufficient for managing overload
+ conditions. This document describes the limitations of the existing
+ mechanisms. Requirements for new overload management mechanisms are
+ also provided.
+
+Status of This Memo
+
+ This document is not an Internet Standards Track specification; it is
+ published for informational purposes.
+
+ This document is a product of the Internet Engineering Task Force
+ (IETF). It represents the consensus of the IETF community. It has
+ received public review and has been approved for publication by the
+ Internet Engineering Steering Group (IESG). Not all documents
+ approved by the IESG are a candidate for any level of Internet
+ Standard; see Section 2 of RFC 5741.
+
+ Information about the current status of this document, any errata,
+ and how to provide feedback on it may be obtained at
+ http://www.rfc-editor.org/info/rfc7068.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+McMurry & Campbell Informational [Page 1]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+Copyright Notice
+
+ Copyright (c) 2013 IETF Trust and the persons identified as the
+ document authors. All rights reserved.
+
+ This document is subject to BCP 78 and the IETF Trust's Legal
+ Provisions Relating to IETF Documents
+ (http://trustee.ietf.org/license-info) in effect on the date of
+ publication of this document. Please review these documents
+ carefully, as they describe your rights and restrictions with respect
+ to this document. Code Components extracted from this document must
+ include Simplified BSD License text as described in Section 4.e of
+ the Trust Legal Provisions and are provided without warranty as
+ described in the Simplified BSD License.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+McMurry & Campbell Informational [Page 2]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+Table of Contents
+
+ 1. Introduction ....................................................4
+ 1.1. Documentation Conventions ..................................4
+ 1.2. Causes of Overload .........................................5
+ 1.3. Effects of Overload ........................................6
+ 1.4. Overload vs. Network Congestion ............................6
+ 1.5. Diameter Applications in a Broader Network .................7
+ 2. Overload Control Scenarios ......................................7
+ 2.1. Peer-to-Peer Scenarios .....................................8
+ 2.2. Agent Scenarios ...........................................10
+ 2.3. Interconnect Scenario .....................................14
+ 3. Diameter Overload Case Studies .................................15
+ 3.1. Overload in Mobile Data Networks ..........................15
+ 3.2. 3GPP Study on Core Network Overload .......................16
+ 4. Existing Mechanisms ............................................17
+ 5. Issues with the Current Mechanisms .............................18
+ 5.1. Problems with Implicit Mechanism ..........................18
+ 5.2. Problems with Explicit Mechanisms .........................18
+ 6. Extensibility and Application Independence .....................19
+ 7. Solution Requirements ..........................................20
+ 7.1. General ...................................................20
+ 7.2. Performance ...............................................21
+ 7.3. Heterogeneous Support for Solution ........................22
+ 7.4. Granular Control ..........................................23
+ 7.5. Priority and Policy .......................................23
+ 7.6. Security ..................................................23
+ 7.7. Flexibility and Extensibility .............................24
+ 8. Security Considerations ........................................25
+ 8.1. Access Control ............................................25
+ 8.2. Denial-of-Service Attacks .................................26
+ 8.3. Replay Attacks ............................................26
+ 8.4. Man-in-the-Middle Attacks .................................26
+ 8.5. Compromised Hosts .........................................27
+ 9. References .....................................................27
+ 9.1. Normative References ......................................27
+ 9.2. Informative References ....................................27
+ Appendix A. Contributors ..........................................29
+ Appendix B. Acknowledgements ......................................29
+
+
+
+
+
+
+
+
+
+
+
+
+McMurry & Campbell Informational [Page 3]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+1. Introduction
+
+ A Diameter [RFC6733] node is said to be overloaded when it has
+ insufficient resources to successfully process all of the Diameter
+ requests that it receives. When a node becomes overloaded, it needs
+ to be able to gracefully reduce its load, typically by advising
+ clients to reduce traffic for some period of time. Otherwise, it
+ must continue to expend resources parsing and responding to Diameter
+ messages, possibly resulting in a progressively severe overload
+ condition. The existing mechanisms provided by Diameter are not
+ sufficient for managing overload conditions. This document describes
+ the limitations of the existing mechanisms and provides requirements
+ for new overload management mechanisms.
+
+ This document draws on the work done on SIP overload control
+ ([RFC5390], [RFC6357]) as well as on experience gained via overload
+ handling in Signaling System No. 7 (SS7) networks and studies done by
+ the Third Generation Partnership Project (3GPP) (Section 3).
+
+ Diameter is not typically an end-user protocol; rather, it is
+ generally used as one component in support of some end-user activity.
+
+ For example, a SIP server might use Diameter to authenticate and
+ authorize user access. Overload in the Diameter backend
+ infrastructure will likely impact the experience observed by the end
+ user in the SIP application.
+
+ The impact of Diameter overload on the client application (a client
+ application may use the Diameter protocol and other protocols to do
+ its job) is beyond the scope of this document.
+
+ This document presents non-normative descriptions of causes of
+ overload, along with related scenarios and studies. Finally, it
+ offers a set of normative requirements for an improved overload
+ indication mechanism.
+
+1.1. Documentation Conventions
+
+ The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
+ "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this
+ document are to be interpreted as defined in [RFC2119], with the
+ exception that they are not intended for interoperability of
+ implementations. Rather, they are used to describe requirements
+ towards future specifications where the interoperability requirements
+ will be defined.
+
+ The terms "client", "server", "agent", "node", "peer", "upstream",
+ and "downstream" are used as defined in [RFC6733].
+
+
+
+McMurry & Campbell Informational [Page 4]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+1.2. Causes of Overload
+
+ Overload occurs when an element, such as a Diameter server or agent,
+ has insufficient resources to successfully process all of the traffic
+ it is receiving. Resources include all of the capabilities of the
+ element used to process a request, including CPU processing, memory,
+ I/O, and disk resources. It can also include external resources such
+ as a database or DNS server, in which case the CPU, processing,
+ memory, I/O, and disk resources of those elements are effectively
+ part of the logical element processing the request.
+
+ External resources can include upstream Diameter nodes; for example,
+ a Diameter agent can become effectively overloaded if one or more
+ upstream nodes are overloaded.
+
+ A Diameter node can become overloaded due to request levels that
+ exceed its capacity, a reduction of available resources (for example,
+ a local or upstream hardware failure), or a combination of the two.
+
+ Overload can occur for many reasons, including:
+
+ Inadequate capacity: When designing Diameter networks, that is,
+ application-layer multi-node Diameter deployments, it can be very
+ difficult to predict all scenarios that may cause elevated
+ traffic. It may also be more costly to implement support for some
+ scenarios than a network operator may deem worthwhile. This
+ results in the likelihood that a Diameter network will not have
+ adequate capacity to handle all situations.
+
+ Dependency failures: A Diameter node can become overloaded because a
+ resource on which it depends has failed or become overloaded,
+ greatly reducing the logical capacity of the node. In these
+ cases, even minimal traffic might cause the node to go into
+ overload. Examples of such dependency overloads include DNS
+ servers, databases, disks, and network interfaces that have failed
+ or become overloaded.
+
+ Component failures: A Diameter node can become overloaded when it is
+ a member of a cluster of servers that each share the load of
+ traffic and one or more of the other members in the cluster fail.
+ In this case, the remaining nodes take over the work of the failed
+ nodes. Normally, capacity planning takes such failures into
+ account, and servers are typically run with enough spare capacity
+ to handle failure of another node. However, unusual failure
+ conditions can cause many nodes to fail at once. This is often
+ the case with software failures, where a bad packet or bad
+ database entry hits the same bug in a set of nodes in a cluster.
+
+
+
+
+McMurry & Campbell Informational [Page 5]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+ Network-initiated traffic flood: Certain access network events can
+ precipitate floods of Diameter signaling traffic. For example,
+ operational changes can trigger avalanche restarts, or frequent
+ radio overlay handovers can generate excessive authorization
+ requests. Failure of a Diameter proxy may also result in a large
+ amount of signaling as connections and sessions are reestablished.
+
+ Subscriber-initiated traffic flood: Large gatherings of subscribers
+ or events that result in many subscribers interacting with the
+ network in close time proximity can result in Diameter signaling
+ traffic floods. For example, the finale of a large fireworks show
+ could be immediately followed by many subscribers posting
+ messages, pictures, and videos concentrated on one portion of a
+ network. Subscriber devices such as smartphones may use
+ aggressive registration strategies that generate unusually high
+ Diameter traffic loads.
+
+ DoS attacks: An attacker wishing to disrupt service in the network
+ can cause a large amount of traffic to be launched at a target
+ element. This can be done from a central source of traffic or
+ through a distributed DoS attack. In all cases, the volume of
+ traffic well exceeds the capacity of the element, sending the
+ system into overload.
+
+1.3. Effects of Overload
+
+ Modern Diameter networks, composed of application-layer multi-node
+ deployments of Diameter elements, may operate at very large
+ transaction volumes. If a Diameter node becomes overloaded or, even
+ worse, fails completely, a large number of messages may be lost very
+ quickly. Even with redundant servers, many messages can be lost in
+ the time it takes for failover to complete. While a Diameter client
+ or agent should be able to retry such requests, an overloaded peer
+ may cause a sudden large increase in the number of transactions
+ needing to be retried, rapidly filling local queues or otherwise
+ contributing to local overload. Therefore, Diameter devices need to
+ be able to shed load before critical failures can occur.
+
+1.4. Overload vs. Network Congestion
+
+ This document uses the term "overload" to refer to application-layer
+ overload at Diameter nodes. This is distinct from "network
+ congestion", that is, congestion that occurs at the lower networking
+ layers that may impact the delivery of Diameter messages between
+ nodes. This document recognizes that element overload and network
+ congestion are interrelated, and that overload can contribute to
+ network congestion and vice versa.
+
+
+
+
+McMurry & Campbell Informational [Page 6]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+ Network congestion issues are better handled by the transport
+ protocols. Diameter uses TCP and the Stream Control Transmission
+ Protocol (SCTP), both of which include congestion management
+ features. Analysis of whether those features are sufficient for
+ transport-level congestion between Diameter nodes and of any work to
+ further mitigate network congestion is out of scope for both this
+ document and the work proposed by it.
+
+1.5. Diameter Applications in a Broader Network
+
+ Most elements using Diameter applications do not use Diameter
+ exclusively. It is important to realize that overload of an element
+ can be caused by a number of factors that may be unrelated to the
+ processing of Diameter or Diameter applications.
+
+ An element that doesn't use Diameter exclusively needs to be able to
+ signal to Diameter peers that it is experiencing overload regardless
+ of the cause of the overload, since the overload will affect that
+ element's ability to process Diameter transactions. If the element
+ communicates with protocols other than Diameter, it may also need to
+ signal the overload situation on these protocols, depending on its
+ function and the architecture of the network and application for
+ which it is providing services. Whether that is necessary can only
+ be decided within the context of that architecture and use cases.
+ This specification details the requirements for a mechanism for
+ signaling overload with Diameter; this mechanism provides Diameter
+ nodes the ability to inform their Diameter peers of overload,
+ mitigating that part of the issue. Diameter nodes may need to use
+ this, as well as other mechanisms, to solve their broader overload
+ issues. Indicating overload on protocols other than Diameter is out
+ of scope for this document and for the work proposed by it.
+
+2. Overload Control Scenarios
+
+ Several Diameter deployment scenarios exist that may impact overload
+ management. The following scenarios help motivate the requirements
+ for an overload management mechanism.
+
+ These scenarios are by no means exhaustive and are in general
+ simplified for the sake of clarity. In particular, this document
+ assumes for the sake of clarity that the client sends Diameter
+ requests to the server, and the server sends responses to the client,
+ even though Diameter supports bidirectional applications. Each
+ direction in such an application can be modeled separately.
+
+ In a large-scale deployment, many of the nodes represented in these
+ scenarios would be deployed as clusters of servers. This document
+ assumes that such a cluster is responsible for managing its own
+
+
+
+McMurry & Campbell Informational [Page 7]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+ internal load-balancing and overload management so that it appears as
+ a single Diameter node. That is, other Diameter nodes can treat it
+ as a single, monolithic node for the purposes of overload management.
+
+ These scenarios do not illustrate the client application. As
+ mentioned in Section 1, Diameter is not typically an end-user
+ protocol; rather, it is generally used in support of some other
+ client application. These scenarios do not consider the impact of
+ Diameter overload on the client application.
+
+2.1. Peer-to-Peer Scenarios
+
+ This section describes Diameter peer-to-peer scenarios, that is,
+ scenarios where a Diameter client talks directly with a Diameter
+ server, without the use of a Diameter agent.
+
+ Figure 1 illustrates the simplest possible Diameter relationship.
+ The client and server share a one-to-one peer-to-peer relationship.
+ If the server becomes overloaded, either because the client exceeds
+ the server's capacity or because the server's capacity is reduced due
+ to some resource dependency, the client needs to reduce the amount of
+ Diameter traffic it sends to the server. Since the client cannot
+ forward requests to another server, it must either queue requests
+ until the server recovers or itself become overloaded in the context
+ of the client application and other protocols it may also use.
+
+ +------------------+
+ | |
+ | |
+ | Server |
+ | |
+ +--------+---------+
+ |
+ |
+ +--------+---------+
+ | |
+ | |
+ | Client |
+ | |
+ +------------------+
+
+ Figure 1: Basic Peer-to-Peer Scenario
+
+
+
+
+
+
+
+
+
+McMurry & Campbell Informational [Page 8]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+ Figure 2 shows a similar scenario, except in this case the client has
+ multiple servers that can handle work for a specific realm and
+ application. If Server 1 becomes overloaded, the client can forward
+ traffic to Server 2. Assuming that Server 2 has sufficient reserve
+ capacity to handle the forwarded traffic, the client should be able
+ to continue serving client application protocol users. If Server 1
+ is approaching overload, but can still handle some number of new
+ requests, it needs to be able to instruct the client to forward a
+ subset of its traffic to Server 2.
+
+ +------------------+ +------------------+
+ | | | |
+ | | | |
+ | Server 1 | | Server 2 |
+ | | | |
+ +--------+-`.------+ +------.'+---------+
+ `. .'
+ `. .'
+ `. .'
+ `. .'
+ +-------`.'--------+
+ | |
+ | |
+ | Client |
+ | |
+ +------------------+
+
+ Figure 2: Multiple-Server Peer-to-Peer Scenario
+
+ Figure 3 illustrates a peer-to-peer scenario with multiple Diameter
+ realm and application combinations. In this example, Server 2 can
+ handle work for both applications. Each application might have
+ different resource dependencies. For example, a server might need to
+ access one database for Application A and another for Application B.
+ This creates a possibility that Server 2 could become overloaded for
+ Application A but not for Application B, in which case the client
+ would need to divert some part of its Application A requests to
+ Server 1, but the client should not divert any Application B
+ requests. This requires that Server 2 be able to distinguish between
+ applications when it indicates an overload condition to the client.
+
+ On the other hand, it's possible that the servers host many
+ applications. If Server 2 becomes overloaded for all applications,
+ it would be undesirable for it to have to notify the client
+ separately for each application. Therefore, it also needs a way to
+ indicate that it is overloaded for all possible applications.
+
+
+
+
+
+McMurry & Campbell Informational [Page 9]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+ +---------------------------------------------+
+ | Application A +----------------------+----------------------+
+ |+------------------+ | +----------------+ | +------------------+|
+ || | | | | | | ||
+ || | | | | | | ||
+ || Server 1 | | | Server 2 | | | Server 3 ||
+ || | | | | | | ||
+ |+--------+---------+ | +-------+--------+ | +-+----------------+|
+ | | | | | | |
+ +---------+-----------+----------+-----------+ | |
+ | | | | |
+ | | | | Application B |
+ | +----------+----------------+-----------------+
+ ``-.._ | |
+ `-..__ | _.-''
+ `--._ | _.-''
+ ``-._ | _.-''
+ +-----`-.-''-----+
+ | |
+ | |
+ | Client |
+ | |
+ +----------------+
+
+ Figure 3: Multiple-Application Peer-to-Peer Scenario
+
+2.2. Agent Scenarios
+
+ This section describes scenarios that include a Diameter agent, in
+ the form of either a Diameter relay or Diameter proxy. These
+ scenarios do not consider Diameter redirect agents, since they are
+ more readily modeled as end servers. The examples have been kept
+ simple deliberately, to illustrate basic concepts. Significantly
+ more complicated topologies are possible with Diameter, including
+ multiple intermediate agents in a path connected in a variety
+ of ways.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+McMurry & Campbell Informational [Page 10]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+ Figure 4 illustrates a simple Diameter agent scenario with a single
+ client, agent, and server. In this case, overload can occur at the
+ server, at the agent, or both. But in most cases, client behavior is
+ the same whether overload occurs at the server or at the agent. From
+ the client's perspective, server overload and agent overload are the
+ same thing.
+
+ +------------------+
+ | |
+ | |
+ | Server |
+ | |
+ +--------+---------+
+ |
+ |
+ +--------+---------+
+ | |
+ | |
+ | Agent |
+ | |
+ +--------+---------+
+ |
+ |
+ +--------+---------+
+ | |
+ | |
+ | Client |
+ | |
+ +------------------+
+
+ Figure 4: Basic Agent Scenario
+
+ Figure 5 shows an agent scenario with multiple servers. If Server 1
+ becomes overloaded but Server 2 has sufficient reserve capacity, the
+ agent may be able to transparently divert some or all Diameter
+ requests originally bound for Server 1 to Server 2.
+
+ In most cases, the client does not have detailed knowledge of the
+ Diameter topology upstream of the agent. If the agent uses dynamic
+ discovery to find eligible servers, the set of eligible servers may
+ not be enumerable from the perspective of the client. Therefore, in
+ most cases the agent needs to deal with any upstream overload issues
+ in a way that is transparent to the client. If one server notifies
+ the agent that it has become overloaded, the notification should not
+ be passed back to the client in a way that the client could
+ mistakenly perceive the agent itself as being overloaded. If the set
+
+
+
+
+
+McMurry & Campbell Informational [Page 11]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+ of all possible destinations upstream of the agent no longer has
+ sufficient capacity for incoming load, the agent itself becomes
+ effectively overloaded.
+
+ On the other hand, there are cases where the client needs to be able
+ to select a particular server from behind an agent. For example, if
+ a Diameter request is part of a multiple-round-trip authentication,
+ or is otherwise part of a Diameter "session", it may have a
+ Destination-Host Attribute-Value Pair (AVP) that requires that the
+ request be served by Server 1. Therefore, the agent may need to
+ inform a client that a particular upstream server is overloaded or
+ otherwise unavailable. Note that there can be many ways a server can
+ be specified, which may have different implications (e.g., by IP
+ address, by host name, etc).
+
+ +------------------+ +------------------+
+ | | | |
+ | | | |
+ | Server 1 | | Server 2 |
+ | | | |
+ +--------+-`.------+ +------.'+---------+
+ `. .'
+ `. .'
+ `. .'
+ `. .'
+ +-------`.'--------+
+ | |
+ | |
+ | Agent |
+ | |
+ +--------+---------+
+ |
+ |
+ |
+ +--------+---------+
+ | |
+ | |
+ | Client |
+ | |
+ +------------------+
+
+ Figure 5: Multiple-Server Agent Scenario
+
+
+
+
+
+
+
+
+
+McMurry & Campbell Informational [Page 12]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+ Figure 6 shows a scenario where an agent routes requests to a set of
+ servers for more than one Diameter realm and application. In this
+ scenario, if Server 1 becomes overloaded or unavailable while
+ Server 2 still has available capacity, the agent may effectively
+ operate at reduced capacity for Application A but at full capacity
+ for Application B. Therefore, the agent needs to be able to report
+ that it is overloaded for one application but not for another.
+
+ +--------------------------------------------+
+ | Application A +----------------------+----------------------+
+ |+------------------+ | +----------------+ | +------------------+|
+ || | | | | | | ||
+ || | | | | | | ||
+ || Server 1 | | | Server 2 | | | Server 3 ||
+ || | | | | | | ||
+ |+---------+--------+ | +-------+--------+ | +--+---------------+|
+ | | | | | | |
+ +----------+----------+----------+-----------+ | |
+ | | | | |
+ | | | | Application B |
+ | +----------+-----------------+----------------+
+ | | |
+ ``--.__ | _.
+ ``-.__ | __.--''
+ `--.._ | _..--'
+ +----``-+.''-----+
+ | |
+ | |
+ | Agent |
+ | |
+ +-------+--------+
+ |
+ |
+ +-------+--------+
+ | |
+ | |
+ | Client |
+ | |
+ +----------------+
+
+ Figure 6: Multiple-Application Agent Scenario
+
+
+
+
+
+
+
+
+
+
+McMurry & Campbell Informational [Page 13]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+2.3. Interconnect Scenario
+
+ Another scenario to consider when looking at Diameter overload is
+ that of multiple network operators using Diameter components
+ connected through an interconnect service, e.g., using IPX (IP Packet
+ eXchange). IPX [IR.34] is an Inter-Operator IP Backbone that
+ provides a roaming interconnection network between mobile operators
+ and service providers. IPX is also used to transport Diameter
+ signaling between operators [IR.88]. Figure 7 shows two network
+ operators with an interconnect network between them. There could be
+ any number of these networks between any two network operators'
+ networks.
+
+ +-------------------------------------------+
+ | Interconnect |
+ | |
+ | +--------------+ +--------------+ |
+ | | Server 3 |------| Server 4 | |
+ | +--------------+ +--------------+ |
+ | .' `. |
+ +------.-'--------------------------`.------+
+ .' `.
+ .-' `.
+ ------------.'-----+ +----`.-------------
+ +----------+ | | +----------+
+ | Server 1 | | | | Server 2 |
+ +----------+ | | +----------+
+ | |
+ Network Operator 1 | | Network Operator 2
+ -------------------+ +-------------------
+
+ Figure 7: Two-Network Interconnect Scenario
+
+ The characteristics of the information that an operator would want to
+ share over such a connection are different from the information
+ shared between components within a network operator's network. For
+ example, network operators may not want to convey topology or
+ operational information; this would in turn limit how much overload
+ and loading information can be sent. For the interconnect scenario
+ shown in Figure 7, Server 2 may want to signal overload to Server 1,
+ to affect traffic coming from Network Operator 1.
+
+ This case is distinct from those internal to a network operator's
+ network, where there may be many more elements in a more complicated
+ topology. Also, the elements in the interconnect network may not
+ support Diameter overload control, and the network operators may not
+ want the interconnect network to use overload or loading information.
+ They may only want the information to pass through the interconnect
+
+
+
+McMurry & Campbell Informational [Page 14]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+ network without further processing or action by the interconnect
+ network, even if the elements in the interconnect network do support
+ Diameter overload control.
+
+3. Diameter Overload Case Studies
+
+3.1. Overload in Mobile Data Networks
+
+ As the number of smartphone devices that are Third Generation (3G)
+ and Long Term Evolution (LTE) enabled continues to expand in mobile
+ networks, there have been situations where high signaling traffic
+ load led to overload events at the Diameter-based Home Location
+ Registers (HLRs) and/or Home Subscriber Servers (HSS) [TR23.843].
+ The root causes of the HLR overload events were manifold but included
+ hardware failure and procedural errors. The result was high
+ signaling traffic load on the HLR and HSS.
+
+ The 3GPP architecture [TS23.002] makes extensive use of Diameter. It
+ is used for mobility management [TS29.272], the IP Multimedia
+ Subsystem (IMS) [TS29.228], and policy and charging control
+ [TS29.212], as well as other functions. The details of the
+ architecture are out of scope for this document, but it is worth
+ noting that there are quite a few Diameter applications, some with
+ quite large amounts of Diameter signaling in deployed networks.
+
+ The 3GPP specifications do not currently address overload for
+ Diameter applications or provide a load control mechanism equivalent
+ to those provided in the more traditional SS7 elements in the Global
+ System for Mobile Communications (GSM); see [TS29.002]. The
+ capabilities specified in the 3GPP standards do not adequately
+ address the abnormal condition where excessively high signaling
+ traffic load situations are experienced.
+
+ Smartphones, which comprise an increasingly large percentage of
+ mobile devices, contribute much more heavily, relative to
+ non-smartphones, to the continuation of a registration surge, due to
+ their very aggressive registration algorithms. Smartphone behavior
+ contributes to network loading and can contribute to overload
+ conditions. The aggressive smartphone logic is designed to:
+
+ a. always have voice and data registration, and
+
+ b. constantly try to be on 3G or LTE data (and thus on 3G voice or
+ Voice over LTE (VoLTE) [IR.92]) for their added benefits.
+
+ Non-smartphones typically have logic to wait for a time period after
+ registering successfully on voice and data.
+
+
+
+
+McMurry & Campbell Informational [Page 15]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+ The aggressive smartphone registration is problematic in two ways:
+
+ o first, by generating excessive signaling load towards the HSS that
+ is ten times the load from a non-smartphone, and
+
+ o second, by causing continual registration attempts when a network
+ failure affects registrations through the 3G data network.
+
+3.2. 3GPP Study on Core Network Overload
+
+ A study in the 3GPP System Aspects working group 2 (SA2) on core
+ network overload has produced the technical report [TR23.843]. This
+ enumerates several causes of overload in mobile core networks,
+ including portions that are signaled using Diameter. [TR23.843] is a
+ work in progress and is not complete. However, it is useful for
+ pointing out scenarios and the general need for an overload control
+ mechanism for Diameter.
+
+ It is common for mobile networks to employ more than one radio
+ technology and to do so in an overlay fashion with multiple
+ technologies present in the same location (such as 2nd or 3rd
+ generation mobile technologies, along with LTE). This presents
+ opportunities for traffic storms when issues occur on one overlay and
+ not another as all devices that had been on the overlay with issues
+ switch. This causes a large amount of Diameter traffic as locations
+ and policies are updated.
+
+ Another scenario called out by this study is a flood of registration
+ and mobility management events caused by some element in the core
+ network failing. This flood of traffic from end nodes falls under
+ the network-initiated traffic flood category. There is likely to
+ also be traffic resulting directly from the component failure in this
+ case. A similar flood can occur when elements or components recover
+ as well.
+
+ Subscriber-initiated traffic floods are also indicated in this study
+ as an overload mechanism where a large number of mobile devices are
+ attempting to access services at the same time, such as in response
+ to an entertainment event or a catastrophic event.
+
+ While this 3GPP study is concerned with the broader effects of these
+ scenarios on wireless networks and their elements, they have
+ implications specifically for Diameter signaling. One of the goals
+ of this document is to provide guidance for a core mechanism that can
+ be used to mitigate the scenarios called out by this study.
+
+
+
+
+
+
+McMurry & Campbell Informational [Page 16]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+4. Existing Mechanisms
+
+ Diameter offers both implicit and explicit mechanisms for a Diameter
+ node to learn that a peer is overloaded or unreachable. The implicit
+ mechanism is simply the lack of responses to requests. If a client
+ fails to receive a response in a certain time period, it assumes that
+ the upstream peer is unavailable or is overloaded to the point of
+ effective unavailability. The watchdog mechanism [RFC3539] ensures
+ that transaction responses occur at a certain rate even when there is
+ otherwise little or no other Diameter traffic.
+
+ The explicit mechanism can involve specific protocol error responses,
+ where an agent or server tells a downstream peer that it is either
+ too busy to handle a request (DIAMETER_TOO_BUSY) or unable to route a
+ request to an upstream destination (DIAMETER_UNABLE_TO_DELIVER)
+ perhaps because that destination itself is overloaded to the point of
+ unavailability.
+
+ Another explicit mechanism, a DPR (Disconnect-Peer-Request) message,
+ can be sent with a Disconnect-Cause of BUSY. This signals the
+ sender's intent to close the transport connection and requests that
+ the client not reconnect.
+
+ Once a Diameter node learns via one of these mechanisms that an
+ upstream peer has become overloaded, it can then attempt to take
+ action to reduce the load. This usually means forwarding traffic to
+ an alternate destination, if available. If no alternate destination
+ is available, the node must either reduce the number of messages it
+ originates (in the case of a client) or inform the client to reduce
+ traffic (in the case of an agent).
+
+ Diameter requires the use of a congestion-managed transport layer,
+ currently TCP or SCTP, to mitigate network congestion. It is
+ expected that these transports manage network congestion and that
+ issues with transport (e.g., congestion propagation and window
+ management) are managed at that level. But even with a congestion-
+ managed transport, a Diameter node can become overloaded at the
+ Diameter protocol or application layers due to the causes described
+ in Section 1.2, and congestion-managed transports do not provide
+ facilities (and are at the wrong level) to handle server overload.
+ Transport-level congestion management is also not sufficient to
+ address overload in cases of multi-hop and multi-destination
+ signaling.
+
+
+
+
+
+
+
+
+McMurry & Campbell Informational [Page 17]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+5. Issues with the Current Mechanisms
+
+ The currently available Diameter mechanisms for indicating an
+ overload condition are not adequate to avoid service outages due to
+ overload. This inadequacy may, in turn, contribute to broader
+ impacts resulting from overload due to unresponsive Diameter nodes
+ causing application-layer or transport-layer retransmissions. In
+ particular, they do not allow a Diameter agent or server to shed load
+ as it approaches overload. At best, a node can only indicate that it
+ needs to entirely stop receiving requests, i.e., that it has
+ effectively failed. Even that is problematic due to the inability to
+ indicate durational validity on the transient errors available in the
+ base Diameter protocol. Diameter offers no mechanism to allow a node
+ to indicate different overload states for different categories of
+ messages, for example, if it is overloaded for one Diameter
+ application but not another.
+
+5.1. Problems with Implicit Mechanism
+
+ The implicit mechanism doesn't allow an agent or server to inform the
+ client of a problem until it is effectively too late to do anything
+ about it. The client does not know that it needs to take action
+ until the upstream node has effectively failed. A Diameter node has
+ no opportunity to shed load early to avoid collapse in the first
+ place.
+
+ Additionally, the implicit mechanism cannot distinguish between
+ overload of a Diameter node and network congestion. Diameter treats
+ the failure to receive an answer as a transport failure.
+
+5.2. Problems with Explicit Mechanisms
+
+ The Diameter specification is ambiguous on how a client should handle
+ receipt of a DIAMETER_TOO_BUSY response. The base specification
+ [RFC6733] indicates that the sending client should attempt to send
+ the request to a different peer. It makes no suggestion that the
+ receipt of a DIAMETER_TOO_BUSY response should affect future Diameter
+ messages in any way.
+
+ The Authentication, Authorization, and Accounting (AAA) Transport
+ Profile [RFC3539] recommends that a AAA node that receives a "Busy"
+ response failover all remaining requests to a different agent or
+ server. But while the Diameter base specification explicitly depends
+ on [RFC3539] to define transport behavior, it does not refer to
+ [RFC3539] in the description of behavior on receipt of a
+ DIAMETER_TOO_BUSY error. There's a strong likelihood that at least
+ some implementations will continue to send Diameter requests to an
+ upstream peer even after receiving a DIAMETER_TOO_BUSY error.
+
+
+
+McMurry & Campbell Informational [Page 18]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+ BCP 41 [RFC2914] describes, among other things, how end-to-end
+ application behavior can help avoid congestion collapse. In
+ particular, an application should avoid sending messages that will
+ never be delivered or processed. The DIAMETER_TOO_BUSY behavior as
+ described in the Diameter base specification fails at this, since if
+ an upstream node becomes overloaded, a client attempts each request
+ and does not discover the need to failover the request until the
+ initial attempt fails.
+
+ The situation is improved if implementations follow the [RFC3539]
+ recommendation to keep state about upstream peer overload. But even
+ then, the Diameter specification offers no guidance on how long a
+ client should wait before retrying the overloaded destination. If an
+ agent or server supports multiple realms and/or applications,
+ DIAMETER_TOO_BUSY offers no way to indicate that it is overloaded for
+ one application but not another. A DIAMETER_TOO_BUSY error can only
+ indicate overload at a "whole server" scope.
+
+ Agent processing of a DIAMETER_TOO_BUSY response is also problematic
+ as described in the base specification. DIAMETER_TOO_BUSY is defined
+ as a protocol error. If an agent receives a protocol error, it may
+ either handle it locally or forward the response back towards the
+ downstream peer. If a downstream peer receives the DIAMETER_TOO_BUSY
+ response, it may stop sending all requests to the agent for some
+ period of time, even though the agent may still be able to deliver
+ requests to other upstream peers.
+
+ DIAMETER_UNABLE_TO_DELIVER errors, or using DPR with cause code BUSY,
+ also have no mechanisms for specifying the scope or cause of the
+ failure, or the durational validity.
+
+ The issues with error responses described in [RFC6733] extend beyond
+ the particular issues for overload control and have been addressed in
+ an ad hoc fashion by various implementations. Addressing these in a
+ standard way would be a useful exercise, but it is beyond the scope
+ of this document.
+
+6. Extensibility and Application Independence
+
+ Given the variety of scenarios in which Diameter elements can be
+ deployed and the variety of roles they can fulfill with Diameter and
+ other technologies, a single algorithm for handling overload may not
+ be sufficient. For purposes of this discussion, an algorithm is
+ inclusive of behavior for control of overload but does not encompass
+ the general mechanism for transporting control information. This
+ effort cannot anticipate all possible future scenarios and roles.
+ Extensibility, particularly of algorithms used to deal with overload,
+ will be important to cover these cases.
+
+
+
+McMurry & Campbell Informational [Page 19]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+ Similarly, the scopes to which overload information may apply may
+ include cases that have not yet been considered. Extensibility in
+ this area will also be important.
+
+ The basic mechanism is intended to be application independent, that
+ is, a Diameter node can use it across any existing and future
+ Diameter applications and expect reasonable results. Certain
+ Diameter applications might, however, benefit from application-
+ specific behavior over and above the mechanism's defaults. For
+ example, an application specification might specify relative
+ priorities of messages or selection of a specific overload control
+ algorithm.
+
+7. Solution Requirements
+
+ This section proposes requirements for an improved mechanism to
+ control Diameter overload, with the goals of addressing the issues
+ described in Section 5 and supporting the scenarios described in
+ Section 2. These requirements are stated primarily in terms of
+ individual node behavior to inform the design of the improved
+ mechanism; solution designers should keep in mind that the overall
+ goal is improved overall system behavior across all the nodes
+ involved, not just improved behavior from specific individual nodes.
+
+7.1. General
+
+ REQ 1: The solution MUST provide a communication method for Diameter
+ nodes to exchange load and overload information.
+
+ REQ 2: The solution MUST allow Diameter nodes to support overload
+ control regardless of which Diameter applications they
+ support. Diameter clients and agents must be able to use the
+ received load and overload information to support graceful
+ behavior during an overload condition. Graceful behavior
+ under overload conditions is best described by REQ 3.
+
+ REQ 3: The solution MUST limit the impact of overload on the overall
+ useful throughput of a Diameter server, even when the
+ incoming load on the network is far in excess of its
+ capacity. The overall useful throughput under load is the
+ ultimate measure of the value of a solution.
+
+ REQ 4: Diameter allows requests to be sent from either side of a
+ connection, and either side of a connection may have need to
+ provide its overload status. The solution MUST allow each
+ side of a connection to independently inform the other of its
+ overload status.
+
+
+
+
+McMurry & Campbell Informational [Page 20]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+ REQ 5: Diameter allows nodes to determine their peers via dynamic
+ discovery or manual configuration. The solution MUST work
+ consistently without regard to how peers are determined.
+
+ REQ 6: The solution designers SHOULD seek to minimize the amount of
+ new configuration required in order to work. For example, it
+ is better to allow peers to advertise or negotiate support
+ for the solution, rather than to require that this knowledge
+ be configured at each node.
+
+7.2. Performance
+
+ REQ 7: The solution and any associated default algorithm(s) MUST
+ ensure that the system remains stable. At some point after
+ an overload condition has ended, the solution MUST enable
+ capacity to stabilize and become equal to what it would be in
+ the absence of an overload condition. Note that this also
+ requires that the solution MUST allow nodes to shed load
+ without introducing non-converging oscillations during or
+ after an overload condition.
+
+ REQ 8: Supporting nodes MUST be able to distinguish current overload
+ information from stale information.
+
+ REQ 9: The solution MUST function across fully loaded as well as
+ quiescent transport connections. This is partially derived
+ from the requirement for stability in REQ 7.
+
+ REQ 10: Consumers of overload information MUST be able to determine
+ when the overload condition improves or ends.
+
+ REQ 11: The solution MUST be able to operate in networks of different
+ sizes.
+
+ REQ 12: When a single network node fails, goes into overload, or
+ suffers from reduced processing capacity, the solution MUST
+ make it possible to limit the impact of the affected node on
+ other nodes in the network. This helps to prevent a small-
+ scale failure from becoming a widespread outage.
+
+ REQ 13: The solution MUST NOT introduce substantial additional work
+ for a node in an overloaded state. For example, a
+ requirement for an overloaded node to send overload
+ information every time it received a new request would
+ introduce substantial work.
+
+
+
+
+
+
+McMurry & Campbell Informational [Page 21]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+ REQ 14: Some scenarios that result in overload involve a rapid
+ increase of traffic with little time between normal levels
+ and levels that induce overload. The solution SHOULD provide
+ for rapid feedback when traffic levels increase.
+
+ REQ 15: The solution MUST NOT interfere with the congestion control
+ mechanisms of underlying transport protocols. For example, a
+ solution that opened additional TCP connections when the
+ network is congested would reduce the effectiveness of the
+ underlying congestion control mechanisms.
+
+7.3. Heterogeneous Support for Solution
+
+ REQ 16: The solution is likely to be deployed incrementally. The
+ solution MUST support a mixed environment where some, but not
+ all, nodes implement it.
+
+ REQ 17: In a mixed environment with nodes that support the solution
+ and nodes that do not, the solution MUST NOT result in
+ materially less useful throughput during overload as would
+ have resulted if the solution were not present. It SHOULD
+ result in less severe overload in this environment.
+
+ REQ 18: In a mixed environment of nodes that support the solution and
+ nodes that do not, the solution MUST NOT preclude elements
+ that support overload control from treating elements that do
+ not support overload control in an equitable fashion relative
+ to those that do. Users and operators of nodes that do not
+ support the solution MUST NOT unfairly benefit from the
+ solution. The solution specification SHOULD provide guidance
+ to implementors for dealing with elements not supporting
+ overload control.
+
+ REQ 19: It MUST be possible to use the solution between nodes in
+ different realms and in different administrative domains.
+
+ REQ 20: Any explicit overload indication MUST be clearly
+ distinguishable from other errors reported via Diameter.
+
+ REQ 21: In cases where a network node fails, is so overloaded that it
+ cannot process messages, or cannot communicate due to a
+ network failure, it may not be able to provide explicit
+ indications of the nature of the failure or its levels of
+ overload. The solution MUST result in at least as much
+ useful throughput as would have resulted if the solution were
+ not in place.
+
+
+
+
+
+McMurry & Campbell Informational [Page 22]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+7.4. Granular Control
+
+ REQ 22: The solution MUST provide a way for a node to throttle the
+ amount of traffic it receives from a peer node. This
+ throttling SHOULD be graded so that it can be applied
+ gradually as offered load increases. Overload is not a
+ binary state; there may be degrees of overload.
+
+ REQ 23: The solution MUST provide sufficient information to enable a
+ load-balancing node to divert messages that are rejected or
+ otherwise throttled by an overloaded upstream node to other
+ upstream nodes that are the most likely to have sufficient
+ capacity to process them.
+
+ REQ 24: The solution MUST provide a mechanism for indicating load
+ levels, even when not in an overload condition, to assist
+ nodes in making decisions to prevent overload conditions from
+ occurring.
+
+7.5. Priority and Policy
+
+ REQ 25: The base specification for the solution SHOULD offer general
+ guidance on which message types might be desirable to send or
+ process over others during times of overload, based on
+ application-specific considerations. For example, it may be
+ more beneficial to process messages for existing sessions
+ ahead of new sessions. Some networks may have a requirement
+ to give priority to requests associated with emergency
+ sessions. Any normative or otherwise detailed definition of
+ the relative priorities of message types during an overload
+ condition will be the responsibility of the application
+ specification.
+
+ REQ 26: The solution MUST NOT prevent a node from prioritizing
+ requests based on any local policy, so that certain requests
+ are given preferential treatment, given additional
+ retransmission, not throttled, or processed ahead of others.
+
+7.6. Security
+
+ REQ 27: The solution MUST NOT provide new vulnerabilities to
+ malicious attack or increase the severity of any existing
+ vulnerabilities. This includes vulnerabilities to DoS and
+ DDoS attacks as well as replay and man-in-the-middle attacks.
+ Note that the Diameter base specification [RFC6733] lacks
+ end-to-end security, and this must be considered (see
+ Security Considerations in this document (Section 8)). Note
+
+
+
+
+McMurry & Campbell Informational [Page 23]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+ that this requirement was expressed at a high level so as to
+ not preclude any particular solution. Is is expected that
+ the solution will address this in more detail.
+
+ REQ 28: The solution MUST NOT depend on being deployed in
+ environments where all Diameter nodes are completely trusted.
+ It SHOULD operate as effectively as possible in environments
+ where other nodes are malicious; this includes preventing
+ malicious nodes from obtaining more than a fair share of
+ service. Note that this does not imply any responsibility on
+ the solution to detect, or take countermeasures against,
+ malicious nodes.
+
+ REQ 29: It MUST be possible for a supporting node to make
+ authorization decisions about what information will be sent
+ to peer nodes based on the identity of those nodes. This
+ allows a domain administrator who considers the load of their
+ nodes to be sensitive information to restrict access to that
+ information. Of course, in such cases, there is no
+ expectation that the solution itself will help prevent
+ overload from that peer node.
+
+ REQ 30: The solution MUST NOT interfere with any Diameter-compliant
+ method that a node may use to protect itself from overload
+ from non-supporting nodes or from denial-of-service attacks.
+
+7.7. Flexibility and Extensibility
+
+ REQ 31: There are multiple situations where a Diameter node may be
+ overloaded for some purposes but not others. For example,
+ this can happen to an agent or server that supports multiple
+ applications, or when a server depends on multiple external
+ resources, some of which may become overloaded while others
+ are fully available. The solution MUST allow Diameter nodes
+ to indicate overload with sufficient granularity to allow
+ clients to take action based on the overloaded resources
+ without unreasonably forcing available capacity to go unused.
+ The solution MUST support specification of overload
+ information with granularities of at least "Diameter node",
+ "realm", and "Diameter application" and MUST allow
+ extensibility for others to be added in the future.
+
+ REQ 32: The solution MUST provide a method for extending the
+ information communicated and the algorithms used for overload
+ control.
+
+
+
+
+
+
+McMurry & Campbell Informational [Page 24]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+ REQ 33: The solution MUST provide a default algorithm that is
+ mandatory to implement.
+
+ REQ 34: The solution SHOULD provide a method for exchanging overload
+ and load information between elements that are connected by
+ intermediaries that do not support the solution.
+
+8. Security Considerations
+
+ A Diameter overload control mechanism is primarily concerned with the
+ load-related and overload-related behavior of nodes in a Diameter
+ network, and the information used to affect that behavior. Load and
+ overload information is shared between nodes and directly affects the
+ behavior, and thus the information is potentially vulnerable to a
+ number of methods of attack.
+
+ Load and overload information may also be sensitive from both
+ business and network protection viewpoints. Operators of Diameter
+ equipment want to control the visibility of load and overload
+ information to keep it from being used for competitive intelligence
+ or for targeting attacks. It is also important that the Diameter
+ overload control mechanism not introduce any way in which any other
+ information carried by Diameter is sent inappropriately.
+
+ Note that the Diameter base specification [RFC6733] lacks end-to-end
+ security, making it difficult for non-adjacent nodes to verify the
+ authenticity and ownership of load and overload information.
+ Authentication of load and overload information helps to alleviate
+ several of the security issues listed in this section.
+
+ This document includes requirements intended to mitigate the effects
+ of attacks and to protect the information used by the mechanism.
+ This section discusses potential security considerations for overload
+ control solutions. This discussion provides the motivation for
+ several normative requirements described in Section 7. The
+ discussion includes specific references to the normative requirements
+ that apply for each issue.
+
+8.1. Access Control
+
+ To control the visibility of load and overload information, sending
+ should be subject to some form of authentication and authorization of
+ the receiver. It is also important to the receivers that they are
+ confident the load and overload information they receive is from a
+ legitimate source. REQ 28 requires that the solution work without
+ assuming that all Diameter nodes in a network are trusted for the
+ purposes of exchanging overload and load information. REQ 29
+ requires that the solution let nodes restrict unauthorized parties
+
+
+
+McMurry & Campbell Informational [Page 25]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+ from seeing overload information. Note that this implies a certain
+ amount of configurability on the nodes supporting the Diameter
+ overload control mechanism.
+
+8.2. Denial-of-Service Attacks
+
+ An overload control mechanism provides a very attractive target for
+ denial-of-service attacks. A small number of messages may effect a
+ large service disruption by falsely reporting overload conditions.
+ Alternately, attacking servers nearing, or in, overload may also be
+ facilitated by disrupting their overload indications, potentially
+ preventing them from mitigating their overload condition.
+
+ A design goal for the Diameter overload control mechanism is to
+ minimize or eliminate the possibility of using the mechanism for this
+ type of attack. More strongly, REQ 27 forbids the solution from
+ introducing new vulnerabilities to malicious attack. Additionally,
+ REQ 30 stipulates that the solution not interfere with other
+ mechanisms used for protection against denial-of-service attacks.
+
+ As the intent of some denial-of-service attacks is to induce overload
+ conditions, an effective overload control mechanism should help to
+ mitigate the effects of such an attack.
+
+8.3. Replay Attacks
+
+ An attacker that has managed to obtain some messages from the
+ overload control mechanism may attempt to affect the behavior of
+ nodes supporting the mechanism by sending those messages at
+ potentially inopportune times. In addition to time shifting, replay
+ attacks may send messages to other nodes as well (target shifting).
+
+ A design goal for the Diameter overload control solution is to
+ minimize or eliminate the possibility of causing disruption by using
+ a replay attack on the Diameter overload control mechanism.
+ (Allowing a replay attack using the overload control solution would
+ violate REQ 27.)
+
+8.4. Man-in-the-Middle Attacks
+
+ By inserting themselves between two nodes supporting the Diameter
+ overload control mechanism, an attacker may potentially both access
+ and alter the information sent between those nodes. This can be used
+ for information gathering for business intelligence and attack
+ targeting, as well as direct attacks.
+
+
+
+
+
+
+McMurry & Campbell Informational [Page 26]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+ REQs 27, 28, and 29 imply a need to prevent man-in-the-middle attacks
+ on the overload control solution. A transport using Transport Layer
+ Security (TLS) and/or IPsec may be desirable for this purpose.
+
+8.5. Compromised Hosts
+
+ A compromised host that supports the Diameter overload control
+ mechanism could be used for information gathering as well as for
+ sending malicious information to any Diameter node that would
+ normally accept information from it. While it is beyond the scope of
+ the Diameter overload control mechanism to mitigate any operational
+ interruption to the compromised host, REQs 28 and 29 imply a need to
+ minimize the impact that a compromised host can have on other nodes
+ through the use of the Diameter overload control mechanism. Of
+ course, a compromised host could be used to cause damage in a number
+ of other ways. This is out of scope for a Diameter overload control
+ mechanism.
+
+9. References
+
+9.1. Normative References
+
+ [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate
+ Requirement Levels", BCP 14, RFC 2119, March 1997.
+
+ [RFC6733] Fajardo, V., Arkko, J., Loughney, J., and G. Zorn,
+ "Diameter Base Protocol", RFC 6733, October 2012.
+
+ [RFC2914] Floyd, S., "Congestion Control Principles", BCP 41,
+ RFC 2914, September 2000.
+
+ [RFC3539] Aboba, B. and J. Wood, "Authentication, Authorization and
+ Accounting (AAA) Transport Profile", RFC 3539, June 2003.
+
+9.2. Informative References
+
+ [RFC5390] Rosenberg, J., "Requirements for Management of Overload
+ in the Session Initiation Protocol", RFC 5390,
+ December 2008.
+
+ [RFC6357] Hilt, V., Noel, E., Shen, C., and A. Abdelal, "Design
+ Considerations for Session Initiation Protocol (SIP)
+ Overload Control", RFC 6357, August 2011.
+
+ [TR23.843] 3GPP, "Study on Core Network (CN) overload solutions",
+ TR 23.843 1.2.0, Work in Progress, October 2013.
+
+
+
+
+
+McMurry & Campbell Informational [Page 27]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+ [IR.34] GSMA, "Inter-Service Provider IP Backbone Guidelines",
+ IR 34 9.1, May 2013.
+
+ [IR.88] GSMA, "LTE Roaming Guidelines", IR 88 9.0, January 2013.
+
+ [IR.92] GSMA, "IMS Profile for Voice and SMS", IR 92 7.0,
+ March 2013.
+
+ [TS23.002] 3GPP, "Network Architecture", TS 23.002 12.2.0,
+ June 2013.
+
+ [TS29.272] 3GPP, "Evolved Packet System (EPS); Mobility Management
+ Entity (MME) and Serving GPRS Support Node (SGSN) related
+ interfaces based on Diameter protocol", TS 29.272 12.2.0,
+ September 2013.
+
+ [TS29.212] 3GPP, "Policy and Charging Control (PCC) over Gx/Sd
+ reference point", TS 29.212 12.2.0, September 2013.
+
+ [TS29.228] 3GPP, "IP Multimedia (IM) Subsystem Cx and Dx interfaces;
+ Signalling flows and message contents", TS 29.228 12.0.0,
+ September 2013.
+
+ [TS29.002] 3GPP, "Mobile Application Part (MAP) specification",
+ TS 29.002 12.2.0, September 2013.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+McMurry & Campbell Informational [Page 28]
+
+RFC 7068 Diameter Overload Control Requirements November 2013
+
+
+Appendix A. Contributors
+
+ Significant contributions to this document were made by Adam Roach
+ and Eric Noel.
+
+Appendix B. Acknowledgements
+
+ Review of, and contributions to, this specification by Martin Dolly,
+ Carolyn Johnson, Jianrong Wang, Imtiaz Shaikh, Jouni Korhonen, Robert
+ Sparks, Dieter Jacobsohn, Janet Gunn, Jean-Jacques Trottin, Laurent
+ Thiebaut, Andrew Booth, and Lionel Morand were most appreciated. We
+ would like to thank them for their time and expertise.
+
+Authors' Addresses
+
+ Eric McMurry
+ Oracle
+ 17210 Campbell Rd.
+ Suite 250
+ Dallas, TX 75252
+ US
+
+
+
+ Ben Campbell
+ Oracle
+ 17210 Campbell Rd.
+ Suite 250
+ Dallas, TX 75252
+ US
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+McMurry & Campbell Informational [Page 29]
+
diff --git a/lib/diameter/doc/standard/rfc7075.txt b/lib/diameter/doc/standard/rfc7075.txt
new file mode 100644
index 0000000000..f5fd905e72
--- /dev/null
+++ b/lib/diameter/doc/standard/rfc7075.txt
@@ -0,0 +1,563 @@
+
+
+
+
+
+
+Internet Engineering Task Force (IETF) T. Tsou
+Request for Comments: 7075 Huawei Technologies (USA)
+Updates: 6733 R. Hao
+Category: Standards Track Comcast Cable
+ISSN: 2070-1721 T. Taylor, Ed.
+ Huawei Technologies
+ November 2013
+
+
+ Realm-Based Redirection In Diameter
+
+Abstract
+
+ The Diameter protocol includes a capability for message redirection,
+ controlled by an application-independent "redirect agent". In some
+ circumstances, an operator may wish to redirect messages to an
+ alternate domain without specifying individual hosts. This document
+ specifies an application-specific mechanism by which a Diameter
+ server or proxy (node) can perform such a redirection when the
+ Straightforward-Naming Authority Pointer (S-NAPTR) is not used for
+ dynamic peer discovery. A node performing this new function is
+ referred to as a "Realm-based Redirect Server".
+
+ This memo updates Sections 6.13 and 6.14 of RFC 6733 with respect to
+ the usage of the Redirect-Host-Usage and Redirect-Max-Cache-Time
+ Attribute-Value Pairs (AVPs).
+
+Status of This Memo
+
+ This is an Internet Standards Track document.
+
+ This document is a product of the Internet Engineering Task Force
+ (IETF). It represents the consensus of the IETF community. It has
+ received public review and has been approved for publication by the
+ Internet Engineering Steering Group (IESG). Further information on
+ Internet Standards is available in Section 2 of RFC 5741.
+
+ Information about the current status of this document, any errata,
+ and how to provide feedback on it may be obtained at
+ http://www.rfc-editor.org/info/rfc7075.
+
+
+
+
+
+
+
+
+
+
+
+Tsou, et al. Standards Track [Page 1]
+
+RFC 7075 Realm-Based Redirection In Diameter November 2013
+
+
+Copyright Notice
+
+ Copyright (c) 2013 IETF Trust and the persons identified as the
+ document authors. All rights reserved.
+
+ This document is subject to BCP 78 and the IETF Trust's Legal
+ Provisions Relating to IETF Documents
+ (http://trustee.ietf.org/license-info) in effect on the date of
+ publication of this document. Please review these documents
+ carefully, as they describe your rights and restrictions with respect
+ to this document. Code Components extracted from this document must
+ include Simplified BSD License text as described in Section 4.e of
+ the Trust Legal Provisions and are provided without warranty as
+ described in the Simplified BSD License.
+
+Table of Contents
+
+ 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . 3
+ 1.1. Terminology . . . . . . . . . . . . . . . . . . . . . . . 3
+ 2. Support of Realm-Based Redirection Within Applications . . . 4
+ 3. Realm-Based Redirection . . . . . . . . . . . . . . . . . . . 5
+ 3.1. Configuration of the Realm-Based Redirect Server . . . . 5
+ 3.2. Behavior of Diameter Nodes . . . . . . . . . . . . . . . 6
+ 3.2.1. Behavior at the Realm-Based Redirect Server . . . . . 6
+ 3.2.2. Proxy Behavior . . . . . . . . . . . . . . . . . . . 6
+ 3.2.3. Client Behavior . . . . . . . . . . . . . . . . . . . 7
+ 3.3. The Redirect-Realm AVP . . . . . . . . . . . . . . . . . 7
+ 3.4. DIAMETER_REALM_REDIRECT_INDICATION Protocol Error Code . 7
+ 4. Security Considerations . . . . . . . . . . . . . . . . . . . 8
+ 5. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 8
+ 6. Acknowledgements . . . . . . . . . . . . . . . . . . . . . . 9
+ 7. References . . . . . . . . . . . . . . . . . . . . . . . . . 9
+ 7.1. Normative References . . . . . . . . . . . . . . . . . . 9
+ 7.2. Informative References . . . . . . . . . . . . . . . . . 9
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Tsou, et al. Standards Track [Page 2]
+
+RFC 7075 Realm-Based Redirection In Diameter November 2013
+
+
+1. Introduction
+
+ The Diameter base protocol [RFC6733] specifies a basic redirection
+ service provided by a redirect agent. The redirect indication
+ returned by the redirect agent is described in Section 6.1.8 and
+ Sections 6.12 through 6.14 of [RFC6733]. It provides one or more
+ individual hosts to the message sender as the destination of the
+ redirected message.
+
+ However, consider the case where an operator has offered a specific
+ service but no longer wishes to do so. The operator has arranged for
+ an alternative domain to provide the service. To aid in the
+ transition to the new arrangement, the original operator maintains a
+ redirect server to indicate to the message sender the alternative
+ domain to which the redirect the request should be sent. However,
+ the original operator should not have to configure the redirect
+ server with a list of hosts to contact in the alternative operator's
+ domain; the original operator should simply be able to provide
+ redirect indications to the domain as a whole.
+
+1.1. Terminology
+
+ The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
+ "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this
+ document are to be interpreted as described in [RFC2119].
+
+ Within this specification, the term "realm-based redirection" is used
+ to refer to a mode of operation where a realm, rather than an
+ individual host, is returned as the redirect indication.
+
+ The term "Realm-based Redirect Server" denotes the Diameter node
+ (Diameter server or proxy) that returns the realm-based redirection.
+ The behavior of the Realm-based Redirect Server itself is a slight
+ modification to the behavior of a basic redirect agent as described
+ in Section 6.1.8 of [RFC6733].
+
+ The use of a number of terms in this document is consistent with the
+ usage in [RFC6733]: "Diameter client", "Diameter node", "Diameter
+ peer", "Diameter server", "proxy", "realm" or "domain", "redirect
+ agent", and "session" as defined in Section 1.2, and "application" as
+ defined implicitly by Sections 1.3.4, 2.3, and 2.4.
+
+
+
+
+
+
+
+
+
+
+Tsou, et al. Standards Track [Page 3]
+
+RFC 7075 Realm-Based Redirection In Diameter November 2013
+
+
+2. Support of Realm-Based Redirection Within Applications
+
+ The DNS-based dynamic peer discovery mechanism defined in the
+ Diameter base protocol [RFC6733] provides a simple mechanism for
+ realm-based redirection using the S-NAPTR DDDS application [RFC3958].
+ When S-NAPTR is used for peer discovery, redirection of Diameter
+ requests from the original realm to a new realm may be performed by
+ updating the existing NAPTR resource records (RRs) for the original
+ realm as follows: the NAPTR RR for the desired application(s) and
+ supported application protocol(s) provided by the new realm will have
+ an empty FLAG field and the REPLACEMENT field will contain the new
+ realm to use for the next DNS lookup. The new realm can be
+ arbitrary; the restriction in [RFC6733] that the NAPTR replacement
+ field match the domain of the original query does not apply for
+ realm-based redirect purposes.
+
+ However, the use of DNS-based dynamic peer discovery is optional for
+ Diameter implementations. For deployments that do not make use of
+ S-NAPTR peer discovery, support of realm-based redirection needs to
+ be specified as part of the functionality supported by a Diameter
+ application. In this way, support of the considered Diameter
+ application (discovered during capabilities exchange phase as defined
+ in Diameter base protocol [RFC6733]) indicates implicit support of
+ the realm-based redirection mechanism. A new application
+ specification can incorporate the mechanism specified here by making
+ it mandatory to implement for the application and referencing this
+ specification normatively.
+
+ The result of making realm-based redirection an application-specific
+ behavior is that it cannot be performed by a redirect agent as
+ defined in [RFC6733], but MUST be performed instead by an
+ application-aware Diameter node (Diameter server or proxy) (hereafter
+ called a "Realm-based Redirect Server").
+
+ An application can specify that realm-based redirection operates only
+ on complete sessions beginning with the initial message or on every
+ message within the application, even if earlier messages of the same
+ session were not redirected. This distinction matters only when
+ realm-based redirection is first initiated. In the former case,
+ existing sessions will not be disrupted by the deployment of realm-
+ based redirection. In the latter case, existing sessions will be
+ disrupted if they are stateful.
+
+
+
+
+
+
+
+
+
+Tsou, et al. Standards Track [Page 4]
+
+RFC 7075 Realm-Based Redirection In Diameter November 2013
+
+
+3. Realm-Based Redirection
+
+ This section specifies an extension of the Diameter base protocol
+ [RFC6733] to achieve realm-based redirection. The elements of this
+ solution are:
+
+ o a new result code, DIAMETER_REALM_REDIRECT_INDICATION (3011);
+
+ o a new attribute-value pair (AVP), Redirect-Realm (620); and
+
+ o associated behavior at Diameter nodes implementing this
+ specification.
+
+ This behavior includes the optional use of the Redirect-Host-Usage
+ and Redirect-Max-Cache-Time AVPs. In this document, these AVPs apply
+ to the peer discovered by a node acting on the redirect server's
+ response, an extension to their normal usage as described in Sections
+ 6.13 and 6.14 of [RFC6733].
+
+ Section 3.2.2 and Section 3.2.3 describe how a proxy or client may
+ update its routing table for the application and initial realm as a
+ result of selecting a peer in the new realm after realm-based
+ redirection. Note that as a result, the proxy or client will
+ automatically route subsequent requests for that application to the
+ new realm (with the possible exception of requests within sessions
+ already established with the initial realm) until the cached routing
+ entry expires. This should be borne in mind if the rerouting is
+ intended to be temporary.
+
+3.1. Configuration of the Realm-Based Redirect Server
+
+ A Diameter node (Diameter server or proxy) acting as a Realm-based
+ Redirect Server MUST be configured as follows to execute realm-based
+ redirection:
+
+ o configured with an application that incorporates realm-based
+ redirection;
+
+ o the Local Action field of the routing table described in
+ Section 2.7 of [RFC6733] is set to LOCAL;
+
+ o an application-specific field is set to indicate that the required
+ local action is to perform realm-based redirection;
+
+ o an associated application-specific field is configured with the
+ identities of one or more realms to which the request should be
+ redirected.
+
+
+
+
+Tsou, et al. Standards Track [Page 5]
+
+RFC 7075 Realm-Based Redirection In Diameter November 2013
+
+
+3.2. Behavior of Diameter Nodes
+
+3.2.1. Behavior at the Realm-Based Redirect Server
+
+ As mentioned in Section 2, an application can specify that realm-
+ based redirection operates only on complete sessions beginning with
+ the initial message (i.e., to prevent disruption of established
+ sessions) or on every message within the application, even if earlier
+ messages of the same session were not redirected.
+
+ If a Realm-based Redirect Server configured as described in
+ Section 3.1 receives a request to which realm-based redirection
+ applies, the Realm-based Redirect Server MUST reply with an answer
+ message with the 'E' bit set, while maintaining the Hop-by-Hop
+ Identifier in the header. The Realm-based Redirect Server MUST
+ include the Result-Code AVP set to
+ DIAMETER_REALM_REDIRECT_INDICATION. The Realm-based Redirect Server
+ MUST also include the alternate realm identifier(s) with which it has
+ been configured, each in a separate Redirect-Realm AVP instance.
+
+ The Realm-based Redirect Server MAY include a copy of the Redirect-
+ Host-Usage AVP, which SHOULD be set to REALM_AND_APPLICATION. If
+ this AVP is added, the Redirect-Max-Cache-Time AVP MUST also be
+ included. Note that these AVPs apply to the peer discovered by a
+ node acting on the Realm-based Redirect Server's response as
+ described in the next section. This is an extension of their normal
+ usage as described by Sections 6.13 and 6.14 of [RFC6733].
+
+ Realm-based redirection MAY be applied even if a Destination-Host
+ AVP is present in the request, depending on the operator-based
+ policy.
+
+3.2.2. Proxy Behavior
+
+ A proxy conforming to this specification that receives an answer
+ message with the Result-Code AVP set to
+ DIAMETER_REALM_REDIRECT_INDICATION MUST attempt to reroute the
+ original request to a server in a realm identified by a Redirect-
+ Realm AVP instance in the answer message, and if it fails MUST
+ forward the indication toward the client. To reroute the request, it
+ MUST take the following actions:
+
+ 1. Select a specific realm from amongst those identified in
+ instances of the Redirect-Realm AVP in the answer message.
+
+ 2. If successful, locate and establish a route to a peer in the
+ realm given by the Redirect-Realm AVP, using normal discovery
+ procedures as described in Section 5.2 of [RFC6733].
+
+
+
+Tsou, et al. Standards Track [Page 6]
+
+RFC 7075 Realm-Based Redirection In Diameter November 2013
+
+
+ 3. If again successful:
+
+ A. update its cache of routing entries for the realm and
+ application to which the original request was directed,
+ taking into account the Redirect-Host-Usage and Redirect-Max-
+ Cache-Time AVPs, if present in the answer.
+
+ B. Remove the Destination-Host (if present) and Destination-
+ Realm AVPs from the original request and add a new
+ Destination-Realm AVP containing the realm selected in the
+ initial step.
+
+ C. Forward the modified request.
+
+ 4. If either of the preceding steps 2-3 fail and additional realms
+ have been identified in the original answer, select another
+ instance of the Redirect-Realm AVP in that answer and repeat
+ steps 2-3 for the realm that it identifies.
+
+3.2.3. Client Behavior
+
+ A client conforming to this specification MUST be prepared to receive
+ either an answer message containing a Result-Code AVP set to
+ DIAMETER_REALM_REDIRECT_INDICATION, or, as the result of proxy
+ action, some other result from a realm differing from the one to
+ which it sent the original request. In the case where it receives
+ DIAMETER_REALM_REDIRECT_INDICATION, the client SHOULD follow the same
+ steps prescribed in the previous section for a proxy, in order to
+ both update its routing table and obtain service for the original
+ request.
+
+3.3. The Redirect-Realm AVP
+
+ The Redirect-Realm AVP (620) is of type DiameterIdentity. It
+ specifies a realm to which a node receiving a redirect indication
+ containing the result code value DIAMETER_REALM_REDIRECT_INDICATION
+ and the Redirect-Realm AVP SHOULD route the original request.
+
+3.4. DIAMETER_REALM_REDIRECT_INDICATION Protocol Error Code
+
+ The DIAMETER_REALM_REDIRECT_INDICATION (3011) Protocol error code
+ indicates that a server has determined that the request within an
+ application supporting realm-based redirection could not be satisfied
+ locally, and the initiator of the request SHOULD direct the request
+ directly to a peer within a realm that has been identified in the
+ response. When set, the Redirect-Realm AVP MUST be present.
+
+
+
+
+
+Tsou, et al. Standards Track [Page 7]
+
+RFC 7075 Realm-Based Redirection In Diameter November 2013
+
+
+4. Security Considerations
+
+ The general recommendations given in Section 13 of the Diameter base
+ protocol [RFC6733] apply. Specific security recommendations related
+ to the realm-based redirection defined in this document are described
+ below.
+
+ Realm-based redirection implies a change in the business relationship
+ between organizations. Before redirecting a request towards a realm
+ different from the initial realm, the client or proxy MUST ensure
+ that the authorization checks have been performed at each connection
+ along the path toward the realm identified in the realm-based
+ redirect indication. Details on Diameter authorization path set-up
+ are given in Section 2.9 of [RFC6733]. Section 13 of [RFC6733]
+ provides recommendations on how to authenticate and secure each peer-
+ to-peer connection (using TLS, DTLS, or IPsec) along the way, thus
+ permitting the necessary hop-by-hop authorization checks.
+
+ Although it is assumed that the administrative domains are secure, a
+ compromised Diameter node acting as a Realm-based Redirect Server
+ would be able to redirect a large number of Diameter requests towards
+ a victim domain that would then be flooded with undesired Diameter
+ requests. Such an attack is nevertheless discouraged by the use of
+ secure Diameter peer-to-peer connections and authorization checks,
+ since these would enable a potential victim domain to discover from
+ where an attack is coming. That in itself, however, does not prevent
+ such a DoS attack.
+
+ Because realm-based redirection defined in this document implies that
+ the Destination-Realm AVP in a client-initiated request can be
+ changed by a Diameter proxy in the path between the client and the
+ server, any cryptographic algorithm that would use the Destination-
+ Realm AVP as input to the calculation performed by the client and the
+ server would be broken by this form of redirection. Application
+ specifications that would rely on such cryptographic algorithms
+ SHOULD NOT incorporate this realm-based redirection.
+
+5. IANA Considerations
+
+ This specification allocates a new AVP code Redirect-Realm (620) in
+ the "AVP Codes" registry under "Authentication, Authorization, and
+ Accounting (AAA) Parameters".
+
+ This specification allocates a new Result-Code value
+ DIAMETER_REALM_REDIRECT_INDICATION (3011) in the "Result-Code AVP
+ Values (code 268) - Protocol Errors" registry under "Authentication,
+ Authorization, and Accounting (AAA) Parameters".
+
+
+
+
+Tsou, et al. Standards Track [Page 8]
+
+RFC 7075 Realm-Based Redirection In Diameter November 2013
+
+
+6. Acknowledgements
+
+ Glen Zorn, Sebastien Decugis, Wolfgang Steigerwald, Mark Jones,
+ Victor Fajardo, Jouni Korhonen, Avi Lior, and Lionel Morand
+ contributed comments that helped to shape this document. As
+ shepherd, Lionel contributed a second set of comments that added
+ polish to the document before it was submitted to the IESG. Benoit
+ Claise picked up additional points that were quickly resolved with
+ Lionel's help. During IETF Last Call Review, Enrico Marocco picked
+ up some important editorial corrections. Stefan Winter contributed
+ text on the use of S-NAPTR as an alternative method of realm-based
+ redirection already specified in [RFC6733]. Derek Atkins performed a
+ review on behalf of the Security Directorate. Lionel noted one more
+ correction.
+
+ Finally, this document benefited from comments and discussion raised
+ by IESG members Stewart Bryant, Stephen Farrell, Barry Leiba, Pete
+ Resnick, Jari Arkko, and Sean Turner during IESG review.
+
+ The authors are very grateful to Lionel Morand for his active role as
+ document shepherd. At each stage, he worked to summarize and resolve
+ comments, making the editor's role easy. Thank you.
+
+7. References
+
+7.1. Normative References
+
+ [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate
+ Requirement Levels", BCP 14, RFC 2119, March 1997.
+
+ [RFC6733] Fajardo, V., Arkko, J., Loughney, J., and G. Zorn,
+ "Diameter Base Protocol", RFC 6733, October 2012.
+
+7.2. Informative References
+
+ [RFC3958] Daigle, L. and A. Newton, "Domain-Based Application
+ Service Location Using SRV RRs and the Dynamic Delegation
+ Discovery Service (DDDS)", RFC 3958, January 2005.
+
+
+
+
+
+
+
+
+
+
+
+
+
+Tsou, et al. Standards Track [Page 9]
+
+RFC 7075 Realm-Based Redirection In Diameter November 2013
+
+
+Authors' Addresses
+
+ Tina Tsou
+ Huawei Technologies (USA)
+ 2330 Central Expressway
+ Santa Clara, CA 95050
+ USA
+
+ Phone: +1 408 330 4424
+ URI: http://tinatsou.weebly.com/contact.html
+
+
+ Ruibing Hao
+ Comcast Cable
+ One Comcast Center
+ Philadelphia, PA 19103
+ USA
+
+ Phone: +1 215 286 3991(O)
+
+
+ Tom Taylor (editor)
+ Huawei Technologies
+ Ottawa
+ Canada
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Tsou, et al. Standards Track [Page 10]
+
diff --git a/lib/diameter/examples/code/GNUmakefile b/lib/diameter/examples/code/GNUmakefile
index 98e36a99e3..81f1da5a39 100644
--- a/lib/diameter/examples/code/GNUmakefile
+++ b/lib/diameter/examples/code/GNUmakefile
@@ -1,7 +1,7 @@
#
# %CopyrightBegin%
#
-# Copyright Ericsson AB 2010-2012. All Rights Reserved.
+# Copyright Ericsson AB 2010-2015. All Rights Reserved.
#
# The contents of this file are subject to the Erlang Public License,
# Version 1.1, (the "License"); you may not use this file except in
@@ -20,7 +20,7 @@
EXAMPLES = client server relay # redirect proxy
CALLBACKS = $(EXAMPLES:%=%_cb)
-MODULES = peer $(EXAMPLES) $(EXAMPLES:%=%_cb)
+MODULES = node $(EXAMPLES) $(EXAMPLES:%=%_cb)
BEAM = $(MODULES:%=%.beam)
diff --git a/lib/diameter/examples/code/client.erl b/lib/diameter/examples/code/client.erl
index bfe71b0e56..844c9cdbdd 100644
--- a/lib/diameter/examples/code/client.erl
+++ b/lib/diameter/examples/code/client.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2012. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -38,9 +38,10 @@
-module(client).
-include_lib("diameter/include/diameter.hrl").
--include_lib("diameter/include/diameter_gen_base_rfc3588.hrl").
+-include_lib("diameter/include/diameter_gen_base_rfc6733.hrl").
-export([start/1, %% start a service
+ start/2, %%
connect/2, %% add a connecting transport
call/1, %% send using the record encoding
cast/1, %% send using the list encoding and detached
@@ -50,17 +51,14 @@
%% both the record and list encoding here, one detached and one not,
%% is just for demonstration purposes.
-%% Convenience functions using the default service name, ?SVC_NAME.
+%% Convenience functions using the default service name.
-export([start/0,
connect/1,
stop/0,
call/0,
cast/0]).
--define(SVC_NAME, ?MODULE).
--define(APP_ALIAS, ?MODULE).
--define(CALLBACK_MOD, client_cb).
-
+-define(DEF_SVC_NAME, ?MODULE).
-define(L, atom_to_list).
%% The service configuration. As in the server example, a client
@@ -70,27 +68,40 @@
{'Origin-Realm', "example.com"},
{'Vendor-Id', 0},
{'Product-Name', "Client"},
- {'Auth-Application-Id', [?DIAMETER_APP_ID_COMMON]},
- {application, [{alias, ?APP_ALIAS},
- {dictionary, ?DIAMETER_DICT_COMMON},
- {module, ?CALLBACK_MOD}]}]).
+ {'Auth-Application-Id', [0]},
+ {string_decode, false},
+ {application, [{alias, common},
+ {dictionary, diameter_gen_base_rfc6733},
+ {module, client_cb}]}]).
%% start/1
start(Name)
when is_atom(Name) ->
- peer:start(Name, ?SERVICE(Name)).
+ start(Name, []);
+
+start(Opts)
+ when is_list(Opts) ->
+ start(?DEF_SVC_NAME, Opts).
+
+%% start/0
start() ->
- start(?SVC_NAME).
+ start(?DEF_SVC_NAME).
+
+%% start/2
+
+start(Name, Opts) ->
+ node:start(Name, Opts ++ [T || {K,_} = T <- ?SERVICE(Name),
+ false == lists:keymember(K, 1, Opts)]).
%% connect/2
connect(Name, T) ->
- peer:connect(Name, T).
+ node:connect(Name, T).
connect(T) ->
- connect(?SVC_NAME, T).
+ connect(?DEF_SVC_NAME, T).
%% call/1
@@ -99,10 +110,10 @@ call(Name) ->
RAR = #diameter_base_RAR{'Session-Id' = SId,
'Auth-Application-Id' = 0,
'Re-Auth-Request-Type' = 0},
- diameter:call(Name, ?APP_ALIAS, RAR, []).
+ diameter:call(Name, common, RAR, []).
call() ->
- call(?SVC_NAME).
+ call(?DEF_SVC_NAME).
%% cast/1
@@ -111,15 +122,15 @@ cast(Name) ->
RAR = ['RAR', {'Session-Id', SId},
{'Auth-Application-Id', 0},
{'Re-Auth-Request-Type', 1}],
- diameter:call(Name, ?APP_ALIAS, RAR, [detach]).
+ diameter:call(Name, common, RAR, [detach]).
cast() ->
- cast(?SVC_NAME).
+ cast(?DEF_SVC_NAME).
%% stop/1
stop(Name) ->
- peer:stop(Name).
+ node:stop(Name).
stop() ->
- stop(?SVC_NAME).
+ stop(?DEF_SVC_NAME).
diff --git a/lib/diameter/examples/code/client_cb.erl b/lib/diameter/examples/code/client_cb.erl
index ee3dcb2fec..843cdd9262 100644
--- a/lib/diameter/examples/code/client_cb.erl
+++ b/lib/diameter/examples/code/client_cb.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2012. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2014. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -77,23 +77,11 @@ prepare_retransmit(Packet, SvcName, Peer) ->
%% handle_answer/4
-%% Since client.erl has detached the call when using the list
-%% encoding and not otherwise, output to the terminal in the
-%% the former case, return in the latter.
-
-handle_answer(#diameter_packet{msg = Msg}, Request, _SvcName, _Peer)
- when is_list(Request) ->
- io:format("answer: ~p~n", [Msg]);
-
handle_answer(#diameter_packet{msg = Msg}, _Request, _SvcName, _Peer) ->
{ok, Msg}.
%% handle_error/4
-handle_error(Reason, Request, _SvcName, _Peer)
- when is_list(Request) ->
- io:format("error: ~p~n", [Reason]);
-
handle_error(Reason, _Request, _SvcName, _Peer) ->
{error, Reason}.
diff --git a/lib/diameter/examples/code/node.erl b/lib/diameter/examples/code/node.erl
new file mode 100644
index 0000000000..4fe9007059
--- /dev/null
+++ b/lib/diameter/examples/code/node.erl
@@ -0,0 +1,174 @@
+%%
+%% %CopyrightBegin%
+%%
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
+%%
+%% The contents of this file are subject to the Erlang Public License,
+%% Version 1.1, (the "License"); you may not use this file except in
+%% compliance with the License. You should have received a copy of the
+%% Erlang Public License along with this software. If not, it can be
+%% retrieved online at http://www.erlang.org/.
+%%
+%% Software distributed under the License is distributed on an "AS IS"
+%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+%% the License for the specific language governing rights and limitations
+%% under the License.
+%%
+%% %CopyrightEnd%
+%%
+
+%%
+%% A library module used by the example Diameter nodes. Does little
+%% more than provide an alternate/simplified transport configuration.
+%%
+
+-module(node).
+
+-export([start/2,
+ listen/2,
+ connect/2,
+ stop/1]).
+
+-type protocol()
+ :: tcp | sctp.
+
+-type ip_address()
+ :: default
+ | inet:ip_address().
+
+-type server_transport()
+ :: protocol()
+ | {protocol(), ip_address(), non_neg_integer()}.
+
+-type server_opts()
+ :: server_transport()
+ | {server_transport(), [diameter:transport_opt()]}
+ | [diameter:transport_opt()].
+
+-type client_transport()
+ :: protocol() | any
+ | {protocol() | any, ip_address(), non_neg_integer()}
+ | {protocol() | any, ip_address(), ip_address(), non_neg_integer()}.
+
+-type client_opts()
+ :: client_transport()
+ | {client_transport(), [diameter:transport_opt()]}
+ | [diameter:transport_opt()].
+
+%% The server_transport() and client_transport() config is just
+%% convenience: arbitrary options can be specifed as a
+%% [diameter:transport_opt()].
+
+-define(DEFAULT_PORT, 3868).
+
+%% ---------------------------------------------------------------------------
+%% Interface functions
+%% ---------------------------------------------------------------------------
+
+%% start/2
+
+-spec start(diameter:service_name(), [diameter:service_opt()])
+ -> ok
+ | {error, term()}.
+
+start(Name, Opts)
+ when is_atom(Name), is_list(Opts) ->
+ diameter:start_service(Name, Opts).
+
+%% connect/2
+
+-spec connect(diameter:service_name(), client_opts())
+ -> {ok, diameter:transport_ref()}
+ | {error, term()}.
+
+connect(Name, Opts)
+ when is_list(Opts) ->
+ diameter:add_transport(Name, {connect, Opts});
+
+connect(Name, {T, Opts}) ->
+ connect(Name, Opts ++ client_opts(T));
+
+connect(Name, T) ->
+ connect(Name, [{connect_timer, 5000} | client_opts(T)]).
+
+%% listen/2
+
+-spec listen(diameter:service_name(), server_opts())
+ -> {ok, diameter:transport_ref()}
+ | {error, term()}.
+
+listen(Name, Opts)
+ when is_list(Opts) ->
+ diameter:add_transport(Name, {listen, Opts});
+
+listen(Name, {T, Opts}) ->
+ listen(Name, Opts ++ server_opts(T));
+
+listen(Name, T) ->
+ listen(Name, server_opts(T)).
+
+%% stop/1
+
+-spec stop(diameter:service_name())
+ -> ok
+ | {error, term()}.
+
+stop(Name) ->
+ diameter:stop_service(Name).
+
+%% ---------------------------------------------------------------------------
+%% Internal functions
+%% ---------------------------------------------------------------------------
+
+%% server_opts/1
+%%
+%% Return transport options for a listening transport.
+
+server_opts({T, Addr, Port}) ->
+ [{transport_module, tmod(T)},
+ {transport_config, [{reuseaddr, true},
+ {ip, addr(Addr)},
+ {port, Port}]}];
+
+server_opts(T) ->
+ server_opts({T, loopback, ?DEFAULT_PORT}).
+
+%% client_opts/1
+%%
+%% Return transport options for a connecting transport.
+
+client_opts({T, LA, RA, RP})
+ when T == all; %% backwards compatibility
+ T == any ->
+ [[S, {C,Os}], T] = [client_opts({P, LA, RA, RP}) || P <- [sctp,tcp]],
+ [S, {C,Os,2000} | T];
+
+client_opts({T, LA, RA, RP}) ->
+ [{transport_module, tmod(T)},
+ {transport_config, [{raddr, addr(RA)},
+ {rport, RP},
+ {reuseaddr, true}
+ | ip(LA)]}];
+
+client_opts({T, RA, RP}) ->
+ client_opts({T, default, RA, RP});
+
+client_opts(T) ->
+ client_opts({T, loopback, loopback, ?DEFAULT_PORT}).
+
+%% ---------------------------------------------------------------------------
+
+tmod(tcp) -> diameter_tcp;
+tmod(sctp) -> diameter_sctp.
+
+ip(default) ->
+ [];
+ip(loopback) ->
+ [{ip, {127,0,0,1}}];
+ip(Addr) ->
+ [{ip, Addr}].
+
+addr(loopback) ->
+ {127,0,0,1};
+addr(A) ->
+ A.
diff --git a/lib/diameter/examples/code/peer.erl b/lib/diameter/examples/code/peer.erl
deleted file mode 100644
index b4ee17e4b7..0000000000
--- a/lib/diameter/examples/code/peer.erl
+++ /dev/null
@@ -1,150 +0,0 @@
-%%
-%% %CopyrightBegin%
-%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
-%%
-%% The contents of this file are subject to the Erlang Public License,
-%% Version 1.1, (the "License"); you may not use this file except in
-%% compliance with the License. You should have received a copy of the
-%% Erlang Public License along with this software. If not, it can be
-%% retrieved online at http://www.erlang.org/.
-%%
-%% Software distributed under the License is distributed on an "AS IS"
-%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
-%% the License for the specific language governing rights and limitations
-%% under the License.
-%%
-%% %CopyrightEnd%
-%%
-
-%%
-%% A library module that factors out commonality in the example
-%% Diameter peers.
-%%
-
--module(peer).
-
--include_lib("diameter/include/diameter.hrl").
--include_lib("diameter/include/diameter_gen_base_rfc3588.hrl").
-
--export([start/2,
- listen/2,
- connect/2,
- stop/1]).
-
--type service_name()
- :: term().
-
--type protocol()
- :: tcp | sctp.
-
--type ip_address()
- :: default
- | inet:ip_address().
-
--type server_config()
- :: protocol()
- | {protocol(), ip_address(), non_neg_integer()}.
-
--type client_config()
- :: protocol()
- | {protocol(), ip_address(), non_neg_integer()}
- | {protocol(), ip_address(), ip_address(), non_neg_integer()}.
-
--define(DEFAULT_PORT, 3868).
-
-%% ---------------------------------------------------------------------------
-%% Interface functions
-%% ---------------------------------------------------------------------------
-
-%% start/2
-
--spec start(service_name(), list())
- -> ok
- | {error, term()}.
-
-start(Name, Opts)
- when is_atom(Name), is_list(Opts) ->
- diameter:start_service(Name, Opts).
-
-%% connect/2
-
--spec connect(service_name(), client_config())
- -> {ok, reference()}
- | {error, term()}.
-
-connect(Name, T) ->
- diameter:add_transport(Name, {connect, [{reconnect_timer, 5000}
- | client(T)]}).
-
-%% listen/2
-
--spec listen(service_name(), server_config())
- -> {ok, reference()}
- | {error, term()}.
-
-listen(Name, T) ->
- diameter:add_transport(Name, {listen, server(T)}).
-
-%% stop/1
-
--spec stop(service_name())
- -> ok
- | {error, term()}.
-
-stop(Name) ->
- diameter:stop_service(Name).
-
-%% ---------------------------------------------------------------------------
-%% Internal functions
-%% ---------------------------------------------------------------------------
-
-%% server/1
-%%
-%% Return config for a listening transport.
-
-server({T, Addr, Port}) ->
- [{transport_module, tmod(T)},
- {transport_config, [{reuseaddr, true},
- {ip, addr(Addr)},
- {port, Port}]}];
-
-server(T) ->
- server({T, loopback, ?DEFAULT_PORT}).
-
-%% client/1
-%%
-%% Return config for a connecting transport.
-
-client({all, LA, RA, RP}) ->
- [[M,{K,C}], T]
- = [client({P, LA, RA, RP}) || P <- [sctp,tcp]],
- [M, {K,C,2000} | T];
-
-client({T, LA, RA, RP}) ->
- [{transport_module, tmod(T)},
- {transport_config, [{raddr, addr(RA)},
- {rport, RP},
- {reuseaddr, true}
- | ip(LA)]}];
-
-client({T, RA, RP}) ->
- client({T, default, RA, RP});
-
-client(T) ->
- client({T, loopback, loopback, ?DEFAULT_PORT}).
-
-tmod(tcp) -> diameter_tcp;
-tmod(sctp) -> diameter_sctp.
-
-ip(default) ->
- [];
-ip(loopback) ->
- [{ip, {127,0,0,1}}];
-ip(Addr) ->
- [{ip, Addr}].
-
-addr(loopback) ->
- {127,0,0,1};
-addr(A) ->
- A.
diff --git a/lib/diameter/examples/code/redirect_cb.erl b/lib/diameter/examples/code/redirect_cb.erl
index 69836774a1..8d98b0d2df 100644
--- a/lib/diameter/examples/code/redirect_cb.erl
+++ b/lib/diameter/examples/code/redirect_cb.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2014. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -34,12 +34,10 @@
-define(UNEXPECTED, erlang:error({unexpected, ?MODULE, ?LINE})).
-peer_up(_SvcName, {PeerRef, _}, State) ->
- io:format("up: ~p~n", [PeerRef]),
+peer_up(_SvcName, _Peer, State) ->
State.
-peer_down(_SvcName, {PeerRef, _}, State) ->
- io:format("down: ~p~n", [PeerRef]),
+peer_down(_SvcName, _Peer, State) ->
State.
pick_peer(_, _, _SvcName, _State) ->
diff --git a/lib/diameter/examples/code/relay.erl b/lib/diameter/examples/code/relay.erl
index d3438f83f3..7bc46dc68d 100644
--- a/lib/diameter/examples/code/relay.erl
+++ b/lib/diameter/examples/code/relay.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2012. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -31,10 +31,8 @@
-module(relay).
--include_lib("diameter/include/diameter.hrl").
--include_lib("diameter/include/diameter_gen_base_rfc3588.hrl").
-
-export([start/1,
+ start/2,
listen/2,
connect/2,
stop/1]).
@@ -44,49 +42,56 @@
connect/1,
stop/0]).
--define(APP_ALIAS, ?MODULE).
--define(SVC_NAME, ?MODULE).
--define(CALLBACK_MOD, relay_cb).
+-define(DEF_SVC_NAME, ?MODULE).
%% The service configuration.
-define(SERVICE(Name), [{'Origin-Host', atom_to_list(Name) ++ ".example.com"},
{'Origin-Realm', "example.com"},
{'Vendor-Id', 193},
{'Product-Name', "RelayAgent"},
- {'Auth-Application-Id', [?DIAMETER_APP_ID_RELAY]},
- {application, [{alias, ?MODULE},
- {dictionary, ?DIAMETER_DICT_RELAY},
- {module, ?CALLBACK_MOD}]}]).
+ {'Auth-Application-Id', [16#FFFFFFFF]},
+ {string_decode, false},
+ {application, [{alias, relay},
+ {dictionary, diameter_relay},
+ {module, relay_cb}]}]).
%% start/1
start(Name)
when is_atom(Name) ->
- peer:start(Name, ?SERVICE(Name)).
+ start(Name, []).
+
+%% start/1
start() ->
- start(?SVC_NAME).
+ start(?DEF_SVC_NAME).
+
+%% start/2
+
+start(Name, Opts) ->
+ node:start(Name, Opts ++ [T || {K,_} = T <- ?SERVICE(Name),
+ false == lists:keymember(K, 1, Opts)]).
%% listen/2
listen(Name, T) ->
- peer:listen(Name, T).
+ node:listen(Name, T).
listen(T) ->
- listen(?SVC_NAME, T).
+ listen(?DEF_SVC_NAME, T).
%% connect/2
connect(Name, T) ->
- peer:connect(Name, T).
+ node:connect(Name, T).
connect(T) ->
- connect(?SVC_NAME, T).
+ connect(?DEF_SVC_NAME, T).
%% stop/1
stop(Name) ->
- peer:stop(Name).
+ node:stop(Name).
stop() ->
- stop(?SVC_NAME).
+ stop(?DEF_SVC_NAME).
diff --git a/lib/diameter/examples/code/relay_cb.erl b/lib/diameter/examples/code/relay_cb.erl
index 9f9cd8d5ae..68798014e6 100644
--- a/lib/diameter/examples/code/relay_cb.erl
+++ b/lib/diameter/examples/code/relay_cb.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2012. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2014. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -32,12 +32,10 @@
handle_error/5,
handle_request/3]).
-peer_up(_SvcName, {PeerRef, _}, State) ->
- io:format("up: ~p~n", [PeerRef]),
+peer_up(_SvcName, _Peer, State) ->
State.
-peer_down(_SvcName, {PeerRef, _}, State) ->
- io:format("down: ~p~n", [PeerRef]),
+peer_down(_SvcName, _Peer, State) ->
State.
%% Returning 'relay' from handle_request causes diameter to resend the
diff --git a/lib/diameter/examples/code/server.erl b/lib/diameter/examples/code/server.erl
index 3959461cec..f32cec594c 100644
--- a/lib/diameter/examples/code/server.erl
+++ b/lib/diameter/examples/code/server.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2012. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -34,21 +34,17 @@
-module(server).
--include_lib("diameter/include/diameter.hrl").
--include_lib("diameter/include/diameter_gen_base_rfc3588.hrl").
-
-export([start/1, %% start a service
+ start/2, %%
listen/2, %% add a listening transport
stop/1]). %% stop a service
-%% Convenience functions using the default service name, ?SVC_NAME.
+%% Convenience functions using the default service name.
-export([start/0,
listen/1,
stop/0]).
--define(SVC_NAME, ?MODULE).
--define(APP_ALIAS, ?MODULE).
--define(CALLBACK_MOD, server_cb).
+-define(DEF_SVC_NAME, ?MODULE).
%% The service configuration. In a server supporting multiple Diameter
%% applications each application may have its own, although they could all
@@ -57,32 +53,46 @@
{'Origin-Realm', "example.com"},
{'Vendor-Id', 193},
{'Product-Name', "Server"},
- {'Auth-Application-Id', [?DIAMETER_APP_ID_COMMON]},
- {application, [{alias, ?APP_ALIAS},
- {dictionary, ?DIAMETER_DICT_COMMON},
- {module, ?CALLBACK_MOD}]}]).
+ {'Auth-Application-Id', [0]},
+ {restrict_connections, false},
+ {string_decode, false},
+ {application, [{alias, common},
+ {dictionary, diameter_gen_base_rfc6733},
+ {module, server_cb}]}]).
%% start/1
start(Name)
when is_atom(Name) ->
- peer:start(Name, ?SERVICE(Name)).
+ start(Name, []);
+
+start(Opts)
+ when is_list(Opts) ->
+ start(?DEF_SVC_NAME, Opts).
+
+%% start/0
start() ->
- start(?SVC_NAME).
+ start(?DEF_SVC_NAME).
+
+%% start/2
+
+start(Name, Opts) ->
+ node:start(Name, Opts ++ [T || {K,_} = T <- ?SERVICE(Name),
+ false == lists:keymember(K, 1, Opts)]).
%% listen/2
listen(Name, T) ->
- peer:listen(Name, T).
+ node:listen(Name, T).
listen(T) ->
- listen(?SVC_NAME, T).
+ listen(?DEF_SVC_NAME, T).
%% stop/1
stop(Name) ->
- peer:stop(Name).
+ node:stop(Name).
stop() ->
- stop(?SVC_NAME).
+ stop(?DEF_SVC_NAME).
diff --git a/lib/diameter/examples/code/server_cb.erl b/lib/diameter/examples/code/server_cb.erl
index 0f6eb32ed6..071e152493 100644
--- a/lib/diameter/examples/code/server_cb.erl
+++ b/lib/diameter/examples/code/server_cb.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2012. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -24,7 +24,7 @@
-module(server_cb).
-include_lib("diameter/include/diameter.hrl").
--include_lib("diameter/include/diameter_gen_base_rfc3588.hrl").
+-include_lib("diameter/include/diameter_gen_base_rfc6733.hrl").
%% diameter callbacks
-export([peer_up/3,
@@ -38,12 +38,10 @@
-define(UNEXPECTED, erlang:error({unexpected, ?MODULE, ?LINE})).
-peer_up(_SvcName, {PeerRef, _}, State) ->
- io:format("up: ~p~n", [PeerRef]),
+peer_up(_SvcName, _Peer, State) ->
State.
-peer_down(_SvcName, {PeerRef, _}, State) ->
- io:format("down: ~p~n", [PeerRef]),
+peer_down(_SvcName, _Peer, State) ->
State.
pick_peer(_, _, _SvcName, _State) ->
@@ -68,10 +66,13 @@ handle_request(#diameter_packet{msg = Req, errors = []}, _SvcName, {_, Caps})
origin_realm = {OR,_}}
= Caps,
#diameter_base_RAR{'Session-Id' = Id,
- 'Re-Auth-Request-Type' = RT}
+ 'Re-Auth-Request-Type' = Type}
= Req,
- {reply, answer(RT, Id, OH, OR)};
+ {reply, #diameter_base_RAA{'Result-Code' = rc(Type),
+ 'Origin-Host' = OH,
+ 'Origin-Realm' = OR,
+ 'Session-Id' = Id}};
%% ... or one that wasn't. 3xxx errors are answered by diameter itself
%% but these are 5xxx errors for which we must contruct a reply.
@@ -84,32 +85,18 @@ handle_request(#diameter_packet{msg = Req}, _SvcName, {_, Caps})
#diameter_base_RAR{'Session-Id' = Id}
= Req,
- Ans = #diameter_base_RAA{'Origin-Host' = OH,
- 'Origin-Realm' = OR,
- 'Session-Id' = Id},
+ {reply, #diameter_base_RAA{'Origin-Host' = OH,
+ 'Origin-Realm' = OR,
+ 'Session-Id' = Id}};
- {reply, Ans};
+%% Answer that any other message is unsupported.
+handle_request(#diameter_packet{}, _SvcName, _) ->
+ {answer_message, 3001}. %% DIAMETER_COMMAND_UNSUPPORTED
-%% Should really reply to other base messages that we don't support
-%% but simply discard them instead.
-handle_request(#diameter_packet{}, _SvcName, {_,_}) ->
- discard.
+%% Map Re-Auth-Request-Type to Result-Code just for the purpose of
+%% generating different answers.
-%% ---------------------------------------------------------------------------
-
-%% Answer using the record or list encoding depending on
-%% Re-Auth-Request-Type. This is just as an example. You would
-%% typically just choose one, and this has nothing to do with the how
-%% client.erl sends.
-
-answer(0, Id, OH, OR) ->
- #diameter_base_RAA{'Result-Code' = 2001, %% DIAMETER_SUCCESS
- 'Origin-Host' = OH,
- 'Origin-Realm' = OR,
- 'Session-Id' = Id};
-
-answer(_, Id, OH, OR) ->
- ['RAA', {'Result-Code', 5012}, %% DIAMETER_UNABLE_TO_COMPLY
- {'Origin-Host', OH},
- {'Origin-Realm', OR},
- {'Session-Id', Id}].
+rc(0) ->
+ 2001; %% DIAMETER_SUCCESS
+rc(_) ->
+ 5012. %% DIAMETER_UNABLE_TO_COMPLY
diff --git a/lib/diameter/examples/dict/.gitignore b/lib/diameter/examples/dict/.gitignore
new file mode 100644
index 0000000000..feeb378fd8
--- /dev/null
+++ b/lib/diameter/examples/dict/.gitignore
@@ -0,0 +1,2 @@
+
+/depend.mk
diff --git a/lib/diameter/examples/dict/GNUmakefile b/lib/diameter/examples/dict/GNUmakefile
new file mode 100644
index 0000000000..60c95c08f9
--- /dev/null
+++ b/lib/diameter/examples/dict/GNUmakefile
@@ -0,0 +1,60 @@
+#
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 2013. All Rights Reserved.
+#
+# The contents of this file are subject to the Erlang Public License,
+# Version 1.1, (the "License"); you may not use this file except in
+# compliance with the License. You should have received a copy of the
+# Erlang Public License along with this software. If not, it can be
+# retrieved online at http://www.erlang.org/.
+#
+# Software distributed under the License is distributed on an "AS IS"
+# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+# the License for the specific language governing rights and limitations
+# under the License.
+#
+# %CopyrightEnd%
+#
+
+#
+# Build example dictionaries. Assumes erlc and diameterc are on PATH.
+#
+
+DICTS = rfc4004_mip \
+ rfc4005_nas \
+ rfc4006_cc \
+ rfc4072_eap \
+ rfc4590_digest \
+ rfc4740_sip
+
+FILES = $(DICTS:%=%.dia)
+BEAMS = $(DICTS:%=%.beam)
+
+COMMON = diameter_gen_base_rfc6733
+
+%.erl: %.dia
+ diameterc --name $(basename $@) \
+ --prefix $(basename $@) \
+ --inherits common/$(COMMON) \
+ $<
+
+%.beam: %.erl
+ erlc -Wall +debug_info $<
+
+all: $(BEAMS)
+
+clean:
+ rm -f $(DICTS:%=%.erl) $(DICTS:%=%.hrl) $(BEAMS) depend.mk
+
+-include depend.mk
+
+depend.mk: depend.sed $(FILES) GNUmakefile
+ (for f in $(FILES); do \
+ (echo $$f; cat $$f) | sed -f depend.sed; \
+ done) \
+ > $@
+
+.PHONY: all clean
+
+.SECONDARY: $(DICTS:%=%.erl)
diff --git a/lib/diameter/examples/dict/depend.sed b/lib/diameter/examples/dict/depend.sed
new file mode 100644
index 0000000000..fd9a38479c
--- /dev/null
+++ b/lib/diameter/examples/dict/depend.sed
@@ -0,0 +1,43 @@
+#
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 2013. All Rights Reserved.
+#
+# The contents of this file are subject to the Erlang Public License,
+# Version 1.1, (the "License"); you may not use this file except in
+# compliance with the License. You should have received a copy of the
+# Erlang Public License along with this software. If not, it can be
+# retrieved online at http://www.erlang.org/.
+#
+# Software distributed under the License is distributed on an "AS IS"
+# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+# the License for the specific language governing rights and limitations
+# under the License.
+#
+# %CopyrightEnd%
+#
+
+#
+# Extract dependencies from .dia files. First line of input is the
+# dictionary's filename, the rest is its contents.
+#
+
+1{
+ s@\.[^.]*$@@
+ h
+ d
+}
+
+# Only interested in @inherits.
+/^@inherits */!d
+
+s///
+s/ .*//
+
+# Ignore the common application.
+/^common$/d
+
+# Retrieve the dictionary name from the hold space and output
+# a dependency.
+G
+s@^\(.*\)\n\(.*\)@\2.erl: \1.beam@
diff --git a/lib/diameter/examples/dict/rfc4004_mip.dia b/lib/diameter/examples/dict/rfc4004_mip.dia
index 575ad4394a..0595cfe9ef 100644
--- a/lib/diameter/examples/dict/rfc4004_mip.dia
+++ b/lib/diameter/examples/dict/rfc4004_mip.dia
@@ -1,7 +1,7 @@
;;
;; %CopyrightBegin%
;;
-;; Copyright Ericsson AB 2010-2011. All Rights Reserved.
+;; Copyright Ericsson AB 2010-2013. All Rights Reserved.
;;
;; The contents of this file are subject to the Erlang Public License,
;; Version 1.1, (the "License"); you may not use this file except in
@@ -30,7 +30,7 @@
@id 2
-@inherits rfc3588_base
+@inherits common
;; ===========================================================================
diff --git a/lib/diameter/examples/dict/rfc4005_nas.dia b/lib/diameter/examples/dict/rfc4005_nas.dia
index a4b44e38bb..6f0e7c1ce5 100644
--- a/lib/diameter/examples/dict/rfc4005_nas.dia
+++ b/lib/diameter/examples/dict/rfc4005_nas.dia
@@ -1,7 +1,7 @@
;;
;; %CopyrightBegin%
;;
-;; Copyright Ericsson AB 2010-2011. All Rights Reserved.
+;; Copyright Ericsson AB 2010-2013. All Rights Reserved.
;;
;; The contents of this file are subject to the Erlang Public License,
;; Version 1.1, (the "License"); you may not use this file except in
@@ -37,7 +37,7 @@
@id 1
-@inherits rfc3588_base
+@inherits common
;; ===========================================================================
diff --git a/lib/diameter/examples/dict/rfc4006_cc.dia b/lib/diameter/examples/dict/rfc4006_cc.dia
index b723e4ddbb..b45ffc8090 100644
--- a/lib/diameter/examples/dict/rfc4006_cc.dia
+++ b/lib/diameter/examples/dict/rfc4006_cc.dia
@@ -1,7 +1,7 @@
;;
;; %CopyrightBegin%
;;
-;; Copyright Ericsson AB 2010-2011. All Rights Reserved.
+;; Copyright Ericsson AB 2010-2013. All Rights Reserved.
;;
;; The contents of this file are subject to the Erlang Public License,
;; Version 1.1, (the "License"); you may not use this file except in
@@ -23,7 +23,7 @@
@id 4
-@inherits rfc3588_base
+@inherits common
@inherits rfc4005_nas Filter-Id
;; ===========================================================================
diff --git a/lib/diameter/examples/dict/rfc4072_eap.dia b/lib/diameter/examples/dict/rfc4072_eap.dia
index 111516b347..676b1b8b9b 100644
--- a/lib/diameter/examples/dict/rfc4072_eap.dia
+++ b/lib/diameter/examples/dict/rfc4072_eap.dia
@@ -1,7 +1,7 @@
;;
;; %CopyrightBegin%
;;
-;; Copyright Ericsson AB 2010-2011. All Rights Reserved.
+;; Copyright Ericsson AB 2010-2013. All Rights Reserved.
;;
;; The contents of this file are subject to the Erlang Public License,
;; Version 1.1, (the "License"); you may not use this file except in
@@ -30,7 +30,7 @@
@id 5
-@inherits rfc3588_base
+@inherits common
@inherits rfc4005_nas
;; ===========================================================================
diff --git a/lib/diameter/examples/dict/rfc4590_digest.dia b/lib/diameter/examples/dict/rfc4590_digest.dia
index a4ebe0c456..de68a6ef7e 100644
--- a/lib/diameter/examples/dict/rfc4590_digest.dia
+++ b/lib/diameter/examples/dict/rfc4590_digest.dia
@@ -1,7 +1,7 @@
;;
;; %CopyrightBegin%
;;
-;; Copyright Ericsson AB 2010-2011. All Rights Reserved.
+;; Copyright Ericsson AB 2010-2013. All Rights Reserved.
;;
;; The contents of this file are subject to the Erlang Public License,
;; Version 1.1, (the "License"); you may not use this file except in
diff --git a/lib/diameter/examples/dict/rfc4740_sip.dia b/lib/diameter/examples/dict/rfc4740_sip.dia
index 8c21882649..cada3ac826 100644
--- a/lib/diameter/examples/dict/rfc4740_sip.dia
+++ b/lib/diameter/examples/dict/rfc4740_sip.dia
@@ -1,7 +1,7 @@
;;
;; %CopyrightBegin%
;;
-;; Copyright Ericsson AB 2010-2011. All Rights Reserved.
+;; Copyright Ericsson AB 2010-2013. All Rights Reserved.
;;
;; The contents of this file are subject to the Erlang Public License,
;; Version 1.1, (the "License"); you may not use this file except in
@@ -23,7 +23,7 @@
@id 6
-@inherits rfc3588_base
+@inherits common
@inherits rfc4590_digest
;; ===========================================================================
diff --git a/lib/diameter/include/diameter.hrl b/lib/diameter/include/diameter.hrl
index 79c4dce541..c2c271a9a3 100644
--- a/lib/diameter/include/diameter.hrl
+++ b/lib/diameter/include/diameter.hrl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2014. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -58,8 +58,8 @@
-record(diameter_header,
{version, %% 8-bit unsigned
length, %% 24-bit unsigned
- cmd_code, %% 8-bit unsigned
- application_id, %% 24-bit unsigned
+ cmd_code, %% 24-bit unsigned
+ application_id, %% 32-bit unsigned
hop_by_hop_id, %% 32-bit unsigned
end_to_end_id, %% 32-bit unsigned
is_request, %% boolean() R flag
@@ -126,7 +126,7 @@
default,
extra = []}).
-%% The diameter service and diameter_apps records are only passed
+%% The diameter service and diameter_app records are only passed
%% through the transport interface when starting a transport process,
%% although typically a transport implementation will (and probably
%% should) only be interested host_ip_address.
@@ -143,6 +143,7 @@
init_state, %% option 'state', initial callback state
id, %% 32-bit unsigned application identifier = Dict:id()
mutable = false, %% boolean(), do traffic callbacks modify state?
- options = [{answer_errors, report}, %% | callback | discard
+ options = [{answer_errors, discard}, %% | callback | report
{request_errors, answer_3xxx}]}). %% | callback | answer
+
-endif. %% -ifdef(diameter_hrl).
diff --git a/lib/diameter/include/diameter_gen.hrl b/lib/diameter/include/diameter_gen.hrl
index 55aae3a243..39ccdc9873 100644
--- a/lib/diameter/include/diameter_gen.hrl
+++ b/lib/diameter/include/diameter_gen.hrl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -25,6 +25,21 @@
-define(THROW(T), throw({?MODULE, T})).
+%% Tag common to generated dictionaries.
+-define(TAG, diameter_gen).
+
+%% Key to a value in the process dictionary that determines whether or
+%% not an unrecognized AVP setting the M-bit should be regarded as an
+%% error or not. See is_strict/0. This is only used to relax M-bit
+%% interpretation inside Grouped AVPs not setting the M-bit. The
+%% service_opt() strict_mbit can be used to disable the check
+%% globally.
+-define(STRICT_KEY, strict).
+
+%% Key that says whether or not we should do a best-effort decode
+%% within Failed-AVP.
+-define(FAILED_KEY, failed).
+
-type parent_name() :: atom(). %% parent = Message or AVP
-type parent_record() :: tuple(). %%
-type avp_name() :: atom().
@@ -35,6 +50,25 @@
-type grouped_avp() :: nonempty_improper_list(#diameter_avp{}, [avp()]).
-type avp() :: non_grouped_avp() | grouped_avp().
+%% Use a (hopefully) unique key when manipulating the process
+%% dictionary.
+
+putr(K,V) ->
+ put({?TAG, K}, V).
+
+getr(K) ->
+ case get({?TAG, K}) of
+ undefined ->
+ V = erase({?MODULE, K}), %% written in old code
+ V == undefined orelse putr(K,V),
+ V;
+ V ->
+ V
+ end.
+
+eraser(K) ->
+ erase({?TAG, K}).
+
%% ---------------------------------------------------------------------------
%% # encode_avps/2
%% ---------------------------------------------------------------------------
@@ -154,9 +188,10 @@ decode_avps(Name, Recs) ->
= lists:foldl(fun(T,A) -> decode(Name, T, A) end,
{[], {newrec(Name), []}},
Recs),
- {Rec, Avps, Failed ++ missing(Rec, Name)}.
-%% Append 5005 errors so that a 5014 for the same AVP will take
-%% precedence in a Result-Code/Failed-AVP setting.
+ {Rec, Avps, Failed ++ missing(Rec, Name, Failed)}.
+%% Append 5005 errors so that errors are reported in the order
+%% encountered. Failed-AVP should typically contain the first
+%% encountered error accordg to the RFC.
newrec(Name) ->
'#new-'(name2rec(Name)).
@@ -169,20 +204,36 @@ newrec(Name) ->
%% Failed-AVP AVP SHOULD be included in the message. The Failed-AVP
%% AVP MUST contain an example of the missing AVP complete with the
%% Vendor-Id if applicable. The value field of the missing AVP
-%% should be of correct minimum length and contain zeroes.
-
-missing(Rec, Name) ->
- [{5005, empty_avp(F)} || F <- '#info-'(element(1, Rec), fields),
- A <- [avp_arity(Name, F)],
- false <- [have_arity(A, '#get-'(F, Rec))]].
+%% should be of correct minimum length and contain zeros.
+
+missing(Rec, Name, Failed) ->
+ Avps = lists:foldl(fun({_, #diameter_avp{code = C, vendor_id = V}}, A) ->
+ sets:add_element({C,V}, A)
+ end,
+ sets:new(),
+ Failed),
+ [{5005, A} || F <- '#info-'(element(1, Rec), fields),
+ not has_arity(avp_arity(Name, F), '#get-'(F, Rec)),
+ #diameter_avp{code = C, vendor_id = V}
+ = A <- [empty_avp(F)],
+ not sets:is_element({C,V}, Avps)].
%% Maximum arities have already been checked in building the record.
-have_arity({Min, _}, L) ->
- Min =< length(L);
-have_arity(N, V) ->
+has_arity({Min, _}, L) ->
+ has_prefix(Min, L);
+has_arity(N, V) ->
N /= 1 orelse V /= undefined.
+%% Compare a non-negative integer and the length of a list without
+%% computing the length.
+has_prefix(0, _) ->
+ true;
+has_prefix(_, []) ->
+ false;
+has_prefix(N, L) ->
+ has_prefix(N-1, tl(L)).
+
%% empty_avp/1
empty_avp(Name) ->
@@ -212,60 +263,244 @@ decode(Name, #diameter_avp{code = Code, vendor_id = Vid} = Avp, Acc) ->
%% decode/4
+%% AVP is defined in the dictionary ...
decode(Name, {AvpName, Type}, Avp, Acc) ->
d(Name, Avp#diameter_avp{name = AvpName, type = Type}, Acc);
+%% ... or not.
decode(Name, 'AVP', Avp, Acc) ->
decode_AVP(Name, Avp, Acc).
-%% d/3
+%% 6733, 4.4:
+%%
+%% Receivers of a Grouped AVP that does not have the 'M' (mandatory)
+%% bit set and one or more of the encapsulated AVPs within the group
+%% has the 'M' (mandatory) bit set MAY simply be ignored if the
+%% Grouped AVP itself is unrecognized. The rule applies even if the
+%% encapsulated AVP with its 'M' (mandatory) bit set is further
+%% encapsulated within other sub-groups, i.e., other Grouped AVPs
+%% embedded within the Grouped AVP.
+%%
+%% The first sentence is slightly mangled, but take it to mean this:
+%%
+%% An unrecognized AVP of type Grouped that does not set the 'M' bit
+%% MAY be ignored even if one of its encapsulated AVPs sets the 'M'
+%% bit.
+%%
+%% The text above is a change from RFC 3588, which instead says this:
+%%
+%% Further, if any of the AVPs encapsulated within a Grouped AVP has
+%% the 'M' (mandatory) bit set, the Grouped AVP itself MUST also
+%% include the 'M' bit set.
+%%
+%% Both of these texts have problems. If the AVP is unknown then its
+%% type is unknown since the type isn't sent over the wire, so the
+%% 6733 text becomes a non-statement: don't know that the AVP not
+%% setting the M-bit is of type Grouped, therefore can't know that its
+%% data consists of encapsulated AVPs, therefore can't but ignore that
+%% one of these might set the M-bit. It should be no worse if we know
+%% the AVP to have type Grouped.
+%%
+%% Similarly, for the 3588 text: if we receive an AVP that doesn't set
+%% the M-bit and don't know that the AVP has type Grouped then we
+%% can't realize that its data contains an AVP that sets the M-bit, so
+%% can't regard the AVP as erroneous on this account. Again, it should
+%% be no worse if the type is known to be Grouped, but in this case
+%% the RFC forces us to regard the AVP as erroneous. This is
+%% inconsistent, and the 3588 text has never been enforced.
+%%
+%% So, if an AVP doesn't set the M-bit then we're free to ignore it,
+%% regardless of the AVP's type. If we know the type to be Grouped
+%% then we must ignore the M-bit on an encapsulated AVP. That means
+%% packing such an encapsulated AVP into an 'AVP' field if need be,
+%% not regarding the lack of a specific field as an error as is
+%% otherwise the case. (The lack of an AVP-specific field being how we
+%% defined the RFC's "unrecognized", which is slightly stronger than
+%% "not defined".)
-%% Don't try to decode the value of a Failed-AVP component since it
-%% probably won't. Note that matching on 'Failed-AVP' assumes that
-%% this is the RFC AVP, with code 279. Strictly, this doesn't need to
-%% be the case, so we're assuming no one defines another Failed-AVP.
-d('Failed-AVP' = Name, Avp, Acc) ->
- decode_AVP(Name, Avp, Acc);
+%% d/3
-%% Or try to decode.
-d(Name, Avp, {Avps, Acc}) ->
+d(Name, Avp, Acc) ->
#diameter_avp{name = AvpName,
- data = Data}
+ data = Data,
+ type = Type,
+ is_mandatory = M}
= Avp,
- try avp(decode, Data, AvpName) of
+ %% Use the process dictionary is to keep track of whether or not
+ %% to ignore an M-bit on an encapsulated AVP. Not ideal, but the
+ %% alternative requires widespread changes to be able to pass the
+ %% value around through the entire decode. The solution here is
+ %% simple in comparison, both to implement and to understand.
+
+ Strict = relax(Type, M),
+
+ %% Use the process dictionary again to keep track of whether we're
+ %% decoding within Failed-AVP and should ignore decode errors
+ %% altogether.
+
+ Failed = relax(Name), %% Not AvpName or else a failed Failed-AVP
+ %% decode is packed into 'AVP'.
+ Mod = dict(Failed), %% Dictionary to decode in.
+
+ %% On decode, a Grouped AVP is represented as a #diameter_avp{}
+ %% list with AVP as head and component AVPs as tail. On encode,
+ %% data can be a list of component AVPs.
+
+ try Mod:avp(decode, Data, AvpName) of
V ->
+ {Avps, T} = Acc,
{H, A} = ungroup(V, Avp),
- {[H | Avps], pack_avp(Name, A, Acc)}
+ {[H | Avps], pack_avp(Name, A, T)}
catch
+ throw: {?TAG, {grouped, Error, ComponentAvps}} ->
+ g(is_failed(), Error, Name, trim(Avp), Acc, ComponentAvps);
error: Reason ->
- %% Failures here won't be visible since they're a "normal"
- %% occurrence if the peer sends a faulty AVP that we need to
- %% respond sensibly to. Log the occurence for traceability,
- %% but the peer will also receive info in the resulting
- %% answer-message.
- diameter_lib:log({decode, failure},
- ?MODULE,
- ?LINE,
- {Reason, Avp, erlang:get_stacktrace()}),
- {Rec, Failed} = Acc,
- {[Avp|Avps], {Rec, [rc(Reason, Avp) | Failed]}}
+ d(is_failed(), Reason, Name, trim(Avp), Acc)
+ after
+ reset(?STRICT_KEY, Strict),
+ reset(?FAILED_KEY, Failed)
end.
+%% trim/1
+%%
+%% Remove any extra bit that was added in diameter_codec to induce a
+%% 5014 error.
+
+trim(#diameter_avp{data = <<0:1, Bin/binary>>} = Avp) ->
+ Avp#diameter_avp{data = Bin};
+
+trim(Avps)
+ when is_list(Avps) ->
+ lists:map(fun trim/1, Avps);
+
+trim(Avp) ->
+ Avp.
+
+%% dict/1
+%%
+%% Retrieve the dictionary for the best-effort decode of Failed-AVP,
+%% as put by diameter_codec:decode/2. See that function for the
+%% explanation.
+
+dict(true) ->
+ case get({diameter_codec, dictionary}) of
+ undefined ->
+ ?MODULE;
+ Mod ->
+ Mod
+ end;
+
+dict(_) ->
+ ?MODULE.
+
+%% g/5
+
+%% Ignore decode errors within Failed-AVP (best-effort) ...
+g(true, [_Error | Rec], Name, Avp, Acc, _ComponentAvps) ->
+ decode_AVP(Name, Avp#diameter_avp{value = Rec}, Acc);
+g(true, _Error, Name, Avp, Acc, _ComponentAvps) ->
+ decode_AVP(Name, Avp, Acc);
+
+%% ... or not.
+g(false, [Error | _Rec], _Name, Avp, Acc, ComponentAvps) ->
+ g(Error, Avp, Acc, ComponentAvps);
+g(false, Error, _Name, Avp, Acc, ComponentAvps) ->
+ g(Error, Avp, Acc, ComponentAvps).
+
+%% g/4
+
+g({RC, ErrorData}, Avp, Acc, ComponentAvps) ->
+ {Avps, {Rec, Errors}} = Acc,
+ E = Avp#diameter_avp{data = [ErrorData]},
+ {[[Avp | trim(ComponentAvps)] | Avps], {Rec, [{RC, E} | Errors]}}.
+
+%% d/5
+
+%% Ignore a decode error within Failed-AVP ...
+d(true, _, Name, Avp, Acc) ->
+ decode_AVP(Name, Avp, Acc);
+
+%% ... or not. Failures here won't be visible since they're a "normal"
+%% occurrence if the peer sends a faulty AVP that we need to respond
+%% sensibly to. Log the occurence for traceability, but the peer will
+%% also receive info in the resulting answer message.
+d(false, Reason, Name, Avp, {Avps, Acc}) ->
+ Stack = diameter_lib:get_stacktrace(),
+ diameter_lib:log(decode_error,
+ ?MODULE,
+ ?LINE,
+ {Name, Avp#diameter_avp.name, Stack}),
+ {Rec, Failed} = Acc,
+ {[Avp|Avps], {Rec, [rc(Reason, Avp) | Failed]}}.
+
+%% relax/2
+
+%% Set false in the process dictionary as soon as we see a Grouped AVP
+%% that doesn't set the M-bit, so that is_strict() can say whether or
+%% not to ignore the M-bit on an encapsulated AVP.
+relax('Grouped', M) ->
+ case getr(?STRICT_KEY) of
+ undefined when not M ->
+ putr(?STRICT_KEY, M);
+ _ ->
+ false
+ end;
+relax(_, _) ->
+ false.
+
+is_strict() ->
+ diameter_codec:getopt(strict_mbit)
+ andalso false /= getr(?STRICT_KEY).
+
+%% relax/1
+%%
+%% Set true in the process dictionary as soon as we see Failed-AVP.
+%% Matching on 'Failed-AVP' assumes that this is the RFC AVP.
+%% Strictly, this doesn't need to be the case.
+
+relax('Failed-AVP') ->
+ putr(?FAILED_KEY, true);
+
+relax(_) ->
+ is_failed().
+
+%% is_failed/0
+%%
+%% Is the AVP currently being decoded nested within Failed-AVP? Note
+%% that this is only true when Failed-AVP is the parent. In
+%% particular, it's not true when Failed-AVP itself is being decoded
+%% (unless nested).
+
+is_failed() ->
+ true == getr(?FAILED_KEY).
+
+%% is_failed/1
+
+is_failed(Name) ->
+ 'Failed-AVP' == Name orelse is_failed().
+
+%% reset/2
+
+reset(Key, undefined) ->
+ eraser(Key);
+reset(_, _) ->
+ ok.
+
%% decode_AVP/3
%%
%% Don't know this AVP: see if it can be packed in an 'AVP' field
%% undecoded. Note that the type field is 'undefined' in this case.
decode_AVP(Name, Avp, {Avps, Acc}) ->
- {[Avp | Avps], pack_AVP(Name, Avp, Acc)}.
+ {[trim(Avp) | Avps], pack_AVP(Name, Avp, Acc)}.
%% rc/1
%% diameter_types will raise an error of this form to communicate
%% DIAMETER_INVALID_AVP_LENGTH (5014). A module specified to a
-%% @custom_types tag in a spec file can also raise an error of this
-%% form.
+%% @custom_types tag in a dictionary file can also raise an error of
+%% this form.
rc({'DIAMETER', 5014 = RC, _}, #diameter_avp{name = AvpName} = Avp) ->
{RC, Avp#diameter_avp{data = empty_value(AvpName)}};
@@ -310,15 +545,25 @@ pack_avp(_, Arity, Avp, Acc) ->
%% pack_AVP/3
-%% Give Failed-AVP special treatment since it'll contain any
-%% unrecognized mandatory AVP's.
-pack_AVP(Name, #diameter_avp{is_mandatory = true} = Avp, Acc)
- when Name /= 'Failed-AVP' ->
+%% Length failure was induced because of a header/payload length
+%% mismatch. The AVP Length is reset to match the received data if
+%% this AVP is encoded in an answer message, since the length is
+%% computed.
+%%
+%% Data is a truncated header if command_code = undefined, otherwise
+%% payload bytes. The former is padded to the length of a header if
+%% the AVP reaches an outgoing encode in diameter_codec.
+%%
+%% RFC 6733 says that an AVP returned with 5014 can contain a minimal
+%% payload for the AVP's type, but in this case we don't know the
+%% type.
+
+pack_AVP(_, #diameter_avp{data = <<0:1, Data/binary>>} = Avp, Acc) ->
{Rec, Failed} = Acc,
- {Rec, [{5001, Avp} | Failed]};
+ {Rec, [{5014, Avp#diameter_avp{data = Data}} | Failed]};
-pack_AVP(Name, #diameter_avp{is_mandatory = M} = Avp, Acc) ->
- case avp_arity(Name, 'AVP') of
+pack_AVP(Name, #diameter_avp{is_mandatory = M, name = AvpName} = Avp, Acc) ->
+ case pack_arity(Name, AvpName, M) of
0 ->
{Rec, Failed} = Acc,
{Rec, [{if M -> 5001; true -> 5008 end, Avp} | Failed]};
@@ -326,6 +571,32 @@ pack_AVP(Name, #diameter_avp{is_mandatory = M} = Avp, Acc) ->
pack(Arity, 'AVP', Avp, Acc)
end.
+%% Give Failed-AVP special treatment since (1) it'll contain any
+%% unrecognized mandatory AVP's and (2) the RFC 3588 grammar failed to
+%% allow for Failed-AVP in an answer-message.
+
+pack_arity(Name, AvpName, M) ->
+
+ %% Not testing just Name /= 'Failed-AVP' means we're changing the
+ %% packing of AVPs nested within Failed-AVP, but the point of
+ %% ignoring errors within Failed-AVP is to decode as much as
+ %% possible, and failing because a mandatory AVP couldn't be
+ %% packed into a dedicated field defeats that point. Note
+ %% is_failed/1 since is_failed/0 will return false when packing
+ %% 'AVP' within Failed-AVP.
+
+ pack_arity(is_failed(Name)
+ orelse {Name, AvpName} == {'answer-message', 'Failed-AVP'}
+ orelse not M
+ orelse not is_strict(),
+ Name).
+
+pack_arity(true, Name) ->
+ avp_arity(Name, 'AVP');
+
+pack_arity(false, _) ->
+ 0.
+
%% 3588:
%%
%% DIAMETER_AVP_UNSUPPORTED 5001
@@ -357,14 +628,17 @@ pack(undefined, 1, FieldName, Avp, Acc) ->
%% AVP MUST be included and contain a copy of the first instance of
%% the offending AVP that exceeded the maximum number of occurrences
%%
+
pack(_, 1, _, Avp, {Rec, Failed}) ->
{Rec, [{5009, Avp} | Failed]};
-pack(L, {_, Max}, _, Avp, {Rec, Failed})
- when length(L) == Max ->
- {Rec, [{5009, Avp} | Failed]};
-
-pack(L, _, FieldName, Avp, Acc) ->
- p(FieldName, fun(V) -> [V|L] end, Avp, Acc).
+pack(L, {_, Max}, FieldName, Avp, Acc) ->
+ case '*' /= Max andalso has_prefix(Max, L) of
+ true ->
+ {Rec, Failed} = Acc,
+ {Rec, [{5009, Avp} | Failed]};
+ false ->
+ p(FieldName, fun(V) -> [V|L] end, Avp, Acc)
+ end.
%% p/4
@@ -380,22 +654,55 @@ value(_, Avp) ->
%% # grouped_avp/3
%% ---------------------------------------------------------------------------
--spec grouped_avp(decode, avp_name(), binary())
+-spec grouped_avp(decode, avp_name(), bitstring())
-> {avp_record(), [avp()]};
(encode, avp_name(), avp_record() | avp_values())
-> binary()
| no_return().
+%% Length error induced by diameter_codec:collect_avps/1: the AVP
+%% length in the header was too short (insufficient for the extracted
+%% header) or too long (past the end of the message). An empty payload
+%% is sufficient according to the RFC text for 5014.
+grouped_avp(decode, _Name, <<0:1, _/binary>>) ->
+ throw({?TAG, {grouped, {5014, []}, []}});
+
grouped_avp(decode, Name, Data) ->
- {Rec, Avps, []} = decode_avps(Name, diameter_codec:collect_avps(Data)),
- {Rec, Avps};
-%% A failed match here will result in 5004. Note that this is the only
-%% AVP type that doesn't just return the decoded record, also
-%% returning the list of component AVP's.
+ grouped_decode(Name, diameter_codec:collect_avps(Data));
grouped_avp(encode, Name, Data) ->
encode_avps(Name, Data).
+%% grouped_decode/2
+%%
+%% Note that Grouped is the only AVP type that doesn't just return a
+%% decoded value, also returning the list of component diameter_avp
+%% records.
+
+%% Length error in trailing component AVP.
+grouped_decode(_Name, {Error, Acc}) ->
+ {5014, Avp} = Error,
+ throw({?TAG, {grouped, Error, [Avp | Acc]}});
+
+%% 7.5. Failed-AVP AVP
+
+%% In the case where the offending AVP is embedded within a Grouped AVP,
+%% the Failed-AVP MAY contain the grouped AVP, which in turn contains
+%% the single offending AVP. The same method MAY be employed if the
+%% grouped AVP itself is embedded in yet another grouped AVP and so on.
+%% In this case, the Failed-AVP MAY contain the grouped AVP hierarchy up
+%% to the single offending AVP. This enables the recipient to detect
+%% the location of the offending AVP when embedded in a group.
+
+%% An error in decoding a component AVP throws the first fauly
+%% component, which the catch in d/3 wraps in the Grouped AVP in
+%% question. A partially decoded record is only used when ignoring
+%% errors in Failed-AVP.
+grouped_decode(Name, ComponentAvps) ->
+ {Rec, Avps, Es} = decode_avps(Name, ComponentAvps),
+ [] == Es orelse throw({?TAG, {grouped, [{_,_} = hd(Es) | Rec], Avps}}),
+ {Rec, Avps}.
+
%% ---------------------------------------------------------------------------
%% # empty_group/1
%% ---------------------------------------------------------------------------
diff --git a/lib/diameter/src/Makefile b/lib/diameter/src/Makefile
index 578bbaee2e..9afccf298c 100644
--- a/lib/diameter/src/Makefile
+++ b/lib/diameter/src/Makefile
@@ -1,7 +1,7 @@
#
# %CopyrightBegin%
#
-# Copyright Ericsson AB 2010-2013. All Rights Reserved.
+# Copyright Ericsson AB 2010-2014. All Rights Reserved.
#
# The contents of this file are subject to the Erlang Public License,
# Version 1.1, (the "License"); you may not use this file except in
@@ -41,7 +41,7 @@ INCDIR = ../include
ABS_EBIN := $(shell cd $(EBIN) && pwd)
# Where make should look for dependencies.
-VPATH = .:base:compiler:transport:gen
+VPATH = .:base:compiler:transport:gen:info
# ----------------------------------------------------
# Target specs
@@ -55,13 +55,13 @@ DICT_ERLS = $(DICT_MODULES:%=%.erl)
DICT_HRLS = $(DICT_MODULES:%=%.hrl)
# Modules to build before compiling dictionaries.
-COMPILER_MODULES = $(notdir $(filter compiler/%, $(CT_MODULES))) \
- $(DICT_YRL)
+COMPILER_MODULES = $(notdir $(CT_MODULES)) $(DICT_YRL)
# All handwritten modules from which a depend.mk is generated.
MODULES = \
$(RT_MODULES) \
- $(CT_MODULES)
+ $(CT_MODULES) \
+ $(INFO_MODULES)
# Modules whose names are inserted into the app file.
APP_MODULES = \
@@ -72,6 +72,7 @@ APP_MODULES = \
TARGET_MODULES = \
$(APP_MODULES) \
$(CT_MODULES) \
+ $(INFO_MODULES) \
$(DICT_YRL:%=gen/%)
# What to build for the 'opt' target.
@@ -147,14 +148,19 @@ gen/$(DICT_YRL).erl: compiler/$(DICT_YRL).yrl
$(ERLC) -Werror -o $(@D) $<
# Generate the app file.
-$(APP_TARGET): $(APP_SRC) ../vsn.mk modules.mk
+$(APP_TARGET): $(APP_SRC) ../vsn.mk modules.mk app.sed
$(gen_verbose) \
M=`echo $(notdir $(APP_MODULES)) | tr ' ' ,`; \
+ C=`echo $(COMPILER_MODULES) | tr ' ' ,`; \
+ I=`echo $(notdir $(INFO_MODULES)) | tr ' ' ,`; \
R=`echo $(REGISTERED) | tr ' ' ,`; \
sed -e 's;%VSN%;$(VSN);' \
-e "s;%MODULES%;$$M;" \
+ -e "s;%COMPILER%;$$C;" \
+ -e "s;%INFO%;$$I;" \
-e "s;%REGISTERED%;$$R;" \
- $< > $@
+ $< \
+ | sed -f app.sed > $@
$(APPUP_TARGET): $(APPUP_SRC) ../vsn.mk
$(vsn_verbose) \
@@ -177,6 +183,8 @@ info:
@echo
@$(call list,CT_MODULES)
@echo
+ @$(call list,INFO_MODULES)
+ @echo
@$(call list,TARGET_MODULES)
@echo
@$(call list,TARGET_DIRS)
@@ -216,7 +224,7 @@ dialyze: opt $(PLT)
-Wno_improper_lists \
$(EBIN)/diameter_gen_base_rfc3588.$(EMULATOR) \
$(patsubst %, $(EBIN)/%.$(EMULATOR), \
- $(notdir $(RT_MODULES) $(CT_MODULES)))
+ $(notdir $(RT_MODULES) $(CT_MODULES) $(INFO_MODULES)))
# Omit all but the common dictionary module since these
# (diameter_gen_relay in particular) generate warning depending on how
# much of the included diameter_gen.hrl they use.
diff --git a/lib/diameter/src/app.sed b/lib/diameter/src/app.sed
new file mode 100644
index 0000000000..7916f65002
--- /dev/null
+++ b/lib/diameter/src/app.sed
@@ -0,0 +1,40 @@
+#
+# %CopyrightBegin%
+#
+# Copyright Ericsson AB 2014. All Rights Reserved.
+#
+# The contents of this file are subject to the Erlang Public License,
+# Version 1.1, (the "License"); you may not use this file except in
+# compliance with the License. You should have received a copy of the
+# Erlang Public License along with this software. If not, it can be
+# retrieved online at http://www.erlang.org/.
+#
+# Software distributed under the License is distributed on an "AS IS"
+# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+# the License for the specific language governing rights and limitations
+# under the License.
+#
+# %CopyrightEnd%
+
+#
+# Generate runtime_dependencies from applications to avoid having to
+# specify the same application more than once.
+#
+
+/{runtime_dependencies,/b v
+/{[-a-z]*, "[0-9.]*"}/!b
+/{vsn,/b
+
+/%%/!H
+s/{\([^,]*\)[^}]*}/\1/g
+s/%%/%,/
+b
+
+:v
+
+p
+x
+s/\n//
+s/%//g
+s/\n */ /g
+s/{\([^,]*\), "\([^"]*"\)}/"\1-\2/g
diff --git a/lib/diameter/src/base/diameter.erl b/lib/diameter/src/base/diameter.erl
index 77200cc7d0..9d71bcbbf8 100644
--- a/lib/diameter/src/base/diameter.erl
+++ b/lib/diameter/src/base/diameter.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -45,6 +45,7 @@
-export_type([evaluable/0,
restriction/0,
+ message_length/0,
remotes/0,
sequence/0,
app_alias/0,
@@ -298,6 +299,9 @@ call(SvcName, App, Message) ->
| [node()]
| evaluable().
+-type message_length()
+ :: 0..16#FFFFFF.
+
%% Options passed to start_service/2
-type service_opt()
@@ -306,6 +310,9 @@ call(SvcName, App, Message) ->
| {restrict_connections, restriction()}
| {sequence, sequence() | evaluable()}
| {share_peers, remotes()}
+ | {string_decode, boolean()}
+ | {strict_mbit, boolean()}
+ | {incoming_maxlen, message_length()}
| {use_shared_peers, remotes()}
| {spawn_opt, list()}.
@@ -337,13 +344,16 @@ call(SvcName, App, Message) ->
:: {transport_module, atom()}
| {transport_config, any()}
| {transport_config, any(), 'Unsigned32'() | infinity}
+ | {pool_size, pos_integer()}
| {applications, [app_alias()]}
| {capabilities, [capability()]}
| {capabilities_cb, evaluable()}
| {capx_timeout, 'Unsigned32'()}
| {disconnect_cb, evaluable()}
+ | {dpr_timeout, 'Unsigned32'()}
+ | {dpa_timeout, 'Unsigned32'()}
| {length_errors, exit | handle | discard}
- | {reconnect_timer, 'Unsigned32'()}
+ | {connect_timer, 'Unsigned32'()}
| {watchdog_timer, 'Unsigned32'() | {module(), atom(), list()}}
| {watchdog_config, [{okay|suspect, non_neg_integer()}]}
| {spawn_opt, list()}
diff --git a/lib/diameter/src/base/diameter_capx.erl b/lib/diameter/src/base/diameter_capx.erl
index 1a931a9854..7dc61f229f 100644
--- a/lib/diameter/src/base/diameter_capx.erl
+++ b/lib/diameter/src/base/diameter_capx.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -50,7 +50,8 @@
-export([build_CER/2,
recv_CER/3,
recv_CEA/3,
- make_caps/2]).
+ make_caps/2,
+ binary_caps/1]).
-include_lib("diameter/include/diameter.hrl").
-include("diameter_internal.hrl").
@@ -115,7 +116,8 @@ mk_caps(Caps0, Opts) ->
-define(SC(K,F),
set_cap({K, Val}, {Caps, #diameter_caps{F = false} = C}) ->
- {Caps#diameter_caps{F = cap(K, Val)}, C#diameter_caps{F = true}}).
+ {Caps#diameter_caps{F = cap(K, copy(Val))},
+ C#diameter_caps{F = true}}).
?SC('Origin-Host', origin_host);
?SC('Origin-Realm', origin_realm);
@@ -168,12 +170,13 @@ ipaddr(A) ->
%%
%% Build a CER record to send to a remote peer.
-%% Use the fact that diameter_caps has the same field names as CER.
+%% Use the fact that diameter_caps is expected to have the same field
+%% names as CER.
bCER(#diameter_caps{} = Rec, Dict) ->
- Values = lists:zip(Dict:'#info-'(diameter_base_CER, fields),
+ RecName = Dict:msg2rec('CER'),
+ Values = lists:zip(Dict:'#info-'(RecName, fields),
tl(tuple_to_list(Rec))),
- Dict:'#new-'(diameter_base_CER, [{K, map(K, V, Dict)}
- || {K,V} <- Values]).
+ Dict:'#new-'(RecName, [{K, map(K, V, Dict)} || {K,V} <- Values]).
%% map/3
%%
@@ -186,8 +189,9 @@ bCER(#diameter_caps{} = Rec, Dict) ->
%% since the corresponding dictionaries expect different values for a
%% 'Vendor-Id': a list for 3588, an integer for 6733.
-map('Vendor-Specific-Application-Id', L, Dict) ->
- Rec = Dict:'#new-'('diameter_base_Vendor-Specific-Application-Id', []),
+map('Vendor-Specific-Application-Id' = T, L, Dict) ->
+ RecName = Dict:name2rec(T),
+ Rec = Dict:'#new-'(RecName, []),
Def = Dict:'#get-'('Vendor-Id', Rec),
[vsa(V, Def) || V <- L];
map(_, V, _) ->
@@ -342,8 +346,9 @@ cs(LS, RS) ->
%% CER is a subset of CEA, the latter adding Result-Code and a few
%% more AVP's.
cea_from_cer(CER, Dict) ->
- [diameter_base_CER | Values] = Dict:'#get-'(CER),
- Dict:'#set-'(Values, Dict:'#new-'(diameter_base_CEA)).
+ RecName = Dict:msg2rec('CEA'),
+ [_ | Values] = Dict:'#get-'(CER),
+ Dict:'#set-'(Values, Dict:'#new-'(RecName)).
%% rCEA/3
@@ -372,10 +377,10 @@ capx_to_caps(CEX, Dict) ->
'Firmware-Revision',
'AVP'],
CEX),
- #diameter_caps{origin_host = OH,
- origin_realm = OR,
+ #diameter_caps{origin_host = copy(OH),
+ origin_realm = copy(OR),
vendor_id = VId,
- product_name = PN,
+ product_name = copy(PN),
origin_state_id = OSI,
host_ip_address = IP,
supported_vendor_id = SV,
@@ -386,6 +391,32 @@ capx_to_caps(CEX, Dict) ->
firmware_revision = FR,
avp = X}.
+%% Copy binaries to avoid retaining a reference to a large binary
+%% containing AVPs we aren't interested in.
+copy(B)
+ when is_binary(B) ->
+ binary:copy(B);
+
+copy(T) ->
+ T.
+
+%% binary_caps/1
+%%
+%% Encode stringish capabilities with {string_decode, false}.
+
+binary_caps(Caps) ->
+ lists:foldl(fun bcaps/2, Caps, [#diameter_caps.origin_host,
+ #diameter_caps.origin_realm,
+ #diameter_caps.product_name]).
+
+bcaps(N, Caps) ->
+ case element(N, Caps) of
+ undefined ->
+ Caps;
+ V ->
+ setelement(N, Caps, iolist_to_binary(V))
+ end.
+
%% ---------------------------------------------------------------------------
%% ---------------------------------------------------------------------------
diff --git a/lib/diameter/src/base/diameter_codec.erl b/lib/diameter/src/base/diameter_codec.erl
index 1d647b8c87..aab8b5887e 100644
--- a/lib/diameter/src/base/diameter_codec.erl
+++ b/lib/diameter/src/base/diameter_codec.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -22,6 +22,8 @@
-export([encode/2,
decode/2,
decode/3,
+ setopts/1,
+ getopt/1,
collect_avps/1,
decode_header/1,
sequence_numbers/1,
@@ -59,6 +61,52 @@
%% +-+-+-+-+-+-+-+-+-+-+-+-+-
%%% ---------------------------------------------------------------------------
+%%% # setopts/1
+%%% # getopt/1
+%%% ---------------------------------------------------------------------------
+
+%% These functions are a compromise in the same vein as the use of the
+%% process dictionary in diameter_gen.hrl in generated codec modules.
+%% Instead of rewriting the entire dictionary generation to pass
+%% encode/decode options around, the calling process sets them by
+%% calling setopts/1. At current, the only option is whether or not to
+%% decode binaries as strings, which is used by diameter_types.
+
+setopts(Opts)
+ when is_list(Opts) ->
+ lists:foreach(fun setopt/1, Opts).
+
+%% The default string_decode true is for backwards compatibility.
+setopt({K, false = B})
+ when K == string_decode;
+ K == strict_mbit ->
+ setopt(K, B);
+
+%% Regard anything but the generated RFC 3588 dictionary as modern.
+%% This affects the interpretation of defaults during the decode
+%% of values of type DiameterURI, this having changed from RFC 3588.
+%% (So much for backwards compatibility.)
+setopt({common_dictionary, diameter_gen_base_rfc3588}) ->
+ setopt(rfc, 3588);
+
+setopt(_) ->
+ ok.
+
+setopt(Key, Value) ->
+ put({diameter, Key}, Value).
+
+getopt(Key) ->
+ case get({diameter, Key}) of
+ undefined when Key == string_decode;
+ Key == strict_mbit ->
+ true;
+ undefined when Key == rfc ->
+ 6733;
+ V ->
+ V
+ end.
+
+%%% ---------------------------------------------------------------------------
%%% # encode/2
%%% ---------------------------------------------------------------------------
@@ -70,12 +118,15 @@ encode(Mod, #diameter_packet{} = Pkt) ->
try
e(Mod, Pkt)
catch
+ exit: {Reason, Stack, #diameter_header{} = H} = T ->
+ %% Exit with a header in the reason to let the caller
+ %% count encode errors.
+ ?LOG(encode_error, {Reason, Stack, H}),
+ exit({?MODULE, encode, T});
error: Reason ->
- %% Be verbose since a crash report may be truncated and
- %% encode errors are self-inflicted.
- X = {?MODULE, encode, {Reason, ?STACK}},
- diameter_lib:error_report(X, {?MODULE, encode, [Mod, Pkt]}),
- exit(X)
+ T = {Reason, diameter_lib:get_stacktrace()},
+ ?LOG(encode_error, T),
+ exit({?MODULE, encode, T})
end;
encode(Mod, Msg) ->
@@ -87,53 +138,62 @@ encode(Mod, Msg) ->
msg = Msg}).
e(_, #diameter_packet{msg = [#diameter_header{} = Hdr | As]} = Pkt) ->
- Avps = encode_avps(As),
- Length = size(Avps) + 20,
-
- #diameter_header{version = Vsn,
- cmd_code = Code,
- application_id = Aid,
- hop_by_hop_id = Hid,
- end_to_end_id = Eid}
- = Hdr,
-
- Flags = make_flags(0, Hdr),
-
- Pkt#diameter_packet{header = Hdr,
- bin = <<Vsn:8, Length:24,
- Flags:8, Code:24,
- Aid:32,
- Hid:32,
- Eid:32,
- Avps/binary>>};
+ try encode_avps(reorder(As)) of
+ Avps ->
+ Length = size(Avps) + 20,
+
+ #diameter_header{version = Vsn,
+ cmd_code = Code,
+ application_id = Aid,
+ hop_by_hop_id = Hid,
+ end_to_end_id = Eid}
+ = Hdr,
+
+ Flags = make_flags(0, Hdr),
+
+ Pkt#diameter_packet{header = Hdr,
+ bin = <<Vsn:8, Length:24,
+ Flags:8, Code:24,
+ Aid:32,
+ Hid:32,
+ Eid:32,
+ Avps/binary>>}
+ catch
+ error: Reason ->
+ exit({Reason, diameter_lib:get_stacktrace(), Hdr})
+ end;
-e(Mod, #diameter_packet{header = Hdr, msg = Msg} = Pkt) ->
+e(Mod, #diameter_packet{header = Hdr0, msg = Msg} = Pkt) ->
#diameter_header{version = Vsn,
hop_by_hop_id = Hid,
end_to_end_id = Eid}
- = Hdr,
+ = Hdr0,
MsgName = rec2msg(Mod, Msg),
- {Code, Flags0, Aid} = msg_header(Mod, MsgName, Hdr),
- Flags = make_flags(Flags0, Hdr),
-
- Avps = encode_avps(Mod, MsgName, values(Msg)),
- Length = size(Avps) + 20,
-
- Pkt#diameter_packet{header = Hdr#diameter_header
- {length = Length,
- cmd_code = Code,
- application_id = Aid,
- is_request = 0 /= ?MASK(7, Flags),
- is_proxiable = 0 /= ?MASK(6, Flags),
- is_error = 0 /= ?MASK(5, Flags),
- is_retransmitted = 0 /= ?MASK(4, Flags)},
- bin = <<Vsn:8, Length:24,
- Flags:8, Code:24,
- Aid:32,
- Hid:32,
- Eid:32,
- Avps/binary>>}.
+ {Code, Flags0, Aid} = msg_header(Mod, MsgName, Hdr0),
+ Flags = make_flags(Flags0, Hdr0),
+ Hdr = Hdr0#diameter_header{cmd_code = Code,
+ application_id = Aid,
+ is_request = 0 /= ?MASK(7, Flags),
+ is_proxiable = 0 /= ?MASK(6, Flags),
+ is_error = 0 /= ?MASK(5, Flags),
+ is_retransmitted = 0 /= ?MASK(4, Flags)},
+ Values = values(Msg),
+
+ try encode_avps(Mod, MsgName, Values) of
+ Avps ->
+ Length = size(Avps) + 20,
+ Pkt#diameter_packet{header = Hdr#diameter_header{length = Length},
+ bin = <<Vsn:8, Length:24,
+ Flags:8, Code:24,
+ Aid:32,
+ Hid:32,
+ Eid:32,
+ Avps/binary>>}
+ catch
+ error: Reason ->
+ exit({Reason, diameter_lib:get_stacktrace(), Hdr})
+ end.
%% make_flags/2
@@ -171,26 +231,50 @@ values(Avps) ->
%% Message as a list of #diameter_avp{} ...
encode_avps(_, _, [#diameter_avp{} | _] = Avps) ->
- encode_avps(reorder(Avps, [], Avps));
+ encode_avps(reorder(Avps));
%% ... or as a tuple list or record.
encode_avps(Mod, MsgName, Values) ->
Mod:encode_avps(MsgName, Values).
%% reorder/1
+%%
+%% Reorder AVPs for the relay case using the index field of
+%% diameter_avp records. Decode populates this field in collect_avps
+%% and presents AVPs in reverse order. A relay then sends the reversed
+%% list with a Route-Record AVP prepended. The goal here is just to do
+%% lists:reverse/1 in Grouped AVPs and the outer list, but only in the
+%% case there are indexed AVPs at all, so as not to reverse lists that
+%% have been explicilty sent (unindexed, in the desired order) as a
+%% diameter_avp list. The effect is the same as lists:keysort/2, but
+%% only on the cases we expect, not a general sort.
+
+reorder(Avps) ->
+ case reorder(Avps, []) of
+ false ->
+ Avps;
+ Sorted ->
+ Sorted
+ end.
-reorder([#diameter_avp{index = 0} | _] = Avps, Acc, _) ->
+%% reorder/3
+
+%% In case someone has reversed the list already. (Not likely.)
+reorder([#diameter_avp{index = 0} | _] = Avps, Acc) ->
Avps ++ Acc;
-reorder([#diameter_avp{index = N} = A | Avps], Acc, _)
+%% Assume indexed AVPs are in reverse order.
+reorder([#diameter_avp{index = N} = A | Avps], Acc)
when is_integer(N) ->
lists:reverse(Avps, [A | Acc]);
-reorder([H | T], Acc, Avps) ->
- reorder(T, [H | Acc], Avps);
+%% An unindexed AVP.
+reorder([H | T], Acc) ->
+ reorder(T, [H | Acc]);
-reorder([], Acc, _) ->
- Acc.
+%% No indexed members.
+reorder([], _) ->
+ false.
%% encode_avps/1
@@ -225,15 +309,35 @@ rec2msg(Mod, Rec) ->
%% Unsuccessfully decoded AVPs will be placed in #diameter_packet.errors.
--spec decode(module(), #diameter_packet{} | bitstring())
+-spec decode(module() | {module(), module()}, #diameter_packet{} | binary())
-> #diameter_packet{}.
+%% An Answer setting the E-bit. The application dictionary is needed
+%% for the best-effort decode of Failed-AVP, and the best way to make
+%% this available to the AVP decode in diameter_gen.hrl, without
+%% having to rewrite the entire codec generation, is to place it in
+%% the process dictionary. It's the code in diameter_gen.hrl (that's
+%% included by every generated codec module) that looks for the entry.
+%% Not ideal, but it solves the problem relatively simply.
+decode({Mod, Mod}, Pkt) ->
+ decode(Mod, Pkt);
+decode({Mod, AppMod}, Pkt) ->
+ Key = {?MODULE, dictionary},
+ put(Key, AppMod),
+ try
+ decode(Mod, Pkt)
+ after
+ erase(Key)
+ end;
+
+%% Or not: a request, or an answer not setting the E-bit.
decode(Mod, Pkt) ->
decode(Mod:id(), Mod, Pkt).
-%% If we're a relay application then just extract the avp's without
-%% any decoding of their data since we don't know the application in
-%% question.
+%% decode/3
+
+%% Relay application: just extract the avp's without any decoding of
+%% their data since we don't know the application in question.
decode(?APP_ID_RELAY, _, #diameter_packet{} = Pkt) ->
case collect_avps(Pkt) of
{E, As} ->
@@ -259,34 +363,36 @@ decode(_, Mod, #diameter_packet{header = Hdr} = Pkt) ->
decode_avps(MsgName, Mod, Pkt, collect_avps(Pkt));
decode(Id, Mod, Bin)
- when is_bitstring(Bin) ->
+ when is_binary(Bin) ->
decode(Id, Mod, #diameter_packet{header = decode_header(Bin), bin = Bin}).
+%% decode_avps/4
+
decode_avps(MsgName, Mod, Pkt, {E, Avps}) ->
- ?LOG(invalid, Pkt#diameter_packet.bin),
+ ?LOG(invalid_avp_length, Pkt#diameter_packet.header),
#diameter_packet{errors = Failed}
= P
= decode_avps(MsgName, Mod, Pkt, Avps),
P#diameter_packet{errors = [E | Failed]};
-decode_avps('', Mod, Pkt, Avps) -> %% unknown message ...
- ?LOG(unknown, {Mod, Pkt#diameter_packet.header}),
+decode_avps('', _, Pkt, Avps) -> %% unknown message ...
+ ?LOG(unknown_message, Pkt#diameter_packet.header),
Pkt#diameter_packet{avps = lists:reverse(Avps),
errors = [3001]}; %% DIAMETER_COMMAND_UNSUPPORTED
%% msg = undefined identifies this case.
decode_avps(MsgName, Mod, Pkt, Avps) -> %% ... or not
- {Rec, As, Failed} = Mod:decode_avps(MsgName, Avps),
- ?LOGC([] /= Failed, failed, {Mod, Failed}),
+ {Rec, As, Errors} = Mod:decode_avps(MsgName, Avps),
+ ?LOGC([] /= Errors, decode_errors, Pkt#diameter_packet.header),
Pkt#diameter_packet{msg = Rec,
- errors = Failed,
+ errors = Errors,
avps = As}.
%%% ---------------------------------------------------------------------------
%%% # decode_header/1
%%% ---------------------------------------------------------------------------
--spec decode_header(bitstring())
+-spec decode_header(binary())
-> #diameter_header{}
| false.
@@ -297,7 +403,7 @@ decode_header(<<Version:8,
ApplicationId:32,
HopByHopId:32,
EndToEndId:32,
- _/bitstring>>) ->
+ _/binary>>) ->
<<R:1, P:1, E:1, T:1, _:4>>
= CmdFlags,
%% 3588 (ch 3) says that reserved bits MUST be set to 0 and ignored
@@ -356,6 +462,9 @@ sequence_numbers(#diameter_packet{bin = Bin})
sequence_numbers(#diameter_packet{header = #diameter_header{} = H}) ->
sequence_numbers(H);
+sequence_numbers(#diameter_packet{msg = [#diameter_header{} = H | _]}) ->
+ sequence_numbers(H);
+
sequence_numbers(#diameter_header{hop_by_hop_id = H,
end_to_end_id = E}) ->
{H,E};
@@ -410,7 +519,7 @@ msg_id(#diameter_header{application_id = A,
is_request = R}) ->
{A, C, if R -> 1; true -> 0 end};
-msg_id(<<_:32, Rbit:1, _:7, CmdCode:24, ApplId:32, _/bitstring>>) ->
+msg_id(<<_:32, Rbit:1, _:7, CmdCode:24, ApplId:32, _/binary>>) ->
{ApplId, CmdCode, Rbit}.
%%% ---------------------------------------------------------------------------
@@ -421,17 +530,18 @@ msg_id(<<_:32, Rbit:1, _:7, CmdCode:24, ApplId:32, _/bitstring>>) ->
%% order in the binary. Note also that grouped avp's aren't unraveled,
%% only those at the top level.
--spec collect_avps(#diameter_packet{} | bitstring())
+-spec collect_avps(#diameter_packet{} | binary())
-> [Avp]
| {Error, [Avp]}
when Avp :: #diameter_avp{},
Error :: {5014, #diameter_avp{}}.
collect_avps(#diameter_packet{bin = Bin}) ->
- <<_:20/binary, Avps/bitstring>> = Bin,
+ <<_:20/binary, Avps/binary>> = Bin,
collect_avps(Avps);
-collect_avps(Bin) ->
+collect_avps(Bin)
+ when is_binary(Bin) ->
collect_avps(Bin, 0, []).
collect_avps(<<>>, _, Acc) ->
@@ -461,7 +571,9 @@ collect_avps(Bin, N, Acc) ->
split_avp(Bin) ->
{Code, V, M, P, Len, HdrLen} = split_head(Bin),
- {Data, B} = split_data(Bin, HdrLen, Len - HdrLen),
+
+ <<_:HdrLen/binary, Rest/binary>> = Bin,
+ {Data, B} = split_data(Rest, Len - HdrLen),
{B, #diameter_avp{code = Code,
vendor_id = V,
@@ -471,14 +583,16 @@ split_avp(Bin) ->
%% split_head/1
-split_head(<<Code:32, 1:1, M:1, P:1, _:5, Len:24, V:32, _/bitstring>>) ->
+split_head(<<Code:32, 1:1, M:1, P:1, _:5, Len:24, V:32, _/binary>>) ->
{Code, V, M, P, Len, 12};
-split_head(<<Code:32, 0:1, M:1, P:1, _:5, Len:24, _/bitstring>>) ->
+split_head(<<Code:32, 0:1, M:1, P:1, _:5, Len:24, _/binary>>) ->
{Code, undefined, M, P, Len, 8};
+%% Header is truncated.
split_head(Bin) ->
?THROW({5014, #diameter_avp{data = Bin}}).
+%% Note that pack_avp/1 will pad this at encode if sent in a Failed-AVP.
%% 3588:
%%
@@ -508,54 +622,59 @@ split_head(Bin) ->
%% AVP header with zero up to the minimum AVP header length.
%%
%% The underlined clause must be in error since (1) a header less than
-%% the minimum value mean we don't know the identity of the AVP and
+%% the minimum value mean we might not know the identity of the AVP and
%% (2) the last sentence covers this case.
%% split_data/3
-split_data(Bin, HdrLen, Len)
- when 0 =< Len ->
- split_data(Bin, HdrLen, Len, (4 - (Len rem 4)) rem 4);
-
-split_data(_, _, _) ->
- invalid_avp_length().
+split_data(Bin, Len) ->
+ Pad = (4 - (Len rem 4)) rem 4,
-%% split_data/4
+ %% Len might be negative here, but that ensures the failure of the
+ %% binary match.
-split_data(Bin, HdrLen, Len, Pad) ->
- <<_:HdrLen/binary, T/bitstring>> = Bin,
- case T of
- <<Data:Len/binary, _:Pad/binary, Rest/bitstring>> ->
+ case Bin of
+ <<Data:Len/binary, _:Pad/binary, Rest/binary>> ->
{Data, Rest};
_ ->
- invalid_avp_length()
+ %% Header length points past the end of the message, or
+ %% doesn't span the header. As stated in the 6733 text
+ %% above, it's sufficient to return a zero-filled minimal
+ %% payload if this is a request. Do this (in cases that we
+ %% know the type) by inducing a decode failure and letting
+ %% the dictionary's decode (in diameter_gen) deal with it.
+ %%
+ %% Note that the extra bit can only occur in the trailing
+ %% AVP of a message or Grouped AVP, since a faulty AVP
+ %% Length is otherwise indistinguishable from a correct
+ %% one here, since we don't know the types of the AVPs
+ %% being extracted.
+ {<<0:1, Bin/binary>>, <<>>}
end.
-%% invalid_avp_length/0
-%%
-%% AVP Length doesn't mesh with payload. Induce a decode error by
-%% returning a payload that no valid Diameter type can have. This is
-%% so that a known AVP will result in 5014 error with a zero'd
-%% payload. Here we simply don't know how to construct this payload.
-%% (Yes, this solution is an afterthought.)
-
-invalid_avp_length() ->
- {<<0:1>>, <<>>}.
-
%%% ---------------------------------------------------------------------------
%%% # pack_avp/1
%%% ---------------------------------------------------------------------------
%% The normal case here is data as an #diameter_avp{} list or an
%% iolist, which are the cases that generated codec modules use. The
-%% other case is as a convenience in the relay case in which the
+%% other cases are a convenience in the relay case in which the
%% dictionary doesn't know about specific AVP's.
-%% Grouped AVP whose components need packing ...
-pack_avp(#diameter_avp{data = [#diameter_avp{} | _] = Avps} = A) ->
- pack_avp(A#diameter_avp{data = encode_avps(Avps)});
+%% Decoded Grouped AVP with decoded components: ignore components
+%% since they're already encoded in the Grouped AVP.
+pack_avp([#diameter_avp{} = Grouped | _Components]) ->
+ pack_avp(Grouped);
+
+%% Grouped AVP whose components need packing. It's intentional that
+%% this isn't equivalent to [Grouped | Components]: here the
+%% components need to be encoded before wrapping with the Grouped AVP,
+%% and the list is flat, nesting being accomplished in the data
+%% fields.
+pack_avp(#diameter_avp{data = [#diameter_avp{} | _] = Components} = Grouped) ->
+ pack_avp(Grouped#diameter_avp{data = encode_avps(Components)});
-%% ... data as a type/value tuple ...
+%% Data as a type/value tuple ...
pack_avp(#diameter_avp{data = {Type, Value}} = A)
when is_atom(Type) ->
pack_avp(A#diameter_avp{data = diameter_types:Type(encode, Value)});
@@ -573,17 +692,23 @@ pack_avp(#diameter_avp{data = {Dict, Name, Value}} = A) ->
{Name, Type} = Dict:avp_name(Code, Vid),
pack_avp(A#diameter_avp{data = {Hdr, {Type, Value}}});
-pack_avp(#diameter_avp{code = undefined, data = Bin})
- when is_binary(Bin) ->
+%% ... with a truncated header ...
+pack_avp(#diameter_avp{code = undefined, data = B})
+ when is_binary(B) ->
%% Reset the AVP Length of an AVP Header resulting from a 5014
%% error. The RFC doesn't explicitly say to do this but the
%% receiver can't correctly extract this and following AVP's
%% without a correct length. On the downside, the header doesn't
%% reveal if the received header has been padded.
- Pad = 8*header_length(Bin) - bit_size(Bin),
- Len = size(<<H:5/binary, _:24, T/binary>> = <<Bin/bitstring, 0:Pad>>),
+ Pad = 8*header_length(B) - bit_size(B),
+ Len = size(<<H:5/binary, _:24, T/binary>> = <<B/binary, 0:Pad>>),
<<H/binary, Len:24, T/binary>>;
+%% ... when ignoring errors in Failed-AVP ...
+%% ... during a relay encode ...
+pack_avp(#diameter_avp{data = <<0:1, B/binary>>} = A) ->
+ pack_avp(A#diameter_avp{data = B});
+
%% ... or as an iolist.
pack_avp(#diameter_avp{code = Code,
vendor_id = V,
diff --git a/lib/diameter/src/base/diameter_config.erl b/lib/diameter/src/base/diameter_config.erl
index fc5c284bf2..242b6b4d08 100644
--- a/lib/diameter/src/base/diameter_config.erl
+++ b/lib/diameter/src/base/diameter_config.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -35,10 +35,10 @@
%%
-module(diameter_config).
--compile({no_auto_import, [monitor/2]}).
-
-behaviour(gen_server).
+-compile({no_auto_import, [monitor/2]}).
+
-export([start_service/2,
stop_service/1,
add_transport/2,
@@ -158,7 +158,8 @@ stop_service(SvcName) ->
%% # add_transport/2
%% --------------------------------------------------------------------------
--spec add_transport(diameter:service_name(), {connect|listen, [diameter:transport_opt()]})
+-spec add_transport(diameter:service_name(),
+ {connect|listen, [diameter:transport_opt()]})
-> {ok, diameter:transport_ref()}
| {error, term()}.
@@ -531,13 +532,18 @@ opt({applications, As}) ->
opt({capabilities, Os}) ->
is_list(Os) andalso ok == encode_CER(Os);
-opt({capx_timeout, Tmo}) ->
+opt({K, Tmo})
+ when K == capx_timeout;
+ K == dpr_timeout;
+ K == dpa_timeout ->
?IS_UINT32(Tmo);
opt({length_errors, T}) ->
lists:member(T, [exit, handle, discard]);
-opt({reconnect_timer, Tmo}) ->
+opt({K, Tmo})
+ when K == reconnect_timer; %% deprecated
+ K == connect_timer ->
?IS_UINT32(Tmo);
opt({watchdog_timer, {M,F,A}})
@@ -552,6 +558,9 @@ opt({watchdog_config, L}) ->
opt({spawn_opt, Opts}) ->
is_list(Opts);
+opt({pool_size, N}) ->
+ is_integer(N) andalso 0 < N;
+
%% Options that we can't validate.
opt({K, _})
when K == transport_config;
@@ -636,13 +645,25 @@ make_config(SvcName, Opts) ->
{false, monitor},
{?NOMASK, sequence},
{nodes, restrict_connections},
+ {16#FFFFFF, incoming_maxlen},
+ {true, strict_mbit},
+ {true, string_decode},
{[], spawn_opt}]),
+ D = proplists:get_value(string_decode, SvcOpts, true),
+
#service{name = SvcName,
rec = #diameter_service{applications = Apps,
- capabilities = Caps},
+ capabilities = binary_caps(Caps, D)},
options = SvcOpts}.
+binary_caps(Caps, true) ->
+ Caps;
+binary_caps(Caps, false) ->
+ diameter_capx:binary_caps(Caps).
+
+%% make_opts/2
+
make_opts(Opts, Defs) ->
Known = [{K, get_opt(K, Opts, D)} || {D,K} <- Defs],
Unknown = Opts -- Known,
@@ -651,16 +672,28 @@ make_opts(Opts, Defs) ->
[{K, opt(K,V)} || {K,V} <- Known].
-opt(spawn_opt, L) ->
- is_list(L);
+opt(incoming_maxlen, N)
+ when 0 =< N, N < 1 bsl 24 ->
+ N;
+
+opt(spawn_opt, L)
+ when is_list(L) ->
+ L;
opt(K, false = B)
- when K /= sequence ->
+ when K == share_peers;
+ K == use_shared_peers;
+ K == monitor;
+ K == restrict_connections;
+ K == strict_mbit;
+ K == string_decode ->
B;
opt(K, true = B)
when K == share_peers;
- K == use_shared_peers ->
+ K == use_shared_peers;
+ K == strict_mbit;
+ K == string_decode ->
B;
opt(restrict_connections, T)
@@ -750,7 +783,7 @@ app_acc({application, Opts} = T, Acc) ->
Alias = get_opt(alias, Opts, Dict),
ModS = get_opt(state, Opts, Alias),
M = get_opt(call_mutates_state, Opts, false, [true]),
- A = get_opt(answer_errors, Opts, report, [callback, discard]),
+ A = get_opt(answer_errors, Opts, discard, [callback, report]),
P = get_opt(request_errors, Opts, answer_3xxx, [answer, callback]),
[#diameter_app{alias = Alias,
dictionary = Dict,
diff --git a/lib/diameter/src/base/diameter_lib.erl b/lib/diameter/src/base/diameter_lib.erl
index 44d81e2778..26cc6137a2 100644
--- a/lib/diameter/src/base/diameter_lib.erl
+++ b/lib/diameter/src/base/diameter_lib.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -25,13 +25,33 @@
now_diff/1,
time/1,
eval/1,
+ eval_name/1,
+ get_stacktrace/0,
ipaddr/1,
spawn_opts/2,
wait/1,
fold_tuple/3,
+ fold_n/3,
+ for_n/2,
log/4]).
%% ---------------------------------------------------------------------------
+%% # get_stacktrace/0
+%% ---------------------------------------------------------------------------
+
+%% Return a stacktrace with a leading, potentially large, argument
+%% list replaced by an arity. Trace on stacktrace/0 to see the
+%% original.
+
+get_stacktrace() ->
+ stacktrace(erlang:get_stacktrace()).
+
+stacktrace([{M,F,A,L} | T]) when is_list(A) ->
+ [{M, F, length(A), L} | T];
+stacktrace(L) ->
+ L.
+
+%% ---------------------------------------------------------------------------
%% # info_report/2
%% ---------------------------------------------------------------------------
@@ -60,17 +80,24 @@ warning_report(Reason, T) ->
report(fun error_logger:warning_report/1, Reason, T).
report(Fun, Reason, T) ->
- Fun([{why, Reason}, {who, self()}, {what, T}]),
+ Fun(io_lib:format("diameter: ~" ++ fmt(Reason) ++ "~n ~p~n",
+ [Reason, T])),
false.
+fmt(T) ->
+ if is_list(T) ->
+ "s";
+ true ->
+ "p"
+ end.
+
%% ---------------------------------------------------------------------------
%% # now_diff/1
%% ---------------------------------------------------------------------------
--spec now_diff(NowT)
+-spec now_diff(NowT :: erlang:timestamp())
-> {Hours, Mins, Secs, MicroSecs}
- when NowT :: {non_neg_integer(), 0..999999, 0..999999},
- Hours :: non_neg_integer(),
+ when Hours :: non_neg_integer(),
Mins :: 0..59,
Secs :: 0..59,
MicroSecs :: 0..999999.
@@ -78,7 +105,7 @@ report(Fun, Reason, T) ->
%% Return timer:now_diff(now(), NowT) as an {H, M, S, MicroS} tuple
%% instead of as integer microseconds.
-now_diff({_,_,_} = Time) ->
+now_diff(Time) ->
time(timer:now_diff(now(), Time)).
%% ---------------------------------------------------------------------------
@@ -89,7 +116,7 @@ now_diff({_,_,_} = Time) ->
-spec time(NowT | Diff)
-> {Hours, Mins, Secs, MicroSecs}
- when NowT :: {non_neg_integer(), 0..999999, 0..999999},
+ when NowT :: erlang:timestamp(),
Diff :: non_neg_integer(),
Hours :: non_neg_integer(),
Mins :: 0..59,
@@ -129,8 +156,8 @@ eval({M,F,A}) ->
eval([{M,F,A} | X]) ->
apply(M, F, X ++ A);
-eval([[F|A] | X]) ->
- eval([F | X ++ A]);
+eval([[F|X] | A]) ->
+ eval([F | A ++ X]);
eval([F|A]) ->
apply(F,A);
@@ -142,6 +169,28 @@ eval(F) ->
F().
%% ---------------------------------------------------------------------------
+%% eval_name/1
+%% ---------------------------------------------------------------------------
+
+eval_name({M,F,A}) ->
+ {M, F, length(A)};
+
+eval_name([{M,F,A} | X]) ->
+ {M, F, length(A) + length(X)};
+
+eval_name([[F|A] | X]) ->
+ eval_name([F | X ++ A]);
+
+eval_name([F|_]) ->
+ F;
+
+eval_name({F}) ->
+ eval_name(F);
+
+eval_name(F) ->
+ F.
+
+%% ---------------------------------------------------------------------------
%% # ipaddr/1
%%
%% Parse an IP address.
@@ -177,7 +226,7 @@ ip(T)
%% Or not: convert from '.'/':'-separated decimal/hex.
ip(Addr) ->
- {ok, A} = inet_parse:address(Addr), %% documented in inet(3)
+ {ok, A} = inet:parse_address(Addr),
A.
%% ---------------------------------------------------------------------------
@@ -199,17 +248,19 @@ opts(HeapSize, Opts) ->
%% # wait/1
%% ---------------------------------------------------------------------------
--spec wait([pid()])
+-spec wait([pid() | reference()])
-> ok.
wait(L) ->
- down([erlang:monitor(process, P) || P <- L]).
+ lists:foreach(fun down/1, L).
-down([]) ->
- ok;
-down([MRef|T]) ->
- receive {'DOWN', MRef, process, _, _} -> ok end,
- down(T).
+down(Pid)
+ when is_pid(Pid) ->
+ down(monitor(process, Pid));
+
+down(MRef)
+ when is_reference(MRef) ->
+ receive {'DOWN', MRef, process, _, _} = T -> T end.
%% ---------------------------------------------------------------------------
%% # fold_tuple/3
@@ -242,6 +293,35 @@ ft(Value, {Idx, T}) ->
setelement(Idx, T, Value).
%% ---------------------------------------------------------------------------
+%% # fold_n/3
+%% ---------------------------------------------------------------------------
+
+-spec fold_n(F, Acc0, N)
+ -> term()
+ when F :: fun((non_neg_integer(), term()) -> term()),
+ Acc0 :: term(),
+ N :: non_neg_integer().
+
+fold_n(F, Acc, N)
+ when is_integer(N), 0 < N ->
+ fold_n(F, F(N, Acc), N-1);
+
+fold_n(_, Acc, _) ->
+ Acc.
+
+%% ---------------------------------------------------------------------------
+%% # for_n/2
+%% ---------------------------------------------------------------------------
+
+-spec for_n(F, N)
+ -> non_neg_integer()
+ when F :: fun((non_neg_integer()) -> term()),
+ N :: non_neg_integer().
+
+for_n(F, N) ->
+ fold_n(fun(M,A) -> F(M), A+1 end, 0, N).
+
+%% ---------------------------------------------------------------------------
%% # log/4
%%
%% Called to have something to trace on for happenings of interest.
diff --git a/lib/diameter/src/base/diameter_peer.erl b/lib/diameter/src/base/diameter_peer.erl
index e5d4b28766..1ae8b567b1 100644
--- a/lib/diameter/src/base/diameter_peer.erl
+++ b/lib/diameter/src/base/diameter_peer.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -18,7 +18,6 @@
%%
-module(diameter_peer).
-
-behaviour(gen_server).
%% Interface towards transport modules ...
@@ -119,7 +118,7 @@ pair([{transport_module, M} | Rest], Mods, Acc) ->
pair([{transport_config = T, C} | Rest], Mods, Acc) ->
pair([{T, C, ?DEFAULT_TTMO} | Rest], Mods, Acc);
pair([{transport_config, C, Tmo} | Rest], Mods, Acc) ->
- pair(Rest, [], acc({Mods, C, Tmo}, Acc));
+ pair(Rest, [], acc({lists:reverse(Mods), C, Tmo}, Acc));
pair([_ | Rest], Mods, Acc) ->
pair(Rest, Mods, Acc);
@@ -128,13 +127,16 @@ pair([_ | Rest], Mods, Acc) ->
pair([], [], []) ->
[{[?DEFAULT_TMOD], ?DEFAULT_TCFG, ?DEFAULT_TTMO}];
-%% One transport_module, one transport_config.
-pair([], [M], [{[], Cfg, Tmo}]) ->
- [{[M], Cfg, Tmo}];
+%% One transport_module, one transport_config: ignore option order.
+%% That is, interpret [{transport_config, _}, {transport_module, _}]
+%% as if the order was reversed, not as config with default module and
+%% module with default config.
+pair([], [_] = Mods, [{[], Cfg, Tmo}]) ->
+ [{Mods, Cfg, Tmo}];
%% Trailing transport_module: default transport_config.
pair([], [_|_] = Mods, Acc) ->
- lists:reverse(acc({Mods, ?DEFAULT_TCFG, ?DEFAULT_TTMO}, Acc));
+ pair([{transport_config, ?DEFAULT_TCFG}], Mods, Acc);
pair([], [], Acc) ->
lists:reverse(def(Acc)).
@@ -199,10 +201,10 @@ match1(Addr, Match) ->
match(Addr, {ok, A}, _) ->
Addr == A;
match(Addr, {error, _}, RE) ->
- match == re:run(inet_parse:ntoa(Addr), RE, [{capture, none}]).
+ match == re:run(inet:ntoa(Addr), RE, [{capture, none}, caseless]).
addr([_|_] = A) ->
- inet_parse:address(A);
+ inet:parse_address(A);
addr(A) ->
{ok, A}.
@@ -230,12 +232,22 @@ recv(Pid, Pkt) ->
%% # send/2
%% ---------------------------------------------------------------------------
-send(Pid, #diameter_packet{transport_data = undefined,
- bin = Bin}) ->
- send(Pid, Bin);
+send(Pid, Msg) ->
+ ifc_send(Pid, {send, strip(Msg)}).
+
+%% Send only binary when possible.
+strip(#diameter_packet{transport_data = undefined,
+ bin = Bin}) ->
+ Bin;
+
+%% Strip potentially large message terms.
+strip(#diameter_packet{transport_data = T,
+ bin = Bin}) ->
+ #diameter_packet{transport_data = T,
+ bin = Bin};
-send(Pid, Pkt) ->
- ifc_send(Pid, {send, Pkt}).
+strip(Msg) ->
+ Msg.
%% ---------------------------------------------------------------------------
%% # close/1
@@ -324,7 +336,6 @@ code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%% ---------------------------------------------------------
-%% INTERNAL FUNCTIONS
%% ---------------------------------------------------------
%% ifc_send/2
diff --git a/lib/diameter/src/base/diameter_peer_fsm.erl b/lib/diameter/src/base/diameter_peer_fsm.erl
index 4e55864168..a9ee4940a3 100644
--- a/lib/diameter/src/base/diameter_peer_fsm.erl
+++ b/lib/diameter/src/base/diameter_peer_fsm.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -28,7 +28,8 @@
-behaviour(gen_server).
%% Interface towards diameter_watchdog.
--export([start/3]).
+-export([start/3,
+ result_code/2]).
%% gen_server callbacks
-export([init/1,
@@ -62,7 +63,8 @@
%% Keys in process dictionary.
-define(CB_KEY, cb). %% capabilities callback
-define(DPR_KEY, dpr). %% disconnect callback
--define(DWA_KEY, dwa). %% outgoing DWA
+-define(DPA_KEY, dpa). %% timeout for incoming DPA, or shutdown after
+ %% outgoing DPA
-define(REF_KEY, ref). %% transport_ref()
-define(Q_KEY, q). %% transport start queue
-define(START_KEY, start). %% start of connected transport
@@ -82,18 +84,26 @@
N == ?GOAWAY; N == goaway;
N == ?BUSY; N == busy).
-%% RFC 3588:
+%% RFC 6733:
%%
%% Timeout An application-defined timer has expired while waiting
%% for some event.
%%
--define(EVENT_TIMEOUT, 10000).
+
%% Default timeout for reception of CER/CEA.
+-define(CAPX_TIMEOUT, 10000).
-%% Default timeout for DPA in response to DPR. A bit short but the
-%% timeout used to be hardcoded. (So it could be worse.)
+%% Default timeout for DPA to be received in response to an outgoing
+%% DPR. A bit short but the timeout used to be hardcoded. (So it could
+%% be worse.)
-define(DPA_TIMEOUT, 1000).
+%% Default timeout for the connection to be closed by the peer
+%% following an outgoing DPA in response to an incoming DPR. It's the
+%% recipient of DPA that should close the connection according to the
+%% RFC.
+-define(DPR_TIMEOUT, 5000).
+
-type uint32() :: diameter:'Unsigned32'().
-record(state,
@@ -107,9 +117,16 @@
transport :: pid(), %% transport process
dictionary :: module(), %% common dictionary
service :: #diameter_service{},
- dpr = false :: false | {uint32(), uint32()},
- %% | hop by hop and end to end identifiers
- length_errors :: exit | handle | discard}).
+ dpr = false :: false
+ | true %% DPR received, DPA sent
+ | {uint32(), uint32()} %% set in old code
+ | {boolean(), uint32(), uint32()},
+ %% hop by hop and end to end identifiers in
+ %% outgoing DPR; boolean says whether or not
+ %% the request was sent explicitly with
+ %% diameter:call/4.
+ length_errors :: exit | handle | discard,
+ incoming_maxlen :: integer() | infinity}).
%% There are non-3588 states possible as a consequence of 5.6.1 of the
%% standard and the corresponding problem for incoming CEA's: we don't
@@ -138,7 +155,8 @@
%% # start/3
%% ---------------------------------------------------------------------------
--spec start(T, [Opt], {diameter:sequence(),
+-spec start(T, [Opt], {[diameter:service_opt()]
+ | diameter:sequence(), %% from old code
[node()],
module(),
#diameter_service{}})
@@ -177,28 +195,27 @@ init(T) ->
proc_lib:init_ack({ok, self()}),
gen_server:enter_loop(?MODULE, [], i(T)).
-i({Ack, WPid, {M, Ref} = T, Opts, {Mask,
- Nodes,
- Dict0,
- #diameter_service{capabilities = LCaps}
- = Svc}}) ->
+i({Ack, WPid, T, Opts, {{_,_} = Mask, Nodes, Dict0, Svc}}) -> %% from old code
+ i({Ack, WPid, T, Opts, {[{sequence, Mask}], Nodes, Dict0, Svc}});
+
+i({Ack, WPid, {M, Ref} = T, Opts, {SvcOpts, Nodes, Dict0, Svc}}) ->
erlang:monitor(process, WPid),
wait(Ack, WPid),
- putr(?DWA_KEY, dwa(LCaps)),
diameter_stats:reg(Ref),
+ diameter_codec:setopts([{common_dictionary, Dict0} | SvcOpts]),
+ {_,_} = Mask = proplists:get_value(sequence, SvcOpts),
+ Maxlen = proplists:get_value(incoming_maxlen, SvcOpts, 16#FFFFFF),
{[Cs,Ds], Rest} = proplists:split(Opts, [capabilities_cb, disconnect_cb]),
putr(?CB_KEY, {Ref, [F || {_,F} <- Cs]}),
putr(?DPR_KEY, [F || {_, F} <- Ds]),
putr(?REF_KEY, Ref),
putr(?SEQUENCE_KEY, Mask),
putr(?RESTRICT_KEY, Nodes),
+ putr(?DPA_KEY, {proplists:get_value(dpr_timeout, Opts, ?DPR_TIMEOUT),
+ proplists:get_value(dpa_timeout, Opts, ?DPA_TIMEOUT)}),
- Tmo = proplists:get_value(capx_timeout, Opts, ?EVENT_TIMEOUT),
- ?IS_TIMEOUT(Tmo) orelse ?ERROR({invalid, {capx_timeout, Tmo}}),
+ Tmo = proplists:get_value(capx_timeout, Opts, ?CAPX_TIMEOUT),
OnLengthErr = proplists:get_value(length_errors, Opts, exit),
- lists:member(OnLengthErr, [exit, handle, discard])
- orelse ?ERROR({invalid, {length_errors, OnLengthErr}}),
- %% Error checking is for configuration added in old code.
{TPid, Addrs} = start_transport(T, Rest, Svc),
@@ -208,7 +225,8 @@ i({Ack, WPid, {M, Ref} = T, Opts, {Mask,
dictionary = Dict0,
mode = M,
service = svc(Svc, Addrs),
- length_errors = OnLengthErr}.
+ length_errors = OnLengthErr,
+ incoming_maxlen = Maxlen}.
%% The transport returns its local ip addresses so that different
%% transports on the same service can use different local addresses.
%% The local addresses are put into Host-IP-Address avps here when
@@ -221,9 +239,12 @@ wait(Ref, Pid) ->
Ref ->
ok;
{'DOWN', _, process, Pid, _} = D ->
- exit({shutdown, D})
+ x(D)
end.
+x(T) ->
+ exit({shutdown, T}).
+
start_transport(T, Opts, #diameter_service{capabilities = LCaps} = Svc) ->
Addrs0 = LCaps#diameter_caps.host_ip_address,
start_transport(Addrs0, {T, Opts, Svc}).
@@ -234,8 +255,8 @@ start_transport(Addrs0, T) ->
erlang:monitor(process, TPid),
q_next(TPid, Addrs0, Tmo, Data),
{TPid, Addrs};
- No ->
- exit({shutdown, No})
+ {error, No} ->
+ x({no_connection, No})
end.
svc(#diameter_service{capabilities = LCaps0} = Svc, Addrs) ->
@@ -292,30 +313,30 @@ handle_info(T, #state{} = State) ->
ok ->
{noreply, State};
#state{state = X} = S ->
- ?LOGC(X =/= State#state.state, transition, X),
+ ?LOGC(X /= State#state.state, transition, X),
{noreply, S};
{stop, Reason} ->
?LOG(stop, Reason),
{stop, {shutdown, Reason}, State};
stop ->
- ?LOG(stop, T),
+ ?LOG(stop, truncate(T)),
{stop, {shutdown, T}, State}
catch
- exit: {diameter_codec, encode, _} = Reason ->
+ exit: {diameter_codec, encode, T} = Reason ->
+ incr_error(send, T, State#state.dictionary),
?LOG(stop, Reason),
- %% diameter_codec:encode/2 emits an error report. Only
- %% indicate the probable reason here.
- diameter_lib:info_report(probable_configuration_error,
- insufficient_capabilities),
{stop, {shutdown, Reason}, State};
{?MODULE, Tag, Reason} ->
- ?LOG(Tag, {Reason, T}),
+ ?LOG(stop, Tag),
{stop, {shutdown, Reason}, State}
- end.
+ end;
%% The form of the throw caught here is historical. It's
%% significant that it's not a 2-tuple, as in ?FAILURE(Reason),
%% since these are caught elsewhere.
+handle_info(T, S) -> %% started in old code
+ handle_info(T, #state{} = erlang:append_element(S, infinity)).
+
%% Note that there's no guarantee that the service and transport
%% capabilities are good enough to build a CER/CEA that can be
%% succesfully encoded. It's not checked at diameter:add_transport/2
@@ -334,6 +355,11 @@ code_change(_, State, _) ->
%% ---------------------------------------------------------------------------
%% ---------------------------------------------------------------------------
+truncate({'DOWN' = T, _, process, Pid, _}) ->
+ {T, Pid};
+truncate(T) ->
+ T.
+
putr(Key, Val) ->
put({?MODULE, Key}, Val).
@@ -345,6 +371,9 @@ eraser(Key) ->
%% transition/2
+transition(T, #state{dpr = {Hid, Eid}} = S) -> %% DPR sent from old code
+ transition(T, S#state{dpr = {false, Hid, Eid}});
+
%% Connection to peer.
transition({diameter, {TPid, connected, Remote}},
#state{transport = TPid,
@@ -380,11 +409,8 @@ transition({diameter, {TPid, connected}},
%% message. This may be followed by an incoming message which arrived
%% before the transport was killed and this can't be distinguished
%% from one from the transport that's been started to replace it.
-transition({diameter, {_, connected}}, _) ->
- {stop, connection_timeout};
-transition({diameter, {_, connected, _}}, _) ->
- {stop, connection_timeout};
-transition({diameter, {_, connected, _, _}}, _) ->
+transition({diameter, T}, _)
+ when tuple_size(T) < 5, connected == element(2,T) ->
{stop, connection_timeout};
%% Connection has timed out: start an alternate.
@@ -412,9 +438,8 @@ transition({timeout, _}, _) ->
ok;
%% Outgoing message.
-transition({send, Msg}, #state{transport = TPid}) ->
- send(TPid, Msg),
- ok;
+transition({send, Msg}, S) ->
+ outgoing(Msg, S);
%% Request for graceful shutdown at remove_transport, stop_service of
%% application shutdown.
@@ -423,7 +448,8 @@ transition({shutdown, Pid, Reason}, #state{parent = Pid, dpr = false} = S) ->
transition({shutdown, Pid, _}, #state{parent = Pid}) ->
ok;
-%% DPA reception has timed out.
+%% DPA reception has timed out, or peer has not closed the connection
+%% as a result of outgoing DPA.
transition(dpa_timeout, _) ->
stop;
@@ -485,12 +511,13 @@ send_CER(#state{state = {'Wait-Conn-Ack', Tmo},
orelse
close({already_connected, Remote, LCaps}),
CER = build_CER(S),
- ?LOG(send, 'CER'),
#diameter_packet{header = #diameter_header{end_to_end_id = Eid,
hop_by_hop_id = Hid}}
= Pkt
= encode(CER, Dict),
+ incr(send, Pkt, Dict),
send(TPid, Pkt),
+ ?LOG(send, 'CER'),
start_timer(Tmo, S#state{state = {'Wait-CEA', Hid, Eid}}).
%% Register ourselves as connecting to the remote endpoint in
@@ -530,13 +557,9 @@ encode(Rec, Dict) ->
recv(#diameter_packet{header = #diameter_header{} = Hdr}
= Pkt,
- #state{parent = Pid,
- dictionary = Dict0}
+ #state{dictionary = Dict0}
= S) ->
- Name = diameter_codec:msg_name(Dict0, Hdr),
- Pid ! {recv, self(), Name, Pkt},
- diameter_stats:incr({msg_id(Name, Hdr), recv}), %% count received
- rcv(Name, Pkt, S);
+ recv1(diameter_codec:msg_name(Dict0, Hdr), Pkt, S);
recv(#diameter_packet{header = undefined,
bin = Bin}
@@ -547,6 +570,47 @@ recv(#diameter_packet{header = undefined,
recv(Bin, S) ->
recv(#diameter_packet{bin = Bin}, S).
+%% recv1/3
+
+recv1(_,
+ #diameter_packet{header = H, bin = Bin},
+ #state{incoming_maxlen = M})
+ when M < size(Bin) ->
+ invalid(false, incoming_maxlen_exceeded, {size(Bin), H});
+
+%% Incoming request after outgoing DPR: discard. Don't discard DPR, so
+%% both ends don't do so when sending simultaneously.
+recv1(Name,
+ #diameter_packet{header = #diameter_header{is_request = true} = H},
+ #state{dpr = {_,_,_}})
+ when Name /= 'DPR' ->
+ invalid(false, recv_after_outgoing_dpr, H);
+
+%% Incoming request after incoming DPR: discard.
+recv1(_,
+ #diameter_packet{header = #diameter_header{is_request = true} = H},
+ #state{dpr = true}) ->
+ invalid(false, recv_after_incoming_dpr, H);
+
+%% DPA with identifier mismatch, or in response to a DPR initiated by
+%% the service.
+recv1('DPA' = N,
+ #diameter_packet{header = #diameter_header{hop_by_hop_id = Hid,
+ end_to_end_id = Eid}}
+ = Pkt,
+ #state{dpr = {X,H,E}}
+ = S)
+ when H /= Hid;
+ E /= Eid;
+ not X ->
+ rcv(N, Pkt, S);
+
+%% Any other message with a header and no length errors: send to the
+%% parent.
+recv1(Name, Pkt, #state{parent = Pid} = S) ->
+ Pid ! {recv, self(), Name, Pkt},
+ rcv(Name, Pkt, S).
+
%% recv/3
recv(#diameter_header{length = Len}
@@ -562,42 +626,30 @@ recv(#diameter_header{length = Len}
recv(#diameter_header{}
= H,
#diameter_packet{bin = Bin},
- #state{length_errors = E}
- = S) ->
- invalid(E,
- invalid_message_length,
- recv,
- [size(Bin), bit_size(Bin) rem 8, H, S]);
+ #state{length_errors = E}) ->
+ T = {size(Bin), bit_size(Bin) rem 8, H},
+ invalid(E, message_length_mismatch, T);
-recv(false, Pkt, #state{length_errors = E} = S) ->
- invalid(E, truncated_header, recv, [Pkt, S]).
+recv(false, #diameter_packet{bin = Bin}, #state{length_errors = E}) ->
+ invalid(E, truncated_header, Bin).
%% Note that counters here only count discarded messages.
-invalid(E, Reason, F, A) ->
+invalid(E, Reason, T) ->
diameter_stats:incr(Reason),
- abort(E, Reason, F, A).
-
-abort(exit, Reason, F, A) ->
- diameter_lib:warning_report(Reason, {?MODULE, F, A}),
- throw({?MODULE, abort, Reason});
-
-abort(_, _, _, _) ->
+ E == exit andalso close({Reason, T}),
+ ?LOG(Reason, T),
ok.
-msg_id({_,_,_} = T, _) ->
- T;
-msg_id(_, Hdr) ->
- {_,_,_} = diameter_codec:msg_id(Hdr).
-
%% rcv/3
%% Incoming CEA.
-rcv('CEA',
+rcv('CEA' = N,
#diameter_packet{header = #diameter_header{end_to_end_id = Eid,
hop_by_hop_id = Hid}}
= Pkt,
#state{state = {'Wait-CEA', Hid, Eid}}
= S) ->
+ ?LOG(recv, N),
handle_CEA(Pkt, S);
%% Incoming CER
@@ -612,42 +664,136 @@ rcv(Name, _, #state{state = PS})
Name == 'CEA' ->
{stop, {Name, PS}};
-rcv(N, Pkt, S)
- when N == 'DWR';
- N == 'DPR' ->
+rcv('DPR' = N, Pkt, S) ->
handle_request(N, Pkt, S);
-%% DPA in response to DPR and with the expected identifiers.
+%% DPA in response to DPR, with the expected identifiers.
rcv('DPA' = N,
#diameter_packet{header = #diameter_header{end_to_end_id = Eid,
- hop_by_hop_id = Hid}},
- #state{transport = TPid,
- dpr = {Hid, Eid}}) ->
+ hop_by_hop_id = Hid}
+ = H}
+ = Pkt,
+ #state{dictionary = Dict0,
+ transport = TPid,
+ dpr = {X, Hid, Eid}}) ->
+ ?LOG(recv, N),
+ X orelse begin
+ %% Only count DPA in response to a DPR sent by the
+ %% service: explicit DPR is counted in the same way
+ %% as other explicitly sent requests.
+ incr(recv, H, Dict0),
+ incr_rc(recv, diameter_codec:decode(Dict0, Pkt), Dict0)
+ end,
diameter_peer:close(TPid),
{stop, N};
-%% Ignore anything else, an unsolicited DPA in particular.
+%% Ignore anything else, an unsolicited DPA in particular. Note that
+%% dpa_timeout deals with the case in which the peer sends the wrong
+%% identifiers in DPA.
+rcv(N, #diameter_packet{header = H}, _)
+ when N == 'CER';
+ N == 'CEA';
+ N == 'DPR';
+ N == 'DPA' ->
+ ?LOG(ignored, N),
+ %% Note that these aren't counted in the normal recv counter.
+ diameter_stats:incr({diameter_codec:msg_id(H), recv, ignored}),
+ ok;
+
rcv(_, _, _) ->
ok.
+%% incr/3
+
+incr(Dir, Hdr, Dict0) ->
+ diameter_traffic:incr(Dir, Hdr, self(), Dict0).
+
+%% incr_rc/3
+
+incr_rc(Dir, Pkt, Dict0) ->
+ diameter_traffic:incr_rc(Dir, Pkt, self(), Dict0).
+
+%% incr_error/3
+
+incr_error(Dir, Pkt, Dict0) ->
+ diameter_traffic:incr_error(Dir, Pkt, self(), Dict0).
+
%% send/2
%% Msg here could be a #diameter_packet or a binary depending on who's
%% sending. In particular, the watchdog will send DWR as a binary
%% while messages coming from clients will be in a #diameter_packet.
+
send(Pid, Msg) ->
- diameter_stats:incr({diameter_codec:msg_id(Msg), send}),
diameter_peer:send(Pid, Msg).
+%% outgoing/2
+
+%% Explicit DPR.
+outgoing(#diameter_packet{header = #diameter_header{application_id = 0,
+ cmd_code = 282,
+ is_request = true}
+ = H}
+ = Pkt,
+ #state{dpr = T,
+ parent = Pid}
+ = S) ->
+ if T == false ->
+ inform_dpr(Pid),
+ send_dpr(true, Pkt, dpa_timeout(), S);
+ T == true ->
+ invalid(false, dpr_after_dpa, H); %% DPA sent: discard
+ true ->
+ invalid(false, dpr_after_dpr, H) %% DPR sent: discard
+ end;
+
+%% Explict CER or DWR: discard. These are sent by us.
+outgoing(#diameter_packet{header = #diameter_header{application_id = 0,
+ cmd_code = C,
+ is_request = true}
+ = H},
+ _)
+ when 257 == C; %% CER
+ 280 == C -> %% DWR
+ invalid(false, invalid_request, H);
+
+%% DPR not sent: send.
+outgoing(Msg, #state{transport = TPid, dpr = false}) ->
+ send(TPid, Msg),
+ ok;
+
+%% Outgoing answer: send.
+outgoing(#diameter_packet{header = #diameter_header{is_request = false}}
+ = Pkt,
+ #state{transport = TPid}) ->
+ send(TPid, Pkt),
+ ok;
+
+%% Outgoing request: discard.
+outgoing(Msg, #state{dpr = {_,_,_}}) ->
+ invalid(false, send_after_dpr, header(Msg)).
+
+header(#diameter_packet{header = H}) ->
+ H;
+header(Bin) -> %% DWR
+ diameter_codec:decode_header(Bin).
+
%% handle_request/3
+%%
+%% Incoming CER or DPR.
-handle_request(Type, #diameter_packet{} = Pkt, #state{dictionary = D} = S) ->
- ?LOG(recv, Type),
- send_answer(Type, diameter_codec:decode(D, Pkt), S).
+handle_request(Name,
+ #diameter_packet{header = H} = Pkt,
+ #state{dictionary = Dict0} = S) ->
+ ?LOG(recv, Name),
+ incr(recv, H, Dict0),
+ send_answer(Name, diameter_codec:decode(Dict0, Pkt), S).
%% send_answer/3
send_answer(Type, ReqPkt, #state{transport = TPid, dictionary = Dict} = S) ->
+ incr_error(recv, ReqPkt, Dict),
+
#diameter_packet{header = H,
transport_data = TD}
= ReqPkt,
@@ -664,13 +810,19 @@ send_answer(Type, ReqPkt, #state{transport = TPid, dictionary = Dict} = S) ->
msg = Msg,
transport_data = TD},
- send(TPid, diameter_codec:encode(Dict, Pkt)),
+ AnsPkt = diameter_codec:encode(Dict, Pkt),
+
+ incr(send, AnsPkt, Dict),
+ incr_rc(send, AnsPkt, Dict),
+ send(TPid, AnsPkt),
+ ?LOG(send, ans(Type)),
eval(PostF, S).
+ans('CER') -> 'CEA';
+ans('DPR') -> 'DPA'.
+
eval([F|A], S) ->
apply(F, A ++ [S]);
-eval(ok, S) ->
- S;
eval(T, _) ->
close(T).
@@ -685,6 +837,8 @@ build_answer('CER',
= Pkt,
#state{dictionary = Dict0}
= S) ->
+ diameter_codec:setopts([{string_decode, false}]),
+
{SupportedApps, RCaps, CEA} = recv_CER(CER, S),
[RC, IS] = Dict0:'#get-'(['Result-Code', 'Inband-Security-Id'], CEA),
@@ -717,8 +871,8 @@ build_answer(Type,
errors = Es}
= Pkt,
S) ->
- RC = rc(H, Es),
- {answer(Type, RC, Es, S), post(Type, RC, Pkt, S)}.
+ {RC, FailedAVP} = result_code(Type, H, Es),
+ {answer(Type, RC, FailedAVP, S), post(Type, RC, Pkt, S)}.
inband_security([]) ->
?NO_INBAND_SECURITY;
@@ -734,8 +888,16 @@ cea(CEA, RC, Dict0) ->
post('CER' = T, RC, Pkt, S) ->
{T, caps(S), {RC, Pkt}};
-post(_, _, _, _) ->
- ok.
+post('DPR', _, _, #state{parent = Pid}) ->
+ [fun(S) -> dpr_timer(), inform_dpr(Pid), dpr(S) end].
+
+dpr(#state{dpr = false} = S) -> %% not awaiting DPA
+ S#state{dpr = true}; %% DPR received
+dpr(S) -> %% DPR already sent or received
+ S.
+
+inform_dpr(Pid) ->
+ Pid ! {'DPR', self()}. %% tell watchdog to die with us
rejected({capabilities_cb, _F, Reason}, T, S) ->
rejected(Reason, T, S);
@@ -743,20 +905,20 @@ rejected({capabilities_cb, _F, Reason}, T, S) ->
rejected(discard, T, _) ->
close(T);
rejected({N, Es}, T, S) ->
- {answer('CER', N, Es, S), T};
+ {answer('CER', N, failed_avp(N, Es), S), T};
rejected(N, T, S) ->
- rejected({N, []}, T, S).
-
-answer(Type, RC, Es, S) ->
- set(answer(Type, RC, S), failed_avp(RC, Es)).
+ {answer('CER', N, [], S), T}.
failed_avp(RC, [{RC, Avp} | _]) ->
- [{'Failed-AVP', [{'AVP', [Avp]}]}];
+ [{'Failed-AVP', [[{'AVP', [Avp]}]]}];
failed_avp(RC, [_ | Es]) ->
failed_avp(RC, Es);
failed_avp(_, [] = No) ->
No.
+answer(Type, RC, FailedAVP, S) ->
+ set(answer(Type, RC, S), FailedAVP).
+
answer(Type, RC, S) ->
answer_message(answer(Type, S), RC).
@@ -784,29 +946,38 @@ set(['answer-message' | _] = Ans, FailedAvp) ->
set([_|_] = Ans, FailedAvp) ->
Ans ++ FailedAvp.
-%% rc/2
+%% result_code/3
+
+%% Be lenient with errors in DPR since there's no reason to be
+%% otherwise. Rejecting may cause the peer to missinterpret the error
+%% as meaning that the connection should not be closed, which may well
+%% lead to more problems than any errors in the DPR.
+
+result_code('DPR', _, _) ->
+ {2001, []};
+
+result_code('CER', H, Es) ->
+ result_code(H, Es).
-rc(#diameter_header{is_error = true}, _) ->
- 3008; %% DIAMETER_INVALID_HDR_BITS
+%% result_code/2
-rc(_, [Bs|_])
- when is_bitstring(Bs) -> %% from old code
- 3009; %% DIAMETER_INVALID_HDR_BITS
+result_code(#diameter_header{is_error = true}, _) ->
+ {3008, []}; %% DIAMETER_INVALID_HDR_BITS
-rc(#diameter_header{version = ?DIAMETER_VERSION}, Es) ->
+result_code(#diameter_header{version = ?DIAMETER_VERSION}, Es) ->
rc(Es);
-rc(_, _) ->
- 5011. %% DIAMETER_UNSUPPORTED_VERSION
+result_code(_, _) ->
+ {5011, []}. %% DIAMETER_UNSUPPORTED_VERSION
%% rc/1
rc([]) ->
- 2001; %% DIAMETER_SUCCESS
-rc([{RC,_}|_]) ->
- RC;
+ {2001, []}; %% DIAMETER_SUCCESS
+rc([{RC, _} | _] = Es) ->
+ {RC, failed_avp(RC, Es)};
rc([RC|_]) ->
- RC.
+ {RC, []}.
%% DIAMETER_INVALID_HDR_BITS 3008
%% A request was received whose bits in the Diameter header were
@@ -832,9 +1003,6 @@ rc([RC|_]) ->
%% answer/2
-answer('DWR', _) ->
- getr(?DWA_KEY);
-
answer(Name, #state{service = #diameter_service{capabilities = Caps}}) ->
a(Name, Caps).
@@ -866,28 +1034,29 @@ recv_CER(CER, #state{service = Svc, dictionary = Dict}) ->
close({'CER', CER, Svc, Dict, Reason})
end.
-%% handle_CEA/1
+%% handle_CEA/2
-handle_CEA(#diameter_packet{bin = Bin}
+handle_CEA(#diameter_packet{header = H}
= Pkt,
#state{dictionary = Dict0,
service = #diameter_service{capabilities = LCaps}}
- = S)
- when is_binary(Bin) ->
- ?LOG(recv, 'CEA'),
+ = S) ->
+ incr(recv, H, Dict0),
- #diameter_packet{msg = CEA}
+ #diameter_packet{}
= DPkt
= diameter_codec:decode(Dict0, Pkt),
+ diameter_codec:setopts([{string_decode, false}]),
+
+ RC = result_code(incr_rc(recv, DPkt, Dict0)),
+
{SApps, IS, RCaps} = recv_CEA(DPkt, S),
#diameter_caps{origin_host = {OH, DH}}
= Caps
= capz(LCaps, RCaps),
- RC = Dict0:'#get-'('Result-Code', CEA),
-
%% Ensure that we don't already have a connection to the peer in
%% question. This isn't the peer election of 3588 except in the
%% sense that, since we don't know who we're talking to until we
@@ -895,7 +1064,7 @@ handle_CEA(#diameter_packet{bin = Bin}
%% connection with the peer.
try
- ?IS_SUCCESS(RC)
+ is_integer(RC) andalso ?IS_SUCCESS(RC)
orelse ?THROW(RC),
[] == SApps
andalso ?THROW(no_common_application),
@@ -915,6 +1084,11 @@ handle_CEA(#diameter_packet{bin = Bin}
%% capabilities exchange could send DIAMETER_LIMITED_SUCCESS = 2002,
%% even if this isn't required by RFC 3588.
+result_code({'Result-Code', N}) ->
+ N;
+result_code(_) ->
+ undefined.
+
%% recv_CEA/2
recv_CEA(#diameter_packet{header = #diameter_header{version
@@ -1006,31 +1180,16 @@ capz(#diameter_caps{} = L, #diameter_caps{} = R) ->
tl(tuple_to_list(R)))]).
%% close/1
+%%
+%% A good function to trace on in case of problems with capabilities
+%% exchange.
close(Reason) ->
- report(Reason),
throw({?MODULE, close, Reason}).
-%% Could possibly log more here.
-report({M, _, _, _, _} = T)
- when M == 'CER';
- M == 'CEA' ->
- diameter_lib:error_report(failure, T);
-report(_) ->
- ok.
-
-%% dwa/1
-
-dwa(#diameter_caps{origin_host = OH,
- origin_realm = OR,
- origin_state_id = OSI}) ->
- ['DWA', {'Origin-Host', OH},
- {'Origin-Realm', OR},
- {'Origin-State-Id', OSI}].
-
%% dpr/2
%%
-%% The RFC isn't clear on whether DPR should be send in a non-Open
+%% The RFC isn't clear on whether DPR should be sent in a non-Open
%% state. The Peer State Machine transitions it documents aren't
%% exhaustive (no Stop in Wait-I-CEA for example) so assume it's up to
%% the implementation and transition to Closed (ie. die) if we haven't
@@ -1046,7 +1205,7 @@ dpr(Reason, #state{state = 'Open',
Peer = {self(), Caps},
dpr(CBs, [Reason, Ref, Peer], S);
-%% Connection is open, DPR already sent.
+%% Connection is open, DPR already sent or received.
dpr(_, #state{state = 'Open'}) ->
ok;
@@ -1061,7 +1220,7 @@ dpr(_Reason, _S) ->
%% process and contact it. (eg. diameter:service_info/2)
dpr([CB|Rest], [Reason | _] = Args, S) ->
- try diameter_lib:eval([CB | Args]) of
+ case diameter_lib:eval([CB | Args]) of
{dpr, Opts} when is_list(Opts) ->
send_dpr(Reason, Opts, S);
dpr ->
@@ -1071,23 +1230,15 @@ dpr([CB|Rest], [Reason | _] = Args, S) ->
ignore ->
dpr(Rest, Args, S);
T ->
- No = {disconnect_cb, T},
- diameter_lib:error_report(invalid, No),
- {stop, No}
- catch
- E:R ->
- No = {disconnect_cb, E, R, ?STACK},
- diameter_lib:error_report(failure, No),
- {stop, No}
+ ?ERROR({disconnect_cb, CB, Args, T})
end;
dpr([], [Reason | _], S) ->
send_dpr(Reason, [], S).
--record(opts, {cause, timeout = ?DPA_TIMEOUT}).
+-record(opts, {cause, timeout}).
-send_dpr(Reason, Opts, #state{transport = TPid,
- dictionary = Dict,
+send_dpr(Reason, Opts, #state{dictionary = Dict,
service = #diameter_service{capabilities = Caps}}
= S) ->
#opts{cause = Cause, timeout = Tmo}
@@ -1096,23 +1247,37 @@ send_dpr(Reason, Opts, #state{transport = TPid,
transport -> ?GOAWAY;
_ -> ?REBOOT
end,
- timeout = ?DPA_TIMEOUT},
+ timeout = dpa_timeout()},
Opts),
#diameter_caps{origin_host = {OH, _},
origin_realm = {OR, _}}
= Caps,
- #diameter_packet{header = #diameter_header{end_to_end_id = Eid,
- hop_by_hop_id = Hid}}
- = Pkt
- = encode(['DPR', {'Origin-Host', OH},
+ Pkt = encode(['DPR', {'Origin-Host', OH},
{'Origin-Realm', OR},
{'Disconnect-Cause', Cause}],
Dict),
+ send_dpr(false, Pkt, Tmo, S).
+
+%% send_dpr/4
+
+send_dpr(X,
+ #diameter_packet{header = #diameter_header{end_to_end_id = Eid,
+ hop_by_hop_id = Hid}}
+ = Pkt,
+ Tmo,
+ #state{transport = TPid,
+ dictionary = Dict}
+ = S) ->
+ %% Only count DPR sent by the service: explicit DPR is counted in
+ %% the same way as other explicitly sent requests.
+ X orelse incr(send, Pkt, Dict),
send(TPid, Pkt),
dpa_timer(Tmo),
?LOG(send, 'DPR'),
- S#state{dpr = {Hid, Eid}}.
+ S#state{dpr = {X, Hid, Eid}}.
+
+%% opt/2
opt({timeout, Tmo}, Rec)
when ?IS_TIMEOUT(Tmo) ->
@@ -1135,6 +1300,27 @@ cause(N) ->
dpa_timer(Tmo) ->
erlang:send_after(Tmo, self(), dpa_timeout).
+dpa_timeout() ->
+ dpa_timeout(getr(?DPA_KEY)).
+
+dpa_timeout({_, Tmo}) ->
+ Tmo;
+dpa_timeout(undefined) -> %% set in old code
+ ?DPA_TIMEOUT;
+dpa_timeout(Tmo) -> %% ditto
+ Tmo.
+
+dpr_timer() ->
+ dpa_timer(dpr_timeout()).
+
+dpr_timeout() ->
+ dpr_timeout(getr(?DPA_KEY)).
+
+dpr_timeout({Tmo, _}) ->
+ Tmo;
+dpr_timeout(_) -> %% set in old code
+ ?DPR_TIMEOUT.
+
%% register_everywhere/1
%%
%% Register a term and ensure it's not registered elsewhere. Note that
diff --git a/lib/diameter/src/base/diameter_reg.erl b/lib/diameter/src/base/diameter_reg.erl
index 3197c1aee1..6bb4710e63 100644
--- a/lib/diameter/src/base/diameter_reg.erl
+++ b/lib/diameter/src/base/diameter_reg.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -22,10 +22,10 @@
%%
-module(diameter_reg).
--compile({no_auto_import, [monitor/2]}).
-
-behaviour(gen_server).
+-compile({no_auto_import, [monitor/2]}).
+
-export([add/1,
add_new/1,
del/1,
diff --git a/lib/diameter/src/base/diameter_service.erl b/lib/diameter/src/base/diameter_service.erl
index 9dd8aafc61..7aa7c422c4 100644
--- a/lib/diameter/src/base/diameter_service.erl
+++ b/lib/diameter/src/base/diameter_service.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2016. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -82,16 +82,8 @@
-define(DEFAULT_TC, 30000). %% RFC 3588 ch 2.1
-define(RESTART_TC, 1000). %% if restart was this recent
-%% Used to be able to swap this with anything else dict-like but now
-%% rely on the fact that a service's #state{} record does not change
-%% in storing in it ?STATE table and not always going through the
-%% service process. In particular, rely on the fact that operations on
-%% a ?Dict don't change the handle to it.
--define(Dict, diameter_dict).
-
-%% Maintains state in a table. In contrast to previously, a service's
-%% stat is not constant and is accessed outside of the service
-%% process.
+%% Maintain state in a table since a service's state is accessed
+%% outside of the service process.
-define(STATE_TABLE, ?MODULE).
%% The default sequence mask.
@@ -116,18 +108,20 @@
service :: #diameter_service{},
watchdogT = ets_new(watchdogs) %% #watchdog{} at start
:: ets:tid(),
- peerT = ets_new(peers) %% #peer{pid = TPid} at okay/reopen
- :: ets:tid(),
- shared_peers = ?Dict:new() %% Alias -> [{TPid, Caps}, ...]
- :: ets:tid(),
- local_peers = ?Dict:new() %% Alias -> [{TPid, Caps}, ...]
- :: ets:tid(),
+ peerT, %% undefined in new code, but remain for upgrade
+ shared_peers, %% reasons. Replaced by local/remote.
+ local_peers, %%
+ local :: {ets:tid(), ets:tid(), ets:tid()},
+ remote :: {ets:tid(), ets:tid(), ets:tid()},
monitor = false :: false | pid(), %% process to die with
options
:: [{sequence, diameter:sequence()} %% sequence mask
| {share_peers, diameter:remotes()} %% broadcast to
| {use_shared_peers, diameter:remotes()} %% use from
- | {restrict_connections, diameter:restriction()}]}).
+ | {restrict_connections, diameter:restriction()}
+ | {strict_mbit, boolean()}
+ | {string_decode, boolean()}
+ | {incoming_maxlen, diameter:message_length()}]}).
%% shared_peers reflects the peers broadcast from remote nodes.
%% Record representing an RFC 3539 watchdog process implemented by
@@ -142,14 +136,16 @@
peer = false :: match(boolean() | pid())}).
%% true at accepted, pid() at okay/reopen
-%% Record representing an Peer State Machine processes implemented by
+%% Record representing a Peer State Machine processes implemented by
%% diameter_peer_fsm.
-record(peer,
- {pid :: pid(),
- apps :: [{0..16#FFFFFFFF, diameter:app_alias()}], %% {Id, Alias}
- caps :: #diameter_caps{},
- started = now(), %% at process start
- watchdog :: pid()}). %% key into watchdogT
+ {pid :: pid(),
+ apps :: match([{0..16#FFFFFFFF, diameter:app_alias()}] %% {Id, Alias}
+ | [diameter:app_alias()]), %% remote
+ caps :: match(#diameter_caps{}),
+ started = now(), %% at process start or sharing
+ watchdog :: match(pid() %% key into watchdogT
+ | undefined)}). %% undefined if remote
%% ---------------------------------------------------------------------------
%% # start/1
@@ -177,7 +173,7 @@ stop(SvcName) ->
end.
stop(ok, Pid) ->
- MRef = erlang:monitor(process, Pid),
+ MRef = monitor(process, Pid),
receive {'DOWN', MRef, process, _, _} -> ok end;
stop(No, _) ->
No.
@@ -204,7 +200,7 @@ stop_transport(SvcName, [_|_] = Refs) ->
info(SvcName, Item) ->
case lookup_state(SvcName) of
- [#state{} = S] ->
+ [S] ->
service_info(Item, S);
[] ->
undefined
@@ -213,7 +209,12 @@ info(SvcName, Item) ->
%% lookup_state/1
lookup_state(SvcName) ->
- ets:lookup(?STATE_TABLE, SvcName).
+ case ets:lookup(?STATE_TABLE, SvcName) of
+ [#state{}] = L ->
+ L;
+ _ ->
+ []
+ end.
%% ---------------------------------------------------------------------------
%% # subscribe/1
@@ -258,16 +259,22 @@ whois(SvcName) ->
%% ---------------------------------------------------------------------------
-spec pick_peer(SvcName, AppOrAlias, Opts)
- -> {{TPid, Caps, App}, Mask}
- | false
- | {error, term()}
+ -> {{TPid, Caps, App}, Mask, SvcOpts}
+ | false %% no selection
+ | {error, no_service}
when SvcName :: diameter:service_name(),
- AppOrAlias :: {alias, diameter:app_alias()} | #diameter_app{},
- Opts :: tuple(),
+ AppOrAlias :: #diameter_app{}
+ | {alias, diameter:app_alias()},
+ Opts :: {fun((Dict :: module()) -> [term()]),
+ diameter:peer_filter(),
+ Xtra :: list()},
TPid :: pid(),
Caps :: #diameter_caps{},
App :: #diameter_app{},
- Mask :: diameter:sequence().
+ Mask :: diameter:sequence(),
+ SvcOpts :: [diameter:service_opt()].
+%% Extract Mask in the returned tuple so that diameter_traffic doesn't
+%% need to know about the ordering of SvcOpts used here.
pick_peer(SvcName, App, Opts) ->
pick(lookup_state(SvcName), App, Opts).
@@ -284,10 +291,10 @@ pick(#state{service = #diameter_service{applications = Apps}}
Opts) -> %% initial call from diameter:call/4
pick(S, find_outgoing_app(Alias, Apps), Opts);
-pick(_, false, _) ->
- false;
+pick(_, false = No, _) ->
+ No;
-pick(#state{options = [{_, Mask} | _]}
+pick(#state{options = [{_, Mask} | SvcOpts]}
= S,
#diameter_app{module = ModX, dictionary = Dict}
= App0,
@@ -296,7 +303,7 @@ pick(#state{options = [{_, Mask} | _]}
[_,_] = RealmAndHost = diameter_lib:eval([DestF, Dict]),
case pick_peer(App, RealmAndHost, Filter, S) of
{TPid, Caps} ->
- {{TPid, Caps, App}, Mask};
+ {{TPid, Caps, App}, Mask, SvcOpts};
false = No ->
No
end.
@@ -480,6 +487,9 @@ transition({service, Pid}, S) ->
transition({peer, TPid, Aliases, Caps}, S) ->
remote_peer_up(TPid, Aliases, Caps, S),
ok;
+transition({peer, TPid}, S) ->
+ remote_peer_down(TPid, S),
+ ok;
%% Remote peer process has died.
transition({'DOWN', _, process, TPid, _}, S) ->
@@ -499,9 +509,21 @@ transition(Req, S) ->
%% # terminate/2
%% ---------------------------------------------------------------------------
-terminate(Reason, #state{service_name = Name} = S) ->
+terminate(Reason, #state{service_name = Name, local = {PeerT, _, _}} = S) ->
send_event(Name, stop),
ets:delete(?STATE_TABLE, Name),
+
+ %% Communicate pending loss of any peers that connection_down/3
+ %% won't. This is needed when stopping a service since we don't
+ %% wait for watchdog state changes to take care of if. That this
+ %% takes place after deleting the state entry ensures that the
+ %% resulting failover by request processes accomplishes nothing.
+ ets:foldl(fun(#peer{pid = TPid}, _) ->
+ diameter_traffic:peer_down(TPid)
+ end,
+ ok,
+ PeerT),
+
shutdown == Reason %% application shutdown
andalso shutdown(application, S).
@@ -509,23 +531,80 @@ terminate(Reason, #state{service_name = Name} = S) ->
%% # code_change/3
%% ---------------------------------------------------------------------------
-code_change(FromVsn,
- #state{service_name = SvcName,
- service = #diameter_service{applications = Apps}}
- = S,
- Extra) ->
- lists:foreach(fun(A) ->
- code_change(FromVsn, SvcName, Extra, A)
- end,
- Apps),
+code_change(_FromVsn, #state{} = S, _Extra) ->
+ {ok, S};
+
+%% Don't support downgrade since we won't in appup.
+code_change({down = T, _}, _, _Extra) ->
+ {error, T};
+
+%% Upgrade local/shared peers dicts populated in old code. Don't
+code_change(_FromVsn, S0, _Extra) ->
+ {state, Id, SvcName, Svc, WT, PeerT, SDict, LDict, Monitor, Opts}
+ = S0,
+
+ init_peers(LT = setelement(1, {PT, _, _} = init_peers(), PeerT),
+ fun({_,A}) -> A end),
+ init_peers(init_peers(RT = init_peers(), SDict),
+ fun(A) -> A end),
+
+ S = #state{id = Id,
+ service_name = SvcName,
+ service = Svc,
+ watchdogT = WT,
+ peerT = PT, %% empty
+ shared_peers = SDict,
+ local_peers = LDict,
+ local = LT,
+ remote = RT,
+ monitor = Monitor,
+ options = Opts},
+
+ %% Replacing the table entry and deleting the old shared tables
+ %% can make outgoing requests return {error, no_connection} until
+ %% everyone is running new code. Don't delete the tables to avoid
+ %% crashing request processes.
+ ets:delete_all_objects(SDict),
+ ets:delete_all_objects(LDict),
+ ets:insert(?STATE_TABLE, S),
{ok, S}.
-code_change(FromVsn, SvcName, Extra, #diameter_app{alias = Alias} = A) ->
- {ok, S} = cb(A, code_change, [FromVsn,
- mod_state(Alias),
- Extra,
- SvcName]),
- mod_state(Alias, S).
+%% init_peers/2
+
+%% Populate app and identity bags from a new-style #peer{} sets.
+init_peers({PeerT, _, _} = T, F)
+ when is_function(F) ->
+ ets:foldl(fun(#peer{pid = P, apps = As, caps = C}, N) ->
+ insert_peer(P, lists:map(F, As), C, T),
+ N+1
+ end,
+ 0,
+ PeerT);
+
+%% Populate #peer{} table given a shared peers dict.
+init_peers({PeerT, _, _}, SDict) ->
+ dict:fold(fun(P, As, N) ->
+ ets:update_element(PeerT, P, {#peer.apps, As}),
+ N+1
+ end,
+ 0,
+ diameter_dict:fold(fun(A, Ps, D) ->
+ init_peers(A, Ps, PeerT, D)
+ end,
+ dict:new(),
+ SDict)).
+
+%% init_peers/4
+
+init_peers(App, TCs, PeerT, Dict) ->
+ lists:foldl(fun({P,C}, D) ->
+ ets:insert(PeerT, #peer{pid = P,
+ apps = [],
+ caps = C}),
+ dict:append(P, App, D)
+ end,
+ Dict,
+ TCs).
%% ===========================================================================
%% ===========================================================================
@@ -533,9 +612,6 @@ code_change(FromVsn, SvcName, Extra, #diameter_app{alias = Alias} = A) ->
unexpected(F, A, #state{service_name = Name}) ->
?UNEXPECTED(F, A ++ [Name]).
-cb(#diameter_app{module = [_|_] = M}, F, A) ->
- eval(M, F, A).
-
eval([M|X], F, A) ->
apply(M, F, A ++ X).
@@ -555,10 +631,6 @@ choose(false, _, X) -> X.
ets_new(Tbl) ->
ets:new(Tbl, [{keypos, 2}]).
-insert(Tbl, Rec) ->
- ets:insert(Tbl, Rec),
- Rec.
-
%% Using the process dictionary for the callback state was initially
%% just a way to make what was horrendous trace (big state record and
%% much else everywhere) somewhat more readable. There's not as much
@@ -598,8 +670,9 @@ st(#watchdog{ref = Ref, pid = Pid}, Refs) ->
%% st/3
st(#watchdog{pid = Pid}, Reason, Acc) ->
+ MRef = monitor(process, Pid),
Pid ! {shutdown, self(), Reason},
- [Pid | Acc].
+ [MRef | Acc].
%% ---------------------------------------------------------------------------
%% # call_service/2
@@ -658,6 +731,8 @@ cfg_acc({SvcName, #diameter_service{applications = Apps} = Rec, Opts},
lists:foreach(fun init_mod/1, Apps),
S = #state{service_name = SvcName,
service = Rec#diameter_service{pid = self()},
+ local = init_peers(),
+ remote = init_peers(),
monitor = mref(get_value(monitor, Opts)),
options = service_options(Opts)},
{S, Acc};
@@ -667,19 +742,30 @@ cfg_acc({_Ref, Type, _Opts} = T, {S, Acc})
Type == listen ->
{S, [T | Acc]}.
+init_peers() ->
+ {ets_new(caps), %% #peer{}
+ ets:new(apps, [bag]), %% {Alias, TPid}
+ ets:new(idents, [bag])}. %% {{host, OH} | {realm, OR} | {OR, OH},
+ %% Alias,
+ %% TPid}
+
service_options(Opts) ->
[{sequence, proplists:get_value(sequence, Opts, ?NOMASK)},
{share_peers, get_value(share_peers, Opts)},
{use_shared_peers, get_value(use_shared_peers, Opts)},
{restrict_connections, proplists:get_value(restrict_connections,
Opts,
- ?RESTRICT)}].
+ ?RESTRICT)},
+ {spawn_opt, proplists:get_value(spawn_opt, Opts, [])},
+ {string_decode, proplists:get_value(string_decode, Opts, true)},
+ {incoming_maxlen, proplists:get_value(incoming_maxlen, Opts, 16#FFFFFF)},
+ {strict_mbit, proplists:get_value(strict_mbit, Opts, true)}].
%% The order of options is significant since we match against the list.
mref(false = No) ->
No;
mref(P) ->
- erlang:monitor(process, P).
+ monitor(process, P).
init_shared(#state{options = [_, _, {_,T} | _],
service_name = Svc}) ->
@@ -700,8 +786,7 @@ notify(Share, SvcName, T) ->
Nodes = remotes(Share),
[] /= Nodes andalso diameter_peer:notify(Nodes, SvcName, T).
%% Test for the empty list for upgrade reasons: there's no
-%% diameter_peer:notify/3 in old code so no call means no load order
-%% requirement.
+%% diameter_peer:notify/3 in old code.
remotes(false) ->
[];
@@ -719,14 +804,27 @@ remotes(F) ->
L when is_list(L) ->
L;
T ->
- diameter_lib:error_report({invalid_return, T}, F),
+ ?LOG(invalid_return, {F,T}),
+ error_report(invalid_return, share_peers, F),
[]
catch
E:R ->
- diameter_lib:error_report({failure, {E, R, ?STACK}}, F),
+ ?LOG(failure, {E, R, F, diameter_lib:get_stacktrace()}),
+ error_report(failure, share_peers, F),
[]
end.
+%% error_report/3
+
+error_report(T, What, F) ->
+ Reason = io_lib:format("~s from ~p callback", [reason(T), What]),
+ diameter_lib:error_report(Reason, diameter_lib:eval_name(F)).
+
+reason(invalid_return) ->
+ "invalid return";
+reason(failure) ->
+ "failure".
+
%% ---------------------------------------------------------------------------
%% # start/3
%% ---------------------------------------------------------------------------
@@ -740,8 +838,9 @@ remotes(F) ->
start(Ref, {T, Opts}, S)
when T == connect;
T == listen ->
+ N = proplists:get_value(pool_size, Opts, 1),
try
- {ok, start(Ref, type(T), Opts, S)}
+ {ok, start(Ref, type(T), Opts, N, S)}
catch
?FAILURE(Reason) ->
{error, Reason}
@@ -759,26 +858,44 @@ type(connect = T) -> T.
%% start/4
-start(Ref, Type, Opts, #state{watchdogT = WatchdogT,
- peerT = PeerT,
- options = SvcOpts,
- service_name = SvcName,
- service = Svc0})
+start(Ref, Type, Opts, State) ->
+ start(Ref, Type, Opts, 1, State).
+
+%% start/5
+
+start(Ref, Type, Opts, N, #state{watchdogT = WatchdogT,
+ local = {PeerT, _, _},
+ options = SvcOpts,
+ service_name = SvcName,
+ service = Svc0})
when Type == connect;
Type == accept ->
#diameter_service{applications = Apps}
- = Svc
+ = Svc1
= merge_service(Opts, Svc0),
- {_,_} = Mask = proplists:get_value(sequence, SvcOpts),
- RecvData = diameter_traffic:make_recvdata([SvcName, PeerT, Apps, Mask]),
- Pid = s(Type, Ref, {{spawn_opts([Opts, SvcOpts]), RecvData},
- Opts,
- SvcOpts,
- Svc}),
- insert(WatchdogT, #watchdog{pid = Pid,
- type = Type,
- ref = Ref,
- options = Opts}),
+ Svc = binary_caps(Svc1, proplists:get_value(string_decode, SvcOpts, true)),
+ RecvData = diameter_traffic:make_recvdata([SvcName,
+ PeerT,
+ Apps,
+ SvcOpts]),
+ T = {{spawn_opts([Opts, SvcOpts]), RecvData}, Opts, SvcOpts, Svc},
+ Rec = #watchdog{type = Type,
+ ref = Ref,
+ options = Opts},
+ diameter_lib:fold_n(fun(_,A) ->
+ [wd(Type, Ref, T, WatchdogT, Rec) | A]
+ end,
+ [],
+ N).
+
+binary_caps(Svc, true) ->
+ Svc;
+binary_caps(#diameter_service{capabilities = Caps} = Svc, false) ->
+ Svc#diameter_service{capabilities = diameter_capx:binary_caps(Caps)}.
+
+wd(Type, Ref, T, WatchdogT, Rec) ->
+ Pid = start_watchdog(Type, Ref, T),
+ ets:insert(WatchdogT, Rec#watchdog{pid = Pid}),
Pid.
%% Note that the service record passed into the watchdog is the merged
@@ -791,7 +908,7 @@ spawn_opts(Optss) ->
T /= link,
T /= monitor].
-s(Type, Ref, T) ->
+start_watchdog(Type, Ref, T) ->
{_MRef, Pid} = diameter_watchdog:start({Type, Ref}, T),
Pid.
@@ -812,7 +929,7 @@ ms({applications, As}, #diameter_service{applications = Apps} = S)
%% The fact that all capabilities can be configured on the transports
%% means that the service doesn't necessarily represent a single
-%% locally implemented Diameter peer as identified by Origin-Host: a
+%% locally implemented Diameter node as identified by Origin-Host: a
%% transport can configure its own Origin-Host. This means that the
%% service little more than a placeholder for default capabilities
%% plus a list of applications that individual transports can choose
@@ -835,8 +952,8 @@ accepted(Pid, _TPid, #state{watchdogT = WatchdogT} = S) ->
#watchdog{ref = Ref, type = accept = T, peer = false, options = Opts}
= Wd
= fetch(WatchdogT, Pid),
- insert(WatchdogT, Wd#watchdog{peer = true}),%% mark replacement as started
- start(Ref, T, Opts, S). %% start new watchdog
+ ets:insert(WatchdogT, Wd#watchdog{peer = true}),%% mark replacement started
+ start(Ref, T, Opts, S). %% start new watchdog
fetch(Tid, Key) ->
[T] = ets:lookup(Tid, Key),
@@ -862,14 +979,15 @@ watchdog(TPid, [], ?WD_SUSPECT, ?WD_OKAY, Wd, State) ->
#watchdog{peer = TPid} = Wd, %% assert
connection_up(Wd, State);
-%% Watchdog has an unresponsive connection.
+%% Watchdog has an unresponsive connection. Note that the peer table
+%% entry isn't removed until DOWN.
watchdog(TPid, [], ?WD_OKAY, ?WD_SUSPECT = To, Wd, State) ->
#watchdog{peer = TPid} = Wd, %% assert
watchdog_down(Wd, To, State);
%% Watchdog has lost its connection.
-watchdog(TPid, [], _, ?WD_DOWN = To, Wd, #state{peerT = PeerT} = S) ->
- close(Wd, S),
+watchdog(TPid, [], _, ?WD_DOWN = To, Wd, #state{local = {PeerT, _, _}} = S) ->
+ close(Wd),
watchdog_down(Wd, To, S),
ets:delete(PeerT, TPid);
@@ -877,7 +995,7 @@ watchdog(_, [], _, _, _, _) ->
ok.
watchdog_down(Wd, To, #state{watchdogT = WatchdogT} = S) ->
- insert(WatchdogT, Wd#watchdog{state = To}),
+ ets:insert(WatchdogT, Wd#watchdog{state = To}),
connection_down(Wd, To, S).
%% ---------------------------------------------------------------------------
@@ -889,14 +1007,14 @@ watchdog_down(Wd, To, #state{watchdogT = WatchdogT} = S) ->
connection_up({TPid, {Caps, SupportedApps, Pkt}},
#watchdog{pid = Pid}
= Wd,
- #state{peerT = PeerT}
+ #state{local = {PeerT, _, _}}
= S) ->
- Pr = #peer{pid = TPid,
- apps = SupportedApps,
- caps = Caps,
- watchdog = Pid},
- insert(PeerT, Pr),
- connection_up([Pkt], Wd#watchdog{peer = TPid}, Pr, S).
+ Rec = #peer{pid = TPid,
+ apps = SupportedApps,
+ caps = Caps,
+ watchdog = Pid},
+ ets:insert(PeerT, Rec),
+ connection_up([Pkt], Wd#watchdog{peer = TPid}, Rec, S).
%% ---------------------------------------------------------------------------
%% # reopen/3
@@ -906,22 +1024,23 @@ reopen({TPid, {Caps, SupportedApps, _Pkt}},
#watchdog{pid = Pid}
= Wd,
#state{watchdogT = WatchdogT,
- peerT = PeerT}) ->
- insert(PeerT, #peer{pid = TPid,
- apps = SupportedApps,
- caps = Caps,
- watchdog = Pid}),
- insert(WatchdogT, Wd#watchdog{state = ?WD_REOPEN,
- peer = TPid}).
+ local = {PeerT, _, _}}) ->
+ ets:insert(PeerT, #peer{pid = TPid,
+ apps = SupportedApps,
+ caps = Caps,
+ watchdog = Pid}),
+ ets:insert(WatchdogT, Wd#watchdog{state = ?WD_REOPEN,
+ peer = TPid}).
%% ---------------------------------------------------------------------------
%% # connection_up/2
%% ---------------------------------------------------------------------------
-%% Watchdog has recovered as suspect connection. Note that there has
+%% Watchdog has recovered a suspect connection. Note that there has
%% been no new capabilties exchange in this case.
-connection_up(#watchdog{peer = TPid} = Wd, #state{peerT = PeerT} = S) ->
+connection_up(#watchdog{peer = TPid} = Wd, #state{local = {PeerT, _, _}}
+ = S) ->
connection_up([], Wd, fetch(PeerT, TPid), S).
%% connection_up/4
@@ -932,23 +1051,23 @@ connection_up(Extra,
#peer{apps = SApps, caps = Caps}
= Pr,
#state{watchdogT = WatchdogT,
- local_peers = LDict,
+ local = LT,
service_name = SvcName,
service = #diameter_service{applications = Apps}}
= S) ->
- insert(WatchdogT, Wd#watchdog{state = ?WD_OKAY}),
+ ets:insert(WatchdogT, Wd#watchdog{state = ?WD_OKAY}),
diameter_traffic:peer_up(TPid),
- insert_local_peer(SApps, {{TPid, Caps}, {SvcName, Apps}}, LDict),
+ local_peer_up(SApps, {TPid, Caps}, {SvcName, Apps}, LT),
report_status(up, Wd, Pr, S, Extra).
-insert_local_peer(SApps, T, LDict) ->
- lists:foldl(fun(A,D) -> ilp(A, T, D) end, LDict, SApps).
+local_peer_up(SApps, {TPid, Caps} = TC, SA, LT) ->
+ insert_peer(TPid, [A || {_,A} <- SApps], Caps, LT),
+ lists:foreach(fun(A) -> peer_up(A, TC, SA) end, SApps).
-ilp({Id, Alias}, {TC, SA}, LDict) ->
- init_conn(Id, Alias, TC, SA),
- ?Dict:append(Alias, TC, LDict).
+peer_up({Id, Alias}, TC, SA) ->
+ peer_up(Id, Alias, TC, SA).
-init_conn(Id, Alias, {TPid, _} = TC, {SvcName, Apps}) ->
+peer_up(Id, Alias, {TPid, _} = TC, {SvcName, Apps}) ->
#diameter_app{id = Id} %% assert
= App
= find_app(Alias, Apps),
@@ -1026,8 +1145,11 @@ peer_cb(App, F, A) ->
true
catch
E:R ->
- diameter_lib:error_report({failure, {E, R, ?STACK}},
- {App, F, A}),
+ %% Don't include arguments since a #diameter_caps{} strings
+ %% from the peer, which could be anything (especially, large).
+ [Mod|X] = App#diameter_app.module,
+ ?LOG(failure, {E, R, Mod, F, diameter_lib:get_stacktrace()}),
+ error_report(failure, F, {Mod, F, A ++ X}),
false
end.
@@ -1043,17 +1165,17 @@ connection_down(#watchdog{state = ?WD_OKAY,
= Pr,
#state{service_name = SvcName,
service = #diameter_service{applications = Apps},
- local_peers = LDict}
+ local = LT}
= S) ->
report_status(down, Wd, Pr, S, []),
- remove_local_peer(SApps, {{TPid, Caps}, {SvcName, Apps}}, LDict),
+ local_peer_down(SApps, {TPid, Caps}, {SvcName, Apps}, LT),
diameter_traffic:peer_down(TPid);
connection_down(#watchdog{state = ?WD_OKAY,
peer = TPid}
= Wd,
To,
- #state{peerT = PeerT}
+ #state{local = {PeerT, _, _}}
= S)
when is_atom(To) ->
connection_down(Wd, #peer{} = fetch(PeerT, TPid), S);
@@ -1061,15 +1183,14 @@ connection_down(#watchdog{state = ?WD_OKAY,
connection_down(#watchdog{}, _, _) ->
ok.
-remove_local_peer(SApps, T, LDict) ->
- lists:foldl(fun(A,D) -> rlp(A, T, D) end, LDict, SApps).
+local_peer_down(SApps, {TPid, _Caps} = TC, SA, LT) ->
+ delete_peer(TPid, LT),
+ lists:foreach(fun(A) -> peer_down(A, TC, SA) end, SApps).
-rlp({Id, Alias}, {TC, SA}, LDict) ->
- L = ?Dict:fetch(Alias, LDict),
- down_conn(Id, Alias, TC, SA),
- ?Dict:store(Alias, lists:delete(TC, L), LDict).
+peer_down({Id, Alias}, TC, SA) ->
+ peer_down(Id, Alias, TC, SA).
-down_conn(Id, Alias, TC, {SvcName, Apps}) ->
+peer_down(Id, Alias, TC, {SvcName, Apps}) ->
#diameter_app{id = Id} %% assert
= App
= find_app(Alias, Apps),
@@ -1094,7 +1215,7 @@ wd_down(#watchdog{peer = B}, _)
ok;
%% ... or maybe it has.
-wd_down(#watchdog{peer = TPid} = Wd, #state{peerT = PeerT} = S) ->
+wd_down(#watchdog{peer = TPid} = Wd, #state{local = {PeerT, _, _}} = S) ->
connection_down(Wd, ?WD_DOWN, S),
ets:delete(PeerT, TPid).
@@ -1142,10 +1263,17 @@ q_restart(false, _) ->
%% communicate.
default_tc(connect, Opts) ->
- proplists:get_value(reconnect_timer, Opts, ?DEFAULT_TC);
+ connect_timer(Opts, ?DEFAULT_TC);
default_tc(accept, _) ->
0.
+%% Accept both connect_timer and the (older) reconnect_timer, the
+%% latter being a remnant from a time in which the timer did apply to
+%% reconnect attempts.
+connect_timer(Opts, Def0) ->
+ Def = proplists:get_value(reconnect_timer, Opts, Def0),
+ proplists:get_value(connect_timer, Opts, Def).
+
%% Bound tc below if the watchdog was restarted recently to avoid
%% continuous restarted in case of faulty config or other problems.
tc(Time, Tc) ->
@@ -1180,29 +1308,19 @@ tc(false = No, _, _) -> %% removed
%% another watchdog to be able to detect that it should transition
%% from initial into reopen rather than okay. That someone is either
%% the accepting watchdog upon reception of a CER from the previously
-%% connected peer, or us after reconnect_timer timeout.
+%% connected peer, or us after connect_timer timeout or immediately.
-close(#watchdog{type = connect}, _) ->
+close(#watchdog{type = connect}) ->
ok;
+
close(#watchdog{type = accept,
pid = Pid,
- ref = Ref,
- options = Opts},
- #state{service_name = SvcName}) ->
- c(Pid, diameter_config:have_transport(SvcName, Ref), Opts).
-
-%% Tell watchdog to (maybe) die later ...
-c(Pid, true, Opts) ->
- Tc = proplists:get_value(reconnect_timer, Opts, 2*?DEFAULT_TC),
- erlang:send_after(Tc, Pid, close);
-
-%% ... or now.
-c(Pid, false, _Opts) ->
- Pid ! close.
-
-%% The RFC's only document the behaviour of Tc, our reconnect_timer,
+ options = Opts}) ->
+ Tc = connect_timer(Opts, 2*?DEFAULT_TC),
+ erlang:send_after(Tc, Pid, close).
+%% The RFC's only document the behaviour of Tc, our connect_timer,
%% for the establishment of connections but we also give
-%% reconnect_timer semantics for a listener, being the time within
+%% connect_timer semantics for a listener, being the time within
%% which a new connection attempt is expected of a connecting peer.
%% The value should be greater than the peer's Tc + jitter.
@@ -1253,13 +1371,14 @@ cm([#diameter_app{alias = Alias} = App], Req, From, Svc) ->
mod_state(Alias, ModS),
{T, RC};
T ->
- diameter_lib:error_report({invalid, T},
- {App, handle_call, Args}),
+ ModX = App#diameter_app.module,
+ ?LOG(invalid_return, {ModX, handle_call, Args, T}),
invalid
catch
E: Reason ->
- diameter_lib:error_report({failure, {E, Reason, ?STACK}},
- {App, handle_call, Args}),
+ ModX = App#diameter_app.module,
+ Stack = diameter_lib:get_stacktrace(),
+ ?LOG(failure, {E, Reason, ModX, handle_call, Stack}),
failure
end;
@@ -1304,19 +1423,37 @@ share_peer(up, Caps, Apps, TPid, #state{options = [_, {_,T} | _],
service_name = Svc}) ->
notify(T, Svc, {peer, TPid, [A || {_,A} <- Apps], Caps});
-share_peer(_, _, _, _, _) ->
- ok.
+share_peer(down, _Caps, _Apps, TPid, #state{options = [_, {_,T} | _],
+ service_name = Svc}) ->
+ notify(T, Svc, {peer, TPid}).
%% ---------------------------------------------------------------------------
%% # share_peers/2
%% ---------------------------------------------------------------------------
-share_peers(Pid, #state{options = [_, {_,T} | _], local_peers = PDict}) ->
- is_remote(Pid, T)
- andalso ?Dict:fold(fun(A,Ps,ok) -> sp(Pid, A, Ps), ok end, ok, PDict).
-
-sp(Pid, Alias, Peers) ->
- lists:foreach(fun({P,C}) -> Pid ! {peer, P, [Alias], C} end, Peers).
+share_peers(Pid, #state{options = [_, {_,SP} | _],
+ local = {PeerT, AppT, _}}) ->
+ is_remote(Pid, SP)
+ andalso ets:foldl(fun(T, N) -> N + sp(Pid, AppT, T) end,
+ 0,
+ PeerT).
+
+%% An entry in the peer table doesn't mean the watchdog state is OKAY,
+%% an entry in the app table does.
+
+sp(Pid, AppT, #peer{pid = TPid,
+ apps = [{_, Alias} | _] = Apps,
+ caps = Caps}) ->
+ Spec = [{{'$1', TPid},
+ [{'==', '$1', {const, Alias}}],
+ ['$_']}],
+ case ets:select(AppT, Spec, 1) of
+ '$end_of_table' ->
+ 0;
+ _ ->
+ Pid ! {peer, TPid, [A || {_,A} <- Apps], Caps},
+ 1
+ end.
is_remote(Pid, T) ->
Node = node(Pid),
@@ -1326,32 +1463,49 @@ is_remote(Pid, T) ->
%% # remote_peer_up/4
%% ---------------------------------------------------------------------------
-remote_peer_up(Pid, Aliases, Caps, #state{options = [_, _, {_,T} | _]} = S) ->
- is_remote(Pid, T)
- andalso rpu(Pid, Aliases, Caps, S).
+remote_peer_up(TPid, Aliases, Caps, #state{options = [_, _, {_,T} | _]} = S) ->
+ is_remote(TPid, T) andalso rpu(TPid, Aliases, Caps, S).
-rpu(Pid, Aliases, Caps, #state{service = Svc, shared_peers = PDict}) ->
+rpu(TPid, Aliases, Caps, #state{service = Svc, remote = RT}) ->
#diameter_service{applications = Apps} = Svc,
Key = #diameter_app.alias,
F = fun(A) -> lists:keymember(A, Key, Apps) end,
- rpu(Pid, lists:filter(F, Aliases), Caps, PDict);
+ rpu(TPid, lists:filter(F, Aliases), Caps, RT);
rpu(_, [] = No, _, _) ->
No;
-rpu(Pid, Aliases, Caps, PDict) ->
- erlang:monitor(process, Pid),
- T = {Pid, Caps},
- lists:foreach(fun(A) -> ?Dict:append(A, T, PDict) end, Aliases).
+rpu(TPid, Aliases, Caps, {PeerT, _, _} = RT) ->
+ monitor(process, TPid),
+ ets:insert(PeerT, #peer{pid = TPid,
+ apps = Aliases,
+ caps = Caps}),
+ insert_peer(TPid, Aliases, Caps, RT).
+
+%% insert_peer/4
+
+insert_peer(TPid, Aliases, Caps, {_PeerT, AppT, IdentT}) ->
+ #diameter_caps{origin_host = {_, OH},
+ origin_realm = {_, OR}}
+ = Caps,
+ ets:insert(AppT, [{A, TPid} || A <- Aliases]),
+ H = iolist_to_binary(OH),
+ R = iolist_to_binary(OR),
+ ets:insert(IdentT, [{T, A, TPid} || T <- [{host, H}, {realm, R}, {R, H}],
+ A <- Aliases]).
%% ---------------------------------------------------------------------------
%% # remote_peer_down/2
%% ---------------------------------------------------------------------------
-remote_peer_down(Pid, #state{shared_peers = PDict}) ->
- lists:foreach(fun(A) -> rpd(Pid, A, PDict) end, ?Dict:fetch_keys(PDict)).
+remote_peer_down(TPid, #state{remote = {PeerT, _, _} = RT}) ->
+ ets:delete(PeerT, TPid),
+ delete_peer(TPid, RT).
+
+%% delete_peer/2
-rpd(Pid, Alias, PDict) ->
- ?Dict:update(Alias, fun(Ps) -> lists:keydelete(Pid, 1, Ps) end, PDict).
+delete_peer(TPid, {_PeerT, AppT, IdentT}) ->
+ ets:select_delete(AppT, [{{'_', TPid}, [], [true]}]),
+ ets:select_delete(IdentT, [{{'_', '_', TPid}, [], [true]}]).
%% ---------------------------------------------------------------------------
%% pick_peer/4
@@ -1361,12 +1515,12 @@ pick_peer(#diameter_app{alias = Alias}
= App,
RealmAndHost,
Filter,
- #state{local_peers = L,
- shared_peers = S,
+ #state{local = LT,
+ remote = RT,
service_name = SvcName,
service = #diameter_service{pid = Pid}}) ->
- pick_peer(peers(Alias, RealmAndHost, Filter, L),
- peers(Alias, RealmAndHost, Filter, S),
+ pick_peer(peers(Alias, RealmAndHost, Filter, LT),
+ peers(Alias, RealmAndHost, Filter, RT),
Pid,
SvcName,
App).
@@ -1382,6 +1536,8 @@ pick_peer(Local, Remote, Pid, _SvcName, #diameter_app{mutable = true} = App)
case call_service(Pid, {pick_peer, Local, Remote, App}) of
{TPid, _} = T when is_pid(TPid) ->
T;
+ false = No ->
+ No;
{error, _} ->
false
end;
@@ -1415,56 +1571,211 @@ pick_peer(Local,
T; %% Accept returned state in the immutable
{false = No, S} -> %% case as long it isn't changed.
No;
- T ->
- diameter_lib:error_report({invalid, T, App},
- {App, pick_peer, Args})
+ T when M ->
+ ModX = App#diameter_app.module,
+ ?LOG(invalid_return, {ModX, pick_peer, T}),
+ false
catch
- E: Reason ->
- diameter_lib:error_report({failure, {E, Reason, ?STACK}},
- {App, pick_peer, Args})
+ E: Reason when M ->
+ ModX = App#diameter_app.module,
+ Stack = diameter_lib:get_stacktrace(),
+ ?LOG(failure, {E, Reason, ModX, pick_peer, Stack}),
+ false
end.
%% peers/4
-peers(Alias, RH, Filter, Peers) ->
- case ?Dict:find(Alias, Peers) of
- {ok, L} ->
- ps(L, RH, Filter, {[],[]});
- error ->
+peers(Alias, RH, Filter, T) ->
+ filter(Alias, RH, Filter, T, true).
+
+%% filter/5
+%%
+%% Try to limit the peers list by starting with a host/realm lookup.
+
+filter(Alias, RH, {neg, F}, T, B) ->
+ filter(Alias, RH, F, T, not B);
+
+filter(_, _, none, _, false) ->
+ [];
+
+filter(Alias, _, none, T, true) ->
+ all_peers(Alias, T);
+
+filter(Alias, [DR,DH] = RH, K, T, B)
+ when K == realm, DR == undefined;
+ K == host, DH == undefined ->
+ filter(Alias, RH, none, T, B);
+
+filter(Alias, [DR,_] = RH, realm = K, T, B) ->
+ filter(Alias, RH, {K, DR}, T, B);
+
+filter(Alias, [_,DH] = RH, host = K, T, B) ->
+ filter(Alias, RH, {K, DH}, T, B);
+
+filter(Alias, _, {K, D}, {PeerT, _AppT, IdentT}, true)
+ when K == host;
+ K == realm ->
+ try iolist_to_binary(D) of
+ B ->
+ caps(PeerT, ets:select(IdentT, [{{{K, B}, '$1', '$2'},
+ [{'==', '$1', {const, Alias}}],
+ ['$2']}]))
+ catch
+ error:_ ->
[]
- end.
+ end;
-%% Place a peer whose Destination-Host/Realm matches those of the
-%% request at the front of the result list. Could add some sort of
-%% 'sort' option to allow more control.
-
-ps([], _, _, {Ys, Ns}) ->
- lists:reverse(Ys, Ns);
-ps([{_TPid, #diameter_caps{} = Caps} = TC | Rest], RH, Filter, Acc) ->
- ps(Rest, RH, Filter, pacc(caps_filter(Caps, RH, Filter),
- caps_filter(Caps, RH, {all, [host, realm]}),
- TC,
- Acc)).
-
-pacc(true, true, Peer, {Ts, Fs}) ->
- {[Peer|Ts], Fs};
-pacc(true, false, Peer, {Ts, Fs}) ->
- {Ts, [Peer|Fs]};
-pacc(_, _, _, Acc) ->
- Acc.
+filter(Alias, RH, {all, Filters}, T, B)
+ when is_list(Filters) ->
+ fltr_all(Alias, RH, Filters, T, B);
+
+filter(Alias, RH, {first, Filters}, T, B)
+ when is_list(Filters) ->
+ fltr_first(Alias, RH, Filters, T, B);
+
+filter(Alias, RH, Filter, T, B) ->
+ {Ts, Fs} = filter(all_peers(Alias, T), RH, Filter),
+ choose(B, Ts, Fs).
+
+%% fltr_all/5
+
+fltr_all(Alias, RH, [{K, any} | Filters], T, B)
+ when K == host;
+ K == realm ->
+ fltr_all(Alias, RH, Filters, T, B);
+
+fltr_all(Alias, RH, [{host, _} = H, {realm, _} = R | Filters], T, B) ->
+ fltr_all(Alias, RH, [R, H | Filters], T, B);
+
+fltr_all(Alias, RH, [{realm, _} = R, {host, any} | Filters], T, B) ->
+ fltr_all(Alias, RH, [R | Filters], T, B);
+
+fltr_all(Alias, RH, [{realm, OR}, {host, OH} | Filters], T, true) ->
+ {PeerT, _AppT, IdentT} = T,
+ try {iolist_to_binary(OR), iolist_to_binary(OH)} of
+ BT ->
+ Peers = caps(PeerT,
+ ets:select(IdentT, [{{BT, '$1', '$2'},
+ [{'==', '$1', {const, Alias}}],
+ ['$2']}])),
+ {Ts, _} = filter(Peers, RH, {all, Filters}),
+ Ts
+ catch
+ error:_ ->
+ []
+ end;
-%% caps_filter/3
+fltr_all(Alias, [undefined,_] = RH, [realm | Filters], T, B) ->
+ fltr_all(Alias, RH, Filters, T, B);
+
+fltr_all(Alias, [DR,_] = RH, [realm | Filters], T, B) ->
+ fltr_all(Alias, RH, [{realm, DR} | Filters], T, B);
+
+fltr_all(Alias, [_,undefined] = RH, [host | Filters], T, B) ->
+ fltr_all(Alias, RH, Filters, T, B);
+
+fltr_all(Alias, [_,DH] = RH, [host | Filters], T, B) ->
+ fltr_all(Alias, RH, [{host, DH} | Filters], T, B);
+
+fltr_all(Alias, RH, [{K, _} = KT, KA | Filters], T, B)
+ when K == host, KA == realm;
+ K == realm, KA == host ->
+ fltr_all(Alias, RH, [KA, KT | Filters], T, B);
+
+fltr_all(Alias, RH, [F | Filters], T, B) ->
+ {Ts, Fs} = filter(filter(Alias, RH, F, T, B), RH, {all, Filters}),
+ choose(B, Ts, Fs);
+
+fltr_all(Alias, RH, [], T, B) ->
+ filter(Alias, RH, none, T, B).
+
+%% fltr_first/5
+%%
+%% Like any, but stop at the first filter with any matches.
+
+fltr_first(Alias, RH, [F | Filters], T, B) ->
+ case filter(Alias, RH, F, T, B) of
+ [] ->
+ fltr_first(Alias, RH, Filters, T, B);
+ [_|_] = Ts ->
+ Ts
+ end;
+
+fltr_first(Alias, RH, [], T, B) ->
+ filter(Alias, RH, none, T, not B).
+
+%% all_peers/2
-caps_filter(C, RH, {neg, F}) ->
- not caps_filter(C, RH, F);
+all_peers(Alias, {PeerT, AppT, _}) ->
+ ets:select(PeerT, [{#peer{pid = P, caps = '$1', _ = '_'},
+ [],
+ [{{P, '$1'}}]}
+ || {_,P} <- ets:lookup(AppT, Alias)]).
-caps_filter(C, RH, {all, L})
+%% caps/2
+
+caps(PeerT, Pids) ->
+ ets:select(PeerT, [{#peer{pid = P, caps = '$1', _ = '_'},
+ [],
+ [{{P, '$1'}}]}
+ || P <- Pids]).
+
+%% filter/3
+%%
+%% Return peers in match order.
+
+filter(Peers, _, none) ->
+ {Peers, []};
+
+filter(Peers, RH, {neg, F}) ->
+ {Ts, Fs} = filter(Peers, RH, F),
+ {Fs, Ts};
+
+filter(Peers, RH, {all, L})
+ when is_list(L) ->
+ lists:foldl(fun(F,A) -> fltr_all(F, A, RH) end,
+ {Peers, []},
+ L);
+
+filter(Peers, RH, {any, L})
when is_list(L) ->
- lists:all(fun(F) -> caps_filter(C, RH, F) end, L);
+ lists:foldl(fun(F,A) -> fltr_any(F, A, RH) end,
+ {[], Peers},
+ L);
-caps_filter(C, RH, {any, L})
+filter(Peers, RH, {first, L})
when is_list(L) ->
- lists:any(fun(F) -> caps_filter(C, RH, F) end, L);
+ fltr_first(Peers, RH, L);
+
+filter(Peers, RH, F) ->
+ lists:partition(fun({_,C}) -> caps_filter(C, RH, F) end, Peers).
+
+%% fltr_all/3
+
+fltr_all(F, {Ts0, Fs0}, RH) ->
+ {Ts1, Fs1} = filter(Ts0, RH, F),
+ {Ts1, Fs0 ++ Fs1}.
+
+%% fltr_any/3
+
+fltr_any(F, {Ts0, Fs0}, RH) ->
+ {Ts1, Fs1} = filter(Fs0, RH, F),
+ {Ts0 ++ Ts1, Fs1}.
+
+%% fltr_first/3
+
+fltr_first(Peers, _, []) ->
+ {[], Peers};
+
+fltr_first(Peers, RH, [F | Filters]) ->
+ case filter(Peers, RH, F) of
+ {[], _} ->
+ fltr_first(Peers, RH, Filters);
+ {_, _} = T ->
+ T
+ end.
+
+%% caps_filter/3
caps_filter(#diameter_caps{origin_host = {_,OH}}, [_,DH], host) ->
eq(undefined, DH, OH);
@@ -1477,9 +1788,6 @@ caps_filter(C, _, Filter) ->
%% caps_filter/2
-caps_filter(_, none) ->
- true;
-
caps_filter(#diameter_caps{origin_host = {_,OH}}, {host, H}) ->
eq(any, H, OH);
@@ -1510,8 +1818,8 @@ eq(Any, Id, PeerId) ->
transports(#state{watchdogT = WatchdogT}) ->
ets:select(WatchdogT, [{#watchdog{peer = '$1', _ = '_'},
- [{'is_pid', '$1'}],
- ['$1']}]).
+ [{'is_pid', '$1'}],
+ ['$1']}]).
%% ---------------------------------------------------------------------------
%% # service_info/2
@@ -1542,7 +1850,8 @@ transports(#state{watchdogT = WatchdogT}) ->
-define(OTHER_INFO, [connections,
name,
peers,
- statistics]).
+ statistics,
+ info]).
service_info(Item, S)
when is_atom(Item) ->
@@ -1563,7 +1872,7 @@ tagged_info(Item, S)
undefined
end;
-tagged_info(TPid, #state{watchdogT = WatchdogT, peerT = PeerT})
+tagged_info(TPid, #state{watchdogT = WatchdogT, local = {PeerT, _, _}})
when is_pid(TPid) ->
try
[#peer{watchdog = Pid}] = ets:lookup(PeerT, TPid),
@@ -1632,6 +1941,7 @@ complete_info(Item, #state{service = Svc} = S) ->
keys -> ?ALL_INFO ++ ?CAP_INFO ++ ?OTHER_INFO;
all -> service_info(?ALL_INFO, S);
statistics -> info_stats(S);
+ info -> info_info(S);
connections -> info_connections(S);
peers -> info_peers(S)
end.
@@ -1678,31 +1988,43 @@ info_transport(S) ->
[],
PeerD).
-%% Only a config entry for a listening transport: use it.
-transport([[{type, listen}, _] = L]) ->
- L ++ [{accept, []}];
-
-%% Only one config or peer entry for a connecting transport: use it.
-transport([[{type, connect} | _] = L]) ->
- L;
+%% Single config entry. Distinguish between pool_size config or not on
+%% a connecting transport for backwards compatibility: with the option
+%% the form is similar to the listening case, with connections grouped
+%% in a pool tuple (for lack of a better name), without as before.
+transport([[{type, Type}, {options, Opts}] = L])
+ when Type == listen;
+ Type == connect ->
+ L ++ [{K, []} || [{_,K}] <- [keys(Type, Opts)]];
%% Peer entries: discard config. Note that the peer entries have
%% length at least 3.
transport([[_,_] | L]) ->
transport(L);
-%% Possibly many peer entries for a listening transport. Note that all
-%% have the same options by construction, which is not terribly space
-%% efficient.
-transport([[{type, accept}, {options, Opts} | _] | _] = Ls) ->
- [{type, listen},
+%% Multiple tranports. Note that all have the same options by
+%% construction, which is not terribly space efficient.
+transport([[{type, Type}, {options, Opts} | _] | _] = Ls) ->
+ transport(keys(Type, Opts), Ls).
+
+%% Group transports in an accept or pool tuple ...
+transport([{Type, Key}], [[{type, _}, {options, Opts} | _] | _] = Ls) ->
+ [{type, Type},
{options, Opts},
- {accept, [lists:nthtail(2,L) || L <- Ls]}].
+ {Key, [tl(tl(L)) || L <- Ls]}];
+
+%% ... or not: there can only be one.
+transport([], [L]) ->
+ L.
+
+keys(connect = T, Opts) ->
+ [{T, pool} || lists:keymember(pool_size, 1, Opts)];
+keys(_, _) ->
+ [{listen, accept}].
-peer_dict(#state{watchdogT = WatchdogT, peerT = PeerT}, Dict0) ->
+peer_dict(#state{watchdogT = WatchdogT, local = {PeerT, _, _}}, Dict0) ->
try ets:tab2list(WatchdogT) of
- L ->
- lists:foldl(fun(T,A) -> peer_acc(PeerT, A, T) end, Dict0, L)
+ L -> lists:foldl(fun(T,A) -> peer_acc(PeerT, A, T) end, Dict0, L)
catch
error: badarg -> Dict0 %% service has gone down
end.
@@ -1714,12 +2036,11 @@ peer_acc(PeerT, Acc, #watchdog{pid = Pid,
state = WS,
started = At,
peer = TPid}) ->
- dict:append(Ref,
- [{type, Type},
- {options, Opts},
- {watchdog, {Pid, At, WS}}
- | info_peer(PeerT, TPid, WS)],
- Acc).
+ Info = [{type, Type},
+ {options, Opts},
+ {watchdog, {Pid, At, WS}}
+ | info_peer(PeerT, TPid, WS)],
+ dict:append(Ref, Info ++ [{info, info_process_info(Info)}], Acc).
info_peer(PeerT, TPid, WS)
when is_pid(TPid), WS /= ?WD_DOWN ->
@@ -1731,6 +2052,49 @@ info_peer(PeerT, TPid, WS)
info_peer(_, _, _) ->
[].
+info_process_info(Info) ->
+ lists:flatmap(fun ipi/1, Info).
+
+ipi({watchdog, {Pid, _, _}}) ->
+ info_pid(Pid);
+
+ipi({peer, {Pid, _}}) ->
+ info_pid(Pid);
+
+ipi({port, [{owner, Pid} | _]}) ->
+ info_pid(Pid);
+
+ipi(_) ->
+ [].
+
+info_pid(Pid) ->
+ case process_info(Pid, [message_queue_len, memory, binary]) of
+ undefined ->
+ [];
+ L ->
+ [{Pid, lists:map(fun({K,V}) -> {K, map_info(K,V)} end, L)}]
+ end.
+
+%% The binary list consists of 3-tuples {Ptr, Size, Count}, where Ptr
+%% is a C pointer value, Size is the size of a referenced binary in
+%% bytes, and Count is a global reference count. The same Ptr can
+%% occur multiple times, once for each reference on the process heap.
+%% In this case, the corresponding tuples will have Size in common but
+%% Count may differ just because no global lock is taken when the
+%% value is retrieved.
+%%
+%% The list can be quite large, and we aren't often interested in the
+%% pointers or counts, so whittle this down to the number of binaries
+%% referenced and their total byte count.
+map_info(binary, L) ->
+ SzD = lists:foldl(fun({P,S,_}, D) -> dict:store(P,S,D) end,
+ dict:new(),
+ L),
+ {dict:size(SzD), dict:fold(fun(_,S,N) -> S + N end, 0, SzD)};
+
+map_info(_, T) ->
+ T.
+
%% The point of extracting the config here is so that 'transport' info
%% has one entry for each transport ref, the peer table only
%% containing entries that have a living watchdog.
@@ -1788,6 +2152,13 @@ mk_app(#diameter_app{} = A) ->
info_pending(#state{} = S) ->
diameter_traffic:pending(transports(S)).
+%% info_info/1
+%%
+%% Extract process_info from connections info.
+
+info_info(S) ->
+ [I || L <- conn_list(S), {info, I} <- L].
+
%% info_connections/1
%%
%% One entry per transport connection. Statistics for each entry are
diff --git a/lib/diameter/src/base/diameter_service_sup.erl b/lib/diameter/src/base/diameter_service_sup.erl
index 153fff902f..e3177f0083 100644
--- a/lib/diameter/src/base/diameter_service_sup.erl
+++ b/lib/diameter/src/base/diameter_service_sup.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2011. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -58,7 +58,7 @@ init([]) ->
ChildSpec = {Mod,
{Mod, start_link, []},
temporary,
- 1000,
+ 5000,
worker,
[Mod]},
{ok, {Flags, [ChildSpec]}}.
diff --git a/lib/diameter/src/base/diameter_stats.erl b/lib/diameter/src/base/diameter_stats.erl
index b68d4af11f..c4526d3a08 100644
--- a/lib/diameter/src/base/diameter_stats.erl
+++ b/lib/diameter/src/base/diameter_stats.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -22,7 +22,6 @@
%%
-module(diameter_stats).
-
-behaviour(gen_server).
-export([reg/2, reg/1,
@@ -140,9 +139,14 @@ read(Refs, B) ->
L.
to_refdict(L) ->
- lists:foldl(fun({{C,R}, N}, D) -> orddict:append(R, {C,N}, D) end,
- orddict:new(),
- L).
+ lists:foldl(fun append/2, orddict:new(), L).
+
+%% Order both references and counters in the returned list.
+append({{Ctr, Ref}, N}, Dict) ->
+ orddict:update(Ref,
+ fun(D) -> orddict:store(Ctr, N, D) end,
+ [{Ctr, N}],
+ Dict).
%% ---------------------------------------------------------------------------
%% # sum(Refs)
@@ -218,7 +222,7 @@ uptime() ->
%% ----------------------------------------------------------
init([]) ->
- ets:new(?TABLE, [named_table, ordered_set, public]),
+ ets:new(?TABLE, [named_table, set, public, {write_concurrency, true}]),
{ok, #state{}}.
%% ----------------------------------------------------------
@@ -245,9 +249,6 @@ handle_call({read, Refs, Del}, _From, State) ->
handle_call({read, Refs}, _, State) ->
{reply, read_refs(Refs), State};
-handle_call({flush, Refs}, _From, State) -> %% from old code
- {reply, to_refdict(read(Refs, true)), State};
-
handle_call(Req, From, State) ->
?UNEXPECTED([Req, From]),
{reply, nok, State}.
diff --git a/lib/diameter/src/base/diameter_sup.erl b/lib/diameter/src/base/diameter_sup.erl
index e5afd23dcd..4ede4086d8 100644
--- a/lib/diameter/src/base/diameter_sup.erl
+++ b/lib/diameter/src/base/diameter_sup.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2011. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -64,7 +64,7 @@ spec(Mod) ->
{Mod,
{Mod, start_link, []},
permanent,
- 1000,
+ infinity,
supervisor,
[Mod]}.
diff --git a/lib/diameter/src/base/diameter_sync.erl b/lib/diameter/src/base/diameter_sync.erl
index ce2db4b3a2..cee06b9e96 100644
--- a/lib/diameter/src/base/diameter_sync.erl
+++ b/lib/diameter/src/base/diameter_sync.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2011. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
diff --git a/lib/diameter/src/base/diameter_traffic.erl b/lib/diameter/src/base/diameter_traffic.erl
index 8b6f026b34..5d39c08213 100644
--- a/lib/diameter/src/base/diameter_traffic.erl
+++ b/lib/diameter/src/base/diameter_traffic.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2013. All Rights Reserved.
+%% Copyright Ericsson AB 2013-2016. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -31,11 +31,15 @@
%% towards diameter_watchdog
-export([receive_message/4]).
+%% towards diameter_peer_fsm and diameter_watchdog
+-export([incr/4,
+ incr_error/4,
+ incr_rc/4]).
+
%% towards diameter_service
-export([make_recvdata/1,
peer_up/1,
peer_down/1,
- failover/1,
pending/1]).
%% towards ?MODULE
@@ -44,6 +48,8 @@
-include_lib("diameter/include/diameter.hrl").
-include("diameter_internal.hrl").
+-define(LOGX(Reason, T), begin ?LOG(Reason, T), x({Reason, T}) end).
+
-define(RELAY, ?DIAMETER_DICT_RELAY).
-define(BASE, ?DIAMETER_DICT_COMMON). %% Note: the RFC 3588 dictionary
@@ -70,7 +76,13 @@
{peerT :: ets:tid(),
service_name :: diameter:service_name(),
apps :: [#diameter_app{}],
- sequence :: diameter:sequence()}).
+ sequence :: diameter:sequence(),
+ codec :: [{string_decode, boolean()}
+ | {strict_mbit, boolean()}
+ | {incoming_maxlen, diameter:message_length()}]}).
+%% Note that incoming_maxlen is currently handled in diameter_peer_fsm,
+%% so that any message exceeding the maximum is discarded. Retain the
+%% option in case we want to extend the values and semantics.
%% Record stored in diameter_request for each outgoing request.
-record(request,
@@ -85,14 +97,19 @@
%% # make_recvdata/1
%% ---------------------------------------------------------------------------
-make_recvdata([SvcName, PeerT, Apps, Mask | _]) ->
+make_recvdata([SvcName, PeerT, Apps, {_,_} = Mask | _]) -> %% from old code
+ make_recvdata([SvcName, PeerT, Apps, [{sequence, Mask}]]);
+
+make_recvdata([SvcName, PeerT, Apps, SvcOpts | _]) ->
+ {_,_} = Mask = proplists:get_value(sequence, SvcOpts),
#recvdata{service_name = SvcName,
peerT = PeerT,
apps = Apps,
- sequence = Mask}.
-%% Take a list so that the caller (diameter_service) can be upgraded
-%% first if new members are added. Note that receive_message/4 might
-%% still get an old term from any watchdog started in old code.
+ sequence = Mask,
+ codec = [T || {K,_} = T <- SvcOpts,
+ lists:member(K, [string_decode,
+ incoming_maxlen,
+ strict_mbit])]}.
%% ---------------------------------------------------------------------------
%% peer_up/1
@@ -112,6 +129,78 @@ peer_down(TPid) ->
failover(TPid).
%% ---------------------------------------------------------------------------
+%% incr/4
+%% ---------------------------------------------------------------------------
+
+incr(Dir, #diameter_packet{header = H}, TPid, AppDict) ->
+ incr(Dir, H, TPid, AppDict);
+
+incr(Dir, #diameter_header{} = H, TPid, AppDict) ->
+ incr(TPid, {msg_id(H, AppDict), Dir}).
+
+%% ---------------------------------------------------------------------------
+%% incr_error/4
+%% ---------------------------------------------------------------------------
+
+%% Identify messages using the application dictionary, not the encode
+%% dictionary, which may differ in the case of answer-message.
+incr_error(Dir, T, Pid, {_MsgDict, AppDict}) ->
+ incr_error(Dir, T, Pid, AppDict);
+
+%% Decoded message without errors.
+incr_error(recv, #diameter_packet{errors = []}, _, _) ->
+ ok;
+
+incr_error(recv = D, #diameter_packet{header = H}, TPid, AppDict) ->
+ incr_error(D, H, TPid, AppDict);
+
+%% Encoded message with errors and an identifiable header ...
+incr_error(send = D, {_, _, #diameter_header{} = H}, TPid, AppDict) ->
+ incr_error(D, H, TPid, AppDict);
+
+%% ... or not.
+incr_error(send = D, {_,_}, TPid, _) ->
+ incr_error(D, unknown, TPid);
+
+incr_error(Dir, #diameter_header{} = H, TPid, AppDict) ->
+ incr_error(Dir, msg_id(H, AppDict), TPid);
+
+incr_error(Dir, Id, TPid, _) ->
+ incr_error(Dir, Id, TPid).
+
+incr_error(Dir, Id, TPid) ->
+ incr(TPid, {Id, Dir, error}).
+
+%% ---------------------------------------------------------------------------
+%% incr_rc/4
+%% ---------------------------------------------------------------------------
+
+-spec incr_rc(send|recv, Pkt, TPid, DictT)
+ -> {Counter, non_neg_integer()}
+ | Reason
+ when Pkt :: #diameter_packet{},
+ TPid :: pid(),
+ DictT :: module() | {MsgDict :: module(),
+ AppDict :: module(),
+ CommonDict:: module()},
+ Counter :: {'Result-Code', integer()}
+ | {'Experimental-Result', integer(), integer()},
+ Reason :: atom().
+
+incr_rc(Dir, Pkt, TPid, {_, AppDict, _} = DictT) ->
+ try
+ incr_result(Dir, Pkt, TPid, DictT)
+ catch
+ exit: {E,_} when E == no_result_code;
+ E == invalid_error_bit ->
+ incr(TPid, {msg_id(Pkt#diameter_packet.header, AppDict), Dir, E}),
+ E
+ end;
+
+incr_rc(Dir, Pkt, TPid, Dict0) ->
+ incr_rc(Dir, Pkt, TPid, {Dict0, Dict0, Dict0}).
+
+%% ---------------------------------------------------------------------------
%% pending/1
%% ---------------------------------------------------------------------------
@@ -153,6 +242,8 @@ receive_message(TPid, Pkt, Dict0, RecvData)
Dict0,
RecvData).
+%% recv/6
+
%% Incoming request ...
recv(true, false, TPid, Pkt, Dict0, T) ->
spawn_request(TPid, Pkt, Dict0, T);
@@ -160,6 +251,7 @@ recv(true, false, TPid, Pkt, Dict0, T) ->
%% ... answer to known request ...
recv(false, #request{ref = Ref, handler = Pid} = Req, _, Pkt, Dict0, _) ->
Pid ! {answer, Ref, Req, Dict0, Pkt};
+
%% Note that failover could have happened prior to this message being
%% received and triggering failback. That is, both a failover message
%% and answer may be on their way to the handler process. In the worst
@@ -170,7 +262,9 @@ recv(false, #request{ref = Ref, handler = Pid} = Req, _, Pkt, Dict0, _) ->
%% any others are discarded.
%% ... or not.
-recv(false, false, _, _, _, _) ->
+recv(false, false, TPid, Pkt, _, _) ->
+ ?LOG(discarded, Pkt#diameter_packet.header),
+ incr(TPid, {{unknown, 0}, recv, discarded}),
ok.
%% spawn_request/4
@@ -185,7 +279,7 @@ spawn_request(TPid, Pkt, Dict0, Opts, RecvData) ->
spawn_opt(fun() -> recv_request(TPid, Pkt, Dict0, RecvData) end, Opts)
catch
error: system_limit = E -> %% discard
- ?LOG({error, E}, now())
+ ?LOG(error, E)
end.
%% ---------------------------------------------------------------------------
@@ -196,8 +290,11 @@ recv_request(TPid,
#diameter_packet{header = #diameter_header{application_id = Id}}
= Pkt,
Dict0,
- #recvdata{peerT = PeerT, apps = Apps}
+ #recvdata{peerT = PeerT,
+ apps = Apps,
+ codec = Opts}
= RecvData) ->
+ diameter_codec:setopts([{common_dictionary, Dict0} | Opts]),
send_A(recv_R(diameter_service:find_incoming_app(PeerT, TPid, Id, Apps),
TPid,
Pkt,
@@ -205,16 +302,24 @@ recv_request(TPid,
RecvData),
TPid,
Dict0,
- RecvData).
+ RecvData);
+
+recv_request(TPid, Pkt, Dict0, RecvData) -> %% from old code
+ recv_request(TPid,
+ Pkt,
+ Dict0,
+ #recvdata{} = erlang:append_element(RecvData, [])).
%% recv_R/5
-recv_R({#diameter_app{id = Id, dictionary = Dict} = App, Caps},
+recv_R({#diameter_app{id = Id, dictionary = AppDict} = App, Caps},
TPid,
Pkt0,
Dict0,
RecvData) ->
- Pkt = errors(Id, diameter_codec:decode(Id, Dict, Pkt0)),
+ incr(recv, Pkt0, TPid, AppDict),
+ Pkt = errors(Id, diameter_codec:decode(Id, AppDict, Pkt0)),
+ incr_error(recv, Pkt, TPid, AppDict),
{Caps, Pkt, App, recv_R(App, TPid, Dict0, Caps, RecvData, Pkt)};
%% Note that the decode is different depending on whether or not Id is
%% ?APP_ID_RELAY.
@@ -286,45 +391,39 @@ rc(N) ->
%% This error is returned when a request is received with an invalid
%% message length.
-errors(_, #diameter_packet{header = #diameter_header{length = Len},
+errors(_, #diameter_packet{header = #diameter_header{length = Len} = H,
bin = Bin,
errors = Es}
= Pkt)
when Len < 20;
0 /= Len rem 4;
8*Len /= bit_size(Bin) ->
+ ?LOG(invalid_message_length, {H, bit_size(Bin)}),
Pkt#diameter_packet{errors = [5015 | Es]};
%% DIAMETER_UNSUPPORTED_VERSION 5011
%% This error is returned when a request was received, whose version
%% number is unsupported.
-errors(_, #diameter_packet{header = #diameter_header{version = V},
+errors(_, #diameter_packet{header = #diameter_header{version = V} = H,
errors = Es}
= Pkt)
when V /= ?DIAMETER_VERSION ->
+ ?LOG(unsupported_version, H),
Pkt#diameter_packet{errors = [5011 | Es]};
-%% DIAMETER_INVALID_AVP_BITS 3009
-%% A request was received that included an AVP whose flag bits are
-%% set to an unrecognized value, or that is inconsistent with the
-%% AVP's definition.
-
-errors(_, #diameter_packet{errors = [Bs | Es]} = Pkt)
- when is_bitstring(Bs) -> %% from old code
- Pkt#diameter_packet{errors = [3009 | Es]};
-
%% DIAMETER_COMMAND_UNSUPPORTED 3001
%% The Request contained a Command-Code that the receiver did not
%% recognize or support. This MUST be used when a Diameter node
%% receives an experimental command that it does not understand.
-errors(Id, #diameter_packet{header = #diameter_header{is_proxiable = P},
+errors(Id, #diameter_packet{header = #diameter_header{is_proxiable = P} = H,
msg = M,
errors = Es}
= Pkt)
when ?APP_ID_RELAY /= Id, undefined == M; %% don't know the command
?APP_ID_RELAY == Id, not P -> %% command isn't proxiable
+ ?LOG(command_unsupported, H),
Pkt#diameter_packet{errors = [3001 | Es]};
%% DIAMETER_INVALID_HDR_BITS 3008
@@ -333,9 +432,11 @@ errors(Id, #diameter_packet{header = #diameter_header{is_proxiable = P},
%% inconsistent with the command code's definition.
errors(_, #diameter_packet{header = #diameter_header{is_request = true,
- is_error = true},
+ is_error = true}
+ = H,
errors = Es}
= Pkt) ->
+ ?LOG(invalid_hdr_bits, H),
Pkt#diameter_packet{errors = [3008 | Es]};
%% Green.
@@ -408,7 +509,7 @@ send_A({Caps, Pkt}, TPid, Dict0, _RecvData) -> %% unsupported application
#diameter_packet{errors = [RC|_]} = Pkt,
send_A(answer_message(RC, Caps, Dict0, Pkt),
TPid,
- Dict0,
+ {Dict0, Dict0},
Pkt,
[],
[]);
@@ -416,7 +517,7 @@ send_A({Caps, Pkt}, TPid, Dict0, _RecvData) -> %% unsupported application
send_A({Caps, Pkt, App, {T, EvalPktFs, EvalFs}}, TPid, Dict0, RecvData) ->
send_A(answer(T, Caps, Pkt, App, Dict0, RecvData),
TPid,
- Dict0,
+ {App#diameter_app.dictionary, Dict0},
Pkt,
EvalPktFs,
EvalFs);
@@ -426,14 +527,17 @@ send_A(_, _, _, _) ->
%% send_A/6
-send_A(T, TPid, Dict0, ReqPkt, EvalPktFs, EvalFs) ->
- reply(T, TPid, Dict0, EvalPktFs, ReqPkt),
+send_A(T, TPid, {AppDict, Dict0} = DictT0, ReqPkt, EvalPktFs, EvalFs) ->
+ {MsgDict, Pkt} = reply(T, TPid, DictT0, EvalPktFs, ReqPkt),
+ incr(send, Pkt, TPid, AppDict),
+ incr_rc(send, Pkt, TPid, {MsgDict, AppDict, Dict0}), %% count outgoing
+ send(TPid, Pkt),
lists:foreach(fun diameter_lib:eval/1, EvalFs).
%% answer/6
answer({reply, Ans}, _Caps, _Pkt, App, Dict0, _RecvData) ->
- {dict(App#diameter_app.dictionary, Dict0, Ans), Ans};
+ {msg_dict(App#diameter_app.dictionary, Dict0, Ans), Ans};
answer({call, Opts}, Caps, Pkt, App, Dict0, RecvData) ->
#diameter_caps{origin_host = {OH,_}}
@@ -456,27 +560,37 @@ answer({answer_message, RC} = T, Caps, Pkt, App, Dict0, _RecvData) ->
orelse ?ERROR({invalid_return, T, handle_request, App}),
answer_message(RC, Caps, Dict0, Pkt).
-%% dict/3
+%% msg_dict/3
+%%
+%% Return the dictionary defining the message grammar in question: the
+%% application dictionary or the common dictionary.
+
+msg_dict(AppDict, Dict0, [Msg])
+ when is_list(Msg);
+ is_tuple(Msg) ->
+ msg_dict(AppDict, Dict0, Msg);
-%% An incoming answer, not yet decoded.
-dict(Dict, Dict0, #diameter_packet{header
- = #diameter_header{is_request = false,
- is_error = E},
- msg = undefined}) ->
- if E -> Dict0; true -> Dict end;
+msg_dict(AppDict, Dict0, Msg) ->
+ choose(is_answer_message(Msg, Dict0), Dict0, AppDict).
-dict(Dict, Dict0, [Msg]) ->
- dict(Dict, Dict0, Msg);
+%% Incoming, not yet decoded.
+is_answer_message(#diameter_packet{header = #diameter_header{} = H,
+ msg = undefined},
+ Dict0) ->
+ is_answer_message([H], Dict0);
-dict(Dict, Dict0, #diameter_packet{msg = Msg}) ->
- dict(Dict, Dict0, Msg);
+is_answer_message(#diameter_packet{msg = Msg}, Dict0) ->
+ is_answer_message(Msg, Dict0);
-dict(Dict, Dict0, Msg) ->
- choose(is_answer_message(Msg, Dict0), Dict0, Dict).
+%% Message sent as a header/avps list.
+is_answer_message([#diameter_header{is_request = R, is_error = E} | _], _) ->
+ E andalso not R;
+%% Message sent as a tagged avp/value list.
is_answer_message([Name | _], _) ->
Name == 'answer-message';
+%% Message sent as a record.
is_answer_message(Rec, Dict) ->
try
'answer-message' == Dict:rec2msg(element(1,Rec))
@@ -491,7 +605,6 @@ answer_message(RC,
origin_realm = {OR,_}},
Dict0,
Pkt) ->
- ?LOG({error, RC}, Pkt),
{Dict0, answer_message(OH, OR, RC, Dict0, Pkt)}.
%% resend/7
@@ -525,7 +638,7 @@ resend(false,
Route = #diameter_avp{data = {Dict0, 'Route-Record', OH}},
Seq = diameter_session:sequence(Mask),
Hdr = Hdr0#diameter_header{hop_by_hop_id = Seq},
- Msg = [Hdr, Route | Avps],
+ Msg = [Hdr, Route | Avps], %% reordered at encode
resend(send_request(SvcName, App, Msg, Opts), Caps, Dict0, Pkt).
%% The incoming request is relayed with the addition of a
%% Route-Record. Note the requirement on the return from call/4 below,
@@ -547,7 +660,7 @@ resend(false,
%%
%% Relay a reply to a relayed request.
-%% Answer from the peer: reset the hop by hop identifier and send.
+%% Answer from the peer: reset the hop by hop identifier.
resend(#diameter_packet{bin = B}
= Pkt,
_Caps,
@@ -586,31 +699,31 @@ is_loop(Code, Vid, OH, Dict0, Avps) ->
%% reply/5
%% Local answer ...
-reply({Dict, Ans}, TPid, Dict0, Fs, ReqPkt) ->
- reply(Ans, Dict, TPid, Dict0, Fs, ReqPkt);
+reply({MsgDict, Ans}, TPid, {AppDict, Dict0}, Fs, ReqPkt) ->
+ local(Ans, TPid, {MsgDict, AppDict, Dict0}, Fs, ReqPkt);
%% ... or relayed.
-reply(#diameter_packet{} = Pkt, TPid, _Dict0, Fs, _ReqPkt) ->
+reply(#diameter_packet{} = Pkt, _TPid, {AppDict, Dict0}, Fs, _ReqPkt) ->
eval_packet(Pkt, Fs),
- send(TPid, Pkt).
+ {msg_dict(AppDict, Dict0, Pkt), Pkt}.
-%% reply/6
+%% local/5
%%
%% Send a locally originating reply.
%% Skip the setting of Result-Code and Failed-AVP's below. This is
%% undocumented and shouldn't be relied on.
-reply([Msg], Dict, TPid, Dict0, Fs, ReqPkt)
+local([Msg], TPid, DictT, Fs, ReqPkt)
when is_list(Msg);
is_tuple(Msg) ->
- reply(Msg, Dict, TPid, Dict0, Fs, ReqPkt#diameter_packet{errors = []});
+ local(Msg, TPid, DictT, Fs, ReqPkt#diameter_packet{errors = []});
-reply(Msg, Dict, TPid, Dict0, Fs, ReqPkt) ->
- Pkt = encode(Dict,
- reset(make_answer_packet(Msg, ReqPkt), Dict, Dict0),
+local(Msg, TPid, {MsgDict, AppDict, Dict0}, Fs, ReqPkt) ->
+ Pkt = encode({MsgDict, AppDict},
+ TPid,
+ reset(make_answer_packet(Msg, ReqPkt), MsgDict, Dict0),
Fs),
- incr(send, Pkt, Dict, TPid, Dict0), %% count outgoing result codes
- send(TPid, Pkt).
+ {MsgDict, Pkt}.
%% reset/3
@@ -883,8 +996,8 @@ answer_message(OH, OR, RC, Dict0, #diameter_packet{avps = Avps,
session_id(Code, Vid, Dict0, Avps)
when is_list(Avps) ->
try
- {value, #diameter_avp{data = D}} = find_avp(Code, Vid, Avps),
- [{'Session-Id', [Dict0:avp(decode, D, 'Session-Id')]}]
+ #diameter_avp{data = Bin} = find_avp(Code, Vid, Avps),
+ [{'Session-Id', [Dict0:avp(decode, Bin, 'Session-Id')]}]
catch
error: _ ->
[]
@@ -901,26 +1014,17 @@ failed_avp(_, [] = No) ->
%% find_avp/3
-find_avp(Code, Vid, Avps)
- when is_integer(Code), (undefined == Vid orelse is_integer(Vid)) ->
- find(fun(A) -> is_avp(Code, Vid, A) end, Avps).
+%% Grouped ...
+find_avp(Code, VId, [[#diameter_avp{code = Code, vendor_id = VId} | _] = As
+ | _]) ->
+ As;
-%% The final argument here could be a list of AVP's, depending on the case,
-%% but we're only searching at the top level.
-is_avp(Code, Vid, #diameter_avp{code = Code, vendor_id = Vid}) ->
- true;
-is_avp(_, _, _) ->
- false.
+%% ... or not.
+find_avp(Code, VId, [#diameter_avp{code = Code, vendor_id = VId} = A | _]) ->
+ A;
-find(_, []) ->
- false;
-find(Pred, [H|T]) ->
- case Pred(H) of
- true ->
- {value, H};
- false ->
- find(Pred, T)
- end.
+find_avp(Code, VId, [_ | Avps]) ->
+ find_avp(Code, VId, Avps).
%% 7. Error Handling
%%
@@ -974,35 +1078,79 @@ find(Pred, [H|T]) ->
%% code, the missing vendor id, and a zero filled payload of the minimum
%% required length for the omitted AVP will be added.
-%% incr/4
+%% incr_result/5
%%
%% Increment a stats counter for result codes in incoming and outgoing
%% answers.
+%% Message sent as a header/avps list.
+incr_result(send = Dir,
+ #diameter_packet{msg = [#diameter_header{} = H | _]}
+ = Pkt,
+ TPid,
+ DictT) ->
+ incr_res(Dir, Pkt#diameter_packet{header = H}, TPid, DictT);
+
%% Outgoing message as binary: don't count. (Sending binaries is only
%% partially supported.)
-incr(_, #diameter_packet{msg = undefined}, _, _, _) ->
- ok;
+incr_result(send, #diameter_packet{header = undefined = No}, _, _) ->
+ No;
-%% Incoming with decode errors.
-incr(recv = D, #diameter_packet{header = H, errors = [_|_]}, _, TPid, _) ->
- incr(TPid, {diameter_codec:msg_id(H), D, error});
+%% Incoming or outgoing. Outgoing with encode errors never gets here
+%% since encode fails.
+incr_result(Dir, Pkt, TPid, DictT) ->
+ incr_res(Dir, Pkt, TPid, DictT).
-%% Incoming without errors or outgoing. Outgoing with encode errors
-%% never gets here since encode fails.
-incr(Dir, Pkt, Dict, TPid, Dict0) ->
- #diameter_packet{header = #diameter_header{is_error = E}
- = Hdr,
- msg = Rec}
- = Pkt,
+incr_res(Dir,
+ #diameter_packet{header = #diameter_header{is_error = E}
+ = Hdr,
+ errors = Es}
+ = Pkt,
+ TPid,
+ DictT) ->
+ {MsgDict, AppDict, Dict0} = DictT,
+
+ Id = msg_id(Hdr, AppDict),
+ %% Could be {relay, 0}, in which case the R-bit is redundant since
+ %% only answers are being counted. Let it be however, so that the
+ %% same tuple is in both send/recv and result code counters.
+
+ %% Count incoming decode errors.
+ recv /= Dir orelse [] == Es orelse incr_error(Dir, Id, TPid, AppDict),
- RC = int(get_avp_value(Dict, 'Result-Code', Rec)),
+ %% Exit on a missing result code.
+ T = rc_counter(MsgDict, Dir, Pkt),
+ T == false andalso ?LOGX(no_result_code, {MsgDict, Dir, Hdr}),
+ {Ctr, RC, Avp} = T,
- %% Exit on an improper Result-Code.
+ %% Or on an inappropriate value.
is_result(RC, E, Dict0)
- orelse x({invalid_error_bit, RC}, answer, [Dir, Pkt]),
+ orelse ?LOGX(invalid_error_bit, {MsgDict, Dir, Hdr, Avp}),
+
+ incr(TPid, {Id, Dir, Ctr}),
+ Ctr.
+
+%% msg_id/2
+
+msg_id(#diameter_packet{header = H}, AppDict) ->
+ msg_id(H, AppDict);
+
+%% Only count on known keys so as not to be vulnerable to attack:
+%% there are 2^32 (application ids) * 2^24 (command codes) = 2^56
+%% pairs for an attacker to choose from.
+msg_id(Hdr, AppDict) ->
+ {Aid, Code, R} = Id = diameter_codec:msg_id(Hdr),
+ case AppDict:id() of
+ ?APP_ID_RELAY ->
+ {relay, R};
+ A ->
+ unknown(A /= Aid orelse '' == AppDict:msg_name(Code, 0 == R), Id)
+ end.
- irc(TPid, Hdr, Dir, rc_counter(Dict, Rec, RC)).
+unknown(true, {_, _, R}) ->
+ {unknown, R};
+unknown(false, Id) ->
+ Id.
%% No E-bit: can't be 3xxx.
is_result(RC, false, _Dict0) ->
@@ -1018,63 +1166,62 @@ is_result(RC, true, _) ->
orelse
5000 =< RC andalso RC < 6000.
-irc(_, _, _, undefined) ->
- false;
-
-irc(TPid, Hdr, Dir, Ctr) ->
- incr(TPid, {diameter_codec:msg_id(Hdr), Dir, Ctr}).
-
%% incr/2
incr(TPid, Counter) ->
diameter_stats:incr(Counter, TPid, 1).
-%% rc_counter/2
+%% rc_counter/3
%% RFC 3588, 7.6:
%%
%% All Diameter answer messages defined in vendor-specific
%% applications MUST include either one Result-Code AVP or one
%% Experimental-Result AVP.
-%%
-%% Maintain statistics assuming one or the other, not both, which is
-%% surely the intent of the RFC.
-rc_counter(Dict, Rec, undefined) ->
- rcc(get_avp_value(Dict, 'Experimental-Result', Rec));
-rc_counter(_, _, RC) ->
- {'Result-Code', RC}.
+rc_counter(Dict, Dir, #diameter_packet{header = H,
+ avps = As,
+ msg = Msg})
+ when Dir == recv; %% decoded incoming
+ Msg == undefined -> %% relayed outgoing
+ rc_counter(Dict, [H|As]);
+
+rc_counter(Dict, _, #diameter_packet{msg = Msg}) ->
+ rc_counter(Dict, Msg).
-%% Outgoing answers may be in any of the forms messages can be sent
-%% in. Incoming messages will be records. We're assuming here that the
-%% arity of the result code AVP's is 0 or 1.
+rc_counter(Dict, Msg) ->
+ rcc(get_result(Dict, Msg)).
-rcc([{_,_,N} = T | _])
+rcc(#diameter_avp{name = 'Result-Code' = Name, value = N} = A)
when is_integer(N) ->
- T;
-rcc({_,_,N} = T)
+ {{Name, N}, N, A};
+
+rcc(#diameter_avp{name = 'Result-Code' = Name, value = [N|_]} = A)
when is_integer(N) ->
- T;
-rcc(_) ->
- undefined.
+ {{Name, N}, N, A};
-%% Extract the first good looking integer. There's no guarantee
-%% that what we're looking for has arity 1.
-int([N|_])
+rcc(#diameter_avp{name = 'Experimental-Result', value = {_,_,N} = T} = A)
when is_integer(N) ->
- N;
-int(N)
+ {T, N, A};
+
+rcc(#diameter_avp{name = 'Experimental-Result', value = [{_,_,N} = T|_]} = A)
when is_integer(N) ->
- N;
-int(_) ->
- undefined.
+ {T, N, A};
--spec x(any(), atom(), list()) -> no_return().
+rcc(_) ->
+ false.
-%% Warn and exit request process on errors in an incoming answer.
-x(Reason, F, A) ->
- diameter_lib:warning_report(Reason, {?MODULE, F, A}),
- x(Reason).
+%% get_result/2
+
+get_result(Dict, Msg) ->
+ try
+ [throw(A) || N <- ['Result-Code', 'Experimental-Result'],
+ #diameter_avp{} = A <- [get_avp(Dict, N, Msg)]]
+ of
+ [] -> false
+ catch
+ #diameter_avp{} = A -> A
+ end.
x(T) ->
exit(T).
@@ -1135,10 +1282,9 @@ answer_rc(_, _, Sent) ->
send_R(SvcName, AppOrAlias, Msg, Opts, Caller) ->
case pick_peer(SvcName, AppOrAlias, Msg, Opts) of
- {{_,_,_} = Transport, Mask} ->
+ {Transport, Mask, SvcOpts} ->
+ diameter_codec:setopts(SvcOpts),
send_request(Transport, Mask, Msg, Opts, Caller, SvcName);
- false ->
- {error, no_connection};
{error, _} = No ->
No
end.
@@ -1200,6 +1346,8 @@ send_request({TPid, Caps, App}
SvcName,
[]).
+%% send_R/7
+
send_R({send, Msg}, Pkt, Transport, Opts, Caller, SvcName, Fs) ->
send_R(make_request_packet(Msg, Pkt),
Transport,
@@ -1302,6 +1450,21 @@ make_request_packet(#diameter_packet{header = Hdr} = Pkt,
make_request_packet(Msg, Pkt) ->
Pkt#diameter_packet{msg = Msg}.
+%% make_retransmit_packet/2
+
+make_retransmit_packet(#diameter_packet{msg = [#diameter_header{} = Hdr
+ | Avps]}
+ = Pkt) ->
+ Pkt#diameter_packet{msg = [make_retransmit_header(Hdr) | Avps]};
+
+make_retransmit_packet(#diameter_packet{header = Hdr} = Pkt) ->
+ Pkt#diameter_packet{header = make_retransmit_header(Hdr)}.
+
+%% make_retransmit_header/1
+
+make_retransmit_header(Hdr) ->
+ Hdr#diameter_header{is_retransmitted = true}.
+
%% fold_record/2
fold_record(undefined, R) ->
@@ -1312,12 +1475,12 @@ fold_record(Rec, R) ->
%% send_R/6
send_R(Pkt0,
- {TPid, Caps, #diameter_app{dictionary = Dict} = App},
+ {TPid, Caps, #diameter_app{dictionary = AppDict} = App},
Opts,
{Pid, Ref},
SvcName,
Fs) ->
- Pkt = encode(Dict, Pkt0, Fs),
+ Pkt = encode(AppDict, TPid, Pkt0, Fs),
#options{timeout = Timeout}
= Opts,
@@ -1329,15 +1492,12 @@ send_R(Pkt0,
caps = Caps,
packet = Pkt0},
- try
- TRef = send_request(TPid, Pkt, Req, SvcName, Timeout),
- Pid ! Ref, %% tell caller a send has been attempted
- handle_answer(SvcName,
- App,
- recv_A(Timeout, SvcName, App, Opts, {TRef, Req}))
- after
- erase_requests(Pkt)
- end.
+ incr(send, Pkt, TPid, AppDict),
+ TRef = send_request(TPid, Pkt, Req, SvcName, Timeout),
+ Pid ! Ref, %% tell caller a send has been attempted
+ handle_answer(SvcName,
+ App,
+ recv_A(Timeout, SvcName, App, Opts, {TRef, Req})).
%% recv_A/5
@@ -1365,14 +1525,14 @@ handle_answer(SvcName, App, {error, Req, Reason}) ->
handle_error(App, Req, Reason, SvcName);
handle_answer(SvcName,
- #diameter_app{dictionary = Dict,
+ #diameter_app{dictionary = AppDict,
id = Id}
= App,
{answer, Req, Dict0, Pkt}) ->
- Mod = dict(Dict, Dict0, Pkt),
- handle_A(errors(Id, diameter_codec:decode(Mod, Pkt)),
+ MsgDict = msg_dict(AppDict, Dict0, Pkt),
+ handle_A(errors(Id, diameter_codec:decode({MsgDict, AppDict}, Pkt)),
SvcName,
- Mod,
+ MsgDict,
Dict0,
App,
Req).
@@ -1382,18 +1542,30 @@ handle_answer(SvcName,
%% want to examine the answer?
handle_A(Pkt, SvcName, Dict, Dict0, App, #request{transport = TPid} = Req) ->
+ AppDict = App#diameter_app.dictionary,
+
+ incr(recv, Pkt, TPid, AppDict),
+
try
- incr(recv, Pkt, Dict, TPid, Dict0) %% count incoming result codes
+ incr_result(recv, Pkt, TPid, {Dict, AppDict, Dict0}) %% count incoming
of
_ -> answer(Pkt, SvcName, App, Req)
catch
- exit: {invalid_error_bit, RC} ->
+ exit: {no_result_code, _} ->
+ %% RFC 6733 requires one of Result-Code or
+ %% Experimental-Result, but the decode will have detected
+ %% a missing AVP. If both are optional in the dictionary
+ %% then this isn't a decode error: just continue on.
+ answer(Pkt, SvcName, App, Req);
+ exit: {invalid_error_bit, {_, _, _, Avp}} ->
#diameter_packet{errors = Es}
= Pkt,
- E = {5004, #diameter_avp{name = 'Result-Code', value = RC}},
+ E = {5004, Avp},
answer(Pkt#diameter_packet{errors = [E|Es]}, SvcName, App, Req)
end.
+%% answer/4
+
answer(Pkt,
SvcName,
#diameter_app{module = ModX,
@@ -1401,6 +1573,8 @@ answer(Pkt,
Req) ->
a(Pkt, SvcName, ModX, AE, Req).
+-spec a(_, _, _) -> no_return(). %% silence dialyzer
+
a(#diameter_packet{errors = Es}
= Pkt,
SvcName,
@@ -1413,11 +1587,16 @@ a(#diameter_packet{errors = Es}
callback == AE ->
cb(ModX, handle_answer, [Pkt, msg(P), SvcName, {TPid, Caps}]);
-a(Pkt, SvcName, _, report, Req) ->
- x(errors, handle_answer, [SvcName, Req, Pkt]);
+a(Pkt, SvcName, _, AE, _) ->
+ a(Pkt#diameter_packet.header, SvcName, AE).
+
+a(Hdr, SvcName, report) ->
+ MFA = {?MODULE, handle_answer, [SvcName, Hdr]},
+ diameter_lib:warning_report(errors, MFA),
+ a(Hdr, SvcName, discard);
-a(Pkt, SvcName, _, discard, Req) ->
- x({errors, handle_answer, [SvcName, Req, Pkt]}).
+a(Hdr, SvcName, discard) ->
+ x({answer_errors, {SvcName, Hdr}}).
%% Note that we don't check that the application id in the answer's
%% header is what we expect. (TODO: Does the rfc says anything about
@@ -1427,7 +1606,9 @@ a(Pkt, SvcName, _, discard, Req) ->
%% timer value is ignored. This means that an answer could be accepted
%% from a peer after timeout in the case of failover.
-retransmit({{_,_,App} = Transport, _Mask}, Req, Opts, SvcName, Timeout) ->
+%% retransmit/5
+
+retransmit({{_,_,App} = Transport, _, _}, Req, Opts, SvcName, Timeout) ->
try retransmit(Transport, Req, SvcName, Timeout) of
T -> recv_A(Timeout, SvcName, App, Opts, T)
catch
@@ -1448,17 +1629,26 @@ pick_peer(SvcName,
pick_peer(SvcName, App, Msg, Opts#options{extra = []});
pick_peer(_, _, undefined, _) ->
- false;
+ {error, no_connection};
pick_peer(SvcName,
AppOrAlias,
Msg,
#options{filter = Filter, extra = Xtra}) ->
- diameter_service:pick_peer(SvcName,
- AppOrAlias,
- {fun(D) -> get_destination(D, Msg) end,
- Filter,
- Xtra}).
+ pick(diameter_service:pick_peer(SvcName,
+ AppOrAlias,
+ {fun(D) -> get_destination(D, Msg) end,
+ Filter,
+ Xtra})).
+
+pick({{_,_,_} = Transport, Mask}) -> %% from old code; dialyzer complains
+ {Transport, Mask, []}; %% about this
+
+pick(false) ->
+ {error, no_connection};
+
+pick(T) ->
+ T.
%% handle_error/4
@@ -1475,10 +1665,10 @@ msg(#diameter_packet{msg = undefined, bin = Bin}) ->
msg(#diameter_packet{msg = Msg}) ->
Msg.
-%% encode/3
+%% encode/4
-encode(Dict, Pkt, Fs) ->
- P = encode(Dict, Pkt),
+encode(Dict, TPid, Pkt, Fs) ->
+ P = encode(Dict, TPid, Pkt),
eval_packet(P, Fs),
P.
@@ -1489,21 +1679,41 @@ encode(Dict, Pkt, Fs) ->
%% an encoded binary. This isn't the usual case and doesn't properly
%% support retransmission but is useful for test.
+encode(Dict, TPid, Pkt)
+ when is_atom(Dict) ->
+ encode({Dict, Dict}, TPid, Pkt);
+
%% A message to be encoded.
-encode(Dict, #diameter_packet{bin = undefined} = Pkt) ->
- diameter_codec:encode(Dict, Pkt);
+encode(DictT, TPid, #diameter_packet{bin = undefined} = Pkt) ->
+ {Dict, AppDict} = DictT,
+ try
+ diameter_codec:encode(Dict, Pkt)
+ catch
+ exit: {diameter_codec, encode, T} = Reason ->
+ incr_error(send, T, TPid, AppDict),
+ exit(Reason)
+ end;
%% An encoded binary: just send.
-encode(_, #diameter_packet{} = Pkt) ->
+encode(_, _, #diameter_packet{} = Pkt) ->
Pkt.
%% send_request/5
send_request(TPid, #diameter_packet{bin = Bin} = Pkt, Req, _SvcName, Timeout)
when node() == node(TPid) ->
- %% Store the outgoing request before sending to avoid a race with
- %% reply reception.
- TRef = store_request(TPid, Bin, Req, Timeout),
+ Seqs = diameter_codec:sequence_numbers(Bin),
+ TRef = erlang:start_timer(Timeout, self(), TPid),
+ Entry = {Seqs, Req, TRef},
+
+ %% Ensure that request table is cleaned even if we receive an exit
+ %% signal. An alternative would be to simply trap exits, but
+ %% callbacks are applied in this process, and these could possibly
+ %% be expecting the prevailing behaviour.
+ Self = self(),
+ spawn(fun() -> diameter_lib:wait([Self]), erase_request(Entry) end),
+
+ store_request(Entry, TPid),
send(TPid, Pkt),
TRef;
@@ -1517,25 +1727,34 @@ send_request(TPid, #diameter_packet{} = Pkt, Req, SvcName, Timeout) ->
%% send/1
-send({TPid, Pkt, #request{handler = Pid} = Req, SvcName, Timeout, TRef}) ->
- Ref = send_request(TPid,
- Pkt,
- Req#request{handler = self()},
- SvcName,
- Timeout),
+send({TPid, Pkt, #request{handler = Pid} = Req0, SvcName, Timeout, TRef}) ->
+ Req = Req0#request{handler = self()},
+ recv(TPid, Pid, TRef, send_request(TPid, Pkt, Req, SvcName, Timeout)).
+
+%% recv/4
+%%
+%% Relay an answer from a remote node.
+
+recv(TPid, Pid, TRef, LocalTRef) ->
receive
{answer, _, _, _, _} = A ->
Pid ! A;
- {failover = T, Ref} ->
+ {failover = T, LocalTRef} ->
Pid ! {T, TRef};
T ->
- exit({timeout, Ref, TPid} = T)
+ exit({timeout, LocalTRef, TPid} = T)
end.
%% send/2
-send(Pid, Pkt) ->
- Pid ! {send, Pkt}.
+send(Pid, Pkt) -> %% Strip potentially large message terms.
+ #diameter_packet{header = H,
+ bin = Bin,
+ transport_data = T}
+ = Pkt,
+ Pid ! {send, #diameter_packet{header = H,
+ bin = Bin,
+ transport_data = T}}.
%% retransmit/4
@@ -1548,9 +1767,7 @@ retransmit({TPid, Caps, App}
have_request(Pkt0, TPid) %% Don't failover to a peer we've
andalso ?THROW(timeout), %% already sent to.
- #diameter_packet{header = Hdr0} = Pkt0,
- Hdr = Hdr0#diameter_header{is_retransmitted = true},
- Pkt = Pkt0#diameter_packet{header = Hdr},
+ Pkt = make_retransmit_packet(Pkt0),
retransmit(cb(App, prepare_retransmit, [Pkt, SvcName, {TPid, Caps}]),
Transport,
@@ -1586,32 +1803,37 @@ retransmit(T, {_, _, App}, _, _, _, _) ->
?ERROR({invalid_return, T, prepare_retransmit, App}).
resend_request(Pkt0,
- {TPid, Caps, #diameter_app{dictionary = Dict}},
+ {TPid, Caps, #diameter_app{dictionary = AppDict}},
Req0,
SvcName,
Tmo,
Fs) ->
- Pkt = encode(Dict, Pkt0, Fs),
+ Pkt = encode(AppDict, TPid, Pkt0, Fs),
Req = Req0#request{transport = TPid,
packet = Pkt0,
caps = Caps},
- ?LOG(retransmission, Req),
+ ?LOG(retransmission, Pkt#diameter_packet.header),
+ incr(TPid, {msg_id(Pkt, AppDict), send, retransmission}),
TRef = send_request(TPid, Pkt, Req, SvcName, Tmo),
{TRef, Req}.
-%% store_request/4
+%% store_request/2
-store_request(TPid, Bin, Req, Timeout) ->
- Seqs = diameter_codec:sequence_numbers(Bin),
- TRef = erlang:start_timer(Timeout, self(), TPid),
- ets:insert(?REQUEST_TABLE, {Seqs, Req, TRef}),
+store_request(T, TPid) ->
+ ets:insert(?REQUEST_TABLE, T),
ets:member(?REQUEST_TABLE, TPid)
- orelse (self() ! {failover, TRef}), %% failover/1 may have missed
- TRef.
+ orelse begin
+ {_Seqs, _Req, TRef} = T,
+ self() ! {failover, TRef} %% failover/1 may have missed
+ end.
%% lookup_request/2
+%%
+%% Note the match on both the key and transport pid. The latter is
+%% necessary since the same Hop-by-Hop and End-to-End identifiers are
+%% reused in the case of retransmission.
lookup_request(Msg, TPid) ->
Seqs = diameter_codec:sequence_numbers(Msg),
@@ -1625,10 +1847,10 @@ lookup_request(Msg, TPid) ->
false
end.
-%% erase_requests/1
+%% erase_request/1
-erase_requests(Pkt) ->
- ets:delete(?REQUEST_TABLE, diameter_codec:sequence_numbers(Pkt)).
+erase_request(T) ->
+ ets:delete_object(?REQUEST_TABLE, T).
%% match_requests/1
@@ -1651,10 +1873,10 @@ failover(TPid)
when is_pid(TPid) ->
lists:foreach(fun failover/1, match_requests(TPid));
%% Note that a request process can store its request after failover
-%% notifications are sent here: store_request/4 sends the notification
+%% notifications are sent here: store_request/2 sends the notification
%% in that case.
-%% Failover as a consequence of request_peer_down/1: inform the
+%% Failover as a consequence of peer_down/1: inform the
%% request process.
failover({_, Req, TRef}) ->
#request{handler = Pid,
@@ -1680,7 +1902,7 @@ str([]) ->
str(T) ->
T.
-%% get_avp_value/3
+%% get_avp/3
%%
%% Find an AVP in a message of one of three forms:
%%
@@ -1697,47 +1919,71 @@ str(T) ->
%% look for are in the common dictionary. This is required since the
%% relay dictionary doesn't inherit the common dictionary (which maybe
%% it should).
-get_avp_value(?RELAY, Name, Msg) ->
- get_avp_value(?BASE, Name, Msg);
+get_avp(?RELAY, Name, Msg) ->
+ get_avp(?BASE, Name, Msg);
-%% Message sent as a header/avps list, probably a relay case but not
-%% necessarily.
-get_avp_value(Dict, Name, [#diameter_header{} | Avps]) ->
+%% Message as a header/avps list.
+get_avp(Dict, Name, [#diameter_header{} | Avps]) ->
try
{Code, _, VId} = Dict:avp_header(Name),
- [A|_] = lists:dropwhile(fun(#diameter_avp{code = C, vendor_id = V}) ->
- C /= Code orelse V /= VId
- end,
- Avps),
- avp_decode(Dict, Name, A)
+ find_avp(Code, VId, Avps)
+ of
+ A ->
+ (avp_decode(Dict, Name, ungroup(A)))#diameter_avp{name = Name}
catch
error: _ ->
undefined
end;
%% Outgoing message as a name/values list.
-get_avp_value(_, Name, [_MsgName | Avps]) ->
+get_avp(_, Name, [_MsgName | Avps]) ->
case lists:keyfind(Name, 1, Avps) of
{_, V} ->
- V;
+ #diameter_avp{name = Name, value = V};
_ ->
undefined
end;
%% Message is typically a record but not necessarily.
-get_avp_value(Dict, Name, Rec) ->
+get_avp(Dict, Name, Rec) ->
try
- Dict:'#get-'(Name, Rec)
+ #diameter_avp{name = Name, value = Dict:'#get-'(Name, Rec)}
catch
error:_ ->
undefined
end.
+%% get_avp_value/3
+
+get_avp_value(Dict, Name, Msg) ->
+ case get_avp(Dict, Name, Msg) of
+ #diameter_avp{value = V} ->
+ V;
+ undefined = No ->
+ No
+ end.
+
+%% ungroup/1
+
+ungroup([Avp|_]) ->
+ Avp;
+ungroup(Avp) ->
+ Avp.
+
+%% avp_decode/3
+
avp_decode(Dict, Name, #diameter_avp{value = undefined,
- data = Bin}) ->
- Dict:avp(decode, Bin, Name);
-avp_decode(_, _, #diameter_avp{value = V}) ->
- V.
+ data = Bin}
+ = Avp) ->
+ try Dict:avp(decode, Bin, Name) of
+ V ->
+ Avp#diameter_avp{value = V}
+ catch
+ error:_ ->
+ Avp
+ end;
+avp_decode(_, _, #diameter_avp{} = Avp) ->
+ Avp.
cb(#diameter_app{module = [_|_] = M}, F, A) ->
eval(M, F, A);
diff --git a/lib/diameter/src/base/diameter_types.erl b/lib/diameter/src/base/diameter_types.erl
index 9ae289034c..87a0f0663d 100644
--- a/lib/diameter/src/base/diameter_types.erl
+++ b/lib/diameter/src/base/diameter_types.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2011. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -75,7 +75,7 @@
%% message indicating this error MUST include the offending AVPs
%% within a Failed-AVP AVP.
%%
--define(INVALID_LENGTH(Bin), erlang:error({'DIAMETER', 5014, Bin})).
+-define(INVALID_LENGTH(Bitstr), erlang:error({'DIAMETER', 5014, Bitstr})).
%% -------------------------------------------------------------------------
%% 3588, 4.2. Basic AVP Data Formats
@@ -90,7 +90,15 @@
'OctetString'(decode, Bin)
when is_binary(Bin) ->
- binary_to_list(Bin);
+ case diameter_codec:getopt(string_decode) of
+ true ->
+ binary_to_list(Bin);
+ false ->
+ Bin
+ end;
+
+'OctetString'(decode, B) ->
+ ?INVALID_LENGTH(B);
'OctetString'(encode = M, zero) ->
'OctetString'(M, []);
@@ -250,44 +258,19 @@
'Address'(encode, zero) ->
<<0:48>>;
-'Address'(decode, <<1:16, B/binary>>)
- when size(B) == 4 ->
- list_to_tuple(binary_to_list(B));
-
-'Address'(decode, <<2:16, B/binary>>)
- when size(B) == 16 ->
- list_to_tuple(v6dec(B, []));
+'Address'(decode, <<A:16, B/binary>>)
+ when 1 == A, 4 == size(B);
+ 2 == A, 16 == size(B) ->
+ list_to_tuple([N || <<N:A/unit:8>> <= B]);
-'Address'(decode, <<A:16, _/binary>> = B)
- when 1 == A;
- 2 == A ->
+'Address'(decode, B) ->
?INVALID_LENGTH(B);
'Address'(encode, T) ->
- ipenc(diameter_lib:ipaddr(T)).
-
-ipenc(T)
- when is_tuple(T), size(T) == 4 ->
- B = list_to_binary(tuple_to_list(T)),
- <<1:16, B/binary>>;
-
-ipenc(T)
- when is_tuple(T), size(T) == 8 ->
- B = v6enc(lists:reverse(tuple_to_list(T)), <<>>),
- <<2:16, B/binary>>.
-
-v6dec(<<N:16, B/binary>>, Acc) ->
- v6dec(B, [N | Acc]);
-
-v6dec(<<>>, Acc) ->
- lists:reverse(Acc).
-
-v6enc([N | Rest], B)
- when ?UINT(16,N) ->
- v6enc(Rest, <<N:16, B/binary>>);
-
-v6enc([], B) ->
- B.
+ Ns = tuple_to_list(diameter_lib:ipaddr(T)), %% length 4 or 8
+ A = length(Ns) div 4, %% 1 or 2
+ B = << <<N:A/unit:8>> || N <- Ns >>,
+ <<A:16, B/binary>>.
%% --------------------
@@ -301,7 +284,10 @@ v6enc([], B) ->
<<_,_/binary>> = 'OctetString'(M, X);
'DiameterIdentity'(decode = M, <<_,_/binary>> = X) ->
- 'OctetString'(M, X).
+ 'OctetString'(M, X);
+
+'DiameterIdentity'(decode, X) ->
+ ?INVALID_LENGTH(X).
%% --------------------
@@ -309,26 +295,37 @@ v6enc([], B) ->
when is_binary(Bin) ->
scan_uri(Bin);
+'DiameterURI'(decode, B) ->
+ ?INVALID_LENGTH(B);
+
%% The minimal DiameterURI is "aaa://x", 7 characters.
'DiameterURI'(encode = M, zero) ->
'OctetString'(M, lists:duplicate(0,7));
'DiameterURI'(encode, #diameter_uri{type = Type,
- fqdn = D,
- port = P,
+ fqdn = DN,
+ port = PN,
transport = T,
- protocol = Prot}
- = U) ->
- S = lists:append([atom_to_list(Type), "://", D,
- ":", integer_to_list(P),
+ protocol = P})
+ when (Type == 'aaa' orelse Type == 'aaas'),
+ is_integer(PN),
+ 0 =< PN,
+ (T == tcp orelse T == sctp orelse T == udp),
+ (P == diameter orelse P == radius orelse P == 'tacacs+'),
+ (P /= diameter orelse T /= udp) ->
+ iolist_to_binary([atom_to_list(Type), "://", DN,
+ ":", integer_to_list(PN),
";transport=", atom_to_list(T),
- ";protocol=", atom_to_list(Prot)]),
- U = scan_uri(S), %% assert
- list_to_binary(S);
+ ";protocol=", atom_to_list(P)]);
+%% Don't omit defaults since they're dependent on whether RFC 3588 or
+%% 6733 is being followed. For one, we don't know this at encode; for
+%% two (more importantly), we don't know how the peer will interpret
+%% defaults, so it's best to be explicit. Interpret defaults on decode
+%% since there's no choice.
'DiameterURI'(encode, Str) ->
Bin = iolist_to_binary(Str),
- #diameter_uri{} = scan_uri(Bin), %% type check
+ #diameter_uri{} = scan_uri(Bin), %% assert
Bin.
%% --------------------
@@ -337,7 +334,6 @@ v6enc([], B) ->
'IPFilterRule'(encode = M, zero) ->
'OctetString'(M, lists:duplicate(0,33));
-%% TODO: parse grammar.
'IPFilterRule'(M, X) ->
'OctetString'(M, X).
@@ -347,43 +343,29 @@ v6enc([], B) ->
'QoSFilterRule'(encode = M, zero = X) ->
'IPFilterRule'(M, X);
-%% TODO: parse grammar.
'QoSFilterRule'(M, X) ->
'OctetString'(M, X).
%% --------------------
-'UTF8String'(decode, Bin) ->
- udec(Bin, []);
+'UTF8String'(decode, Bin)
+ when is_binary(Bin) ->
+ case diameter_codec:getopt(string_decode) of
+ true ->
+ %% assert list return
+ tl([0|_] = unicode:characters_to_list([0, Bin]));
+ false ->
+ <<_/binary>> = unicode:characters_to_binary(Bin)
+ end;
+
+'UTF8String'(decode, B) ->
+ ?INVALID_LENGTH(B);
'UTF8String'(encode = M, zero) ->
'UTF8String'(M, []);
'UTF8String'(encode, S) ->
- uenc(S, []).
-
-udec(<<>>, Acc) ->
- lists:reverse(Acc);
-
-udec(<<C/utf8, Rest/binary>>, Acc) ->
- udec(Rest, [C | Acc]).
-
-uenc(E, Acc)
- when E == [];
- E == <<>> ->
- list_to_binary(lists:reverse(Acc));
-
-uenc(<<C/utf8, Rest/binary>>, Acc) ->
- uenc(Rest, [<<C/utf8>> | Acc]);
-
-uenc([[] | Rest], Acc) ->
- uenc(Rest, Acc);
-
-uenc([[H|T] | Rest], Acc) ->
- uenc([H, T | Rest], Acc);
-
-uenc([C | Rest], Acc) ->
- uenc(Rest, [<<C/utf8>> | Acc]).
+ <<_/binary>> = unicode:characters_to_binary(S). %% assert binary return
%% --------------------
@@ -542,55 +524,90 @@ msb(false) -> ?TIME_2036.
%%
%% aaa-protocol = ( "diameter" / "radius" / "tacacs+" )
-scan_uri(Bin)
- when is_binary(Bin) ->
- scan_uri(binary_to_list(Bin));
-scan_uri("aaa://" ++ Rest) ->
- scan_fqdn(Rest, #diameter_uri{type = aaa});
-scan_uri("aaas://" ++ Rest) ->
- scan_fqdn(Rest, #diameter_uri{type = aaas}).
-
-scan_fqdn(S, U) ->
- {[_|_] = F, Rest} = lists:splitwith(fun is_fqdn/1, S),
- scan_opt_port(Rest, U#diameter_uri{fqdn = F}).
-
-scan_opt_port(":" ++ S, U) ->
- {[_|_] = P, Rest} = lists:splitwith(fun is_digit/1, S),
- scan_opt_transport(Rest, U#diameter_uri{port = list_to_integer(P)});
-scan_opt_port(S, U) ->
- scan_opt_transport(S, U).
-
-scan_opt_transport(";transport=" ++ S, U) ->
- {P, Rest} = transport(S),
- scan_opt_protocol(Rest, U#diameter_uri{transport = P});
-scan_opt_transport(S, U) ->
- scan_opt_protocol(S, U).
-
-scan_opt_protocol(";protocol=" ++ S, U) ->
- {P, ""} = protocol(S),
- U#diameter_uri{protocol = P};
-scan_opt_protocol("", U) ->
- U.
-
-transport("tcp" ++ S) ->
- {tcp, S};
-transport("sctp" ++ S) ->
- {sctp, S};
-transport("udp" ++ S) ->
- {udp, S}.
-
-protocol("diameter" ++ S) ->
- {diameter, S};
-protocol("radius" ++ S) ->
- {radius, S};
-protocol("tacacs+" ++ S) ->
- {'tacacs+', S}.
-
-is_fqdn(C) ->
- is_digit(C) orelse is_alpha(C) orelse C == $. orelse C == $-.
-
-is_alpha(C) ->
- ($a =< C andalso C =< $z) orelse ($A =< C andalso C =< $Z).
-
-is_digit(C) ->
- $0 =< C andalso C =< $9.
+%% RFC 6733, 4.3.1, changes the defaults:
+%%
+%% "aaa://" FQDN [ port ] [ transport ] [ protocol ]
+%%
+%% ; No transport security
+%%
+%% "aaas://" FQDN [ port ] [ transport ] [ protocol ]
+%%
+%% ; Transport security used
+%%
+%% FQDN = < Fully Qualified Domain Name >
+%%
+%% port = ":" 1*DIGIT
+%%
+%% ; One of the ports used to listen for
+%% ; incoming connections.
+%% ; If absent, the default Diameter port
+%% ; (3868) is assumed if no transport
+%% ; security is used and port 5658 when
+%% ; transport security (TLS/TCP and DTLS/SCTP)
+%% ; is used.
+%%
+%% transport = ";transport=" transport-protocol
+%%
+%% ; One of the transports used to listen
+%% ; for incoming connections. If absent,
+%% ; the default protocol is assumed to be TCP.
+%% ; UDP MUST NOT be used when the aaa-protocol
+%% ; field is set to diameter.
+%%
+%% transport-protocol = ( "tcp" / "sctp" / "udp" )
+%%
+%% protocol = ";protocol=" aaa-protocol
+%%
+%% ; If absent, the default AAA protocol
+%% ; is Diameter.
+%%
+%% aaa-protocol = ( "diameter" / "radius" / "tacacs+" )
+
+scan_uri(Bin) ->
+ RE = "^(aaas?)://"
+ "([-a-zA-Z0-9.]{1,255})"
+ "(:0{0,5}([0-9]{1,5}))?"
+ "(;transport=(tcp|sctp|udp))?"
+ "(;protocol=(diameter|radius|tacacs\\+))?$",
+ %% A port number is 16-bit, so an arbitrary number of digits is
+ %% just a vulnerability, but provide a little slack with leading
+ %% zeros in a port number just because the regexp was previously
+ %% [0-9]+ and it's not inconceivable that a value might be padded.
+ %% Don't fantasize about this padding being more than the number
+ %% of digits in the port number proper.
+ %%
+ %% Similarly, a FQDN can't be arbitrarily long: at most 255
+ %% octets.
+ {match, [A, DN, PN, T, P]} = re:run(Bin,
+ RE,
+ [{capture, [1,2,4,6,8], binary}]),
+ Type = to_atom(A),
+ {PN0, T0} = defaults(diameter_codec:getopt(rfc), Type),
+ PortNr = to_int(PN, PN0),
+ 0 = PortNr bsr 16, %% assert
+ #diameter_uri{type = Type,
+ fqdn = 'OctetString'(decode, DN),
+ port = PortNr,
+ transport = to_atom(T, T0),
+ protocol = to_atom(P, diameter)}.
+
+%% Choose defaults based on the RFC, since 6733 has changed them.
+defaults(3588, _) ->
+ {3868, sctp};
+defaults(6733, aaa) ->
+ {3868, tcp};
+defaults(6733, aaas) ->
+ {5658, tcp}.
+
+to_int(<<>>, N) ->
+ N;
+to_int(B, _) ->
+ binary_to_integer(B).
+
+to_atom(<<>>, A) ->
+ A;
+to_atom(B, _) ->
+ to_atom(B).
+
+to_atom(B) ->
+ binary_to_atom(B, latin1).
diff --git a/lib/diameter/src/base/diameter_watchdog.erl b/lib/diameter/src/base/diameter_watchdog.erl
index 88ccf630e2..26bca7a5bc 100644
--- a/lib/diameter/src/base/diameter_watchdog.erl
+++ b/lib/diameter/src/base/diameter_watchdog.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -49,8 +49,6 @@
-define(IS_NATURAL(N), (is_integer(N) andalso 0 =< N)).
--define(CHOOSE(B,T,F), if (B) -> T; true -> F end).
-
-record(config,
{suspect = 1 :: non_neg_integer(), %% OKAY -> SUSPECT
okay = 3 :: non_neg_integer()}). %% REOPEN -> OKAY
@@ -67,7 +65,9 @@
%% end PCB
parent = self() :: pid(), %% service process
transport :: pid() | undefined, %% peer_fsm process
- tref :: reference(), %% reference for current watchdog timer
+ tref :: reference() %% reference for current watchdog timer
+ | tuple() %% now()
+ | undefined,
dictionary :: module(), %% common dictionary
receive_data :: term(),
%% term passed into diameter_service with incoming message
@@ -95,7 +95,7 @@ start({_,_} = Type, T) ->
Ack = make_ref(),
{ok, Pid} = diameter_watchdog_sup:start_child({Ack, Type, self(), T}),
try
- {erlang:monitor(process, Pid), Pid}
+ {monitor(process, Pid), Pid}
after
send(Pid, Ack)
end.
@@ -122,17 +122,19 @@ i({Ack, T, Pid, {RecvData,
#diameter_service{applications = Apps,
capabilities = Caps}
= Svc}}) ->
- erlang:monitor(process, Pid),
+ monitor(process, Pid),
wait(Ack, Pid),
random:seed(now()),
- putr(restart, {T, Opts, Svc}), %% save seeing it in trace
- putr(dwr, dwr(Caps)), %%
+ putr(restart, {T, Opts, Svc, SvcOpts}), %% save seeing it in trace
+ putr(dwr, dwr(Caps)), %%
{_,_} = Mask = proplists:get_value(sequence, SvcOpts),
Restrict = proplists:get_value(restrict_connections, SvcOpts),
Nodes = restrict_nodes(Restrict),
Dict0 = common_dictionary(Apps),
+ diameter_codec:setopts([{common_dictionary, Dict0},
+ {string_decode, false}]),
#watchdog{parent = Pid,
- transport = start(T, Opts, Mask, Nodes, Dict0, Svc),
+ transport = start(T, Opts, SvcOpts, Nodes, Dict0, Svc),
tw = proplists:get_value(watchdog_timer,
Opts,
?DEFAULT_TW_INIT),
@@ -157,8 +159,7 @@ wait(Ref, Pid) ->
config(Opts) ->
Config = proplists:get_value(watchdog_config, Opts, []),
- is_list(Config) orelse config_error({watchdog_config, Config}),
- lists:foldl(fun config/2, #config{}, Config). %% ^ added in old code
+ lists:foldl(fun config/2, #config{}, Config).
config({suspect, N}, Rec)
when ?IS_NATURAL(N) ->
@@ -166,16 +167,13 @@ config({suspect, N}, Rec)
config({okay, N}, Rec)
when ?IS_NATURAL(N) ->
- Rec#config{okay = N};
-
-config(T, _) -> %% added in old code
- config_error(T).
+ Rec#config{okay = N}.
-%% start/5
+%% start/6
-start(T, Opts, Mask, Nodes, Dict0, Svc) ->
+start(T, Opts, SvcOpts, Nodes, Dict0, Svc) ->
{_MRef, Pid}
- = diameter_peer_fsm:start(T, Opts, {Mask, Nodes, Dict0, Svc}),
+ = diameter_peer_fsm:start(T, Opts, {SvcOpts, Nodes, Dict0, Svc}),
Pid.
%% common_dictionary/1
@@ -201,7 +199,7 @@ common_dictionary(Apps) ->
%% means a user won't be able either send of receive
%% messages in the common dictionary: incoming request
%% will be answered with 3007 and outgoing requests cannot
- %% be sent. The dictionary returned here is oly used for
+ %% be sent. The dictionary returned here is only used for
%% messages diameter sends and receives: CER/CEA, DPR/DPA
%% and DWR/DWA.
?BASE
@@ -225,7 +223,6 @@ dict0(_, _, Acc) ->
Acc.
config_error(T) ->
- diameter_lib:error_report(configuration_error, T),
exit({shutdown, {configuration_error, T}}).
%% handle_call/3
@@ -249,22 +246,16 @@ handle_info(T, #watchdog{} = State) ->
event(T, State, S), %% before 'watchdog'
{noreply, S};
stop ->
- ?LOG(stop, T),
+ ?LOG(stop, truncate(T)),
event(T, State, State#watchdog{status = down}),
{stop, {shutdown, T}, State}
- end;
-
-handle_info(T, State) -> %% started in old code
- handle_info(T, upgrade(State)).
-
-upgrade(State) ->
- case erlang:append_element(State, #config{}) of
- #watchdog{status = okay, config = #config{suspect = OS}} = S ->
- S#watchdog{num_dwa = OS};
- #watchdog{} = S ->
- S
end.
+truncate({'DOWN' = T, _, process, Pid, _}) ->
+ {T, Pid};
+truncate(T) ->
+ T.
+
close({'DOWN', _, process, TPid, {shutdown, Reason}},
#watchdog{transport = TPid,
parent = Pid}) ->
@@ -273,11 +264,15 @@ close({'DOWN', _, process, TPid, {shutdown, Reason}},
close(_, _) ->
ok.
-event(_, #watchdog{status = T}, #watchdog{status = T}) ->
- ok;
-
-event(_, #watchdog{transport = undefined}, #watchdog{transport = undefined}) ->
+event(_,
+ #watchdog{status = From, transport = F},
+ #watchdog{status = To, transport = T})
+ when F == undefined, T == undefined; %% transport not started
+ From == initial, To == down; %% never really left INITIAL
+ From == To -> %% no state transition
ok;
+%% Note that there is no INITIAL -> DOWN transition in RFC 3539: ours
+%% is just a consequence of stop.
event(Msg,
#watchdog{status = From, transport = F, parent = Pid},
@@ -285,7 +280,7 @@ event(Msg,
TPid = tpid(F,T),
E = {[TPid | data(Msg, TPid, From, To)], From, To},
send(Pid, {watchdog, self(), E}),
- ?LOG(transition, {self(), E}).
+ ?LOG(transition, {From, To}).
data(Msg, TPid, reopen, okay) ->
{recv, TPid, 'DWA', _Pkt} = Msg, %% assert
@@ -328,14 +323,13 @@ code_change(_, State, _) ->
%% The state transitions documented here are extracted from RFC 3539,
%% the commentary is ours.
-%% Service or watchdog is telling the watchdog of an accepting
-%% transport to die after reconnect_timer expiry or reestablished
-%% connection (in another transport process) respectively.
-transition(close, #watchdog{status = down}) ->
- {{accept, _}, _, _} = getr(restart), %% assert
- stop;
+%% Service is telling the watchdog of an accepting transport to die
+%% following transport death in state INITIAL, or after connect_timer
+%% expiry; or another watchdog is saying the same after reestablishing
+%% a connection previously had by this one.
transition(close, #watchdog{}) ->
- ok;
+ {accept, _} = role(), %% assert
+ stop;
%% Service is asking for the peer to be taken down gracefully.
transition({shutdown, Pid, _}, #watchdog{parent = Pid,
@@ -347,6 +341,12 @@ transition({shutdown = T, Pid, Reason}, #watchdog{parent = Pid,
send(TPid, {T, self(), Reason}),
S#watchdog{shutdown = true};
+%% Transport is telling us that DPA has been sent in response to DPR,
+%% or that DPR has been explicitly sent: transport death should lead
+%% to ours.
+transition({'DPR', TPid}, #watchdog{transport = TPid} = S) ->
+ S#watchdog{shutdown = true};
+
%% Parent process has died,
transition({'DOWN', _, process, Pid, _Reason},
#watchdog{parent = Pid}) ->
@@ -378,7 +378,7 @@ transition({open, TPid, Hosts, _} = Open,
restrict = {_,R},
config = #config{suspect = OS}}
= S) ->
- case okay(getr(restart), Hosts, R) of
+ case okay(role(), Hosts, R) of
okay ->
set_watchdog(S#watchdog{status = okay,
num_dwa = OS});
@@ -418,18 +418,33 @@ transition({open = Key, TPid, _Hosts, T},
%% REOPEN Connection down CloseConnection()
%% SetWatchdog() DOWN
+%% Transport has died after DPA or service requested termination ...
transition({'DOWN', _, process, TPid, _Reason},
#watchdog{transport = TPid,
shutdown = true}) ->
stop;
-transition({'DOWN', _, process, TPid, _Reason},
+%% ... or not.
+transition({'DOWN', _, process, TPid, _Reason} = D,
#watchdog{transport = TPid,
- status = T}
- = S) ->
- set_watchdog(S#watchdog{status = ?CHOOSE(initial == T, T, down),
- pending = false,
- transport = undefined});
+ status = T,
+ restrict = {_,R}}
+ = S0) ->
+ S = S0#watchdog{pending = false,
+ transport = undefined},
+ {M,_} = role(),
+
+ %% Close an accepting watchdog immediately if there's no
+ %% restriction on the number of connections to the same peer: the
+ %% state machine never enters state REOPEN in this case.
+
+ if T == initial;
+ M == accept, not R ->
+ close(D, S0),
+ stop;
+ true ->
+ set_watchdog(S#watchdog{status = down})
+ end;
%% Incoming message.
transition({recv, TPid, Name, Pkt}, #watchdog{transport = TPid} = S) ->
@@ -437,11 +452,12 @@ transition({recv, TPid, Name, Pkt}, #watchdog{transport = TPid} = S) ->
%% Current watchdog has timed out.
transition({timeout, TRef, tw}, #watchdog{tref = TRef} = S) ->
- set_watchdog(timeout(S));
+ set_watchdog(0, timeout(S));
-%% Timer was canceled after message was already sent.
-transition({timeout, _, tw}, #watchdog{}) ->
- ok;
+%% Message has arrived since the timer was started: subtract time
+%% already elapsed from new timer.
+transition({timeout, _, tw}, #watchdog{tref = T0} = S) ->
+ set_watchdog(timer:now_diff(now(), T0) div 1000, S);
%% State query.
transition({state, Pid}, #watchdog{status = S}) ->
@@ -461,19 +477,30 @@ eraser(Key) ->
%% encode/3
-encode(Msg, Mask, Dict) ->
+encode(dwr = M, Dict0, Mask) ->
+ Msg = getr(M),
Seq = diameter_session:sequence(Mask),
Hdr = #diameter_header{version = ?DIAMETER_VERSION,
end_to_end_id = Seq,
hop_by_hop_id = Seq},
Pkt = #diameter_packet{header = Hdr,
msg = Msg},
- #diameter_packet{bin = Bin} = diameter_codec:encode(Dict, Pkt),
- Bin.
+ diameter_codec:encode(Dict0, Pkt);
+
+encode(dwa, Dict0, #diameter_packet{header = H, transport_data = TD}
+ = ReqPkt) ->
+ AnsPkt = #diameter_packet{header
+ = H#diameter_header{is_request = false,
+ is_error = undefined,
+ is_retransmitted = false},
+ msg = dwa(ReqPkt),
+ transport_data = TD},
+
+ diameter_codec:encode(Dict0, AnsPkt).
%% okay/3
-okay({{accept, Ref}, _, _}, Hosts, Restrict) ->
+okay({accept, Ref}, Hosts, Restrict) ->
T = {?MODULE, connection, Ref, Hosts},
diameter_reg:add(T),
if Restrict ->
@@ -484,7 +511,7 @@ okay({{accept, Ref}, _, _}, Hosts, Restrict) ->
%% Register before matching so that at least one of two registering
%% processes will match the other.
-okay({{connect, _}, _, _}, _, _) ->
+okay({connect, _}, _, _) ->
okay.
%% okay/2
@@ -499,20 +526,34 @@ okay(C) ->
[_|_] = [send(P, close) || {_,P} <- C, self() /= P],
reopen.
+%% role/0
+
+role() ->
+ element(1, getr(restart)).
+
%% set_watchdog/1
-set_watchdog(#watchdog{tw = TwInit,
- tref = TRef}
- = S) ->
- cancel(TRef),
- S#watchdog{tref = erlang:start_timer(tw(TwInit), self(), tw)};
-set_watchdog(stop = No) ->
- No.
+%% Timer not yet set.
+set_watchdog(#watchdog{tref = undefined} = S) ->
+ set_watchdog(0, S);
-cancel(undefined) ->
- ok;
-cancel(TRef) ->
- erlang:cancel_timer(TRef).
+%% Timer already set: start at new one only at expiry.
+set_watchdog(#watchdog{} = S) ->
+ S#watchdog{tref = now()}.
+
+%% set_watchdog/2
+
+set_watchdog(_, stop = No) ->
+ No;
+
+set_watchdog(Ms, #watchdog{tw = TwInit} = S) ->
+ S#watchdog{tref = erlang:start_timer(tw(TwInit, Ms), self(), tw)}.
+
+%% A callback could return anything, so ensure the result isn't
+%% negative. Don't prevent abuse, even though the smallest valid
+%% timeout is 4000.
+tw(TwInit, Ms) ->
+ max(tw(TwInit) - Ms, 0).
tw(T)
when is_integer(T), T >= 6000 ->
@@ -527,10 +568,14 @@ send_watchdog(#watchdog{pending = false,
dictionary = Dict0,
sequence = Mask}
= S) ->
- send(TPid, {send, encode(getr(dwr), Mask, Dict0)}),
+ #diameter_packet{bin = Bin} = EPkt = encode(dwr, Dict0, Mask),
+ diameter_traffic:incr(send, EPkt, TPid, Dict0),
+ send(TPid, {send, Bin}),
?LOG(send, 'DWR'),
S#watchdog{pending = true}.
+%% Don't count encode errors since we don't expect any on DWR/DWA.
+
%% recv/3
recv(Name, Pkt, S) ->
@@ -545,14 +590,42 @@ recv(Name, Pkt, S) ->
%% rcv/3
+rcv('DWR', Pkt, #watchdog{transport = TPid,
+ dictionary = Dict0}) ->
+ ?LOG(recv, 'DWR'),
+ DPkt = diameter_codec:decode(Dict0, Pkt),
+ diameter_traffic:incr(recv, DPkt, TPid, Dict0),
+ diameter_traffic:incr_error(recv, DPkt, TPid, Dict0),
+ #diameter_packet{header = H,
+ transport_data = T,
+ bin = Bin}
+ = EPkt
+ = encode(dwa, Dict0, Pkt),
+ diameter_traffic:incr(send, EPkt, TPid, Dict0),
+ diameter_traffic:incr_rc(send, EPkt, TPid, Dict0),
+
+ %% Strip potentially large message terms.
+ send(TPid, {send, #diameter_packet{header = H,
+ transport_data = T,
+ bin = Bin}}),
+ ?LOG(send, 'DWA');
+
+rcv('DWA', Pkt, #watchdog{transport = TPid,
+ dictionary = Dict0}) ->
+ ?LOG(recv, 'DWA'),
+ diameter_traffic:incr(recv, Pkt, TPid, Dict0),
+ diameter_traffic:incr_rc(recv,
+ diameter_codec:decode(Dict0, Pkt),
+ TPid,
+ Dict0);
+
rcv(N, _, _)
when N == 'CER';
N == 'CEA';
- N == 'DWR';
- N == 'DWA';
- N == 'DPR';
- N == 'DPA' ->
+ N == 'DPR' ->
false;
+%% DPR can be sent explicitly with diameter:call/4. Only the
+%% corresponding DPAs arrive here.
rcv(_, Pkt, #watchdog{transport = TPid,
dictionary = Dict0,
@@ -642,6 +715,9 @@ rcv('DWA', #watchdog{status = reopen,
%% REOPEN Receive non-DWA Throwaway() REOPEN
+rcv('DWR', #watchdog{status = reopen} = S) ->
+ S; %% ensure DWA: the RFC isn't explicit about answering
+
rcv(_, #watchdog{status = reopen} = S) ->
throwaway(S).
@@ -735,7 +811,7 @@ timeout(#watchdog{status = T} = S)
restart(#watchdog{transport = undefined} = S) ->
restart(getr(restart), S);
-restart(S) ->
+restart(S) -> %% reconnect has won race with timeout
S.
%% restart/2
@@ -750,25 +826,28 @@ restart(S) ->
%% state down rather then initial when receiving notification of an
%% open connection.
-restart({{connect, _} = T, Opts, Svc},
+restart({T, Opts, Svc}, S) -> %% put in old code
+ restart({T, Opts, Svc, []}, S);
+
+restart({{connect, _} = T, Opts, Svc, SvcOpts},
#watchdog{parent = Pid,
- sequence = Mask,
restrict = {R,_},
dictionary = Dict0}
= S) ->
send(Pid, {reconnect, self()}),
Nodes = restrict_nodes(R),
- S#watchdog{transport = start(T, Opts, Mask, Nodes, Dict0, Svc),
+ S#watchdog{transport = start(T, Opts, SvcOpts, Nodes, Dict0, Svc),
restrict = {R, lists:member(node(), Nodes)}};
%% No restriction on the number of connections to the same peer: just
%% die. Note that a state machine never enters state REOPEN in this
%% case.
-restart({{accept, _}, _, _}, #watchdog{restrict = {_, false}}) ->
- stop;
+restart({{accept, _}, _, _, _}, #watchdog{restrict = {_, false}}) ->
+ stop; %% 'DOWN' was in old code: 'close' was not sent
-%% Otherwise hang around until told to die.
-restart({{accept, _}, _, _}, S) ->
+%% Otherwise hang around until told to die, either by the service or
+%% by another watchdog.
+restart({{accept, _}, _, _, _}, S) ->
S.
%% Don't currently use Opts/Svc in the accept case.
@@ -782,6 +861,13 @@ dwr(#diameter_caps{origin_host = OH,
{'Origin-Realm', OR},
{'Origin-State-Id', OSI}].
+%% dwa/1
+
+dwa(#diameter_packet{header = H, errors = Es}) ->
+ {RC, FailedAVP} = diameter_peer_fsm:result_code(H, Es),
+ ['DWA', {'Result-Code', RC}
+ | tl(getr(dwr)) ++ FailedAVP].
+
%% restrict_nodes/1
restrict_nodes(false) ->
diff --git a/lib/diameter/src/compiler/diameter_codegen.erl b/lib/diameter/src/compiler/diameter_codegen.erl
index e687145263..d91a776321 100644
--- a/lib/diameter/src/compiler/diameter_codegen.erl
+++ b/lib/diameter/src/compiler/diameter_codegen.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2014. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -31,12 +31,8 @@
%% on the beam file of another dictionary.
%%
--export([from_dict/4]).
-
-%% Internal exports (for test).
--export([file/1,
- file/2,
- file/3]).
+-export([from_dict/4,
+ is_printable_ascii/1]). %% used by ?TERM/1 in diameter_forms.hrl
-include("diameter_forms.hrl").
-include("diameter_vsn.hrl").
@@ -48,18 +44,61 @@
%% ===========================================================================
--spec from_dict(File, Spec, Opts, Mode)
+-spec from_dict(File, ParseD, Opts, Mode)
-> ok
+ | term()
when File :: string(),
- Spec :: orddict:orddict(),
+ ParseD :: orddict:orddict(),
Opts :: list(),
- Mode :: spec | erl | hrl.
+ Mode :: parse | forms | erl | hrl.
-from_dict(File, Spec, Opts, Mode) ->
+from_dict(File, ParseD, Opts, Mode) ->
Outdir = proplists:get_value(outdir, Opts, "."),
+ Return = proplists:get_value(return, Opts, false),
+ Mod = mod(File, orddict:find(name, ParseD)),
putr(verbose, lists:member(verbose, Opts)),
- putr(debug, lists:member(debug, Opts)),
- codegen(File, Spec, Outdir, Mode).
+ try
+ maybe_write(Return, Mode, Outdir, Mod, gen(Mode, ParseD, ?A(Mod)))
+ after
+ eraser(verbose)
+ end.
+
+mod(File, error) ->
+ filename:rootname(filename:basename(File));
+mod(_, {ok, Mod}) ->
+ Mod.
+
+maybe_write(true, _, _, _, T) ->
+ T;
+
+maybe_write(_, Mode, Outdir, Mod, T) ->
+ Path = filename:join(Outdir, Mod), %% minus extension
+ do_write(Mode, [Path, $., ext(Mode)], T).
+
+ext(parse) ->
+ "D";
+ext(forms) ->
+ "F";
+ext(T) ->
+ ?S(T).
+
+do_write(M, Path, T)
+ when M == parse;
+ M == forms ->
+ write_term(Path, T);
+do_write(_, Path, T) ->
+ write(Path, T).
+
+write(Path, T) ->
+ write(Path, "~s", T).
+
+write_term(Path, T) ->
+ write(Path, "~p.~n", T).
+
+write(Path, Fmt, T) ->
+ {ok, Fd} = file:open(Path, [write]),
+ io:fwrite(Fd, Fmt, [T]),
+ ok = file:close(Fd).
%% Optional reports when running verbosely.
report(What, Data) ->
@@ -77,118 +116,80 @@ putr(Key, Value) ->
getr(Key) ->
get({?MODULE, Key}).
-%% ===========================================================================
-%% ===========================================================================
-
-%% Generate from parsed dictionary in a file.
-
-file(F) ->
- file(F, spec).
-
-file(F, Mode) ->
- file(F, ".", Mode).
-
-file(F, Outdir, Mode) ->
- {ok, [Spec]} = file:consult(F),
- from_dict(F, Spec, Outdir, Mode).
+eraser(Key) ->
+ erase({?MODULE, Key}).
%% ===========================================================================
%% ===========================================================================
+is_printable_ascii(C) ->
+ 16#20 =< C andalso C =< 16#7F.
+
get_value(Key, Plist) ->
proplists:get_value(Key, Plist, []).
-write(Path, Str) ->
- w(Path, Str, "~s").
-
-write_term(Path, T) ->
- w(Path, T, "~p.").
-
-w(Path, T, Fmt) ->
- {ok, Fd} = file:open(Path, [write]),
- io:fwrite(Fd, Fmt ++ "~n", [T]),
- file:close(Fd).
-
-codegen(File, Spec, Outdir, Mode) ->
- Mod = mod(File, orddict:find(name, Spec)),
- Path = filename:join(Outdir, Mod), %% minus extension
- gen(Mode, Spec, ?A(Mod), Path),
- ok.
-
-mod(File, error) ->
- filename:rootname(filename:basename(File));
-mod(_, {ok, Mod}) ->
- Mod.
-
-gen(spec, Spec, _Mod, Path) ->
- write_term(Path ++ ".spec", [?VERSION | Spec]);
-
-gen(hrl, Spec, Mod, Path) ->
- gen_hrl(Path ++ ".hrl", Mod, Spec);
-
-gen(erl, Spec, Mod, Path) ->
- Forms = [{?attribute, module, Mod},
- {?attribute, compile, {parse_transform, diameter_exprecs}},
- {?attribute, compile, nowarn_unused_function},
- {?attribute, export, [{name, 0},
- {id, 0},
- {vendor_id, 0},
- {vendor_name, 0},
- {decode_avps, 2}, %% in diameter_gen.hrl
- {encode_avps, 2}, %%
- {msg_name, 2},
- {msg_header, 1},
- {rec2msg, 1},
- {msg2rec, 1},
- {name2rec, 1},
- {avp_name, 2},
- {avp_arity, 2},
- {avp_header, 1},
- {avp, 3},
- {grouped_avp, 3},
- {enumerated_avp, 3},
- {empty_value, 1},
- {dict, 0}]},
- %% diameter.hrl is included for #diameter_avp
- {?attribute, include_lib, "diameter/include/diameter.hrl"},
- {?attribute, include_lib, "diameter/include/diameter_gen.hrl"},
- f_name(Mod),
- f_id(Spec),
- f_vendor_id(Spec),
- f_vendor_name(Spec),
- f_msg_name(Spec),
- f_msg_header(Spec),
- f_rec2msg(Spec),
- f_msg2rec(Spec),
- f_name2rec(Spec),
- f_avp_name(Spec),
- f_avp_arity(Spec),
- f_avp_header(Spec),
- f_avp(Spec),
- f_enumerated_avp(Spec),
- f_empty_value(Spec),
- f_dict(Spec),
- {eof, ?LINE}],
-
- gen_erl(Path, insert_hrl_forms(Spec, Forms)).
-
-gen_erl(Path, Forms) ->
- getr(debug) andalso write_term(Path ++ ".forms", Forms),
- write(Path ++ ".erl",
- header() ++ erl_prettypr:format(erl_syntax:form_list(Forms))).
-
-insert_hrl_forms(Spec, Forms) ->
- {H,T} = lists:splitwith(fun is_header/1, Forms),
- H ++ make_hrl_forms(Spec) ++ T.
-
-is_header({attribute, _, export, _}) ->
- false;
-is_header(_) ->
- true.
-
-make_hrl_forms(Spec) ->
+gen(parse, ParseD, _Mod) ->
+ [?VERSION | ParseD];
+
+gen(forms, ParseD, Mod) ->
+ preprocess(Mod, erl_forms(Mod, ParseD));
+
+gen(hrl, ParseD, Mod) ->
+ gen_hrl(Mod, ParseD);
+
+gen(erl, ParseD, Mod) ->
+ [header(), prettypr(erl_forms(Mod, ParseD)), $\n].
+
+erl_forms(Mod, ParseD) ->
+ Forms = [[{?attribute, module, Mod},
+ {?attribute, compile, {parse_transform, diameter_exprecs}},
+ {?attribute, compile, nowarn_unused_function}],
+ make_hrl_forms(ParseD),
+ [{?attribute, export, [{name, 0},
+ {id, 0},
+ {vendor_id, 0},
+ {vendor_name, 0},
+ {decode_avps, 2}, %% in diameter_gen.hrl
+ {encode_avps, 2}, %%
+ {msg_name, 2},
+ {msg_header, 1},
+ {rec2msg, 1},
+ {msg2rec, 1},
+ {name2rec, 1},
+ {avp_name, 2},
+ {avp_arity, 2},
+ {avp_header, 1},
+ {avp, 3},
+ {grouped_avp, 3},
+ {enumerated_avp, 3},
+ {empty_value, 1},
+ {dict, 0}]},
+ %% diameter.hrl is included for #diameter_avp
+ {?attribute, include_lib, "diameter/include/diameter.hrl"},
+ {?attribute, include_lib, "diameter/include/diameter_gen.hrl"},
+ f_name(Mod),
+ f_id(ParseD),
+ f_vendor_id(ParseD),
+ f_vendor_name(ParseD),
+ f_msg_name(ParseD),
+ f_msg_header(ParseD),
+ f_rec2msg(ParseD),
+ f_msg2rec(ParseD),
+ f_name2rec(ParseD),
+ f_avp_name(ParseD),
+ f_avp_arity(ParseD),
+ f_avp_header(ParseD),
+ f_avp(ParseD),
+ f_enumerated_avp(ParseD),
+ f_empty_value(ParseD),
+ f_dict(ParseD),
+ {eof, ?LINE}]],
+
+ lists:append(Forms).
+
+make_hrl_forms(ParseD) ->
{_Prefix, MsgRecs, GrpRecs, ImportedGrpRecs}
- = make_record_forms(Spec),
+ = make_record_forms(ParseD),
RecordForms = MsgRecs ++ GrpRecs ++ lists:flatmap(fun({_,Fs}) -> Fs end,
ImportedGrpRecs),
@@ -199,16 +200,16 @@ make_hrl_forms(Spec) ->
%% export_records is used by the diameter_exprecs parse transform.
[{?attribute, export_records, RecNames} | RecordForms].
-make_record_forms(Spec) ->
- Prefix = prefix(Spec),
+make_record_forms(ParseD) ->
+ Prefix = prefix(ParseD),
- MsgRecs = a_record(Prefix, fun msg_proj/1, get_value(messages, Spec)),
- GrpRecs = a_record(Prefix, fun grp_proj/1, get_value(grouped, Spec)),
+ MsgRecs = a_record(Prefix, fun msg_proj/1, get_value(messages, ParseD)),
+ GrpRecs = a_record(Prefix, fun grp_proj/1, get_value(grouped, ParseD)),
ImportedGrpRecs = [{M, a_record(Prefix, fun grp_proj/1, Gs)}
- || {M,Gs} <- get_value(import_groups, Spec)],
+ || {M,Gs} <- get_value(import_groups, ParseD)],
- {Prefix, MsgRecs, GrpRecs, ImportedGrpRecs}.
+ {to_upper(Prefix), MsgRecs, GrpRecs, ImportedGrpRecs}.
msg_proj({Name, _, _, _, Avps}) ->
{Name, Avps}.
@@ -246,9 +247,9 @@ f_name(Name) ->
%%% # id/0
%%% ------------------------------------------------------------------------
-f_id(Spec) ->
+f_id(ParseD) ->
{?function, id, 0,
- [c_id(orddict:find(id, Spec))]}.
+ [c_id(orddict:find(id, ParseD))]}.
c_id({ok, Id}) ->
{?clause, [], [], [?INTEGER(Id)]};
@@ -260,9 +261,9 @@ c_id(error) ->
%%% # vendor_id/0
%%% ------------------------------------------------------------------------
-f_vendor_id(Spec) ->
+f_vendor_id(ParseD) ->
{?function, vendor_id, 0,
- [{?clause, [], [], [b_vendor_id(orddict:find(vendor, Spec))]}]}.
+ [{?clause, [], [], [b_vendor_id(orddict:find(vendor, ParseD))]}]}.
b_vendor_id({ok, {Id, _}}) ->
?INTEGER(Id);
@@ -273,9 +274,9 @@ b_vendor_id(error) ->
%%% # vendor_name/0
%%% ------------------------------------------------------------------------
-f_vendor_name(Spec) ->
+f_vendor_name(ParseD) ->
{?function, vendor_name, 0,
- [{?clause, [], [], [b_vendor_name(orddict:find(vendor, Spec))]}]}.
+ [{?clause, [], [], [b_vendor_name(orddict:find(vendor, ParseD))]}]}.
b_vendor_name({ok, {_, Name}}) ->
?Atom(Name);
@@ -286,15 +287,15 @@ b_vendor_name(error) ->
%%% # msg_name/1
%%% ------------------------------------------------------------------------
-f_msg_name(Spec) ->
- {?function, msg_name, 2, msg_name(Spec)}.
+f_msg_name(ParseD) ->
+ {?function, msg_name, 2, msg_name(ParseD)}.
%% Return the empty name for any unknown command to which
%% DIAMETER_COMMAND_UNSUPPORTED should be replied.
-msg_name(Spec) ->
+msg_name(ParseD) ->
lists:flatmap(fun c_msg_name/1, proplists:get_value(command_codes,
- Spec,
+ ParseD,
[]))
++ [{?clause, [?VAR('_'), ?VAR('_')], [], [?ATOM('')]}].
@@ -310,12 +311,12 @@ c_msg_name({Code, Req, Ans}) ->
%%% # msg2rec/1
%%% ------------------------------------------------------------------------
-f_msg2rec(Spec) ->
- {?function, msg2rec, 1, msg2rec(Spec)}.
+f_msg2rec(ParseD) ->
+ {?function, msg2rec, 1, msg2rec(ParseD)}.
-msg2rec(Spec) ->
- Pre = prefix(Spec),
- lists:map(fun(T) -> c_msg2rec(T, Pre) end, get_value(messages, Spec))
+msg2rec(ParseD) ->
+ Pre = prefix(ParseD),
+ lists:map(fun(T) -> c_msg2rec(T, Pre) end, get_value(messages, ParseD))
++ [?BADARG(1)].
c_msg2rec({N,_,_,_,_}, Pre) ->
@@ -325,12 +326,12 @@ c_msg2rec({N,_,_,_,_}, Pre) ->
%%% # rec2msg/1
%%% ------------------------------------------------------------------------
-f_rec2msg(Spec) ->
- {?function, rec2msg, 1, rec2msg(Spec)}.
+f_rec2msg(ParseD) ->
+ {?function, rec2msg, 1, rec2msg(ParseD)}.
-rec2msg(Spec) ->
- Pre = prefix(Spec),
- lists:map(fun(T) -> c_rec2msg(T, Pre) end, get_value(messages, Spec))
+rec2msg(ParseD) ->
+ Pre = prefix(ParseD),
+ lists:map(fun(T) -> c_rec2msg(T, Pre) end, get_value(messages, ParseD))
++ [?BADARG(1)].
c_rec2msg({N,_,_,_,_}, Pre) ->
@@ -340,13 +341,13 @@ c_rec2msg({N,_,_,_,_}, Pre) ->
%%% # name2rec/1
%%% ------------------------------------------------------------------------
-f_name2rec(Spec) ->
- {?function, name2rec, 1, name2rec(Spec)}.
+f_name2rec(ParseD) ->
+ {?function, name2rec, 1, name2rec(ParseD)}.
-name2rec(Spec) ->
- Pre = prefix(Spec),
- Groups = get_value(grouped, Spec)
- ++ lists:flatmap(fun avps/1, get_value(import_groups, Spec)),
+name2rec(ParseD) ->
+ Pre = prefix(ParseD),
+ Groups = get_value(grouped, ParseD)
+ ++ lists:flatmap(fun avps/1, get_value(import_groups, ParseD)),
lists:map(fun({N,_,_,_}) -> c_name2rec(N, Pre) end, Groups)
++ [{?clause, [?VAR('T')], [], [?CALL(msg2rec, [?VAR('T')])]}].
@@ -360,8 +361,8 @@ avps({_Mod, Avps}) ->
%%% # avp_name/1
%%% ------------------------------------------------------------------------
-f_avp_name(Spec) ->
- {?function, avp_name, 2, avp_name(Spec)}.
+f_avp_name(ParseD) ->
+ {?function, avp_name, 2, avp_name(ParseD)}.
%% 3588, 4.1:
%%
@@ -372,11 +373,11 @@ f_avp_name(Spec) ->
%% field. AVP numbers 256 and above are used for Diameter, which are
%% allocated by IANA (see Section 11.1).
-avp_name(Spec) ->
- Avps = get_value(avp_types, Spec),
- Imported = get_value(import_avps, Spec),
- Vid = orddict:find(vendor, Spec),
- Vs = vendor_id_map(Spec),
+avp_name(ParseD) ->
+ Avps = get_value(avp_types, ParseD),
+ Imported = get_value(import_avps, ParseD),
+ Vid = orddict:find(vendor, ParseD),
+ Vs = vendor_id_map(ParseD),
lists:map(fun(T) -> c_avp_name(T, Vs, Vid) end, Avps)
++ lists:flatmap(fun(T) -> c_imported_avp_name(T, Vs) end, Imported)
@@ -407,25 +408,25 @@ c_avp_name_(T, Code, Vid) ->
[],
[T]}.
-vendor_id_map(Spec) ->
+vendor_id_map(ParseD) ->
lists:flatmap(fun({V,Ns}) -> [{N,V} || N <- Ns] end,
- get_value(avp_vendor_id, Spec))
+ get_value(avp_vendor_id, ParseD))
++ lists:flatmap(fun({_,_,[],_}) -> [];
({N,_,[V],_}) -> [{N,V}]
end,
- get_value(grouped, Spec)).
+ get_value(grouped, ParseD)).
%%% ------------------------------------------------------------------------
%%% # avp_arity/2
%%% ------------------------------------------------------------------------
-f_avp_arity(Spec) ->
- {?function, avp_arity, 2, avp_arity(Spec)}.
+f_avp_arity(ParseD) ->
+ {?function, avp_arity, 2, avp_arity(ParseD)}.
-avp_arity(Spec) ->
- Msgs = get_value(messages, Spec),
- Groups = get_value(grouped, Spec)
- ++ lists:flatmap(fun avps/1, get_value(import_groups, Spec)),
+avp_arity(ParseD) ->
+ Msgs = get_value(messages, ParseD),
+ Groups = get_value(grouped, ParseD)
+ ++ lists:flatmap(fun avps/1, get_value(import_groups, ParseD)),
c_avp_arity(Msgs ++ Groups)
++ [{?clause, [?VAR('_'), ?VAR('_')], [], [?INTEGER(0)]}].
@@ -449,15 +450,15 @@ c_arity(Name, Avp) ->
%%% # avp/3
%%% ------------------------------------------------------------------------
-f_avp(Spec) ->
- {?function, avp, 3, avp(Spec) ++ [?BADARG(3)]}.
+f_avp(ParseD) ->
+ {?function, avp, 3, avp(ParseD) ++ [?BADARG(3)]}.
-avp(Spec) ->
- Native = get_value(avp_types, Spec),
- CustomMods = get_value(custom_types, Spec),
- TypeMods = get_value(codecs, Spec),
- Imported = get_value(import_avps, Spec),
- Enums = get_value(enum, Spec),
+avp(ParseD) ->
+ Native = get_value(avp_types, ParseD),
+ CustomMods = get_value(custom_types, ParseD),
+ TypeMods = get_value(codecs, ParseD),
+ Imported = get_value(import_avps, ParseD),
+ Enums = get_value(enum, ParseD),
Custom = lists:map(fun({M,As}) -> {M, custom_types, As} end,
CustomMods)
@@ -548,14 +549,14 @@ custom(codecs, AvpName, Type) ->
%%% # enumerated_avp/3
%%% ------------------------------------------------------------------------
-f_enumerated_avp(Spec) ->
- {?function, enumerated_avp, 3, enumerated_avp(Spec) ++ [?BADARG(3)]}.
+f_enumerated_avp(ParseD) ->
+ {?function, enumerated_avp, 3, enumerated_avp(ParseD) ++ [?BADARG(3)]}.
-enumerated_avp(Spec) ->
- Enums = get_value(enum, Spec),
+enumerated_avp(ParseD) ->
+ Enums = get_value(enum, ParseD),
lists:flatmap(fun cs_enumerated_avp/1, Enums)
++ lists:flatmap(fun({M,Es}) -> enumerated_avp(M, Es, Enums) end,
- get_value(import_enums, Spec)).
+ get_value(import_enums, ParseD)).
enumerated_avp(Mod, Es, Enums) ->
lists:flatmap(fun({N,_}) ->
@@ -585,16 +586,16 @@ c_enumerated_avp(AvpName, {_,I}) ->
%%% msg_header/1
%%% ------------------------------------------------------------------------
-f_msg_header(Spec) ->
- {?function, msg_header, 1, msg_header(Spec) ++ [?BADARG(1)]}.
+f_msg_header(ParseD) ->
+ {?function, msg_header, 1, msg_header(ParseD) ++ [?BADARG(1)]}.
-msg_header(Spec) ->
- msg_header(get_value(messages, Spec), Spec).
+msg_header(ParseD) ->
+ msg_header(get_value(messages, ParseD), ParseD).
msg_header([], _) ->
[];
-msg_header(Msgs, Spec) ->
- ApplId = orddict:fetch(id, Spec),
+msg_header(Msgs, ParseD) ->
+ ApplId = orddict:fetch(id, ParseD),
lists:map(fun({M,C,F,_,_}) -> c_msg_header(M, C, F, ApplId) end, Msgs).
@@ -616,14 +617,14 @@ emf('ERR', N) -> N bor 2#00100000.
%%% # avp_header/1
%%% ------------------------------------------------------------------------
-f_avp_header(Spec) ->
- {?function, avp_header, 1, avp_header(Spec) ++ [?BADARG(1)]}.
+f_avp_header(ParseD) ->
+ {?function, avp_header, 1, avp_header(ParseD) ++ [?BADARG(1)]}.
-avp_header(Spec) ->
- Native = get_value(avp_types, Spec),
- Imported = get_value(import_avps, Spec),
- Vid = orddict:find(vendor, Spec),
- Vs = vendor_id_map(Spec),
+avp_header(ParseD) ->
+ Native = get_value(avp_types, ParseD),
+ Imported = get_value(import_avps, ParseD),
+ Vid = orddict:find(vendor, ParseD),
+ Vs = vendor_id_map(ParseD),
lists:flatmap(fun(A) -> c_avp_header(A, Vs, Vid) end,
Native ++ Imported).
@@ -679,14 +680,14 @@ v(false, _, _, _) ->
%%% # empty_value/0
%%% ------------------------------------------------------------------------
-f_empty_value(Spec) ->
- {?function, empty_value, 1, empty_value(Spec)}.
+f_empty_value(ParseD) ->
+ {?function, empty_value, 1, empty_value(ParseD)}.
-empty_value(Spec) ->
- Imported = lists:flatmap(fun avps/1, get_value(import_enums, Spec)),
- Groups = get_value(grouped, Spec)
- ++ lists:flatmap(fun avps/1, get_value(import_groups, Spec)),
- Enums = [T || {N,_} = T <- get_value(enum, Spec),
+empty_value(ParseD) ->
+ Imported = lists:flatmap(fun avps/1, get_value(import_enums, ParseD)),
+ Groups = get_value(grouped, ParseD)
+ ++ lists:flatmap(fun avps/1, get_value(import_groups, ParseD)),
+ Enums = [T || {N,_} = T <- get_value(enum, ParseD),
not lists:keymember(N, 1, Imported)]
++ Imported,
lists:map(fun c_empty_value/1, Groups ++ Enums)
@@ -706,72 +707,52 @@ c_empty_value({Name, _}) ->
%%% # dict/0
%%% ------------------------------------------------------------------------
-f_dict(Spec) ->
+f_dict(ParseD) ->
{?function, dict, 0,
- [{?clause, [], [], [?TERM([?VERSION | Spec])]}]}.
+ [{?clause, [], [], [?TERM([?VERSION | ParseD])]}]}.
%%% ------------------------------------------------------------------------
-%%% # gen_hrl/3
+%%% # gen_hrl/2
%%% ------------------------------------------------------------------------
-gen_hrl(Path, Mod, Spec) ->
- {ok, Fd} = file:open(Path, [write]),
-
+gen_hrl(Mod, ParseD) ->
{Prefix, MsgRecs, GrpRecs, ImportedGrpRecs}
- = make_record_forms(Spec),
-
- file:write(Fd, hrl_header(Mod)),
-
- forms("Message records", Fd, MsgRecs),
- forms("Grouped AVP records", Fd, GrpRecs),
-
- lists:foreach(fun({M,Fs}) ->
- forms("Grouped AVP records from " ++ atom_to_list(M),
- Fd,
- Fs)
- end,
- ImportedGrpRecs),
-
- PREFIX = to_upper(Prefix),
-
- write("ENUM Macros",
- Fd,
- m_enums(PREFIX, false, get_value(enum, Spec))),
- write("DEFINE Macros",
- Fd,
- m_enums(PREFIX, false, get_value(define, Spec))),
-
- lists:foreach(fun({M,Es}) ->
- write("ENUM Macros from " ++ atom_to_list(M),
- Fd,
- m_enums(PREFIX, true, Es))
- end,
- get_value(import_enums, Spec)),
-
- file:close(Fd).
-
-forms(_, _, []) ->
- ok;
-forms(Banner, Fd, Forms) ->
- write(Banner, Fd, prettypr(Forms)).
-
-write(_, _, []) ->
- ok;
-write(Banner, Fd, Str) ->
- banner(Fd, Banner),
- io:fwrite(Fd, "~s~n", [Str]).
+ = make_record_forms(ParseD),
+
+ [hrl_header(Mod),
+ forms("Message records", MsgRecs),
+ forms("Grouped AVP records", GrpRecs),
+ lists:map(fun({M,Fs}) ->
+ forms("Grouped AVP records from " ++ atom_to_list(M),
+ Fs)
+ end,
+ ImportedGrpRecs),
+ format("ENUM Macros", m_enums(Prefix, false, get_value(enum, ParseD))),
+ format("DEFINE Macros", m_enums(Prefix, false, get_value(define, ParseD))),
+ lists:map(fun({M,Es}) ->
+ format("ENUM Macros from " ++ atom_to_list(M),
+ m_enums(Prefix, true, Es))
+ end,
+ get_value(import_enums, ParseD))].
+
+forms(_, [] = No) ->
+ No;
+forms(Banner, Forms) ->
+ format(Banner, prettypr(Forms)).
+
+format(_, [] = No) ->
+ No;
+format(Banner, Str) ->
+ [banner(Banner), Str, $\n].
prettypr(Forms) ->
erl_prettypr:format(erl_syntax:form_list(Forms)).
-banner(Fd, Heading) ->
- file:write(Fd, banner(Heading)).
-
banner(Heading) ->
- ("\n\n"
+ ["\n\n"
"%%% -------------------------------------------------------\n"
- "%%% " ++ Heading ++ ":\n"
- "%%% -------------------------------------------------------\n\n").
+ "%%% ", Heading, ":\n"
+ "%%% -------------------------------------------------------\n\n"].
z(S) ->
string:join(string:tokens(S, "\s\t"), "\s").
@@ -845,8 +826,8 @@ arity([_], '*' = Inf) -> {0, Inf};
arity({_}, '*' = Inf) -> {1, Inf};
arity(_, {_,_} = Q) -> Q.
-prefix(Spec) ->
- case orddict:find(prefix, Spec) of
+prefix(ParseD) ->
+ case orddict:find(prefix, ParseD) of
{ok, P} ->
P ++ "_";
error ->
@@ -855,3 +836,93 @@ prefix(Spec) ->
rec_name(Name, Prefix) ->
Prefix ++ Name.
+
+%% ===========================================================================
+%% preprocess/2
+%%
+%% Preprocess forms as generated by 'forms' option. In particular,
+%% replace the include_lib attributes in generated forms by the
+%% corresponding forms, extracting the latter from an existing
+%% dictionary (diameter_gen_relay). The resulting forms can be
+%% compiled to beam using compile:forms/2 (which does no preprocessing
+%% of it's own; DiY currently appears to be the only way to preprocess
+%% a forms list).
+
+preprocess(Mod, Forms) ->
+ {_, Beam, _} = code:get_object_code(diameter_gen_relay),
+ pp(Forms, remod(Mod, abstract_code(Beam))).
+
+pp(Forms, {ok, Code}) ->
+ Files = files(Code, []),
+ lists:flatmap(fun(T) -> include(T, Files) end, Forms);
+
+pp(Forms, {error, Reason}) ->
+ erlang:error({forms, Reason, Forms}).
+
+%% Replace literal diameter_gen_relay atoms in the extracted forms.
+%% ?MODULE for example.
+
+remod(Mod, L)
+ when is_list(L) ->
+ [remod(Mod, T) || T <- L];
+
+remod(Mod, {atom, _, diameter_gen_relay} = T) ->
+ setelement(3, T, Mod);
+
+remod(Mod, T)
+ when is_tuple(T) ->
+ list_to_tuple(remod(Mod, tuple_to_list(T)));
+
+remod(_, T) ->
+ T.
+
+%% Replace include_lib by the corresponding forms.
+
+include({attribute, _, include_lib, Path}, Files) ->
+ Inc = filename:basename(Path),
+ [{Inc, Forms}] = [T || {F, _} = T <- Files, F == Inc], %% expect one
+ lists:flatmap(fun filter/1, Forms);
+
+include(T, _) ->
+ [T].
+
+%% Extract abstract code.
+
+abstract_code(Beam) ->
+ case beam_lib:chunks(Beam, [abstract_code]) of
+ {ok, {_Mod, [{abstract_code, {_Vsn, Code}}]}} ->
+ {ok, Code};
+ {ok, {_Mod, [{abstract_code, no_abstract_code = No}]}} ->
+ {error, No};
+ {error = E, beam_lib, Reason} ->
+ {E, Reason}
+ end.
+
+%% Extract filename/forms pairs for included forms.
+
+files([{attribute, _, file, {Path, _}} | T], Acc) ->
+ {Body, Rest} = lists:splitwith(fun({attribute, _, file, _}) -> false;
+ (_) -> true
+ end,
+ T),
+ files(Rest, [{filename:basename(Path), Body} | Acc]);
+
+files([], Acc) ->
+ Acc.
+
+%% Only retain record diameter_avp and functions not generated by
+%% diameter_exprecs.
+
+filter({attribute, _, record, {diameter_avp, _}} = T) ->
+ [T];
+
+filter({function, _, Name, _, _} = T) ->
+ case ?S(Name) of
+ [$#|_] -> %% generated by diameter_exprecs
+ [];
+ _ ->
+ [T]
+ end;
+
+filter(_) ->
+ [].
diff --git a/lib/diameter/src/compiler/diameter_dict_util.erl b/lib/diameter/src/compiler/diameter_dict_util.erl
index 36a6efa294..cf4741e563 100644
--- a/lib/diameter/src/compiler/diameter_dict_util.erl
+++ b/lib/diameter/src/compiler/diameter_dict_util.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2011. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2014. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -46,7 +46,7 @@
-spec parse(File, Opts)
-> {ok, orddict:orddict()}
| {error, term()}
- when File :: {path, string()}
+ when File :: {path, file:name_all()}
| iolist()
| binary(),
Opts :: list().
@@ -155,6 +155,8 @@ fmt(grouped_avp_has_wrong_type) ->
"Grouped AVP ~s at line ~p defined with type ~s at line ~p";
fmt(grouped_avp_not_defined) ->
"Grouped AVP ~s on line ~p not defined in @avp_types";
+fmt(grouped_avp_not_grouped) ->
+ "Grouped AVP ~s on line ~p not defined in @grouped";
fmt(grouped_vendor_id_without_flag) ->
"Grouped AVP ~s at line ~p has vendor id "
"but definition at line ~p does not specify V flag";
@@ -265,6 +267,9 @@ io(K, Id)
io(vendor = K, {Id, Name}) ->
[?NL, section(K) | [[?SP, tok(X)] || X <- [Id, Name]]];
+io(_, []) ->
+ [];
+
io(avp_types = K, Body) ->
[?NL, ?NL, section(K), ?NL, [body(K,A) || A <- Body]];
@@ -398,9 +403,9 @@ read(File) ->
{ok, iolist_to_binary([File])}.
make_dict(Parse, Opts) ->
- make_orddict(pass4(pass3(pass2(pass1(reset(make_dict(Parse),
- Opts))),
- Opts))).
+ Dict = pass3(pass2(pass1(reset(make_dict(Parse), Opts))), Opts),
+ ok = examine(Dict),
+ make_orddict(Dict).
%% make_orddict/1
@@ -726,8 +731,8 @@ no_messages_without_id(Dict) ->
%% explode/4
%%
-%% {avp_vendor_id, AvpName} -> [Lineno, Id::integer()]
-%% {custom_types|codecs|inherits, AvpName} -> [Lineno, Mod::string()]
+%% {avp_vendor_id, AvpName} -> [Lineno, Id::integer()]
+%% {custom|inherits, AvpName} -> [Lineno, Mod::string()]
explode({_, Line, AvpName}, Dict, {_, _, X} = T, K) ->
true = K /= avp_vendor_id orelse is_uint32(T, [K]),
@@ -1089,7 +1094,7 @@ explode_avps([{_, Line, Name} | Toks], Dict) ->
Vid = avp_vendor_id(Flags, Name, Line, Dict),
%% An AVP is uniquely defined by its AVP code and vendor id (if any).
- %% Ensure there are no duplicate.
+ %% Ensure there are no duplicates.
store_new({avp_types, {Code, Vid}},
[Line, Name],
Dict,
@@ -1165,7 +1170,7 @@ import_avps(Dict, Opts) ->
Import = inherit(Dict, Opts),
report(imported, Import),
- %% pass4/1 tests that all referenced AVP's are either defined
+ %% examine/1 tests that all referenced AVP's are either defined
%% or imported.
dict:store(import_avps,
@@ -1273,21 +1278,21 @@ dict(Mod) ->
end.
%% ===========================================================================
-%% pass4/1
+%% examine/1
%%
%% Sanity checks.
-pass4(Dict) ->
- dict:fold(fun(K, V, _) -> p4(K, V, Dict) end, ok, Dict),
- Dict.
+examine(Dict) ->
+ dict:fold(fun(K, V, _) -> x(K, V, Dict) end, ok, Dict),
+ ok.
%% Ensure enum AVP's have type Enumerated.
-p4({enum, Name}, [Line | _], Dict)
+x({enum, Name}, [Line | _], Dict)
when is_list(Name) ->
true = is_enumerated_avp(Name, Dict, Line);
%% Ensure all referenced AVP's are either defined locally or imported.
-p4({K, {Name, AvpName}}, [Line | _], Dict)
+x({K, {Name, AvpName}}, [Line | _], Dict)
when (K == grouped orelse K == messages),
is_list(Name),
is_list(AvpName),
@@ -1295,13 +1300,21 @@ p4({K, {Name, AvpName}}, [Line | _], Dict)
true = avp_is_defined(AvpName, Dict, Line);
%% Ditto.
-p4({K, AvpName}, [Line | _], Dict)
+x({K, AvpName}, [Line | _], Dict)
when K == avp_vendor_id;
- K == custom_types;
- K == codecs ->
+ K == custom ->
true = avp_is_defined(AvpName, Dict, Line);
-p4(_, _, _) ->
+%% Ensure that all local AVP's of type Grouped are also present in @grouped.
+x({avp_types, Name}, [Line | Toks], Dict)
+ when 0 < Line, is_list(Name) ->
+ [{number, _, _Code}, {word, _, Type}, {word, _, _Flags}] = Toks,
+ "Grouped" == Type
+ andalso error == dict:find({grouped, Name}, Dict)
+ andalso ?RETURN(grouped_avp_not_grouped, [Name, Line]),
+ ok;
+
+x(_, _, _) ->
ok.
%% has_enumerated_type/3
diff --git a/lib/diameter/src/compiler/diameter_forms.hrl b/lib/diameter/src/compiler/diameter_forms.hrl
index 9b14c1715a..dd03401b9e 100644
--- a/lib/diameter/src/compiler/diameter_forms.hrl
+++ b/lib/diameter/src/compiler/diameter_forms.hrl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2014. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -57,4 +57,6 @@
-define(FIELDS(Fs), [{?record_field, ?ATOM(F), V} || {F,V} <- Fs]).
%% Literal term.
--define(TERM(T), erl_parse:abstract(T, ?LINE)).
+-define(TERM(T), erl_parse:abstract(T, [
+ {line, ?LINE},
+ {encoding, fun diameter_codegen:is_printable_ascii/1}])).
diff --git a/lib/diameter/src/compiler/diameter_make.erl b/lib/diameter/src/compiler/diameter_make.erl
index 16e30c1ffb..72f5d36da4 100644
--- a/lib/diameter/src/compiler/diameter_make.erl
+++ b/lib/diameter/src/compiler/diameter_make.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2011. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2014. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -30,38 +30,58 @@
-module(diameter_make).
--export([codec/1,
- codec/2,
- dict/1,
- dict/2,
+-export([codec/2,
+ codec/1,
format/1,
- reformat/1]).
+ flatten/1,
+ format_error/1]).
-export_type([opt/0]).
+-include("diameter_vsn.hrl").
+
+%% Options passed to codec/2.
-type opt() :: {include|outdir|name|prefix|inherits, string()}
+ | return
| verbose
- | debug.
+ | parse %% internal parsed form
+ | forms %% abstract format for compile:forms/1,2
+ | erl
+ | hrl.
+
+%% Internal parsed format with a version tag.
+-type parsed() :: list().
+
+%% Literal dictionary or path. A NL of CR identifies the former.
+-type dict() :: iolist()
+ | binary()
+ | parsed(). %% as returned by codec/2
+
+%% Name of a literal dictionary if otherwise unspecified.
+-define(DEFAULT_DICT_FILE, "dictionary.dia").
%% ===========================================================================
%% codec/1-2
%%
-%% Parse a dictionary file and generate a codec module.
+%% Parse a dictionary file and generate a codec module. Input
+%% dictionary can be either a path or the dictionary itself: the
+%% occurrence of \n or \r in the argument is used to distinguish the
+%% two.
--spec codec(Path, [opt()])
+-spec codec(File, [opt()])
-> ok
+ | {ok, list()} %% with option 'return', one element for each output
| {error, Reason}
- when Path :: string(),
+ when File :: dict()
+ | {path, file:name_all()},
Reason :: string().
codec(File, Opts) ->
- case dict(File, Opts) of
- {ok, Dict} ->
- make(File,
- Opts,
- Dict,
- [spec || _ <- [1], lists:member(debug, Opts)] ++ [erl, hrl]);
+ {Dict, Path} = identify(File),
+ case parse(Dict, Opts) of
+ {ok, ParseD} ->
+ make(Path, default(Opts), ParseD);
{error, _} = E ->
E
end.
@@ -69,63 +89,186 @@ codec(File, Opts) ->
codec(File) ->
codec(File, []).
-%% dict/2
-%%
-%% Parse a dictionary file and return the orddict that a codec module
-%% returns from dict/0.
-
--spec dict(string(), [opt()])
- -> {ok, orddict:orddict()}
- | {error, string()}.
-
-dict(Path, Opts) ->
- case diameter_dict_util:parse({path, Path}, Opts) of
- {ok, _} = Ok ->
- Ok;
- {error = E, Reason} ->
- {E, diameter_dict_util:format_error(Reason)}
- end.
-
-dict(File) ->
- dict(File, []).
-
%% format/1
%%
-%% Turn an orddict returned by dict/1-2 back into a dictionary file
-%% in the form of an iolist().
+%% Turn an orddict returned by dict/1-2 back into a dictionary.
--spec format(orddict:orddict())
+-spec format(parsed())
-> iolist().
-format(Dict) ->
+format([?VERSION | Dict]) ->
diameter_dict_util:format(Dict).
-%% reformat/1
+%% flatten/1
%%
-%% Parse a dictionary file and return its formatted equivalent.
+%% Reconstitute a dictionary without @inherits.
--spec reformat(File)
- -> {ok, iolist()}
- | {error, Reason}
- when File :: string(),
- Reason :: string().
+-spec flatten(parsed())
+ -> parsed().
+
+flatten([?VERSION = V | Dict]) ->
+ [V | lists:foldl(fun flatten/2,
+ Dict,
+ [avp_vendor_id,
+ custom_types,
+ codecs,
+ [avp_types, import_avps],
+ [grouped, import_groups],
+ [enum, import_enums]])].
+
+%% format_error/1
+
+format_error(T) ->
+ diameter_dict_util:format_error(T).
+
+%% ===========================================================================
+
+%% flatten/2
+
+flatten([_,_] = Keys, Dict) ->
+ [Values, Imports] = [orddict:fetch(K, Dict) || K <- Keys],
+ Vs = lists:append([Values | [V || {_Mod, V} <- Imports]]),
+ lists:foldl(fun({K,V},D) -> orddict:store(K,V,D) end,
+ Dict,
+ lists:zip([inherits | Keys], [[], Vs, []]));
+
+%% Inherited avp's setting the 'V' flag get their value either from
+%% @avp_vendor_id in the inheriting dictionary or from @vendor in the
+%% *inherited* (not inheriting) dictionary: add the latter to
+%% @avp_vendor_id as required.
+flatten(avp_vendor_id = Key, Dict) ->
+ Def = orddict:find(vendor, Dict),
+ ModD = imports(Dict),
+ Vids = orddict:fetch(Key, Dict),
+ Avps = lists:append([As || {_,As} <- Vids]),
+ orddict:store(Key,
+ dict:fold(fun(M, As, A) -> vid(M, As -- Avps, Def, A) end,
+ Vids,
+ ModD),
+ Dict);
+
+%% Import @codecs and @custom_types from inherited dictionaries as
+%% required.
+flatten(Key, Dict) ->
+ ImportAvps = orddict:fetch(import_avps, Dict),
+ ImportItems = [{M, As}
+ || {Mod, Avps} <- ImportAvps,
+ [_|D] <- [Mod:dict()],
+ {M,As0} <- orddict:fetch(Key, D),
+ F <- [fun(A) -> lists:keymember(A, 1, Avps) end],
+ [_|_] = As <- [lists:filter(F, As0)]],
+ orddict:store(Key,
+ lists:foldl(fun merge/2,
+ orddict:fetch(Key, Dict),
+ ImportItems),
+ Dict).
+
+%% merge/2
+
+merge({Mod, _Avps} = T, Acc) ->
+ merge(lists:keyfind(Mod, 1, Acc), T, Acc).
+
+merge({Mod, Avps}, {Mod, As}, Acc) ->
+ lists:keyreplace(Mod, 1, Acc, {Mod, Avps ++ As});
+merge(false, T, Acc) ->
+ [T | Acc].
-reformat(File) ->
- case dict(File) of
- {ok, Dict} ->
- {ok, format(Dict)};
- {error, _} = No ->
- No
+%% imports/1
+%%
+%% Return a module() -> [AVP] dict of inherited AVP's setting the V flag.
+
+imports(Dict) ->
+ lists:foldl(fun imports/2,
+ dict:new(),
+ orddict:fetch(import_avps, Dict)).
+
+imports({Mod, Avps}, Dict) ->
+ dict:store(Mod,
+ [A || {A,_,_,Fs} <- Avps, lists:member($V, Fs)],
+ Dict).
+
+%% vid/4
+
+vid(_, [], _, Acc) ->
+ Acc;
+vid(Mod, Avps, Def, Acc) ->
+ v(Mod:vendor_id(), Avps, Def, Acc).
+
+v(Vid, _, {ok, {Vid, _}}, Acc) -> %% same id as inheriting dictionary's
+ Acc;
+v(Vid, Avps, _, Acc) ->
+ case lists:keyfind(Vid, 1, Acc) of
+ {Vid, As} ->
+ lists:keyreplace(Vid, 1, Acc, {Vid, As ++ Avps});
+ false ->
+ [{Vid, Avps} | Acc]
end.
%% ===========================================================================
-make(_, _, _, []) ->
+parse({dict, ParseD}, _) ->
+ {ok, ParseD};
+parse(File, Opts) ->
+ diameter_dict_util:parse(File, Opts).
+
+default(Opts) ->
+ def(modes(Opts), Opts).
+
+def([], Opts) ->
+ [erl, hrl | Opts];
+def(_, Opts) ->
+ Opts.
+
+modes(Opts) ->
+ lists:filter(fun is_mode/1, Opts).
+
+is_mode(T) ->
+ lists:member(T, [erl, hrl, parse, forms]).
+
+identify([Vsn | [T|_] = ParseD])
+ when is_tuple(T) ->
+ ?VERSION == Vsn orelse erlang:error({version, {Vsn, ?VERSION}}),
+ {{dict, ParseD}, ?DEFAULT_DICT_FILE};
+identify({path, File} = T) ->
+ {T, File};
+identify(File) ->
+ case is_path([File]) of
+ true -> {{path, File}, File};
+ false -> {File, ?DEFAULT_DICT_FILE}
+ end.
+
+%% Interpret anything containing \n or \r as a literal dictionary.
+
+is_path([<<C,B/binary>> | T]) ->
+ is_path([C, B | T]);
+
+is_path([[C|L] | T]) ->
+ is_path([C, L | T]);
+
+is_path([C|_])
+ when $\n == C;
+ $\r == C ->
+ false;
+
+is_path([_|T]) ->
+ is_path(T);
+
+is_path([]) ->
+ true.
+
+make(File, Opts, Dict) ->
+ ok(lists:foldl(fun(M,A) -> [make(File, Opts, Dict, M) | A] end,
+ [],
+ modes(Opts))).
+
+ok([ok|_]) ->
ok;
-make(File, Opts, Dict, [Mode | Rest]) ->
+ok([_|_] = L) ->
+ {ok, lists:reverse(L)}.
+
+make(File, Opts, Dict, Mode) ->
try
- ok = diameter_codegen:from_dict(File, Dict, Opts, Mode),
- make(File, Opts, Dict, Rest)
+ diameter_codegen:from_dict(File, Dict, Opts, Mode)
catch
error: Reason ->
erlang:error({Reason, Mode, erlang:get_stacktrace()})
diff --git a/lib/diameter/src/diameter.app.src b/lib/diameter/src/diameter.app.src
index ceefb9b398..ac1d847753 100644
--- a/lib/diameter/src/diameter.app.src
+++ b/lib/diameter/src/diameter.app.src
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2014. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -20,9 +20,27 @@
{application, diameter,
[{description, "Diameter protocol"},
{vsn, "%VSN%"},
- {modules, [%MODULES%]},
+ {modules, [
+ %MODULES%
+ %,%COMPILER%
+ %,%INFO%
+ ]},
{registered, [%REGISTERED%]},
- {applications, [stdlib, kernel]},
+ {applications, [
+ {stdlib, "2.0"}, {kernel, "3.0"}%, {erts, "6.0"}
+ %% {syntax-tools, "1.6.14"}
+ %% {runtime-tools, "1.8.14"}
+ %, {ssl, "5.3.4"}
+ ]},
{env, []},
- {mod, {diameter_app, []}}
+ {mod, {diameter_app, []}},
+ {runtime_dependencies, [
+ ]}
+ %%
+ %% Note that ssl is only required if configured on TCP transports,
+ %% and syntax-tools and runtime-tools are only required if the
+ %% dictionary compiler and debug modules (respectively) are
+ %% needed/wanted at runtime, which they typically aren't. These
+ %% modules are the two commented lines in the 'modules' tuple.
+ %%
]}.
diff --git a/lib/diameter/src/diameter.appup.src b/lib/diameter/src/diameter.appup.src
index 62ace16faa..2c91bb38b4 100644
--- a/lib/diameter/src/diameter.appup.src
+++ b/lib/diameter/src/diameter.appup.src
@@ -2,7 +2,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -20,59 +20,59 @@
{"%VSN%",
[
- {"0.9", [{restart_application, diameter}]}, %% R14B03
- {"0.10", [{restart_application, diameter}]}, %% R14B04
- {"1.0", [{restart_application, diameter}]}, %% R15B
- {"1.1", [{restart_application, diameter}]}, %% R15B01
- {"1.2", [{restart_application, diameter}]}, %% R15B02
- {"1.2.1", [{restart_application, diameter}]},
- {"1.3", [{restart_application, diameter}]}, %% R15B03
- {"1.3.1", [{restart_application, diameter}]},
- {"1.4", [{restart_application, diameter}]}, %% R16A
- {"1.4.1", [{load_module, diameter_reg}, %% R16B
- {load_module, diameter_stats},
- {load_module, diameter_traffic},
- {load_module, diameter_service},
- {load_module, diameter_config},
- {load_module, diameter_peer},
- {load_module, diameter_peer_fsm},
- {load_module, diameter_watchdog},
- {load_module, diameter_capx},
- {load_module, diameter_codec},
- {load_module, diameter_gen_base_rfc3588},
- {load_module, diameter_gen_base_accounting},
- {load_module, diameter_gen_base_rfc6733},
- {load_module, diameter_gen_base_acct6733},
- {load_module, diameter_tcp},
- {load_module, diameter_lib},
- {load_module, diameter}]},
- {"1.4.1.1", [{load_module, diameter_traffic},
- {load_module, diameter_service},
- {load_module, diameter_config},
- {load_module, diameter_peer},
- {load_module, diameter_peer_fsm},
- {load_module, diameter_watchdog},
- {load_module, diameter_capx},
- {load_module, diameter_codec},
- {load_module, diameter_gen_base_rfc3588},
- {load_module, diameter_gen_base_accounting},
- {load_module, diameter_gen_base_rfc6733},
- {load_module, diameter_gen_base_acct6733},
- {load_module, diameter_tcp},
- {load_module, diameter_lib},
- {load_module, diameter}]}
+ {"0.9", [{restart_application, diameter}]}, %% R14B03
+ {"0.10", [{restart_application, diameter}]}, %% R14B04
+ {"1.0", [{restart_application, diameter}]}, %% R15B
+ {"1.1", [{restart_application, diameter}]}, %% R15B01
+ {"1.2", [{restart_application, diameter}]}, %% R15B02
+ {"1.2.1", [{restart_application, diameter}]},
+ {"1.3", [{restart_application, diameter}]}, %% R15B03
+ {"1.3.1", [{restart_application, diameter}]},
+ {"1.4", [{restart_application, diameter}]}, %% R16A
+ {"1.4.1", [{restart_application, diameter}]}, %% R16B
+ {"1.4.1.1", [{restart_application, diameter}]},
+ {"1.4.2", [{restart_application, diameter}]}, %% R16B01
+ {"1.4.3", [{restart_application, diameter}]}, %% R16B02
+ {"1.4.4", [{restart_application, diameter}]},
+ {"1.5", [{restart_application, diameter}]}, %% R16B03
+ {"1.5.1", [{restart_application, diameter}]},
+ {"1.6", [{restart_application, diameter}]}, %% 17.0
+ {<<"^1\\.(7(\\.1)?|8)$">>, %% 17.[134]
+ [{restart_application, diameter}]},
+ {<<"^1.9(\\.1)?$">>, %% 17.5(.3)?
+ [{restart_application, diameter}]},
+ {"1.9.2", [{restart_application, diameter}]}, %% 17.5.5
+ {"1.9.2.1", [{restart_application, diameter}]}, %% 17.5.6.3
+ {"1.9.2.2", [{restart_application, diameter}]}, %% 17.5.6.7
+ {"1.9.2.3", [{load_module, diameter_traffic}, %% 17.5.6.8
+ {load_module, diameter_service}]}
],
[
- {"0.9", [{restart_application, diameter}]},
- {"0.10", [{restart_application, diameter}]},
- {"1.0", [{restart_application, diameter}]},
- {"1.1", [{restart_application, diameter}]},
- {"1.2", [{restart_application, diameter}]},
- {"1.2.1", [{restart_application, diameter}]},
- {"1.3", [{restart_application, diameter}]},
- {"1.3.1", [{restart_application, diameter}]},
- {"1.4", [{restart_application, diameter}]},
- {"1.4.1", [{restart_application, diameter}]},
- {"1.4.1.1", [{restart_application, diameter}]}
+ {"0.9", [{restart_application, diameter}]},
+ {"0.10", [{restart_application, diameter}]},
+ {"1.0", [{restart_application, diameter}]},
+ {"1.1", [{restart_application, diameter}]},
+ {"1.2", [{restart_application, diameter}]},
+ {"1.2.1", [{restart_application, diameter}]},
+ {"1.3", [{restart_application, diameter}]},
+ {"1.3.1", [{restart_application, diameter}]},
+ {"1.4", [{restart_application, diameter}]},
+ {"1.4.1", [{restart_application, diameter}]},
+ {"1.4.1.1", [{restart_application, diameter}]},
+ {"1.4.2", [{restart_application, diameter}]},
+ {"1.4.3", [{restart_application, diameter}]},
+ {"1.4.4", [{restart_application, diameter}]},
+ {"1.5", [{restart_application, diameter}]},
+ {"1.5.1", [{restart_application, diameter}]},
+ {"1.6", [{restart_application, diameter}]},
+ {<<"^1\\.(7(\\.1)?|8)$">>,
+ [{restart_application, diameter}]},
+ {<<"^1.9(\\.1)?$">>,
+ [{restart_application, diameter}]},
+ {"1.9.2", [{restart_application, diameter}]},
+ {"1.9.2.1", [{restart_application, diameter}]},
+ {"1.9.2.2", [{restart_application, diameter}]},
+ {"1.9.2.3", [{load_module, diameter_service},
+ {load_module, diameter_traffic}]}
]
}.
diff --git a/lib/diameter/src/base/diameter_dbg.erl b/lib/diameter/src/info/diameter_dbg.erl
index 5b0ac3a3b6..b536e5e80b 100644
--- a/lib/diameter/src/base/diameter_dbg.erl
+++ b/lib/diameter/src/info/diameter_dbg.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2011. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2014. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -17,12 +17,15 @@
%% %CopyrightEnd%
%%
+%%
+%% Information and debug functions.
+%%
+
-module(diameter_dbg).
-export([table/1,
tables/0,
fields/1,
- help/0,
modules/0,
versions/0,
version_info/0,
@@ -30,7 +33,7 @@
procs/0,
latest/0,
nl/0,
- log/4]).
+ sizes/0]).
-export([diameter_config/0,
diameter_peer/0,
@@ -52,11 +55,9 @@
tp/1]).
-include_lib("diameter/include/diameter.hrl").
--include("diameter_internal.hrl").
-
--define(INFO, diameter_info).
--define(SEP(), ?INFO:sep()).
+-define(APP, diameter).
+-define(I, diameter_info).
-define(LOCAL, [diameter_config,
diameter_peer,
@@ -68,27 +69,25 @@
-define(VALUES(Rec), tl(tuple_to_list(Rec))).
-log(_Slogan, _Mod, _Line, _Details) ->
- ok.
-
-%%% ----------------------------------------------------------
-%%% # help()
-%%% ----------------------------------------------------------
+%% ----------------------------------------------------------
+%% # sizes/0
+%%
+%% Return sizes of named tables.
+%% ----------------------------------------------------------
-help() ->
- not_yet_implemented.
+sizes() ->
+ [{T, ets:info(T, size)} || T <- ?LOCAL, T /= diameter_peer].
-%%% ----------------------------------------------------------
-%%% # table(TableName)
-%%%
-%%% Input: TableName = diameter table containing record entries.
-%%%
-%%% Output: Count | undefined
-%%% ----------------------------------------------------------
+%% ----------------------------------------------------------
+%% # table/1
+%%
+%% Pretty-print a diameter table. Returns the number of records
+%% printed, or undefined.
+%% ----------------------------------------------------------
table(T)
when (T == diameter_peer) orelse (T == diameter_reg) ->
- ?INFO:format(collect(T), fields(T), fun ?INFO:split/2);
+ ?I:format(collect(T), fields(T), fun ?I:split/2);
table(Table)
when is_atom(Table) ->
@@ -96,7 +95,7 @@ table(Table)
undefined = No ->
No;
Fields ->
- ?INFO:format(Table, Fields, fun split/2)
+ ?I:format(Table, Fields, fun split/2)
end.
split([started, name | Fs], [S, N | Vs]) ->
@@ -107,9 +106,9 @@ split([[F|FT]|Fs], [Rec|Vs]) ->
split([F|Fs], [V|Vs]) ->
{F, Fs, V, Vs}.
-%%% ----------------------------------------------------------
-%%% # TableName()
-%%% ----------------------------------------------------------
+%% ----------------------------------------------------------
+%% # TableName/0
+%% ----------------------------------------------------------
-define(TABLE(Name), Name() -> table(Name)).
@@ -121,16 +120,15 @@ split([F|Fs], [V|Vs]) ->
?TABLE(diameter_service).
?TABLE(diameter_stats).
-%%% ----------------------------------------------------------
-%%% # tables()
-%%%
-%%% Output: Number of records output.
-%%%
-%%% Description: Pretty-print records in diameter tables from all nodes.
-%%% ----------------------------------------------------------
+%% ----------------------------------------------------------
+%% # tables/0
+%%
+%% Pretty-print diameter tables from all nodes. Returns the number of
+%% records printed.
+%% ----------------------------------------------------------
tables() ->
- ?INFO:format(field(?LOCAL), fun split/3, fun collect/1).
+ ?I:format(field(?LOCAL), fun split/3, fun collect/1).
field(Tables) ->
lists:map(fun(T) -> {T, fields(T)} end, lists:sort(Tables)).
@@ -138,66 +136,66 @@ field(Tables) ->
split(_, Fs, Vs) ->
split(Fs, Vs).
-%%% ----------------------------------------------------------
-%%% # modules()
-%%% ----------------------------------------------------------
+%% ----------------------------------------------------------
+%% # modules/0
+%% ----------------------------------------------------------
modules() ->
- Path = filename:join([appdir(), atom_to_list(?APPLICATION) ++ ".app"]),
- {ok, [{application, ?APPLICATION, Attrs}]} = file:consult(Path),
+ Path = filename:join([appdir(), atom_to_list(?APP) ++ ".app"]),
+ {ok, [{application, ?APP, Attrs}]} = file:consult(Path),
{modules, Mods} = lists:keyfind(modules, 1, Attrs),
Mods.
appdir() ->
- [_|_] = code:lib_dir(?APPLICATION, ebin).
+ [_|_] = code:lib_dir(?APP, ebin).
-%%% ----------------------------------------------------------
-%%% # versions()
-%%% ----------------------------------------------------------
+%% ----------------------------------------------------------
+%% # versions/0
+%% ----------------------------------------------------------
versions() ->
- ?INFO:versions(modules()).
+ ?I:versions(modules()).
-%%% ----------------------------------------------------------
-%%% # versions()
-%%% ----------------------------------------------------------
+%% ----------------------------------------------------------
+%% # version_info/0
+%% ----------------------------------------------------------
version_info() ->
- ?INFO:version_info(modules()).
+ ?I:version_info(modules()).
-%%% ----------------------------------------------------------
-%%% # compiled()
-%%% ----------------------------------------------------------
+%% ----------------------------------------------------------
+%% # compiled/0
+%% ----------------------------------------------------------
compiled() ->
- ?INFO:compiled(modules()).
+ ?I:compiled(modules()).
-%%% ----------------------------------------------------------
-%%% procs()
-%%% ----------------------------------------------------------
+%% ----------------------------------------------------------
+%% # procs/0
+%% ----------------------------------------------------------
procs() ->
- ?INFO:procs(?APPLICATION).
+ ?I:procs(?APP).
-%%% ----------------------------------------------------------
-%%% # latest()
-%%% ----------------------------------------------------------
+%% ----------------------------------------------------------
+%% # latest/0
+%% ----------------------------------------------------------
latest() ->
- ?INFO:latest(modules()).
+ ?I:latest(modules()).
-%%% ----------------------------------------------------------
-%%% # nl()
-%%% ----------------------------------------------------------
+%% ----------------------------------------------------------
+%% # nl/0
+%% ----------------------------------------------------------
nl() ->
lists:foreach(fun(M) -> abcast = c:nl(M) end, modules()).
-%%% ----------------------------------------------------------
-%%% # pp(Bin)
-%%%
-%%% Description: Pretty-print a message binary.
-%%% ----------------------------------------------------------
+%% ----------------------------------------------------------
+%% # pp/1
+%%
+%% Description: Pretty-print a message binary.
+%% ----------------------------------------------------------
%% Network byte order = big endian.
@@ -207,7 +205,7 @@ pp(<<Version:8, MsgLength:24,
HbHid:32,
E2Eid:32,
AVPs/binary>>) ->
- ?SEP(),
+ ?I:sep(),
ppp(["Version",
"Message length",
"[Actual length]",
@@ -227,7 +225,7 @@ pp(<<Version:8, MsgLength:24,
HbHid,
E2Eid]),
N = avp_loop({AVPs, MsgLength - 20}, 0),
- ?SEP(),
+ ?I:sep(),
N;
pp(<<_Version:8, MsgLength:24, _/binary>> = Bin) ->
@@ -328,23 +326,23 @@ ppp(Fields, Values) ->
ppp({Field, Value}) ->
io:format(": ~-22s : ~p~n", [Field, Value]).
-%%% ----------------------------------------------------------
-%%% # subscriptions()
-%%%
-%%% Output: list of {SvcName, Pid}
-%%% ----------------------------------------------------------
+%% ----------------------------------------------------------
+%% # subscriptions/0
+%%
+%% Returns a list of {SvcName, Pid}.
+%% ----------------------------------------------------------
subscriptions() ->
diameter_service:subscriptions().
-%%% ----------------------------------------------------------
-%%% # children()
-%%% ----------------------------------------------------------
+%% ----------------------------------------------------------
+%% # children/0
+%% ----------------------------------------------------------
children() ->
diameter_sup:tree().
-%%% ----------------------------------------------------------
+%% ----------------------------------------------------------
%% tracer/[12]
@@ -430,7 +428,7 @@ peers(Name, Ts) ->
mk_peers(Name, [_, {type, connect} | _] = Ts) ->
[[Name | mk_peer(Ts)]];
-mk_peers(Name, [R, {type, listen}, O, {accept = A, As}]) ->
+mk_peers(Name, [R, {type, listen}, O, {accept = A, As} | _]) ->
[[Name | mk_peer([R, {type, A}, O | Ts])] || Ts <- As].
%% This is a bit lame: service_info works to build this list and out
%% of something like what we want here and then we take it apart.
@@ -485,13 +483,12 @@ fields(diameter_service) ->
[started,
name,
record_info(fields, diameter_service),
+ watchdogT,
peerT,
- connT,
- share_peers,
- use_shared_peers,
shared_peers,
local_peers,
- monitor];
+ monitor,
+ options];
?FIELDS(diameter_event);
?FIELDS(diameter_uri);
diff --git a/lib/diameter/src/base/diameter_info.erl b/lib/diameter/src/info/diameter_info.erl
index 39d32d07cd..5ecce2206f 100644
--- a/lib/diameter/src/base/diameter_info.erl
+++ b/lib/diameter/src/info/diameter_info.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2011. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -17,6 +17,11 @@
%% %CopyrightEnd%
%%
+%%
+%% Generic functions for formatting table listings and more. Used by
+%% diameter_dbg.
+%%
+
-module(diameter_info).
-export([usage/1,
@@ -46,8 +51,6 @@
p/1,
p/3]).
--compile({no_auto_import,[max/2]}).
-
-export([collect/2]).
-define(LONG_TIMEOUT, 30000).
@@ -573,12 +576,7 @@ sys_info() ->
{A,V}.
os_info() ->
- {os:version(), case os:type() of
- {_Fam, _Name} = T ->
- T;
- Fam ->
- {Fam, ""}
- end}.
+ {os:version(), os:type()}.
chomp(S) ->
string:strip(S, right, $\n).
@@ -683,9 +681,6 @@ pt(T) ->
recsplit(SFun, Rec) ->
fun(Fs,Vs) -> SFun(element(1, Rec), Fs, Vs) end.
-max(A, B) ->
- if A > B -> A; true -> B end.
-
keyfetch(Key, List) ->
{Key,V} = lists:keyfind(Key, 1, List),
V.
diff --git a/lib/diameter/src/modules.mk b/lib/diameter/src/modules.mk
index f8d3cf1d6f..c9dd4e683a 100644
--- a/lib/diameter/src/modules.mk
+++ b/lib/diameter/src/modules.mk
@@ -1,8 +1,7 @@
-#-*-makefile-*- ; force emacs to enter makefile-mode
# %CopyrightBegin%
#
-# Copyright Ericsson AB 2010-2013. All Rights Reserved.
+# Copyright Ericsson AB 2010-2015. All Rights Reserved.
#
# The contents of this file are subject to the Erlang Public License,
# Version 1.1, (the "License"); you may not use this file except in
@@ -64,16 +63,19 @@ RT_MODULES = \
transport/diameter_transport \
transport/diameter_transport_sup
-# Handwritten (compile time) modules not included in the app file.
+# Handwritten compiler modules not included in the app file.
CT_MODULES = \
- base/diameter_dbg \
- base/diameter_info \
compiler/diameter_codegen \
compiler/diameter_exprecs \
compiler/diameter_dict_scanner \
compiler/diameter_dict_util \
compiler/diameter_make
+# Info/debug modules, also not included in the app file.
+INFO_MODULES = \
+ info/diameter_dbg \
+ info/diameter_info
+
# Released hrl files in ../include intended for public consumption.
EXTERNAL_HRLS = \
diameter.hrl \
@@ -92,7 +94,7 @@ BINS = \
# Released files relative to ../examples.
EXAMPLES = \
code/GNUmakefile \
- code/peer.erl \
+ code/node.erl \
code/client.erl \
code/client_cb.erl \
code/server.erl \
diff --git a/lib/diameter/src/transport/diameter_sctp.erl b/lib/diameter/src/transport/diameter_sctp.erl
index 49a530b4eb..e9c52c9de5 100644
--- a/lib/diameter/src/transport/diameter_sctp.erl
+++ b/lib/diameter/src/transport/diameter_sctp.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -18,7 +18,6 @@
%%
-module(diameter_sctp).
-
-behaviour(gen_server).
%% interface
@@ -37,7 +36,8 @@
code_change/3,
terminate/2]).
--export([info/1]). %% service_info callback
+-export([listener/1,%% diameter_sync callback
+ info/1]). %% service_info callback
-export([ports/0,
ports/1]).
@@ -70,14 +70,14 @@
-type connect_option() :: {raddr, inet:ip_address()}
| {rport, inet:port_number()}
- | gen_sctp:open_option().
+ | term(). %% gen_sctp:open_option().
-type match() :: inet:ip_address()
| string()
| [match()].
-type listen_option() :: {accept, match()}
- | gen_sctp:open_option().
+ | term(). %% gen_sctp:open_option().
-type uint() :: non_neg_integer().
@@ -99,22 +99,31 @@
-record(listener,
{ref :: reference(),
socket :: gen_sctp:sctp_socket(),
- count = 0 :: uint(),
+ count = 0 :: uint(), %% attached transport processes
tmap = ets:new(?MODULE, []) :: ets:tid(),
%% {MRef, Pid|AssocId}, {AssocId, Pid}
pending = {0, ets:new(?MODULE, [ordered_set])},
tref :: reference(),
accept :: [match()]}).
%% Field tmap is used to map an incoming message or event to the
-%% relevent transport process. Field pending implements a queue of
-%% transport processes to which an association has been assigned (at
-%% comm_up and written into tmap) but for which diameter hasn't yet
-%% spawned a transport process: a short-lived state of affairs as a
-%% new transport is spawned as a consequence of a peer being taken up,
-%% transport processes being spawned by the listener on demand. In
-%% case diameter starts a transport before comm_up on a new
-%% association, pending is set to an improper list with the spawned
-%% transport as head and the queue as tail.
+%% relevant transport process. Field pending implements two queues:
+%% the first of transport-to-be processes to which an association has
+%% been assigned (at comm_up and written into tmap) but for which
+%% diameter hasn't yet spawned a transport process, a short-lived
+%% state of affairs as a new transport is spawned as a consequence of
+%% a peer being taken up, transport processes being spawned by the
+%% listener on demand; the second of started transport processes that
+%% have not yet been assigned an association.
+%%
+%% When diameter calls start/3, the transport process is either taken
+%% from the first queue or spawned and placed in the second queue
+%% until an association is established. When an association is
+%% established, a controlling process is either taken from the second
+%% queue or spawned and placed in the first queue. Thus, there are
+%% only elements in one queue at a time, so share an ets table queue
+%% and tag it with a positive length if it contains the first queue, a
+%% negative length if it contains the second queue. The case -1 is
+%% handled differently for backwards compatibility reasons.
%% ---------------------------------------------------------------------------
%% # start/3
@@ -139,9 +148,9 @@ ip(T) ->
T.
%% A listener spawns transports either as a consequence of this call
-%% when there is not yet an association to associate with it, or at
-%% comm_up on a new association in which case the call retrieves a
-%% transport from the pending queue.
+%% when there is not yet an association to assign it, or at comm_up on
+%% a new association in which case the call retrieves a transport from
+%% the pending queue.
s({accept, Ref} = A, Addrs, Opts) ->
{LPid, LAs} = listener(Ref, {Opts, Addrs}),
try gen_server:call(LPid, {A, self()}, infinity) of
@@ -171,18 +180,33 @@ start_link(T) ->
info({gen_sctp, Sock}) ->
lists:flatmap(fun(K) -> info(K, Sock) end,
- [{socket, sockname},
- {peer, peername},
+ [{socket, socknames},
+ {peer, peernames},
{statistics, getstat}]).
info({K,F}, Sock) ->
case inet:F(Sock) of
{ok, V} ->
- [{K,V}];
+ [{K, map(F,V)}];
_ ->
[]
end.
+%% inet:{sock,peer}names/1 returns [{Addr, Port}] but the port number
+%% should be the same in each tuple. Map to a {[Addr], Port} tuple if
+%% so.
+map(K, [{_, Port} | _] = APs)
+ when K == socknames;
+ K == peernames ->
+ try [A || {A,P} <- APs, P == Port orelse throw(?MODULE)] of
+ As -> {As, Port}
+ catch
+ ?MODULE -> APs
+ end;
+
+map(_, V) ->
+ V.
+
%% ---------------------------------------------------------------------------
%% # init/1
%% ---------------------------------------------------------------------------
@@ -196,9 +220,9 @@ init(T) ->
i({listen, Ref, {Opts, Addrs}}) ->
{[Matches], Rest} = proplists:split(Opts, [accept]),
{LAs, Sock} = AS = open(Addrs, Rest, ?DEFAULT_PORT),
- proc_lib:init_ack({ok, self(), LAs}),
ok = gen_sctp:listen(Sock, true),
true = diameter_reg:add_new({?MODULE, listener, {Ref, AS}}),
+ proc_lib:init_ack({ok, self(), LAs}),
start_timer(#listener{ref = Ref,
socket = Sock,
accept = accept(Matches)});
@@ -211,7 +235,7 @@ i({connect, Pid, Opts, Addrs, Ref}) ->
{LAs, Sock} = open(Addrs, Rest, 0),
putr(?REF_KEY, Ref),
proc_lib:init_ack({ok, self(), LAs}),
- erlang:monitor(process, Pid),
+ monitor(process, Pid),
#transport{parent = Pid,
mode = {connect, connect(Sock, RAs, RP, [])},
socket = Sock};
@@ -221,8 +245,8 @@ i({accept, Pid, LPid, Sock, Ref})
when is_pid(Pid) ->
putr(?REF_KEY, Ref),
proc_lib:init_ack({ok, self()}),
- erlang:monitor(process, Pid),
- erlang:monitor(process, LPid),
+ monitor(process, Pid),
+ monitor(process, LPid),
#transport{parent = Pid,
mode = {accept, LPid},
socket = Sock};
@@ -231,7 +255,7 @@ i({accept, Pid, LPid, Sock, Ref})
i({accept, Ref, LPid, Sock, Id}) ->
putr(?REF_KEY, Ref),
proc_lib:init_ack({ok, self()}),
- MRef = erlang:monitor(process, LPid),
+ MRef = monitor(process, LPid),
%% Wait for a signal that the transport has been started before
%% processing other messages.
receive
@@ -255,15 +279,23 @@ close(Sock, Id) ->
%% listener/2
+%% Accepting processes can be started concurrently: ensure only one
+%% listener is started.
listener(LRef, T) ->
+ diameter_sync:call({?MODULE, listener, LRef},
+ {?MODULE, listener, [{LRef, T}]},
+ infinity,
+ infinity).
+
+listener({LRef, T}) ->
l(diameter_reg:match({?MODULE, listener, {LRef, '_'}}), LRef, T).
-%% Existing process with the listening socket ...
+%% Existing listening process ...
l([{{?MODULE, listener, {_, AS}}, LPid}], _, _) ->
- {LAs, _Sock} = AS,
- {LPid, LAs};
-
-%% ... or not: start one.
+ {LAs, _Sock} = AS,
+ {LPid, LAs};
+
+%% ... or not.
l([], LRef, T) ->
{ok, LPid, LAs} = diameter_sctp_sup:start_child({listen, LRef, T}),
{LPid, LAs}.
@@ -332,14 +364,17 @@ type(T) ->
%% # handle_call/3
%% ---------------------------------------------------------------------------
+handle_call(T, From, #listener{pending = L} = S)
+ when is_list(L) ->
+ handle_call(T, From, upgrade(S));
+
handle_call({{accept, Ref}, Pid}, _, #listener{ref = Ref,
- count = N}
+ pending = {N,Q},
+ count = K}
= S) ->
- {TPid, NewS} = accept(Ref, Pid, S),
- {reply, {ok, TPid}, NewS#listener{count = N+1}};
-
-handle_call(T, From, {listener,_,_,_,_,_,_} = S) -> % started in old code
- handle_call(T, From, upgrade(S));
+ TPid = accept(Ref, Pid, S),
+ {reply, {ok, TPid}, downgrade(S#listener{pending = {N-1,Q},
+ count = K+1})};
handle_call(_, _, State) ->
{reply, nok, State}.
@@ -358,11 +393,46 @@ handle_cast(_, State) ->
handle_info(T, #transport{} = S) ->
{noreply, #transport{} = t(T,S)};
+handle_info(T, #listener{pending = L} = S)
+ when is_list(L) ->
+ handle_info(T, upgrade(S));
+
handle_info(T, #listener{} = S) ->
- {noreply, #listener{} = l(T,S)};
+ {noreply, downgrade(#listener{} = l(T,S))}.
+
+%% upgrade/1
-handle_info(T, {listener,_,_,_,_,_,_} = S) -> % started in old code
- handle_info(T, upgrade(S)).
+upgrade(#listener{pending = [TPid | {0,Q}]} = S) ->
+ ets:insert(Q, {TPid, now()}),
+ S#listener{pending = {-1,Q}}.
+%% Prior to the possiblity of setting pool_size on in transport
+%% configuration, a new accepting transport was only started following
+%% the death of a predecessor, so that there was only at most one
+%% previously started transport process waiting for an association.
+%% This assumption no longer holds with pool_size > 1, in which case
+%% several accepting transports are started concurrently. Deal with
+%% this by placing the started transports in a new queue of transport
+%% processes waiting for an association.
+%%
+%% Since only one of this queue and the existing queue of controlling
+%% processes waiting for a transport to be started can be non-empty at
+%% any given time, implement both queues in the same ets table. The
+%% absolute value of the first element of the 2-tuple is the queue
+%% length, the sign says which queue it is.
+
+%% downgrade/1
+%%
+%% Revert to the pre-pool_size representation when possible, for
+%% backwards compatibility in the case that the pool_size option
+%% hasn't been used.
+
+downgrade(#listener{pending = {-1,Q}} = S) ->
+ TPid = ets:first(Q),
+ ets:delete(Q, TPid),
+ S#listener{pending = [TPid | {0,Q}]};
+
+downgrade(S) ->
+ S.
%% ---------------------------------------------------------------------------
%% # code_change/3
@@ -396,9 +466,6 @@ terminate(_, #listener{socket = Sock}) ->
%% ---------------------------------------------------------------------------
-upgrade(S) ->
- #listener{} = erlang:append_element(S, ?DEFAULT_ACCEPT).
-
putr(Key, Val) ->
put({?MODULE, Key}, Val).
@@ -430,54 +497,46 @@ l({sctp, Sock, _RA, _RP, Data} = Msg, #listener{socket = Sock} = S) ->
setopts(Sock)
end;
-%% Transport is asking message to be sent. See send/3 for why the send
-%% isn't directly from the transport.
-l({send, AssocId, StreamId, Bin}, #listener{socket = Sock} = S) ->
- send(Sock, AssocId, StreamId, Bin),
- S;
+l({'DOWN', MRef, process, TPid, _}, #listener{pending = {_,Q}} = S) ->
+ down(ets:member(Q, TPid), MRef, TPid, S);
+
+%% Timeout after the last accepting process has died.
+l({timeout, TRef, close = T}, #listener{tref = TRef,
+ count = 0}) ->
+ x(T);
+l({timeout, _, close}, #listener{} = S) ->
+ S.
+
+%% down/4
%% Accepting transport has died. One that's awaiting an association ...
-l({'DOWN', MRef, process, TPid, _}, #listener{pending = [TPid | Q],
- tmap = T,
- count = N}
- = S) ->
+down(true, MRef, TPid, #listener{pending = {N,Q},
+ tmap = T,
+ count = K}
+ = S)
+ when N < 0 ->
+ ets:delete(Q, TPid),
ets:delete(T, MRef),
ets:delete(T, TPid),
- start_timer(S#listener{count = N-1,
- pending = Q});
-
-%% ... ditto and a new transport has already been started ...
-l({'DOWN', _, process, _, _} = T, #listener{pending = [TPid | Q]}
- = S) ->
- #listener{pending = NQ}
- = NewS
- = l(T, S#listener{pending = Q}),
- NewS#listener{pending = [TPid | NQ]};
-
-%% ... or not.
-l({'DOWN', MRef, process, TPid, _}, #listener{socket = Sock,
- tmap = T,
- count = N,
- pending = {P,Q}}
- = S) ->
+ start_timer(S#listener{count = K-1,
+ pending = {N+1,Q}});
+
+%% ... or one that already has one.
+down(B, MRef, TPid, #listener{socket = Sock,
+ tmap = T,
+ count = K,
+ pending = {N,Q}}
+ = S) ->
[{MRef, Id}] = ets:lookup(T, MRef), %% Id = TPid | AssocId
ets:delete(T, MRef),
ets:delete(T, Id),
Id == TPid orelse close(Sock, Id),
- case ets:lookup(Q, TPid) of
- [{TPid, _}] -> %% transport in the pending queue ...
+ if B -> %% Waiting for attachment in the pending queue ...
ets:delete(Q, TPid),
- S#listener{pending = {P-1, Q}};
- [] -> %% ... or not
- start_timer(S#listener{count = N-1})
- end;
-
-%% Timeout after the last accepting process has died.
-l({timeout, TRef, close = T}, #listener{tref = TRef,
- count = 0}) ->
- x(T);
-l({timeout, _, close}, #listener{} = S) ->
- S.
+ S#listener{pending = {N-1,Q}};
+ true -> %% ... or already attached
+ start_timer(S#listener{count = K-1})
+ end.
%% t/2
%%
@@ -502,8 +561,6 @@ transition({peeloff, Sock, {sctp, LSock, _RA, _RP, _Data} = Msg, Matches},
= S) ->
ok = accept_peer(Sock, Matches),
transition(Msg, S#transport{socket = Sock});
-transition({peeloff = T, _Sock, _Msg} = T, #transport{} = S) ->% from old code
- transition(erlang:append_element(T, ?DEFAULT_ACCEPT), S);
%% Incoming message.
transition({sctp, _Sock, _RA, _RP, Data}, #transport{socket = Sock} = S) ->
@@ -560,7 +617,7 @@ accept_peer(_, []) ->
ok;
accept_peer(Sock, Matches) ->
- {RAddrs, _} = ok(inet:peername(Sock)),
+ RAddrs = [A || {A,_} <- ok(inet:peernames(Sock))],
diameter_peer:match(RAddrs, Matches)
orelse x({accept, RAddrs, Matches}),
ok.
@@ -578,38 +635,37 @@ accept(Opts) ->
%% No pending associations: spawn a new transport.
accept(Ref, Pid, #listener{socket = Sock,
tmap = T,
- pending = {0,_} = Q}
- = S) ->
+ pending = {N,Q}})
+ when N =< 0 ->
Arg = {accept, Pid, self(), Sock, Ref},
{ok, TPid} = diameter_sctp_sup:start_child(Arg),
- MRef = erlang:monitor(process, TPid),
+ MRef = monitor(process, TPid),
ets:insert(T, [{MRef, TPid}, {TPid, MRef}]),
- {TPid, S#listener{pending = [TPid | Q]}};
-%% Placing the transport in the pending field makes it available to
-%% the next association. The stack starts a new accepting transport
-%% only after this one brings the connection up (or dies).
-
-%% Accepting transport has died. This can happen if a new transport is
-%% started before the DOWN has arrived.
-accept(Ref, Pid, #listener{pending = [TPid | {0,_} = Q]} = S) ->
- false = is_process_alive(TPid), %% assert
- accept(Ref, Pid, S#listener{pending = Q});
+ ets:insert(Q, {TPid, now()}),
+ TPid;
+%% Placing the transport in the second pending table makes it
+%% available to the next association.
%% Pending associations: attach to the first in the queue.
-accept(_, Pid, #listener{ref = Ref, pending = {N,Q}} = S) ->
+accept(_, Pid, #listener{ref = Ref,
+ pending = {_,Q}}) ->
TPid = ets:first(Q),
TPid ! {Ref, Pid},
ets:delete(Q, TPid),
- {TPid, S#listener{pending = {N-1, Q}}}.
+ TPid.
%% send/2
%% Outbound Diameter message on a specified stream ...
-send(#diameter_packet{bin = Bin, transport_data = {stream, SId}}, S) ->
- send(SId, Bin, S),
+send(#diameter_packet{bin = Bin, transport_data = {outstream, SId}},
+ #transport{streams = {_, OS}}
+ = S) ->
+ send(SId rem OS, Bin, S),
S;
-%% ... or not: rotate through all steams.
+%% ... or not: rotate through all streams.
+send(#diameter_packet{bin = Bin}, S) ->
+ send(Bin, S);
send(Bin, #transport{streams = {_, OS},
os = N}
= S)
@@ -710,34 +766,12 @@ up(#transport{parent = Pid,
find(Id, Data, #listener{tmap = T} = S) ->
f(ets:lookup(T, Id), Data, S).
-%% New association and a transport waiting for one: use it.
+%% New association ...
f([],
- {_, #sctp_assoc_change{state = comm_up,
- assoc_id = Id}},
- #listener{tmap = T,
- pending = [TPid | {_,_} = Q]}
+ {_, #sctp_assoc_change{state = comm_up, assoc_id = Id}},
+ #listener{pending = {N,Q}}
= S) ->
- [{TPid, MRef}] = ets:lookup(T, TPid),
- ets:insert(T, [{MRef, Id}, {Id, TPid}]),
- ets:delete(T, TPid),
- {TPid, S#listener{pending = Q}};
-
-%% New association and no transport start yet: spawn one and place it
-%% in the queue.
-f([],
- {_, #sctp_assoc_change{state = comm_up,
- assoc_id = Id}},
- #listener{ref = Ref,
- socket = Sock,
- tmap = T,
- pending = {N,Q}}
- = S) ->
- Arg = {accept, Ref, self(), Sock, Id},
- {ok, TPid} = diameter_sctp_sup:start_child(Arg),
- MRef = erlang:monitor(process, TPid),
- ets:insert(T, [{MRef, Id}, {Id, TPid}]),
- ets:insert(Q, {TPid, now()}),
- {TPid, S#listener{pending = {N+1, Q}}};
+ {find(Id, S), S#listener{pending = {N+1,Q}}};
%% Known association ...
f([{_, TPid}], _, S) ->
@@ -747,6 +781,31 @@ f([{_, TPid}], _, S) ->
f([], _, _) ->
false.
+%% find/2
+
+%% Transport waiting for an association: use it.
+find(Id, #listener{tmap = T,
+ pending = {N,Q}})
+ when N < 0 ->
+ TPid = ets:first(Q),
+ [{TPid, MRef}] = ets:lookup(T, TPid),
+ ets:insert(T, [{MRef, Id}, {Id, TPid}]),
+ ets:delete(T, TPid),
+ ets:delete(Q, TPid),
+ TPid;
+
+%% No transport start yet: spawn one and queue.
+find(Id, #listener{ref = Ref,
+ socket = Sock,
+ tmap = T,
+ pending = {_,Q}}) ->
+ Arg = {accept, Ref, self(), Sock, Id},
+ {ok, TPid} = diameter_sctp_sup:start_child(Arg),
+ MRef = monitor(process, TPid),
+ ets:insert(T, [{MRef, Id}, {Id, TPid}]),
+ ets:insert(Q, {TPid, now()}),
+ TPid.
+
%% assoc_id/1
assoc_id({[#sctp_sndrcvinfo{assoc_id = Id}], _}) ->
diff --git a/lib/diameter/src/transport/diameter_tcp.erl b/lib/diameter/src/transport/diameter_tcp.erl
index 4d1b8bec51..0b26f429fb 100644
--- a/lib/diameter/src/transport/diameter_tcp.erl
+++ b/lib/diameter/src/transport/diameter_tcp.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -37,7 +37,8 @@
code_change/3,
terminate/2]).
--export([info/1]). %% service_info callback
+-export([listener/1,%% diameter_sync callback
+ info/1]). %% service_info callback
-export([ports/0,
ports/1]).
@@ -191,7 +192,7 @@ init(T) ->
i({T, Ref, Mod, Pid, Opts, Addrs})
when T == accept;
T == connect ->
- erlang:monitor(process, Pid),
+ monitor(process, Pid),
%% Since accept/connect might block indefinitely, spawn a process
%% that does nothing but kill us with the parent until call
%% returns.
@@ -218,8 +219,8 @@ i({T, Ref, Mod, Pid, Opts, Addrs})
%% A monitor process to kill the transport if the parent dies.
i(#monitor{parent = Pid, transport = TPid} = S) ->
proc_lib:init_ack({ok, self()}),
- erlang:monitor(process, Pid),
- erlang:monitor(process, TPid),
+ monitor(process, Pid),
+ monitor(process, TPid),
S;
%% In principle a link between the transport and killer processes
%% could do the same thing: have the accepting/connecting process be
@@ -235,7 +236,7 @@ i({listen, LRef, APid, {Mod, Opts, Addrs}}) ->
LAddr = laddr(LAddrOpt, Mod, LSock),
true = diameter_reg:add_new({?MODULE, listener, {LRef, {LAddr, LSock}}}),
proc_lib:init_ack({ok, self(), {LAddr, LSock}}),
- erlang:monitor(process, APid),
+ monitor(process, APid),
start_timer(#listener{socket = LSock}).
laddr([], Mod, Sock) ->
@@ -336,17 +337,25 @@ accept(Opts) ->
%% listener/2
+%% Accepting processes can be started concurrently: ensure only one
+%% listener is started.
listener(LRef, T) ->
- l(diameter_reg:match({?MODULE, listener, {LRef, '_'}}), LRef, T).
+ diameter_sync:call({?MODULE, listener, LRef},
+ {?MODULE, listener, [{LRef, T, self()}]},
+ infinity,
+ infinity).
-%% Existing process with the listening socket ...
-l([{{?MODULE, listener, {_, AS}}, LPid}], _, _) ->
- LPid ! {accept, self()},
+listener({LRef, T, TPid}) ->
+ l(diameter_reg:match({?MODULE, listener, {LRef, '_'}}), LRef, T, TPid).
+
+%% Existing listening process ...
+l([{{?MODULE, listener, {_, AS}}, LPid}], _, _, TPid) ->
+ LPid ! {accept, TPid},
AS;
-%% ... or not: start one.
-l([], LRef, T) ->
- {ok, _, AS} = diameter_tcp_sup:start_child({listen, LRef, self(), T}),
+%% ... or not.
+l([], LRef, T, TPid) ->
+ {ok, _, AS} = diameter_tcp_sup:start_child({listen, LRef, TPid, T}),
AS.
%% get_addr/1
@@ -502,7 +511,7 @@ m({'DOWN', _, process, Pid, _}, #monitor{parent = Pid,
%% Another accept transport is attaching.
l({accept, TPid}, #listener{count = N} = S) ->
- erlang:monitor(process, TPid),
+ monitor(process, TPid),
S#listener{count = N+1};
%% Accepting process has died.
diff --git a/lib/diameter/src/transport/diameter_transport_sup.erl b/lib/diameter/src/transport/diameter_transport_sup.erl
index 6457ab78b0..284a41a752 100644
--- a/lib/diameter/src/transport/diameter_transport_sup.erl
+++ b/lib/diameter/src/transport/diameter_transport_sup.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2011. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -54,7 +54,7 @@ start_child(Name, Module) ->
Spec = {Name,
{Module, start_link, [Name]},
permanent,
- 1000,
+ infinity,
supervisor,
[Module]},
supervisor:start_child(?MODULE, Spec).
diff --git a/lib/diameter/test/diameter_3xxx_SUITE.erl b/lib/diameter/test/diameter_3xxx_SUITE.erl
index 071b1a1177..44cb0cc484 100644
--- a/lib/diameter/test/diameter_3xxx_SUITE.erl
+++ b/lib/diameter/test/diameter_3xxx_SUITE.erl
@@ -47,6 +47,7 @@
send_double_error/1,
send_3xxx/1,
send_5xxx/1,
+ counters/1,
stop/1]).
%% diameter callbacks
@@ -111,7 +112,7 @@ all() ->
groups() ->
Tc = tc(),
- [{?util:name([E,D]), [], [start] ++ Tc ++ [stop]}
+ [{?util:name([E,D]), [], [start] ++ Tc ++ [counters, stop]}
|| E <- ?ERRORS, D <- ?RFCS].
init_per_suite(Config) ->
@@ -169,6 +170,203 @@ stop(_Config) ->
ok = diameter:stop_service(?SERVER),
ok = diameter:stop_service(?CLIENT).
+%% counters/1
+%%
+%% Check that counters are as expected.
+
+counters(Config) ->
+ Group = proplists:get_value(group, Config),
+ [_Errors, _Rfc] = G = ?util:name(Group),
+ [] = ?util:run([[fun counters/3, K, S, G]
+ || K <- [statistics, transport, connections],
+ S <- [?CLIENT, ?SERVER]]).
+
+counters(Key, Svc, Group) ->
+ counters(Key, Svc, Group, [_|_] = diameter:service_info(Svc, Key)).
+
+counters(statistics, Svc, [Errors, Rfc], L) ->
+ [{P, Stats}] = L,
+ true = is_pid(P),
+ stats(Svc, Errors, Rfc, lists:sort(Stats));
+
+counters(_, _, _, _) ->
+ todo.
+
+stats(?CLIENT, E, rfc3588, L)
+ when E == answer;
+ E == answer_3xxx ->
+ [{{{unknown,0},recv},2},
+ {{{0,257,0},recv},1},
+ {{{0,257,1},send},1},
+ {{{0,275,0},recv},6},
+ {{{0,275,1},send},10},
+ {{{unknown,0},recv,{'Result-Code',3001}},1},
+ {{{unknown,0},recv,{'Result-Code',3007}},1},
+ {{{0,257,0},recv,{'Result-Code',2001}},1},
+ {{{0,275,0},recv,{'Result-Code',2001}},1},
+ {{{0,275,0},recv,{'Result-Code',3008}},2},
+ {{{0,275,0},recv,{'Result-Code',3999}},1},
+ {{{0,275,0},recv,{'Result-Code',5002}},1},
+ {{{0,275,0},recv,{'Result-Code',5005}},1}]
+ = L;
+
+stats(?SERVER, E, rfc3588, L)
+ when E == answer;
+ E == answer_3xxx ->
+ [{{{unknown,0},send},2},
+ {{{unknown,1},recv},1},
+ {{{0,257,0},send},1},
+ {{{0,257,1},recv},1},
+ {{{0,275,0},send},6},
+ {{{0,275,1},recv},8},
+ {{{unknown,0},send,{'Result-Code',3001}},1},
+ {{{unknown,0},send,{'Result-Code',3007}},1},
+ {{{unknown,1},recv,error},1},
+ {{{0,257,0},send,{'Result-Code',2001}},1},
+ {{{0,275,0},send,{'Result-Code',2001}},1},
+ {{{0,275,0},send,{'Result-Code',3008}},2},
+ {{{0,275,0},send,{'Result-Code',3999}},1},
+ {{{0,275,0},send,{'Result-Code',5002}},1},
+ {{{0,275,0},send,{'Result-Code',5005}},1},
+ {{{0,275,1},recv,error},5}]
+ = L;
+
+stats(?CLIENT, answer, rfc6733, L) ->
+ [{{{unknown,0},recv},2},
+ {{{0,257,0},recv},1},
+ {{{0,257,1},send},1},
+ {{{0,275,0},recv},8},
+ {{{0,275,1},send},10},
+ {{{unknown,0},recv,{'Result-Code',3001}},1},
+ {{{unknown,0},recv,{'Result-Code',3007}},1},
+ {{{0,257,0},recv,{'Result-Code',2001}},1},
+ {{{0,275,0},recv,{'Result-Code',3008}},2},
+ {{{0,275,0},recv,{'Result-Code',3999}},1},
+ {{{0,275,0},recv,{'Result-Code',5002}},1},
+ {{{0,275,0},recv,{'Result-Code',5005}},3},
+ {{{0,275,0},recv,{'Result-Code',5999}},1}]
+ = L;
+
+stats(?SERVER, answer, rfc6733, L) ->
+ [{{{unknown,0},send},2},
+ {{{unknown,1},recv},1},
+ {{{0,257,0},send},1},
+ {{{0,257,1},recv},1},
+ {{{0,275,0},send},8},
+ {{{0,275,1},recv},8},
+ {{{unknown,0},send,{'Result-Code',3001}},1},
+ {{{unknown,0},send,{'Result-Code',3007}},1},
+ {{{unknown,1},recv,error},1},
+ {{{0,257,0},send,{'Result-Code',2001}},1},
+ {{{0,275,0},send,{'Result-Code',3008}},2},
+ {{{0,275,0},send,{'Result-Code',3999}},1},
+ {{{0,275,0},send,{'Result-Code',5002}},1},
+ {{{0,275,0},send,{'Result-Code',5005}},3},
+ {{{0,275,0},send,{'Result-Code',5999}},1},
+ {{{0,275,1},recv,error},5}]
+ = L;
+
+stats(?CLIENT, answer_3xxx, rfc6733, L) ->
+ [{{{unknown,0},recv},2},
+ {{{0,257,0},recv},1},
+ {{{0,257,1},send},1},
+ {{{0,275,0},recv},8},
+ {{{0,275,1},send},10},
+ {{{unknown,0},recv,{'Result-Code',3001}},1},
+ {{{unknown,0},recv,{'Result-Code',3007}},1},
+ {{{0,257,0},recv,{'Result-Code',2001}},1},
+ {{{0,275,0},recv,{'Result-Code',2001}},1},
+ {{{0,275,0},recv,{'Result-Code',3008}},2},
+ {{{0,275,0},recv,{'Result-Code',3999}},1},
+ {{{0,275,0},recv,{'Result-Code',5002}},1},
+ {{{0,275,0},recv,{'Result-Code',5005}},2},
+ {{{0,275,0},recv,{'Result-Code',5999}},1}]
+ = L;
+
+stats(?SERVER, answer_3xxx, rfc6733, L) ->
+ [{{{unknown,0},send},2},
+ {{{unknown,1},recv},1},
+ {{{0,257,0},send},1},
+ {{{0,257,1},recv},1},
+ {{{0,275,0},send},8},
+ {{{0,275,1},recv},8},
+ {{{unknown,0},send,{'Result-Code',3001}},1},
+ {{{unknown,0},send,{'Result-Code',3007}},1},
+ {{{unknown,1},recv,error},1},
+ {{{0,257,0},send,{'Result-Code',2001}},1},
+ {{{0,275,0},send,{'Result-Code',2001}},1},
+ {{{0,275,0},send,{'Result-Code',3008}},2},
+ {{{0,275,0},send,{'Result-Code',3999}},1},
+ {{{0,275,0},send,{'Result-Code',5002}},1},
+ {{{0,275,0},send,{'Result-Code',5005}},2},
+ {{{0,275,0},send,{'Result-Code',5999}},1},
+ {{{0,275,1},recv,error},5}]
+ = L;
+
+stats(?CLIENT, callback, rfc3588, L) ->
+ [{{{unknown,0},recv},1},
+ {{{0,257,0},recv},1},
+ {{{0,257,1},send},1},
+ {{{0,275,0},recv},6},
+ {{{0,275,1},send},10},
+ {{{unknown,0},recv,{'Result-Code',3007}},1},
+ {{{0,257,0},recv,{'Result-Code',2001}},1},
+ {{{0,275,0},recv,{'Result-Code',2001}},2},
+ {{{0,275,0},recv,{'Result-Code',3999}},1},
+ {{{0,275,0},recv,{'Result-Code',5002}},1},
+ {{{0,275,0},recv,{'Result-Code',5005}},2}]
+ = L;
+
+stats(?SERVER, callback, rfc3588, L) ->
+ [{{{unknown,0},send},1},
+ {{{unknown,1},recv},1},
+ {{{0,257,0},send},1},
+ {{{0,257,1},recv},1},
+ {{{0,275,0},send},6},
+ {{{0,275,1},recv},8},
+ {{{unknown,0},send,{'Result-Code',3007}},1},
+ {{{unknown,1},recv,error},1},
+ {{{0,257,0},send,{'Result-Code',2001}},1},
+ {{{0,275,0},send,{'Result-Code',2001}},2},
+ {{{0,275,0},send,{'Result-Code',3999}},1},
+ {{{0,275,0},send,{'Result-Code',5002}},1},
+ {{{0,275,0},send,{'Result-Code',5005}},2},
+ {{{0,275,1},recv,error},5}]
+ = L;
+
+stats(?CLIENT, callback, rfc6733, L) ->
+ [{{{unknown,0},recv},1},
+ {{{0,257,0},recv},1},
+ {{{0,257,1},send},1},
+ {{{0,275,0},recv},8},
+ {{{0,275,1},send},10},
+ {{{unknown,0},recv,{'Result-Code',3007}},1},
+ {{{0,257,0},recv,{'Result-Code',2001}},1},
+ {{{0,275,0},recv,{'Result-Code',2001}},2},
+ {{{0,275,0},recv,{'Result-Code',3999}},1},
+ {{{0,275,0},recv,{'Result-Code',5002}},1},
+ {{{0,275,0},recv,{'Result-Code',5005}},3},
+ {{{0,275,0},recv,{'Result-Code',5999}},1}]
+ = L;
+
+stats(?SERVER, callback, rfc6733, L) ->
+ [{{{unknown,0},send},1},
+ {{{unknown,1},recv},1},
+ {{{0,257,0},send},1},
+ {{{0,257,1},recv},1},
+ {{{0,275,0},send},8},
+ {{{0,275,1},recv},8},
+ {{{unknown,0},send,{'Result-Code',3007}},1},
+ {{{unknown,1},recv,error},1},
+ {{{0,257,0},send,{'Result-Code',2001}},1},
+ {{{0,275,0},send,{'Result-Code',2001}},2},
+ {{{0,275,0},send,{'Result-Code',3999}},1},
+ {{{0,275,0},send,{'Result-Code',5002}},1},
+ {{{0,275,0},send,{'Result-Code',5005}},3},
+ {{{0,275,0},send,{'Result-Code',5999}},1},
+ {{{0,275,1},recv,error},5}]
+ = L.
+
%% send_unknown_application/1
%%
%% Send an unknown application that a callback (which shouldn't take
diff --git a/lib/diameter/test/diameter_app_SUITE.erl b/lib/diameter/test/diameter_app_SUITE.erl
index 1e262895a6..84f8a66a8a 100644
--- a/lib/diameter/test/diameter_app_SUITE.erl
+++ b/lib/diameter/test/diameter_app_SUITE.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -50,7 +50,7 @@
diameter_exprecs,
diameter_make]).
--define(HELP_MODULES, [diameter_dbg,
+-define(INFO_MODULES, [diameter_dbg,
diameter_info]).
%% ===========================================================================
@@ -99,13 +99,13 @@ vsn(Config) ->
%% # modules/1
%%
%% Ensure that the app file modules and installed modules differ by
-%% compiler/help modules.
+%% compiler/info modules.
%% ===========================================================================
modules(Config) ->
Mods = fetch(modules, fetch(app, Config)),
Installed = code_mods(),
- Help = lists:sort(?HELP_MODULES ++ ?COMPILER_MODULES),
+ Help = lists:sort(?INFO_MODULES ++ ?COMPILER_MODULES),
{[], Help} = {Mods -- Installed, lists:sort(Installed -- Mods)}.
@@ -158,12 +158,15 @@ appvsn(Name) ->
%% # xref/1
%%
%% Ensure that no function in our application calls an undefined function
-%% or one in an application we haven't specified as a dependency. (Almost.)
+%% or one in an application we haven't declared as a dependency. (Almost.)
%% ===========================================================================
xref(Config) ->
App = fetch(app, Config),
- Mods = fetch(modules, App),
+ Mods = fetch(modules, App), %% modules listed in the app file
+
+ %% List of application names extracted from runtime_dependencies.
+ Deps = lists:map(fun unversion/1, fetch(runtime_dependencies, App)),
{ok, XRef} = xref:start(make_name(xref_test_name)),
ok = xref:set_default(XRef, [{verbose, false}, {warnings, false}]),
@@ -178,30 +181,88 @@ xref(Config) ->
[?APP, erts | fetch(applications, App)]),
{ok, Undefs} = xref:analyze(XRef, undefined_function_calls),
- {ok, Called} = xref:analyze(XRef, {module_call, ?COMPILER_MODULES}),
+ {ok, RTmods} = xref:analyze(XRef, {module_use, Mods}),
+ {ok, CTmods} = xref:analyze(XRef, {module_use, ?COMPILER_MODULES}),
+ {ok, RTdeps} = xref:analyze(XRef, {module_call, Mods}),
xref:stop(XRef),
+ Rel = release(), %% otp_release-ish
+
%% Only care about calls from our own application.
- [] = lists:filter(fun({{F,_,_},{T,_,_}}) ->
+ [] = lists:filter(fun({{F,_,_} = From, {_,_,_} = To}) ->
lists:member(F, Mods)
- andalso {F,T} /= {diameter_tcp, ssl}
+ andalso not ignored(From, To, Rel)
end,
Undefs),
+
+ %% Ensure that only runtime or info modules call runtime modules.
+ %% It's not strictly necessary that diameter compiler modules not
+ %% depend on other diameter modules but it's a simple source of
+ %% build errors if not properly encoded in the makefile so guard
+ %% against it.
+ [] = (RTmods -- Mods) -- ?INFO_MODULES,
+
+ %% Ensure that runtime modules don't call compiler modules.
+ CTmods = CTmods -- Mods,
+
+ %% Ensure that runtime modules only call other runtime modules, or
+ %% applications declared as in runtime_dependencies in the app
+ %% file. Note that the declared application versions are ignored
+ %% since we only know what we can see now.
+ [] = lists:filter(fun(M) -> not lists:member(app(M), Deps) end,
+ RTdeps -- Mods).
+
+ignored({FromMod,_,_}, {ToMod,_,_} = To, Rel)->
%% diameter_tcp does call ssl despite the latter not being listed
%% as a dependency in the app file since ssl is only required for
- %% TLS security: it's up to a client who wants TLS it to start
- %% ssl.
-
- [] = lists:filter(fun is_bad_dependency/1, Called).
+ %% TLS security: it's up to a client who wants TLS to start ssl.
+ %% The OTP 18 time api is also called if it exists, so that the
+ %% same code can be run on older releases.
+ {FromMod, ToMod} == {diameter_tcp, ssl}
+ orelse (FromMod == diameter_lib
+ andalso Rel < 18
+ andalso lists:member(To, time_api())).
+
+%% New time api in OTP 18.
+time_api() ->
+ [{erlang, F, A} || {F,A} <- [{convert_time_unit,3},
+ {monotonic_time,0},
+ {monotonic_time,1},
+ {system_time,0},
+ {system_time,1},
+ {time_offset,0},
+ {time_offset,1},
+ {timestamp,0},
+ {unique_integer,0},
+ {unique_integer,1}]]
+ ++ [{os, system_time, 0},
+ {os, system_time, 1}].
+
+release() ->
+ Rel = erlang:system_info(otp_release),
+ try list_to_integer(Rel) of
+ N -> N
+ catch
+ error:_ ->
+ 0 %% aka < 17
+ end.
+
+unversion(App) ->
+ {Name, [$-|Vsn]} = lists:splitwith(fun(C) -> C /= $- end, App),
+ true = is_app(Name), %% assert
+ Vsn = vsn_str(Vsn), %%
+ Name.
-%% It's not strictly necessary that diameter compiler modules not
-%% depend on other diameter modules but it's a simple source of build
-%% errors if not encoded in the makefile (hence the test) so guard
-%% against it.
-is_bad_dependency(Mod) ->
- lists:prefix("diameter", atom_to_list(Mod))
- andalso not lists:member(Mod, ?COMPILER_MODULES).
+app('$M_EXPR') -> %% could be anything but assume it's ok
+ "erts";
+app(Mod) ->
+ case code:which(Mod) of
+ preloaded ->
+ "erts";
+ Path ->
+ unversion(lists:nth(3, lists:reverse(filename:split(Path))))
+ end.
add_application(XRef, App) ->
add_application(XRef, App, code:lib_dir(App)).
@@ -260,11 +321,11 @@ acc_rel(Dir, Rel, {Vsn, _}, Acc) ->
%% Write a rel file and return its name.
write_rel(Dir, [Erts | Apps], Vsn) ->
- true = is_vsn(Vsn),
- Name = "diameter_test_" ++ Vsn,
+ VS = vsn_str(Vsn),
+ Name = "diameter_test_" ++ VS,
ok = write_file(filename:join([Dir, Name ++ ".rel"]),
{release,
- {"diameter " ++ Vsn ++ " test release", Vsn},
+ {"diameter " ++ VS ++ " test release", VS},
Erts,
Apps}),
Name.
@@ -279,10 +340,34 @@ fetch(Key, List) ->
write_file(Path, T) ->
file:write_file(Path, io_lib:format("~p.", [T])).
-%% Is a version string of the expected form? Return the argument
-%% itself for 'false' for a useful badmatch.
+%% Is a version string of the expected form?
is_vsn(V) ->
- is_list(V)
- andalso length(V) == string:span(V, "0123456789.")
- andalso V == string:join(string:tokens(V, [$.]), ".") %% no ".."
- orelse {error, V}.
+ V = vsn_str(V),
+ true.
+
+%% Turn a from/to version in appup to a version string after ensuring
+%% that it's valid version number of regexp. In the regexp case, the
+%% regexp itself becomes the version string since there's no
+%% requirement that a version in appup be anything but a string. The
+%% restrictions placed on string-valued version numbers (that they be
+%% '.'-separated integers) are our own.
+
+vsn_str(S)
+ when is_list(S) ->
+ {_, match} = {S, match(S, "^(0|[1-9][0-9]*)(\\.(0|[1-9][0-9]*))*$")},
+ {_, nomatch} = {S, match(S, "\\.0\\.0$")},
+ S;
+
+vsn_str(B)
+ when is_binary(B) ->
+ {ok, _} = re:compile(B),
+ binary_to_list(B).
+
+match(S, RE) ->
+ re:run(S, RE, [{capture, none}]).
+
+%% Is an application name of the expected form?
+is_app(S)
+ when is_list(S) ->
+ {_, match} = {S, match(S, "^([a-z]([a-z_]*|[a-zA-Z]*))$")},
+ true.
diff --git a/lib/diameter/test/diameter_capx_SUITE.erl b/lib/diameter/test/diameter_capx_SUITE.erl
index deabdd720b..02501ce779 100644
--- a/lib/diameter/test/diameter_capx_SUITE.erl
+++ b/lib/diameter/test/diameter_capx_SUITE.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -144,8 +144,8 @@ end_per_suite(_Config) ->
%% Generate a unique hostname for each testcase so that watchdogs
%% don't prevent a connection from being brought up immediately.
init_per_testcase(Name, Config) ->
- Uniq = ["." ++ integer_to_list(N) || N <- tuple_to_list(now())],
- [{host, lists:flatten([?L(Name) | Uniq])} | Config].
+ [{host, ?L(Name) ++ "." ++ diameter_util:unique_string()}
+ | Config].
init_per_group(Name, Config) ->
[{rfc, Name} | Config].
diff --git a/lib/diameter/test/diameter_codec_SUITE.erl b/lib/diameter/test/diameter_codec_SUITE.erl
index cd8ca41f66..64ea90554d 100644
--- a/lib/diameter/test/diameter_codec_SUITE.erl
+++ b/lib/diameter/test/diameter_codec_SUITE.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -29,6 +29,9 @@
-export([suite/0,
all/0,
+ groups/0,
+ init_per_group/2,
+ end_per_group/2,
init_per_testcase/2,
end_per_testcase/2]).
@@ -36,9 +39,13 @@
-export([base/1,
gen/1,
lib/1,
- unknown/1]).
+ unknown/1,
+ success/1,
+ grouped_error/1,
+ failed_error/1]).
-include("diameter_ct.hrl").
+-include("diameter.hrl").
-define(L, atom_to_list).
@@ -48,7 +55,19 @@ suite() ->
[{timetrap, {seconds, 10}}].
all() ->
- [base, gen, lib, unknown].
+ [base, gen, lib, unknown, {group, recode}].
+
+groups() ->
+ [{recode, [], [success,
+ grouped_error,
+ failed_error]}].
+
+init_per_group(recode, Config) ->
+ ok = diameter:start(),
+ Config.
+
+end_per_group(_, _) ->
+ ok = diameter:stop().
init_per_testcase(gen, Config) ->
[{application, ?APP, App}] = diameter_util:consult(?APP, app),
@@ -98,3 +117,166 @@ compile(File) ->
compile(File, Opts) ->
compile:file(File, [return | Opts]).
+
+%% ===========================================================================
+
+%% Ensure a Grouped AVP is represented by a list in the avps field.
+success(_) ->
+ Avps = [{295, <<1:32>>}, %% Termination-Cause
+ {284, [{280, "Proxy-Host"}, %% Proxy-Info
+ {33, "Proxy-State"}, %%
+ {295, <<2:32>>}]}], %% Termination-Cause
+ #diameter_packet{avps = [#diameter_avp{code = 295,
+ value = 1,
+ data = <<1:32>>},
+ [#diameter_avp{code = 284},
+ #diameter_avp{code = 280},
+ #diameter_avp{code = 33},
+ #diameter_avp{code = 295,
+ value = 2,
+ data = <<2:32>>}]],
+ errors = []}
+ = str(recode(str(Avps))).
+
+%% ===========================================================================
+
+%% Ensure a Grouped AVP is represented by a list in the avps field
+%% even in the case of a decode error on a component AVP.
+grouped_error(_) ->
+ Avps = [{295, <<1:32>>}, %% Termination-Cause
+ {284, [{295, <<0:32>>}, %% Proxy-Info, Termination-Cause
+ {280, "Proxy-Host"},
+ {33, "Proxy-State"}]}],
+ #diameter_packet{avps = [#diameter_avp{code = 295,
+ value = 1,
+ data = <<1:32>>},
+ [#diameter_avp{code = 284},
+ #diameter_avp{code = 295,
+ value = undefined,
+ data = <<0:32>>},
+ #diameter_avp{code = 280},
+ #diameter_avp{code = 33}]],
+ errors = [{5004, #diameter_avp{code = 284}}]}
+ = str(recode(str(Avps))).
+
+%% ===========================================================================
+
+%% Ensure that a failed decode in Failed-AVP is acceptable, and that
+%% the component AVPs are decoded if possible.
+failed_error(_) ->
+ Avps = [{279, [{295, <<0:32>>}, %% Failed-AVP, Termination-Cause
+ {258, <<1:32>>}, %% Auth-Application-Id
+ {284, [{280, "Proxy-Host"}, %% Proxy-Info
+ {33, "Proxy-State"},
+ {295, <<0:32>>}, %% Termination-Cause, invalid
+ {258, <<2:32>>}]}]}], %% Auth-Application-Id
+ #diameter_packet{avps = [[#diameter_avp{code = 279},
+ #diameter_avp{code = 295,
+ value = undefined,
+ data = <<0:32>>},
+ #diameter_avp{code = 258,
+ value = 1,
+ data = <<1:32>>},
+ [#diameter_avp{code = 284},
+ #diameter_avp{code = 280},
+ #diameter_avp{code = 33},
+ #diameter_avp{code = 295,
+ value = undefined},
+ #diameter_avp{code = 258,
+ value = 2,
+ data = <<2:32>>}]]],
+ errors = []}
+ = sta(recode(sta(Avps))).
+
+%% ===========================================================================
+
+%% str/1
+
+str(#diameter_packet{avps = [#diameter_avp{code = 263},
+ #diameter_avp{code = 264},
+ #diameter_avp{code = 296},
+ #diameter_avp{code = 283},
+ #diameter_avp{code = 258,
+ value = 0}
+ | T]}
+ = Pkt) ->
+ Pkt#diameter_packet{avps = T};
+
+str(Avps) ->
+ OH = "diameter.erlang.org",
+ OR = "erlang.org",
+ DR = "example.com",
+ Sid = "diameter.erlang.org;123;456",
+
+ [#diameter_header{version = 1,
+ cmd_code = 275, %% STR
+ is_request = true,
+ application_id = 0,
+ hop_by_hop_id = 17,
+ end_to_end_id = 42,
+ is_proxiable = false,
+ is_error = false,
+ is_retransmitted = false}
+ | avp([{263, Sid}, %% Session-Id
+ {264, OH}, %% Origin-Host
+ {296, OR}, %% Origin-Realm
+ {283, DR}, %% Destination-Realm
+ {258, <<0:32>>}] %% Auth-Application-Id
+ ++ Avps)].
+
+%% sta/1
+
+sta(#diameter_packet{avps = [#diameter_avp{code = 263},
+ #diameter_avp{code = 268},
+ #diameter_avp{code = 264},
+ #diameter_avp{code = 296},
+ #diameter_avp{code = 278,
+ value = 4}
+ | T]}
+ = Pkt) ->
+ Pkt#diameter_packet{avps = T};
+
+sta(Avps) ->
+ OH = "diameter.erlang.org",
+ OR = "erlang.org",
+ Sid = "diameter.erlang.org;123;456",
+
+ [#diameter_header{version = 1,
+ cmd_code = 275, %% STA
+ is_request = false,
+ application_id = 0,
+ hop_by_hop_id = 17,
+ end_to_end_id = 42,
+ is_proxiable = false,
+ is_error = false,
+ is_retransmitted = false}
+ | avp([{263, Sid}, %% Session-Id
+ {268, <<2002:32>>}, %% Result-Code
+ {264, OH}, %% Origin-Host
+ {296, OR}, %% Origin-Realm
+ {278, <<4:32>>}] %% Origin-State-Id
+ ++ Avps)].
+
+avp({Code, Data}) ->
+ #diameter_avp{code = Code,
+ data = avp(Data)};
+
+avp(#diameter_avp{} = A) ->
+ A;
+
+avp([{_,_} | _] = Avps) ->
+ lists:map(fun avp/1, Avps);
+
+avp(V) ->
+ V.
+
+%% recode/1
+
+recode(Msg) ->
+ recode(Msg, diameter_gen_base_rfc6733).
+
+recode(#diameter_packet{} = Pkt, Dict) ->
+ diameter_codec:decode(Dict, diameter_codec:encode(Dict, Pkt));
+
+recode(Msg, Dict) ->
+ recode(#diameter_packet{msg = Msg}, Dict).
diff --git a/lib/diameter/test/diameter_codec_test.erl b/lib/diameter/test/diameter_codec_test.erl
index 24d4c7665e..17f5833101 100644
--- a/lib/diameter/test/diameter_codec_test.erl
+++ b/lib/diameter/test/diameter_codec_test.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -19,7 +19,9 @@
-module(diameter_codec_test).
--compile(export_all).
+-export([base/0,
+ gen/1,
+ lib/0]).
%%
%% Test encode/decode of dictionary-related modules.
@@ -38,37 +40,34 @@
%% Interface.
base() ->
- [] = run([{?MODULE, [base, T]} || T <- [zero, decode]]).
+ [] = run([[fun base/1, T] || T <- [zero, decode]]).
gen(Mod) ->
Fs = [{Mod, F, []} || F <- [name, id, vendor_id, vendor_name]],
- [] = run(Fs ++ [{?MODULE, [gen, Mod, T]} || T <- [messages,
- command_codes,
- avp_types,
- grouped,
- enum,
- import_avps,
- import_groups,
- import_enums]]).
+ [] = run(Fs ++ [[fun gen/2, Mod, T] || T <- [messages,
+ command_codes,
+ avp_types,
+ grouped,
+ enum,
+ import_avps,
+ import_groups,
+ import_enums]]).
lib() ->
- Vs = {_,_} = values('Address'),
- [] = run([[fun lib/2, N, Vs] || N <- [1,2]]).
+ Vs = {_,_,_} = values('Address'),
+ [] = run([[fun lib/2, N, Vs] || N <- [{1, true}, {3, false}]]).
%% ===========================================================================
%% Internal functions.
-lib(N, {_,_} = T) ->
- B = 1 == N rem 2,
- [] = run([[fun lib/2, A, B] || A <- element(N,T)]);
+lib({N,B}, {_,_,_} = T) ->
+ [] = run([[fun lib/2, A, B] || A <- element(N,T), is_tuple(A)]);
lib(IP, B) ->
- LA = tuple_to_list(IP),
- {SA,Fun} = ip(LA),
- [] = run([[fun lib/4, IP, B, Fun, A] || A <- [IP, SA]]).
+ [] = run([[fun lib/3, IP, B, A] || A <- [IP, ntoa(tuple_to_list(IP))]]).
-lib(IP, B, Fun, A) ->
- try Fun(A) of
+lib(IP, B, A) ->
+ try diameter_lib:ipaddr(A) of
IP when B ->
ok
catch
@@ -76,12 +75,12 @@ lib(IP, B, Fun, A) ->
ok
end.
-ip([_,_,_,_] = A) ->
+ntoa([_,_,_,_] = A) ->
[$.|S] = lists:append(["." ++ integer_to_list(N) || N <- A]),
- {S, fun diameter_lib:ipaddr/1};
-ip([_,_,_,_,_,_,_,_] = A) ->
+ S;
+ntoa([_,_,_,_,_,_,_,_] = A) ->
[$:|S] = lists:flatten([":" ++ io_lib:format("~.16B", [N]) || N <- A]),
- {S, fun diameter_lib:ipaddr/1}.
+ S.
%% ------------------------------------------------------------------------
%% base/1
@@ -90,7 +89,7 @@ ip([_,_,_,_,_,_,_,_] = A) ->
%% ------------------------------------------------------------------------
base(T) ->
- [] = run([{?MODULE, [base, T, F]} || F <- types()]).
+ [] = run([[fun base/2, T, F] || F <- types()]).
%% Ensure that 'zero' values encode only zeros.
base(zero = T, F) ->
@@ -100,32 +99,23 @@ base(zero = T, F) ->
%% Ensure that we can decode what we encode and vice-versa, and that
%% we can't decode invalid values.
base(decode, F) ->
- {Eq, Vs, Ns} = b(values(F)),
- [] = run([{?MODULE, [base_decode, F, Eq, V]} || V <- Vs]),
- [] = run([{?MODULE, [base_invalid, F, Eq, V]} || V <- Ns]).
+ {Ts, Fs, Is} = values(F),
+ [] = run([[fun base_decode/3, F, true, V] || V <- Ts]),
+ [] = run([[fun base_decode/3, F, false, V] || V <- Fs]),
+ [] = run([[fun base_invalid/2, F, V] || V <- Is]).
base_decode(F, Eq, Value) ->
d(fun(X,V) -> diameter_types:F(X,V) end, Eq, Value).
-base_invalid(F, Eq, Value) ->
+base_invalid(F, Value) ->
try
- base_decode(F, Eq, Value),
+ base_decode(F, false, Value),
exit(nok)
catch
error: _ ->
ok
end.
-b({_,_,_} = T) ->
- T;
-b({B,Vs})
- when is_atom(B) ->
- {B,Vs,[]};
-b({Vs,Ns}) ->
- {true, Vs, Ns};
-b(Vs) ->
- {true, Vs, []}.
-
types() ->
[F || {F,2} <- diameter_types:module_info(exports)].
@@ -136,7 +126,7 @@ types() ->
%% ------------------------------------------------------------------------
gen(M, T) ->
- [] = run(lists:map(fun(X) -> {?MODULE, [gen, M, T, X]} end,
+ [] = run(lists:map(fun(X) -> [fun gen/3, M, T, X] end,
fetch(T, dict(M)))).
fetch(T, Spec) ->
@@ -197,18 +187,20 @@ gen(M, enum = T, {Name, ED})
gen(M, T, {?A(Name), lists:map(fun({E,D}) -> {?A(E), D} end, ED)});
gen(M, enum, {Name, ED}) ->
- [] = run([{?MODULE, [enum, M, Name, T]} || T <- ED]);
+ [] = run([[fun enum/3, M, Name, T] || T <- ED]);
gen(M, Tag, {_Mod, L}) ->
T = retag(Tag),
- [] = run([{?MODULE, [gen, M, T, I]} || I <- L]).
+ [] = run([[fun gen/3, M, T, I] || I <- L]).
%% avp_decode/3
avp_decode(Mod, Type, Name) ->
- {Eq, Vs, _} = b(values(Type, Name, Mod)),
- [] = run([{?MODULE, [avp_decode, Mod, Name, Type, Eq, V]}
- || V <- v(Vs)]).
+ {Ts, Fs, _} = values(Type, Name, Mod),
+ [] = run([[fun avp_decode/5, Mod, Name, Type, true, V]
+ || V <- v(Ts)]),
+ [] = run([[fun avp_decode/5, Mod, Name, Type, false, V]
+ || V <- v(Fs)]).
avp_decode(Mod, Name, Type, Eq, Value) ->
d(fun(X,V) -> avp(Mod, X, V, Name, Type) end, Eq, Value).
@@ -237,8 +229,7 @@ v(Max, Ord, E)
when Ord =< Max ->
diameter_enum:to_list(E);
v(Max, Ord, E) ->
- {M,S,U} = now(),
- random:seed(M,S,U),
+ random:seed(now()),
v(Max, Ord, E, []).
v(0, _, _, Acc) ->
@@ -250,7 +241,7 @@ v(N, Ord, E, Acc) ->
arity(M, Name, Rname) ->
Rec = M:'#new-'(Rname),
- [] = run([{?MODULE, [arity, M, Name, F, Rec]}
+ [] = run([[fun arity/4, M, Name, F, Rec]
|| F <- M:'#info-'(Rname, fields)]).
arity(M, Name, AvpName, Rec) ->
@@ -299,68 +290,104 @@ z(B) ->
%% tested.)
values('OctetString' = T) ->
- {["", atom_to_list(T)], [-1, 256]};
+ {["", atom_to_list(T)],
+ [],
+ [-1, 256]};
values('Integer32') ->
Mx = (1 bsl 31) - 1,
Mn = -1*Mx,
- {[Mn, 0, random(Mn,Mx), Mx], [Mn - 1, Mx + 1]};
+ {[Mn, 0, random(Mn,Mx), Mx],
+ [],
+ [Mn - 1, Mx + 1]};
values('Integer64') ->
Mx = (1 bsl 63) - 1,
Mn = -1*Mx,
- {[Mn, 0, random(Mn,Mx), Mx], [Mn - 1, Mx + 1]};
+ {[Mn, 0, random(Mn,Mx), Mx],
+ [],
+ [Mn - 1, Mx + 1]};
values('Unsigned32') ->
M = (1 bsl 32) - 1,
- {[0, random(M), M], [-1, M + 1]};
+ {[0, random(M), M],
+ [],
+ [-1, M + 1]};
values('Unsigned64') ->
M = (1 bsl 64) - 1,
- {[0, random(M), M], [-1, M + 1]};
+ {[0, random(M), M],
+ [],
+ [-1, M + 1]};
values('Float32') ->
E = (1 bsl 8) - 2,
F = (1 bsl 23) - 1,
<<Mx:32/float>> = <<0:1, E:8, F:23>>,
<<Mn:32/float>> = <<1:1, E:8, F:23>>,
- {[0.0, infinity, '-infinity', Mx, Mn], [0]};
+ {[0.0, infinity, '-infinity', Mx, Mn],
+ [],
+ [0]};
values('Float64') ->
E = (1 bsl 11) - 2,
F = (1 bsl 52) - 1,
<<Mx:64/float>> = <<0:1, E:11, F:52>>,
<<Mn:64/float>> = <<1:1, E:11, F:52>>,
- {[0.0, infinity, '-infinity', Mx, Mn], [0]};
+ {[0.0, infinity, '-infinity', Mx, Mn],
+ [],
+ [0]};
values('Address') ->
{[{255,0,random(16#FF),1}, {65535,0,0,random(16#FFFF),0,0,0,1}],
- [{256,0,0,1}, {65536,0,0,0,0,0,0,1}]};
+ ["127.0.0.1", "FFFF:FF::1.2.3.4"],
+ [{256,0,0,1}, {65536,0,0,0,0,0,0,1}, "256.0.0.1", "10000::1"]};
values('DiameterIdentity') ->
- {["x", "diameter.com"], [""]};
+ {["x", "diameter.com"],
+ [],
+ [""]};
values('DiameterURI') ->
- {false, ["aaa" ++ S ++ "://diameter.se" ++ P ++ Tr ++ Pr
- || S <- ["", "s"],
- P <- ["", ":1234"],
- Tr <- ["" | [";transport=" ++ X
- || X <- ["tcp", "sctp", "udp"]]],
- Pr <- ["" | [";protocol=" ++ X
- || X <- ["diameter","radius","tacacs+"]]]]};
+ {[],
+ ["aaa" ++ S ++ "://diameter.se" ++ P ++ Tr ++ Pr
+ || S <- ["", "s"],
+ P <- ["", ":1234", ":0", ":65535"],
+ Tr <- ["" | [";transport=" ++ X
+ || X <- ["tcp", "sctp", "udp"]]],
+ Pr <- ["" | [";protocol=" ++ X
+ || X <- ["diameter","radius","tacacs+"]]],
+ Tr /= ";transport=udp"
+ orelse (Pr /= ";protocol=diameter" andalso Pr /= "")]
+ ++ ["aaa://" ++ lists:duplicate(255, $x)],
+ ["aaa://diameter.se:65536",
+ "aaa://diameter.se:-1",
+ "aaa://diameter.se;transport=udp;protocol=diameter",
+ "aaa://diameter.se;transport=udp",
+ "aaa://" ++ lists:duplicate(256, $x),
+ "aaa://:3868",
+ "aaax://diameter.se",
+ "aaa://diameter.se;transport=tcpx",
+ "aaa://diameter.se;transport=tcp;protocol=diameter "]};
values(T)
when T == 'IPFilterRule';
T == 'QoSFilterRule' ->
- ["deny in 0 from 127.0.0.1 to 10.0.0.1"];
+ {["deny in 0 from 127.0.0.1 to 10.0.0.1"],
+ [],
+ []};
%% RFC 3629 defines the UTF-8 encoding of U+0000 through U+10FFFF with the
%% exception of U+D800 through U+DFFF.
values('UTF8String') ->
+ S = "ᚠᚢᚦᚨᚱᚲ",
+ B = unicode:characters_to_binary(S),
{[[],
+ S,
lists:seq(0,16#1FF),
[0,16#D7FF,16#E000,16#10FFFF],
[random(16#D7FF), random(16#E000,16#10FFFF)]],
+ [B, [B, S, hd(S)], [S, B]],
[[-1],
[16#D800],
[16#DFFF],
@@ -372,6 +399,7 @@ values('Time') ->
{{2036,2,7},{6,28,15}},
{{2036,2,7},{6,28,16}}, %% 19000101T000000 + 2 bsl 31
{{2104,2,26},{9,42,23}}],
+ [],
[{{1968,1,20},{3,14,7}},
{{2104,2,26},{9,42,24}}]}. %% 19000101T000000 + 3 bsl 31
@@ -382,18 +410,24 @@ values('Time') ->
values('Enumerated', Name, Mod) ->
{_Name, Vals} = lists:keyfind(?S(Name), 1, types(enum, Mod)),
- lists:map(fun({_,N}) -> N end, Vals);
+ {lists:map(fun({_,N}) -> N end, Vals),
+ [],
+ []};
values('Grouped', Name, Mod) ->
Rname = Mod:name2rec(Name),
Rec = Mod:'#new-'(Rname),
Avps = Mod:'#info-'(Rname, fields),
- Enum = diameter_enum:combine(lists:map(fun({_,Vs,_}) -> to_enum(Vs) end,
+ Enum = diameter_enum:combine(lists:map(fun({Vs,_,_}) -> to_enum(Vs) end,
[values(F, Mod) || F <- Avps])),
- {false, diameter_enum:append(group(Mod, Name, Rec, Avps, Enum))};
+ {[],
+ diameter_enum:append(group(Mod, Name, Rec, Avps, Enum)),
+ []};
values(_, 'Framed-IP-Address', _) ->
- [{127,0,0,1}];
+ {[{127,0,0,1}],
+ [],
+ []};
values(Type, _, _) ->
values(Type).
@@ -407,12 +441,14 @@ to_enum(E) ->
%% values/2
values('AVP', _) ->
- {true, [#diameter_avp{code = 0, data = <<0>>}], []};
+ {[#diameter_avp{code = 0, data = <<0>>}],
+ [],
+ []};
values(Name, Mod) ->
Avps = types(avp_types, Mod),
{_Name, _Code, Type, _Flags} = lists:keyfind(?S(Name), 1, Avps),
- b(values(?A(Type), Name, Mod)).
+ values(?A(Type), Name, Mod).
%% group/5
%%
@@ -446,9 +482,6 @@ pack(true, Arity, Avp, Value, Acc) ->
pack(false, Arity, Avp, Value, Acc) ->
min(Arity, Avp, Value, Acc).
-all(Mod, Name, Avp, V) ->
- all(Mod:avp_arity(Name, Avp), Avp, V).
-
all(1, Avp, V) ->
{Avp, V};
all({0,'*'}, Avp, V) ->
@@ -462,9 +495,6 @@ a(N, Avp, V)
when N /= 0 ->
{Avp, lists:duplicate(N,V)}.
-min(Mod, Name, Avp, V, Acc) ->
- min(Mod:avp_arity(Name, Avp), Avp, V, Acc).
-
min(1, Avp, V, Acc) ->
[{Avp, V} | Acc];
min({0,_}, _, _, Acc) ->
diff --git a/lib/diameter/test/diameter_compiler_SUITE.erl b/lib/diameter/test/diameter_compiler_SUITE.erl
index 81722c8dca..20c9275808 100644
--- a/lib/diameter/test/diameter_compiler_SUITE.erl
+++ b/lib/diameter/test/diameter_compiler_SUITE.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2014. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -31,10 +31,15 @@
%% testcases
-export([format/1, format/2,
replace/1, replace/2,
- generate/1, generate/4]).
+ generate/1, generate/4,
+ flatten1/1, flatten1/3,
+ flatten2/1]).
-export([dict/0]). %% fake dictionary module
+%% dictionary callbacks for flatten2/1
+-export(['A1'/3, 'Unsigned32'/3]).
+
-define(base, "base_rfc3588.dia").
-define(util, diameter_util).
-define(S, atom_to_list).
@@ -45,7 +50,7 @@
%% RE/Replacement (in the sense of re:replace/4) pairs for morphing
%% base_rfc3588.dia. The key is 'ok' or the the expected error as
%% returned in the first element of the error tuple returned by
-%% diameter_dict_util:parse/2.
+%% diameter_make:codec/2.
-define(REPLACE,
[{ok,
"",
@@ -115,6 +120,16 @@
{avp_has_duplicate_flag,
" -",
" MM"},
+ {ok,
+ "@vendor 0",
+ "@vendor 10415"},
+ {ok,
+ [{"@vendor 0", "@vendor 10415"},
+ {"Proxy-Info .*M$", "&V"},
+ {"Proxy-Info ::= [^>]*", "& 10415 "}]},
+ {grouped_vendor_id_without_flag,
+ [{"@vendor 0", "@vendor 10415"},
+ {"Proxy-Info ::= [^>]*", "& 10415 "}]},
{avp_has_vendor_id,
"@avp_types",
"@avp_vendor_id 667 Class\n&"},
@@ -133,6 +148,9 @@
{grouped_avp_not_defined,
"Failed-AVP *.*",
""},
+ {grouped_avp_not_grouped,
+ "Failed-AVP ::=.*\n.*}",
+ ""},
{grouped_vendor_id_without_flag,
"(Failed-AVP .*)>",
"\\1 668>"},
@@ -299,6 +317,21 @@
{avp_not_defined,
"CEA ::=",
"<XXX> &"},
+ {ok,
+ "@avp_types",
+ "@codecs tmod Session-Id &"},
+ {ok,
+ "@avp_types",
+ "@custom_types tmod Session-Id &"},
+ {avp_not_defined,
+ "@avp_types",
+ "@codecs tmod OctetString &"},
+ {avp_not_defined,
+ "@avp_types",
+ "@custom_types tmod OctetString &"},
+ {avp_already_defined,
+ "@avp_types",
+ "@codecs tmod Session-Id @custom_types tmod Session-Id &"},
{not_loaded,
[{"@avp_types", "@inherits nomod XXX &"},
{"CEA ::=", "<XXX> &"}]},
@@ -335,7 +368,9 @@ suite() ->
all() ->
[format,
replace,
- generate].
+ generate,
+ flatten1,
+ flatten2].
%% Error handling testcases will make an erroneous dictionary out of
%% the base dictionary and check that the expected error results.
@@ -361,10 +396,18 @@ format(Config) ->
format(Mods, Bin) ->
B = modify(Bin, Mods),
- {ok, Dict} = diameter_dict_util:parse(B, []),
- {ok, D} = diameter_dict_util:parse(diameter_dict_util:format(Dict), []),
+ {ok, Dict} = parse(B, []),
+ {ok, D} = parse(diameter_make:format(Dict), []),
{Dict, Dict} = {Dict, D}.
+parse(File, Opts) ->
+ case diameter_make:codec(File, [parse, hrl, return | Opts]) of
+ {ok, [Dict, _]} ->
+ {ok, Dict};
+ {error, _} = E ->
+ E
+ end.
+
%% ===========================================================================
%% replace/1
%%
@@ -379,14 +422,11 @@ replace(Config) ->
replace({E, Mods}, Bin) ->
B = modify(Bin, Mods),
- case {E, diameter_dict_util:parse(B, [{include, here()}]), Mods} of
+ case {E, parse(B, [{include, here()}]), Mods} of
{ok, {ok, Dict}, _} ->
Dict;
- {_, {error, {E,_} = T}, _} ->
- S = diameter_dict_util:format_error(T),
- true = nochar($", S, E),
- true = nochar($', S, E),
- S
+ {_, {error, {E,_} = T}, _} when E /= ok ->
+ diameter_make:format_error(T)
end.
re({RE, Repl}, Bin) ->
@@ -403,20 +443,127 @@ generate(Config) ->
[] = ?util:run([{?MODULE, [generate, M, Bin, N, T]}
|| {E,N} <- Rs,
{ok, M} <- [norm(E)],
- T <- [erl, hrl, spec]]).
+ T <- [erl, hrl, parse, forms]]).
generate(Mods, Bin, N, Mode) ->
B = modify(Bin, Mods ++ [{"@name .*", "@name dict" ++ ?L(N)}]),
- {ok, Dict} = diameter_dict_util:parse(B, []),
+ {ok, Dict} = parse(B, []),
File = "dict" ++ integer_to_list(N),
- {_, ok} = {Dict, diameter_codegen:from_dict("dict",
- Dict,
- [{name, File},
- {prefix, "base"},
- debug],
- Mode)},
- Mode == erl
- andalso ({ok, _} = compile:file(File ++ ".erl", [return_errors])).
+ {_, ok} = {Dict, diameter_make:codec(Dict,
+ [{name, File},
+ {prefix, "base"},
+ Mode])},
+ generate(Mode, File, Dict).
+
+generate(erl, File, _) ->
+ {ok, _} = compile:file(File ++ ".erl", [return_errors]);
+
+generate(forms, File, _) ->
+ {ok, [_]} = file:consult(File ++ ".F");
+
+generate(parse, File, Dict) ->
+ {ok, [Dict]} = file:consult(File ++ ".D"), %% assert
+ {ok, [F]} = diameter_make:codec(Dict, [forms, return]),
+ {ok, _, _, _} = compile:forms(F, [return]);
+
+generate(hrl, _, _) ->
+ ok.
+
+%% ===========================================================================
+%% flatten1/1
+
+flatten1(_Config) ->
+ [Vsn | BaseD] = diameter_gen_base_rfc6733:dict(),
+ {ok, I} = parse("@inherits diameter_gen_base_rfc6733\n", []),
+ [Vsn | FlatD] = diameter_make:flatten(I),
+ [] = ?util:run([{?MODULE, [flatten1, K, BaseD, FlatD]}
+ || K <- [avp_types, grouped, enum]]).
+
+flatten1(Key, BaseD, FlatD) ->
+ Vs = orddict:fetch(Key, BaseD),
+ Vs = orddict:fetch(Key, FlatD).
+
+%% ===========================================================================
+%% flatten2/1
+
+flatten2(_Config) ->
+ Dict1 =
+ "@name diameter_test1\n"
+ "@prefix diameter_test1\n"
+ "@vendor 666 test\n"
+ "@avp_vendor_id 111 A1 A3\n"
+ "@avp_vendor_id 222 A4 A6\n"
+ "@custom_types " ++ ?S(?MODULE) ++ " A1 A4\n"
+ "@codecs " ++ ?S(?MODULE) ++ " A3 A6\n"
+ "@avp_types\n"
+ "A1 1001 Unsigned32 V\n"
+ "A2 1002 Unsigned32 V\n"
+ "A3 1003 Unsigned32 V\n"
+ "A4 1004 Unsigned32 V\n"
+ "A5 1005 Unsigned32 V\n"
+ "A6 1006 Unsigned32 V\n"
+ "@end ignored\n",
+ Dict2 =
+ "@name diameter_test2\n"
+ "@prefix diameter_test2\n"
+ "@vendor 777 test\n"
+ "@inherits diameter_test1 A1 A2 A3\n"
+ "@inherits diameter_gen_base_rfc6733\n"
+ "@avp_vendor_id 333 A1\n",
+
+ {ok, [E1, F1]}
+ = diameter_make:codec(Dict1, [erl, forms, return]),
+ ct:pal("~s", [E1]),
+ diameter_test1 = M1 = load_forms(F1),
+
+ {ok, [D2, E2, F2]}
+ = diameter_make:codec(Dict2, [parse, erl, forms, return]),
+ ct:pal("~s", [E2]),
+ diameter_test2 = M2 = load_forms(F2),
+
+ Flat = lists:flatten(diameter_make:format(diameter_make:flatten(D2))),
+ ct:pal("~s", [Flat]),
+ {ok, [E3, F3]}
+ = diameter_make:codec(Flat, [erl, forms, return,
+ {name, "diameter_test3"}]),
+ ct:pal("~s", [E3]),
+ diameter_test3 = M3 = load_forms(F3),
+
+ [{1001, 111, M1, 'A1'}, %% @avp_vendor_id
+ {1002, 666, M1, 'A2'}, %% @vendor
+ {1003, 111, M1, 'A3'}, %% @avp_vendor_id
+ {1004, 222, M1, 'A4'}, %% @avp_vendor_id
+ {1005, 666, M1, 'A5'}, %% @vendor
+ {1006, 222, M1, 'A6'}, %% @avp_vendor_id
+ {1001, 333, M2, 'A1'}, %% M2 @avp_vendor_id
+ {1002, 666, M2, 'A2'}, %% M1 @vendor
+ {1003, 666, M2, 'A3'}, %% M1 @vendor
+ {1001, 333, M3, 'A1'}, %% (as for M2)
+ {1002, 666, M3, 'A2'}, %% "
+ {1003, 666, M3, 'A3'}] %% "
+ = [{Code, Vid, Mod, Name}
+ || Mod <- [M1, M2, M3],
+ Code <- lists:seq(1001, 1006),
+ Vid <- [666, 111, 222, 777, 333],
+ {Name, 'Unsigned32'} <- [Mod:avp_name(Code, Vid)]],
+
+ [] = [{A,T,M,RC} || A <- ['A1', 'A3'],
+ T <- [encode, decode],
+ M <- [M2, M3],
+ Ref <- [make_ref()],
+ RC <- [M:avp(T, Ref, A)],
+ RC /= {T, Ref}].
+
+'A1'(T, 'Unsigned32', Ref) ->
+ {T, Ref}.
+
+'Unsigned32'(T, 'A3', Ref) ->
+ {T, Ref}.
+
+load_forms(Forms) ->
+ {ok, Mod, Bin, _} = compile:forms(Forms, [return]),
+ {module, Mod} = code:load_binary(Mod, ?S(Mod), Bin),
+ Mod.
%% ===========================================================================
@@ -428,9 +575,6 @@ norm({E, RE, Repl}) ->
norm({_,_} = T) ->
T.
-nochar(Char, Str, Err) ->
- Err == parse orelse not lists:member(Char, Str) orelse Str.
-
here() ->
filename:dirname(code:which(?MODULE)).
diff --git a/lib/diameter/test/diameter_config_SUITE.erl b/lib/diameter/test/diameter_config_SUITE.erl
index 46ff63756d..bbdf672291 100644
--- a/lib/diameter/test/diameter_config_SUITE.erl
+++ b/lib/diameter/test/diameter_config_SUITE.erl
@@ -1,8 +1,7 @@
-%% coding: utf-8
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2013. All Rights Reserved.
+%% Copyright Ericsson AB 2013-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -83,6 +82,15 @@
[false],
[[node(), node()]]],
[[x]]},
+ {string_decode,
+ [[true], [false]],
+ [[0], [x]]},
+ {incoming_maxlen,
+ [[0], [65536], [16#FFFFFF]],
+ [[-1], [1 bsl 24], [infinity], [false]]},
+ {spawn_opt,
+ [[[]], [[monitor, link]]],
+ [[false]]},
{invalid_option, %% invalid service options are rejected
[],
[[x],
@@ -158,7 +166,13 @@
{length_errors,
[[exit], [handle], [discard]],
[[x]]},
- {reconnect_timer,
+ {dpr_timeout,
+ [[0], [3000], [16#FFFFFFFF]],
+ [[infinity], [-1], [1 bsl 32], [x]]},
+ {dpa_timeout,
+ [[0], [3000], [16#FFFFFFFF]],
+ [[infinity], [-1], [1 bsl 32], [x]]},
+ {connect_timer,
[[3000]],
[[infinity]]},
{watchdog_timer,
@@ -172,9 +186,15 @@
[[{suspect, 2}]]],
[[x],
[[{open, 0}]]]},
+ {pool_size,
+ [[1], [100]],
+ [[0], [infinity], [-1], [x]]},
{private,
[[x]],
[]},
+ {spawn_opt,
+ [[[]], [[monitor, link]]],
+ [[false]]},
{invalid_option, %% invalid transport options are silently ignored
[[x],
[x,x]],
diff --git a/lib/diameter/test/diameter_ct.erl b/lib/diameter/test/diameter_ct.erl
index ed2f884681..788cbbbe3e 100644
--- a/lib/diameter/test/diameter_ct.erl
+++ b/lib/diameter/test/diameter_ct.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
diff --git a/lib/diameter/test/diameter_dpr_SUITE.erl b/lib/diameter/test/diameter_dpr_SUITE.erl
index 9252650bf7..81178e2bda 100644
--- a/lib/diameter/test/diameter_dpr_SUITE.erl
+++ b/lib/diameter/test/diameter_dpr_SUITE.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2012. All Rights Reserved.
+%% Copyright Ericsson AB 2012-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -32,6 +32,7 @@
%% testcases
-export([start/1,
connect/1,
+ send_dpr/1,
remove_transport/1,
stop_service/1,
check/1,
@@ -41,6 +42,7 @@
-export([disconnect/5]).
-include("diameter.hrl").
+-include("diameter_gen_base_rfc6733.hrl").
%% ===========================================================================
@@ -51,9 +53,6 @@
-define(CLIENT, "CLIENT").
-define(SERVER, "SERVER").
--define(DICT_COMMON, ?DIAMETER_DICT_COMMON).
--define(APP_ID, ?DICT_COMMON:id()).
-
%% Config for diameter:start_service/2.
-define(SERVICE(Host),
[{'Origin-Host', Host},
@@ -61,9 +60,10 @@
{'Host-IP-Address', [?ADDR]},
{'Vendor-Id', hd(Host)}, %% match this in disconnect/5
{'Product-Name', "OTP/diameter"},
- {'Acct-Application-Id', [?APP_ID]},
+ {'Acct-Application-Id', [0]},
{restrict_connections, false},
- {application, [{dictionary, ?DICT_COMMON},
+ {application, [{dictionary, diameter_gen_base_rfc6733},
+ {alias, common},
{module, #diameter_callback{_ = false}}]}]).
%% Disconnect reasons that diameter passes as the first argument of a
@@ -73,11 +73,13 @@
%% Valid values for Disconnect-Cause.
-define(CAUSES, [0, rebooting, 1, busy, 2, goaway]).
-%% Establish one client connection for element of this list,
-%% configured with disconnect/5 as disconnect_cb and returning the
-%% specified value.
+%% Establish one client connection for each element of this list,
+%% configured with disconnect/5, disconnect_cb returning the specified
+%% value.
-define(RETURNS,
- [[close, {dpr, [{cause, invalid}]}], [ignore, close], []]
+ [[close, {dpr, [{cause, invalid}]}],
+ [ignore, close],
+ []]
++ [[{dpr, [{timeout, 5000}, {cause, T}]}] || T <- ?CAUSES]).
%% ===========================================================================
@@ -86,7 +88,7 @@ suite() ->
[{timetrap, {seconds, 60}}].
all() ->
- [{group, R} || R <- ?REASONS].
+ [start, send_dpr, stop | [{group, R} || R <- ?REASONS]].
%% The group determines how transports are terminated: by remove_transport,
%% stop_service or application stop.
@@ -111,6 +113,22 @@ start(_Config) ->
ok = diameter:start_service(?SERVER, ?SERVICE(?SERVER)),
ok = diameter:start_service(?CLIENT, ?SERVICE(?CLIENT)).
+send_dpr(_Config) ->
+ LRef = ?util:listen(?SERVER, tcp),
+ Ref = ?util:connect(?CLIENT, tcp, LRef, [{dpa_timeout, 10000}]),
+ #diameter_base_DPA{'Result-Code' = 2001}
+ = diameter:call(?CLIENT,
+ common,
+ ['DPR', {'Origin-Host', "CLIENT.erlang.org"},
+ {'Origin-Realm', "erlang.org"},
+ {'Disconnect-Cause', 0}]),
+ ok = receive %% endure the transport dies on DPA
+ #diameter_event{service = ?CLIENT, info = {down, Ref, _, _}} ->
+ ok
+ after 5000 ->
+ erlang:process_info(self(), messages)
+ end.
+
connect(Config) ->
Pid = spawn(fun init/0), %% process for disconnect_cb to bang
Grp = group(Config),
@@ -129,8 +147,8 @@ stop_service(Config) ->
service == group(Config)
andalso (ok = diameter:stop_service(?CLIENT)).
-%% Check for callbacks and stop the service. (Not the other way around
-%% for the timing reason explained below.)
+%% Check for callbacks before diameter:stop/0, not the other way around
+%% for the timing reason explained below.
check(Config) ->
Grp = group(Config),
[Pid | Refs] = ?util:read_priv(Config, config),
diff --git a/lib/diameter/test/diameter_event_SUITE.erl b/lib/diameter/test/diameter_event_SUITE.erl
index 94b4967921..8ede8a51a8 100644
--- a/lib/diameter/test/diameter_event_SUITE.erl
+++ b/lib/diameter/test/diameter_event_SUITE.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2013. All Rights Reserved.
+%% Copyright Ericsson AB 2013-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -107,29 +107,38 @@ start_server(Config) ->
%% Connect with matching capabilities and expect the connection to
%% come up.
up(Config) ->
- {Svc, Ref} = connect(Config, []),
+ {Svc, Ref} = connect(Config, [{connect_timer, 5000},
+ {watchdog_timer, 15000}]),
start = event(Svc),
- {up, Ref, {_,_Caps}, _Config, #diameter_packet{}} = event(Svc),
- {watchdog, Ref, _, {initial, okay}, _} = event(Svc).
+ {up, Ref, {TPid, Caps}, Cfg, #diameter_packet{}} = event(Svc),
+ {watchdog, Ref, _, {initial, okay}, _} = event(Svc),
+ %% Kill the transport process and see that the connection is
+ %% reestablished after a watchdog timeout, not after connect_timer
+ %% expiry.
+ exit(TPid, kill),
+ {down, Ref, {TPid, Caps}, Cfg} = event(Svc),
+ {watchdog, Ref, _, {okay, down}, _} = event(Svc),
+ {reconnect, Ref, _} = event(Svc, 10000, 20000).
%% Connect with non-matching capabilities and expect CEA from the peer
%% to indicate as much and then for the transport to be restarted
-%% (after reconnect_timer).
+%% (after connect_timer).
down(Config) ->
{Svc, Ref} = connect(Config, [{capabilities, [{'Acct-Application-Id',
[?DICT_ACCT:id()]}]},
{applications, [?DICT_ACCT]},
- {reconnect_timer, 5000}]),
+ {connect_timer, 5000},
+ {watchdog_timer, 20000}]),
start = event(Svc),
{closed, Ref, {'CEA', ?NO_COMMON_APP, _, #diameter_packet{}}, _}
= event(Svc),
- {reconnect, Ref, _} = event(Svc).
+ {reconnect, Ref, _} = event(Svc, 4000, 10000).
%% Connect with matching capabilities but have the server delay its
%% CEA and cause the client to timeout.
cea_timeout(Config) ->
{Svc, Ref} = connect(Config, [{capx_timeout, ?SERVER_CAPX_TMO div 2},
- {reconnect_timer, 2*?SERVER_CAPX_TMO}]),
+ {connect_timer, 2*?SERVER_CAPX_TMO}]),
start = event(Svc),
{closed, Ref, {'CEA', timeout}, _} = event(Svc).
@@ -159,12 +168,18 @@ connect(Config, Opts) ->
{Name, Ref}.
uniq() ->
- {MS,S,US} = now(),
- lists:flatten(io_lib:format("-~p-~p-~p-", [MS,S,US])).
+ "-" ++ diameter_util:unique_string().
event(Name) ->
receive #diameter_event{service = Name, info = T} -> T end.
+event(Name, TL, TH) ->
+ T0 = now(),
+ Event = event(Name),
+ DT = timer:now_diff(now(), T0) div 1000,
+ {true, true, DT, Event} = {TL < DT, DT < TH, DT, Event},
+ Event.
+
start_service(Name, Opts) ->
diameter:start_service(Name, [{monitor, self()} | Opts]).
diff --git a/lib/diameter/test/diameter_examples_SUITE.erl b/lib/diameter/test/diameter_examples_SUITE.erl
index 75b542b679..dc0b466b59 100644
--- a/lib/diameter/test/diameter_examples_SUITE.erl
+++ b/lib/diameter/test/diameter_examples_SUITE.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2013. All Rights Reserved.
+%% Copyright Ericsson AB 2013-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -24,7 +24,10 @@
-module(diameter_examples_SUITE).
-export([suite/0,
- all/0]).
+ all/0,
+ groups/0,
+ init_per_group/2,
+ end_per_group/2]).
%% testcases
-export([dict/1, dict/0,
@@ -46,7 +49,7 @@
%% The order here is significant and causes the server to listen
%% before the clients connect.
--define(NODES, [compile, server, client]).
+-define(NODES, [server, client]).
%% Options to ct_slave:start/2.
-define(TIMEOUTS, [{T, 15000} || T <- [boot_timeout,
@@ -63,6 +66,9 @@
%% Common dictionaries to inherit from examples.
-define(DICT0, [rfc3588_base, rfc6733_base]).
+%% Transport protocols over which the example Diameter nodes are run.
+-define(PROTS, [tcp, sctp]).
+
%% ===========================================================================
suite() ->
@@ -71,7 +77,34 @@ suite() ->
all() ->
[dict,
code,
- slave,
+ {group, all}].
+
+groups() ->
+ Tc = tc(),
+ [{all, [parallel], [{group, P} || P <- ?PROTS]}
+ | [{P, [], Tc} || P <- ?PROTS]].
+
+init_per_group(all, Config) ->
+ Config;
+
+init_per_group(tcp = N, Config) ->
+ [{group, N} | Config];
+
+init_per_group(sctp = N, Config) ->
+ case gen_sctp:open() of
+ {ok, Sock} ->
+ gen_sctp:close(Sock),
+ [{group, N} | Config];
+ {error, E} when E == eprotonosupport;
+ E == esocktnosupport -> %% fail on any other reason
+ {skip, no_sctp}
+ end.
+
+end_per_group(_, _) ->
+ ok.
+
+tc() ->
+ [slave,
enslave,
start,
traffic,
@@ -88,7 +121,7 @@ dict() ->
dict(_Config) ->
Dirs = [filename:join(H ++ ["examples", "dict"])
|| H <- [[code:lib_dir(diameter)], [here(), ".."]]],
- [] = [{F,D,RC} || {_,F} <- sort(find_files(Dirs, ".*\\.dia")),
+ [] = [{F,D,RC} || {_,F} <- sort(find_files(Dirs, ".*\\.dia$")),
D <- ?DICT0,
RC <- [make(F,D)],
RC /= ok].
@@ -133,7 +166,7 @@ make(Path, Dict0) ->
try
ok = to_erl(Path, [{name, Name},
{prefix, Pre},
- {inherits, "rfc3588_base/" ++ Mod0}
+ {inherits, "common/" ++ Mod0}
| [{inherits, D ++ "/" ++ M ++ Suf}
|| {D,M} <- dep(Dict)]]),
ok = to_beam(Name)
@@ -184,17 +217,18 @@ make_name(Dict) ->
%% Compile example code under examples/code.
code(Config) ->
- Node = slave(hd(?NODES), here()),
+ Node = slave(compile, here()),
[] = rpc:call(Node,
?MODULE,
install,
- [proplists:get_value(priv_dir, Config)]).
+ [proplists:get_value(priv_dir, Config)]),
+ {ok, Node} = ct_slave:stop(compile).
%% Compile on another node since the code path may be modified.
install(PrivDir) ->
Top = install(here(), PrivDir),
Src = filename:join([Top, "examples", "code"]),
- Files = find_files([Src], ".*\\.erl"),
+ Files = find_files([Src], ".*\\.erl$"),
[] = [{F,E} || {_,F} <- Files,
{error, _, _} = E <- [compile:file(F, [warnings_as_errors,
return_errors])]].
@@ -226,7 +260,7 @@ install(Dir, PrivDir) ->
Inc = filename:join([Top, "include"]),
Gen = filename:join([Top, "src", "gen"]),
- Files = find_files([Inc, Gen], ".*\\.hrl"),
+ Files = find_files([Inc, Gen], ".*\\.hrl$"),
[] = [{F,E} || {_,F} <- Files,
B <- [filename:basename(F)],
D <- [filename:join([TmpInc, B])],
@@ -280,9 +314,10 @@ now_diff(_) ->
%% Start two nodes: one for the server, one for the client.
enslave(Config) ->
+ Prot = proplists:get_value(group, Config),
Dir = here(),
- Nodes = [{N, slave(N, Dir)} || N <- tl(?NODES)],
- ?util:write_priv(Config, nodes, Nodes).
+ Nodes = [{S, slave(N, Dir)} || S <- ?NODES, N <- [concat(Prot, S)]],
+ ?util:write_priv(Config, Prot, Nodes).
slave(Name, Dir) ->
{ok, Node} = ct_slave:start(Name, ?TIMEOUTS),
@@ -292,6 +327,9 @@ slave(Name, Dir) ->
[[Dir, filename:join([Dir, "..", "ebin"])]]),
Node.
+concat(Prot, Svc) ->
+ list_to_atom(atom_to_list(Prot) ++ atom_to_list(Svc)).
+
here() ->
filename:dirname(code:which(?MODULE)).
@@ -304,24 +342,25 @@ top(Dir, LibDir) ->
%% start/1
-start(server) ->
+start({server, Prot}) ->
ok = diameter:start(),
ok = server:start(),
- {ok, Ref} = server:listen(tcp),
- [_] = ?util:lport(tcp, Ref),
+ {ok, Ref} = server:listen(Prot),
+ [_] = ?util:lport(Prot, Ref),
ok;
-start(client) ->
+start({client = Svc, Prot}) ->
ok = diameter:start(),
- true = diameter:subscribe(client),
+ true = diameter:subscribe(Svc),
ok = client:start(),
- {ok, Ref} = client:connect(tcp),
+ {ok, Ref} = client:connect(Prot),
receive #diameter_event{info = {up, Ref, _, _, _}} -> ok end;
start(Config) ->
- Nodes = ?util:read_priv(Config, nodes),
+ Prot = proplists:get_value(group, Config),
+ Nodes = ?util:read_priv(Config, Prot),
[] = [RC || {T,N} <- Nodes,
- RC <- [rpc:call(N, ?MODULE, start, [T])],
+ RC <- [rpc:call(N, ?MODULE, start, [{T, Prot}])],
RC /= ok].
%% traffic/1
@@ -336,7 +375,8 @@ traffic(client) ->
receive {'DOWN', MRef, process, _, Reason} -> Reason end;
traffic(Config) ->
- Nodes = ?util:read_priv(Config, nodes),
+ Prot = proplists:get_value(group, Config),
+ Nodes = ?util:read_priv(Config, Prot),
[] = [RC || {T,N} <- Nodes,
RC <- [rpc:call(N, ?MODULE, traffic, [T])],
RC /= ok].
@@ -355,5 +395,6 @@ stop(Name)
{ok, _Node} = ct_slave:stop(Name),
ok;
-stop(_Config) ->
- [] = [RC || N <- ?NODES, RC <- [stop(N)], RC /= ok].
+stop(Config) ->
+ Prot = proplists:get_value(group, Config),
+ [] = [RC || N <- ?NODES, RC <- [catch stop(concat(Prot, N))], RC /= ok].
diff --git a/lib/diameter/test/diameter_failover_SUITE.erl b/lib/diameter/test/diameter_failover_SUITE.erl
index dfd3253827..c1494dcdb1 100644
--- a/lib/diameter/test/diameter_failover_SUITE.erl
+++ b/lib/diameter/test/diameter_failover_SUITE.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2014. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -47,6 +47,7 @@
send_discard_1/1,
send_discard_2/1,
stop_services/1,
+ empty/1,
stop/1]).
%% diameter callbacks
@@ -121,6 +122,7 @@ all() ->
send_discard_1,
send_discard_2,
stop_services,
+ empty,
stop].
%% ===========================================================================
@@ -147,6 +149,10 @@ stop_services(_Config) ->
T <- [diameter:stop_service(H)],
T /= ok].
+%% Ensure transports have been removed from request table.
+empty(_Config) ->
+ [] = ets:tab2list(diameter_request).
+
stop(_Config) ->
ok = diameter:stop().
diff --git a/lib/diameter/test/diameter_gen_sctp_SUITE.erl b/lib/diameter/test/diameter_gen_sctp_SUITE.erl
index 51ccb1e6ec..ced897c714 100644
--- a/lib/diameter/test/diameter_gen_sctp_SUITE.erl
+++ b/lib/diameter/test/diameter_gen_sctp_SUITE.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -119,10 +119,10 @@ send_not_from_controlling_process(_) ->
send_not_from_controlling_process() ->
FPid = self(),
- {L, MRef} = spawn_monitor(fun() -> listen(FPid) end),%% listening process
+ {L, MRef} = spawn_monitor(fun() -> listen(FPid) end),
receive
{?MODULE, C, S} ->
- erlang:demonitor(MRef, [flush]),
+ demonitor(MRef, [flush]),
[L,C,S];
{'DOWN', MRef, process, _, _} = T ->
error(T)
@@ -137,13 +137,7 @@ listen(FPid) ->
LPid = self(),
spawn(fun() -> connect1(PortNr, FPid, LPid) end), %% connecting process
Id = assoc(Sock),
- ?SCTP(Sock, {[#sctp_sndrcvinfo{assoc_id = Id}], _Bin})
- = recv(). %% Waits with this as current_function.
-
-%% recv/0
-
-recv() ->
- receive T -> T end.
+ recv(Sock, Id).
%% connect1/3
@@ -154,7 +148,7 @@ connect1(PortNr, FPid, LPid) ->
FPid ! {?MODULE,
self(),
spawn(fun() -> send(Sock, Id) end)}, %% sending process
- MRef = erlang:monitor(process, LPid),
+ MRef = monitor(process, LPid),
down(MRef). %% Waits with this as current_function.
%% down/1
@@ -277,7 +271,8 @@ acc(N, Acc) ->
loop(Sock, MRef, Bin) ->
receive
- ?SCTP(Sock, {[#sctp_sndrcvinfo{assoc_id = Id}], B}) ->
+ ?SCTP(Sock, {[#sctp_sndrcvinfo{assoc_id = Id}], B})
+ when is_binary(B) ->
Sz = size(Bin),
{Sz, Bin} = {size(B), B}, %% assert
ok = send(Sock, Id, mark(Bin)),
@@ -291,7 +286,7 @@ loop(Sock, MRef, Bin) ->
%% connect2/3
connect2(Pid, PortNr, Bin) ->
- erlang:monitor(process, Pid),
+ monitor(process, Pid),
{ok, Sock} = open(),
ok = gen_sctp:connect_init(Sock, ?ADDR, PortNr, []),
@@ -305,15 +300,21 @@ connect2(Pid, PortNr, Bin) ->
ok = send(Sock, Id, Bin),
T2 = unmark(recv(Sock, Id)),
T3 = now(),
- {timer:now_diff(T2, T1), timer:now_diff(T3, T2)}. %% {Outbound, Inbound}
+ {timer:now_diff(T2, T1), %% Outbound
+ timer:now_diff(T3, T2)}. %% Inbound
%% recv/2
recv(Sock, Id) ->
receive
- ?SCTP(Sock, {[#sctp_sndrcvinfo{assoc_id = Id}], Bin}) ->
+ ?SCTP(Sock, {[#sctp_sndrcvinfo{assoc_id = I}], Bin})
+ when is_binary(Bin) ->
+ Id = I, %% assert
Bin;
- T -> %% eg. 'DOWN'
+ ?SCTP(S, _) ->
+ Sock = S, %% assert
+ recv(Sock, Id);
+ T ->
exit(T)
end.
diff --git a/lib/diameter/test/diameter_gen_tcp_SUITE.erl b/lib/diameter/test/diameter_gen_tcp_SUITE.erl
index 7e232edb44..4b542e0156 100644
--- a/lib/diameter/test/diameter_gen_tcp_SUITE.erl
+++ b/lib/diameter/test/diameter_gen_tcp_SUITE.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2013. All Rights Reserved.
+%% Copyright Ericsson AB 2014-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -18,10 +18,10 @@
%%
%%
-%% Some gen_sctp-specific tests demonstrating problems that were
+%% Some gen_tcp-specific tests demonstrating problems that were
%% encountered during diameter development but have nothing
-%% specifically to do with diameter. At least one of them can cause
-%% diameter_traffic_SUITE testcases to fail.
+%% specifically to do with diameter. These can cause testcases in
+%% other suites to fail.
%%
-module(diameter_gen_tcp_SUITE).
@@ -30,7 +30,8 @@
all/0]).
%% testcases
--export([send_long/1]).
+-export([send_long/1,
+ connect/1]).
-define(LOOPBACK, {127,0,0,1}).
-define(GEN_OPTS, [binary, {active, true}, {ip, ?LOOPBACK}]).
@@ -41,7 +42,8 @@ suite() ->
[{timetrap, {minutes, 2}}].
all() ->
- [send_long].
+ [connect, %% Appears to fail only when run first.
+ send_long].
%% ===========================================================================
@@ -87,15 +89,6 @@ connect(PortNr, LPid) ->
LPid ! {self(), fun(B) -> send(Sock, B) end},
down(LPid).
-%% down/1
-
-down(Pid)
- when is_pid(Pid) ->
- down(erlang:monitor(process, Pid));
-
-down(MRef) ->
- receive {'DOWN', MRef, process, _, Reason} -> Reason end.
-
%% send/2
%%
%% Send from a spawned process just to avoid sending from the
@@ -104,3 +97,47 @@ down(MRef) ->
send(Sock, Bin) ->
{_, MRef} = spawn_monitor(fun() -> exit(gen_tcp:send(Sock, Bin)) end),
down(MRef).
+
+%% ===========================================================================
+
+%% connect/1
+%%
+%% Test that simultaneous connections succeed. This fails sporadically
+%% on OS X at the time of writing, when gen_tcp:connect/2 returns
+%% {error, econnreset}.
+
+connect(_) ->
+ {ok, LSock} = gen_tcp:listen(0, ?GEN_OPTS),
+ {ok, {_,PortNr}} = inet:sockname(LSock),
+ Count = lists:seq(1,8), %% 8 simultaneous connects
+ As = [gen_accept(LSock) || _ <- Count],
+ %% Wait for spawned processes to have called gen_tcp:accept/1
+ %% (presumably).
+ receive after 2000 -> ok end,
+ Cs = [gen_connect(PortNr) || _ <- Count],
+ [] = failures(Cs),
+ [] = failures(As).
+
+failures(Monitors) ->
+ [RC || {_, MRef} <- Monitors, RC <- [down(MRef)], ok /= element(1, RC)].
+
+gen_accept(LSock) ->
+ spawn_monitor(fun() ->
+ exit(gen_tcp:accept(LSock))
+ end).
+
+gen_connect(PortNr) ->
+ spawn_monitor(fun() ->
+ exit(gen_tcp:connect(?LOOPBACK, PortNr, ?GEN_OPTS))
+ end).
+
+%% ===========================================================================
+
+%% down/1
+
+down(Pid)
+ when is_pid(Pid) ->
+ down(monitor(process, Pid));
+
+down(MRef) ->
+ receive {'DOWN', MRef, process, _, Reason} -> Reason end.
diff --git a/lib/diameter/test/diameter_pool_SUITE.erl b/lib/diameter/test/diameter_pool_SUITE.erl
new file mode 100644
index 0000000000..a59cd66a2e
--- /dev/null
+++ b/lib/diameter/test/diameter_pool_SUITE.erl
@@ -0,0 +1,133 @@
+%%
+%% %CopyrightBegin%
+%%
+%% Copyright Ericsson AB 2015. All Rights Reserved.
+%%
+%% The contents of this file are subject to the Erlang Public License,
+%% Version 1.1, (the "License"); you may not use this file except in
+%% compliance with the License. You should have received a copy of the
+%% Erlang Public License along with this software. If not, it can be
+%% retrieved online at http://www.erlang.org/.
+%%
+%% Software distributed under the License is distributed on an "AS IS"
+%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
+%% the License for the specific language governing rights and limitations
+%% under the License.
+%%
+%% %CopyrightEnd%
+%%
+
+%%
+%% Test of the pool_size option in connecting nodes with multiple
+%% connections.
+%%
+
+-module(diameter_pool_SUITE).
+
+-export([suite/0,
+ all/0,
+ init_per_testcase/2,
+ end_per_testcase/2,
+ init_per_suite/1,
+ end_per_suite/1]).
+
+%% testcases
+-export([tcp_connect/1,
+ sctp_connect/1,
+ any_connect/1]).
+
+%% ===========================================================================
+
+-define(util, diameter_util).
+
+%% Config for diameter:start_service/2.
+-define(SERVICE(Host),
+ [{'Origin-Host', Host ++ ".ericsson.com"},
+ {'Origin-Realm', "ericsson.com"},
+ {'Host-IP-Address', [{127,0,0,1}]},
+ {'Vendor-Id', 12345},
+ {'Product-Name', "OTP/diameter"},
+ {'Auth-Application-Id', [0]}, %% common
+ {'Acct-Application-Id', [3]}, %% accounting
+ {restrict_connections, false},
+ {application, [{alias, common},
+ {dictionary, diameter_gen_base_rfc6733},
+ {module, diameter_callback}]},
+ {application, [{alias, accounting},
+ {dictionary, diameter_gen_acct_rfc6733},
+ {module, diameter_callback}]}]).
+
+%% ===========================================================================
+
+suite() ->
+ [{timetrap, {seconds, 30}}].
+
+all() ->
+ [tcp_connect,
+ sctp_connect,
+ any_connect].
+
+init_per_testcase(_Name, Config) ->
+ Config.
+
+end_per_testcase(_Name, _Config) ->
+ diameter:stop().
+
+init_per_suite(Config) ->
+ [{sctp, ?util:have_sctp()} | Config].
+
+end_per_suite(_Config) ->
+ ok.
+
+%% ===========================================================================
+
+tcp_connect(_Config) ->
+ connect(tcp, tcp).
+
+sctp_connect(Config) ->
+ case lists:member({sctp, true}, Config) of
+ true -> connect(sctp, sctp);
+ false -> {skip, no_sctp}
+ end.
+
+any_connect(_Config) ->
+ connect(any, tcp).
+
+%% connect/2
+
+%% Establish multiple connections between a client and server.
+connect(ClientProt, ServerProt) ->
+ ok = diameter:start(),
+ [] = [{S,T} || S <- ["server", "client"],
+ T <- [diameter:start_service(S, ?SERVICE(S))],
+ T /= ok],
+ %% Listen with a single transport with pool_size = 4. Ensure the
+ %% expected number of transport processes are started.
+ LRef = ?util:listen("server", ServerProt, [{pool_size, 4}]),
+ {4,0} = count("server", LRef, accept), %% 4 transports, no connections
+ %% Establish 5 connections.
+ Ref = ?util:connect("client", ClientProt, LRef, [{pool_size, 5}]),
+ {5,5} = count("client", Ref, pool), %% 5 connections
+ %% Ensure the server has started replacement transports within a
+ %% reasonable time. Sleepsince there's no guarantee the
+ %% replacements have been started before the client has received
+ %% 'up' events. (Although it's likely.)
+ sleep(),
+ {9,5} = count("server", LRef, accept), %% 5 connections + 4 accepting
+ %% Ensure ther are still the expected number of accepting transports
+ %% after stopping the client service.
+ ok = diameter:stop_service("client"),
+ sleep(),
+ {4,0} = count("server", LRef, accept), %% 4 transports, no connections
+ %% Done.
+ ok = diameter:stop_service("server").
+
+count(Name, Ref, Key) ->
+ [{transport, [[{ref, Ref} | T]]},
+ {connections, Cs}]
+ = diameter:service_info(Name, [transport, connections]),
+ {Key, Ps} = lists:keyfind(Key, 1, T),
+ {length(Ps), length(Cs)}. %% number of processes, connections
+
+sleep() ->
+ receive after 1000 -> ok end.
diff --git a/lib/diameter/test/diameter_relay_SUITE.erl b/lib/diameter/test/diameter_relay_SUITE.erl
index 735a908d97..5f7837e879 100644
--- a/lib/diameter/test/diameter_relay_SUITE.erl
+++ b/lib/diameter/test/diameter_relay_SUITE.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -49,6 +49,7 @@
send_timeout_1/1,
send_timeout_2/1,
info/1,
+ counters/1,
disconnect/1,
stop_services/1,
stop/1]).
@@ -120,6 +121,7 @@ all() ->
start_services,
connect,
{group, all},
+ counters,
{group, all, [parallel]},
disconnect,
stop_services,
@@ -201,8 +203,8 @@ send3(_Config) ->
send4(_Config) ->
call(?SERVER4).
-%% Send an ASR that loops between the relays and expect the loop to
-%% be detected.
+%% Send an ASR that loops between the relays (RELAY1 -> RELAY2 ->
+%% RELAY1) and expect the loop to be detected.
send_loop(_Config) ->
Req = ['ASR', {'Destination-Realm', realm(?SERVER1)},
{'Destination-Host', ?SERVER1},
@@ -227,8 +229,103 @@ send_timeout(Tmo) ->
call(Req, [{filter, realm}, {timeout, Tmo}]).
info(_Config) ->
+ %% Wait for RELAY1 to have answered all requests, so that the
+ %% suite doesn't end before all answers are sent and counted.
+ receive after 6000 -> ok end,
[] = ?util:info().
+counters(_Config) ->
+ [] = ?util:run([[fun counters/2, K, S]
+ || K <- [statistics, transport, connections],
+ S <- ?SERVICES]).
+
+counters(Key, Svc) ->
+ counters(Key, Svc, [_|_] = diameter:service_info(Svc, Key)).
+
+counters(statistics, Svc, Stats) ->
+ stats(Svc, lists:foldl(fun({K,N},D) -> orddict:update_counter(K, N, D) end,
+ orddict:new(),
+ lists:append([L || {P,L} <- Stats, is_pid(P)])));
+
+counters(_, _, _) ->
+ todo.
+
+stats(?CLIENT, L) ->
+ [{{{0,257,0},recv},2}, %% CEA
+ {{{0,257,1},send},2}, %% CER
+ {{{0,258,0},recv},1}, %% RAA (send_timeout_1)
+ {{{0,258,1},send},2}, %% RAR (send_timeout_[12])
+ {{{0,274,0},recv},1}, %% ASA (send_loop)
+ {{{0,274,1},send},1}, %% ASR (send_loop)
+ {{{0,275,0},recv},4}, %% STA (send[1-4])
+ {{{0,275,1},send},4}, %% STR (send[1-4])
+ {{{unknown,0},recv,discarded},1}, %% RAR (send_timeout_2)
+ {{{0,257,0},recv,{'Result-Code',2001}},2}, %% CEA
+ {{{0,258,0},recv,{'Result-Code',3002}},1}, %% RAA (send_timeout_1)
+ {{{0,274,0},recv,{'Result-Code',3005}},1}, %% ASA (send_loop)
+ {{{0,275,0},recv,{'Result-Code',2001}},4}] %% STA (send[1-4])
+ = L;
+
+stats(S, L)
+ when S == ?SERVER1;
+ S == ?SERVER2;
+ S == ?SERVER3;
+ S == ?SERVER4 ->
+ [{{{0,257,0},send},1}, %% CEA
+ {{{0,257,1},recv},1}, %% CER
+ {{{0,275,0},send},1}, %% STA (send[1-4])
+ {{{0,275,1},recv},1}, %% STR (send[1-4])
+ {{{0,257,0},send,{'Result-Code',2001}},1}, %% CEA
+ {{{0,275,0},send,{'Result-Code',2001}},1}] %% STA (send[1-4])
+ = L;
+
+stats(?RELAY1, L) ->
+ [{{{relay,0},recv},3}, %% STA x 2 (send[12])
+ %% ASA (send_loop)
+ {{{relay,0},send},6}, %% STA x 2 (send[12])
+ %% ASA x 2 (send_loop)
+ %% RAA x 2 (send_timeout_[12])
+ {{{relay,1},recv},6}, %% STR x 2 (send[12])
+ %% ASR x 2 (send_loop)
+ %% RAR x 2 (send_timeout_[12])
+ {{{relay,1},send},5}, %% STR x 2 (send[12])
+ %% ASR (send_loop)
+ %% RAR x 2 (send_timeout_[12])
+ {{{0,257,0},recv},3}, %% CEA
+ {{{0,257,0},send},1}, %% "
+ {{{0,257,1},recv},1}, %% CER
+ {{{0,257,1},send},3}, %% "
+ {{{relay,0},recv,{'Result-Code',2001}},2}, %% STA x 2 (send[34])
+ {{{relay,0},recv,{'Result-Code',3005}},1}, %% ASA (send_loop)
+ {{{relay,0},send,{'Result-Code',2001}},2}, %% STA x 2 (send[34])
+ {{{relay,0},send,{'Result-Code',3002}},2}, %% RAA (send_timeout_[12])
+ {{{relay,0},send,{'Result-Code',3005}},2}, %% ASA (send_loop)
+ {{{0,257,0},recv,{'Result-Code',2001}},3}, %% CEA
+ {{{0,257,0},send,{'Result-Code',2001}},1}] %% "
+ = L;
+
+stats(?RELAY2, L) ->
+ [{{{relay,0},recv},3}, %% STA x 2 (send[34])
+ %% ASA (send_loop)
+ {{{relay,0},send},3}, %% STA x 2 (send[34])
+ %% ASA (send_loop)
+ {{{relay,1},recv},5}, %% STR x 2 (send[34])
+ %% RAR x 2 (send_timeout_[12])
+ %% ASR (send_loop)
+ {{{relay,1},send},3}, %% STR x 2 (send[34])
+ %% ASR (send_loop)
+ {{{0,257,0},recv},2}, %% CEA
+ {{{0,257,0},send},2}, %% "
+ {{{0,257,1},recv},2}, %% CER
+ {{{0,257,1},send},2}, %% "
+ {{{relay,0},recv,{'Result-Code',2001}},2}, %% STA x 2 (send[34])
+ {{{relay,0},recv,{'Result-Code',3005}},1}, %% ASA (send_loop)
+ {{{relay,0},send,{'Result-Code',2001}},2}, %% STA x 2 (send[34])
+ {{{relay,0},send,{'Result-Code',3005}},1}, %% ASA (send_loop)
+ {{{0,257,0},recv,{'Result-Code',2001}},2}, %% CEA
+ {{{0,257,0},send,{'Result-Code',2001}},2}] %% "
+ = L.
+
%% ===========================================================================
realm(Host) ->
@@ -236,13 +333,39 @@ realm(Host) ->
call(Server) ->
Realm = realm(Server),
+ %% Include some arbitrary AVPs to exercise encode/decode, that
+ %% are received back in the STA.
+ Avps = [#diameter_avp{code = 111,
+ data = [#diameter_avp{code = 222,
+ data = <<222:24>>},
+ #diameter_avp{code = 333,
+ data = <<333:16>>}]},
+ #diameter_avp{code = 444,
+ data = <<444:24>>},
+ #diameter_avp{code = 555,
+ data = [#diameter_avp{code = 666,
+ data = [#diameter_avp
+ {code = 777,
+ data = <<7>>}]},
+ #diameter_avp{code = 888,
+ data = <<8>>},
+ #diameter_avp{code = 999,
+ data = <<9>>}]}],
+
Req = ['STR', {'Destination-Realm', Realm},
{'Destination-Host', [Server]},
{'Termination-Cause', ?LOGOUT},
- {'Auth-Application-Id', ?APP_ID}],
+ {'Auth-Application-Id', ?APP_ID},
+ {'AVP', Avps}],
+
#diameter_base_STA{'Result-Code' = ?SUCCESS,
'Origin-Host' = Server,
- 'Origin-Realm' = Realm}
+ 'Origin-Realm' = Realm,
+ %% Unknown AVPs can't be decoded as Grouped since
+ %% types aren't known.
+ 'AVP' = [#diameter_avp{code = 111},
+ #diameter_avp{code = 444},
+ #diameter_avp{code = 555}]}
= call(Req, [{filter, realm}]).
call(Req, Opts) ->
@@ -303,18 +426,24 @@ handle_request(Pkt, OH, {_Ref, #diameter_caps{origin_host = {OH,_}} = Caps})
when OH /= ?CLIENT ->
request(Pkt, Caps).
-%% RELAY1 routes any ASR or RAR to RELAY2 ...
+%% RELAY1 answers ACR after it's timed out at the client.
+request(#diameter_packet{header = #diameter_header{cmd_code = 271}},
+ #diameter_caps{origin_host = {?RELAY1, _}}) ->
+ receive after 1000 -> {answer_message, 3004} end; %% TOO_BUSY
+
+%% RELAY1 routes any ASR or RAR to RELAY2.
request(#diameter_packet{header = #diameter_header{cmd_code = C}},
#diameter_caps{origin_host = {?RELAY1, _}})
when C == 274; %% ASR
C == 258 -> %% RAR
{relay, [{filter, {realm, realm(?RELAY2)}}]};
-%% ... which in turn routes it back. Expect diameter to either answer
-%% either with DIAMETER_LOOP_DETECTED/DIAMETER_UNABLE_TO_COMPLY.
+%% RELAY2 routes ASR back to RELAY1 to induce DIAMETER_LOOP_DETECTED.
request(#diameter_packet{header = #diameter_header{cmd_code = 274}},
#diameter_caps{origin_host = {?RELAY2, _}}) ->
{relay, [{filter, {host, ?RELAY1}}]};
+
+%% RELAY2 discards RAR to induce DIAMETER_UNABLE_TO_DELIVER.
request(#diameter_packet{header = #diameter_header{cmd_code = 258}},
#diameter_caps{origin_host = {?RELAY2, _}}) ->
discard;
@@ -330,9 +459,18 @@ request(_Pkt, #diameter_caps{origin_host = {OH, _}})
request(#diameter_packet{msg = #diameter_base_STR{'Session-Id' = SId,
'Origin-Host' = Host,
'Origin-Realm' = Realm,
- 'Route-Record' = Route}},
+ 'Route-Record' = Route,
+ 'AVP' = Avps}},
#diameter_caps{origin_host = {OH, _},
origin_realm = {OR, _}}) ->
+
+ %% Payloads of unknown AVPs aren't decoded, so we don't know that
+ %% some types here are Grouped.
+ [#diameter_avp{code = 111, vendor_id = undefined},
+ #diameter_avp{code = 444, vendor_id = undefined, data = <<444:24>>},
+ #diameter_avp{code = 555, vendor_id = undefined}]
+ = Avps,
+
%% The request should have the Origin-Host/Realm of the original
%% sender.
R = realm(?CLIENT),
@@ -343,4 +481,5 @@ request(#diameter_packet{msg = #diameter_base_STR{'Session-Id' = SId,
{reply, #diameter_base_STA{'Result-Code' = ?SUCCESS,
'Session-Id' = SId,
'Origin-Host' = OH,
- 'Origin-Realm' = OR}}.
+ 'Origin-Realm' = OR,
+ 'AVP' = Avps}}.
diff --git a/lib/diameter/test/diameter_stats_SUITE.erl b/lib/diameter/test/diameter_stats_SUITE.erl
index 76ff764671..b08d7a05d2 100644
--- a/lib/diameter/test/diameter_stats_SUITE.erl
+++ b/lib/diameter/test/diameter_stats_SUITE.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -95,7 +95,7 @@ read(_) ->
7 = ?stat:incr(C1, Ref, 7),
Self = self(),
[{Ref, [{C1,7}]}, {Self, [{C1,2}, {C2,1}]}]
- = lists:sort(?stat:read([self(), Ref, make_ref()])),
+ = ?stat:read([self(), Ref, make_ref()]),
[] = ?stat:read([]),
[] = ?stat:read([make_ref()]),
?stat:flush([self(), Ref, make_ref()]).
@@ -115,7 +115,7 @@ sum(_) ->
[{Self, [{C1,1}, {C2,2}]}]
= ?stat:sum([self()]),
[{Ref, [{C1,7}]}, {Self, [{C1,1}, {C2,2}]}]
- = lists:sort(?stat:flush([self(), Ref])).
+ = ?stat:flush([self(), Ref]).
flush(_) ->
Ref = make_ref(),
diff --git a/lib/diameter/test/diameter_tls_SUITE.erl b/lib/diameter/test/diameter_tls_SUITE.erl
index 55565692ec..e5bbda9c91 100644
--- a/lib/diameter/test/diameter_tls_SUITE.erl
+++ b/lib/diameter/test/diameter_tls_SUITE.erl
@@ -319,19 +319,19 @@ make_cert(Dir, Base) ->
make_cert(Dir, Base ++ "_key.pem", Base ++ "_ca.pem").
make_cert(Dir, Keyfile, Certfile) ->
- [K,C] = Paths = [filename:join([Dir, F]) || F <- [Keyfile, Certfile]],
+ [KP,CP] = [filename:join([Dir, F]) || F <- [Keyfile, Certfile]],
- KCmd = join(["openssl genrsa -out", K, "2048"]),
- CCmd = join(["openssl req -new -x509 -key", K, "-out", C, "-days 7",
- "-subj /C=SE/ST=./L=Stockholm/CN=www.erlang.org"]),
+ KC = join(["openssl genrsa -out", KP, "2048"]),
+ CC = join(["openssl req -new -x509 -key", KP, "-out", CP, "-days 7",
+ "-subj /C=SE/ST=./L=Stockholm/CN=www.erlang.org"]),
%% Hope for the best and only check that files are written.
- os:cmd(KCmd),
- os:cmd(CCmd),
+ [{_, _, {ok,_}},{_, _, {ok,_}}]
+ = [{P,O,T} || {P,C} <- [{KP,KC}, {CP,CC}],
+ O <- [os:cmd(C)],
+ T <- [file:read_file_info(P)]],
- [_,_] = [T || P <- Paths, {ok, T} <- [file:read_file_info(P)]],
-
- {K,C}.
+ {KP,CP}.
join(Strs) ->
string:join(Strs, " ").
diff --git a/lib/diameter/test/diameter_traffic_SUITE.erl b/lib/diameter/test/diameter_traffic_SUITE.erl
index a97c54fc04..76e939f272 100644
--- a/lib/diameter/test/diameter_traffic_SUITE.erl
+++ b/lib/diameter/test/diameter_traffic_SUITE.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -41,10 +41,14 @@
send_eval/1,
send_bad_answer/1,
send_protocol_error/1,
+ send_experimental_result/1,
send_arbitrary/1,
send_unknown/1,
+ send_unknown_short/1,
send_unknown_mandatory/1,
+ send_unknown_short_mandatory/1,
send_noreply/1,
+ send_grouped_error/1,
send_unsupported/1,
send_unsupported_app/1,
send_error_bit/1,
@@ -54,8 +58,10 @@
send_zero_avp_length/1,
send_invalid_avp_length/1,
send_invalid_reject/1,
- send_unrecognized_mandatory/1,
+ send_unexpected_mandatory_decode/1,
+ send_unexpected_mandatory/1,
send_long/1,
+ send_maxlen/1,
send_nopeer/1,
send_noapp/1,
send_discard/1,
@@ -119,8 +125,6 @@
-define(ADDR, {127,0,0,1}).
--define(CLIENT, "CLIENT").
--define(SERVER, "SERVER").
-define(REALM, "erlang.org").
-define(HOST(Host, Realm), Host ++ [$.|Realm]).
@@ -138,11 +142,23 @@
%% Which common dictionary to use in the clients.
-define(RFCS, [rfc3588, rfc6733]).
+%% Whether to decode stringish Diameter types to strings, or leave
+%% them as binary.
+-define(STRING_DECODES, [true, false]).
+
+%% Which transport protocol to use.
+-define(TRANSPORTS, [tcp, sctp]).
+
-record(group,
- {client_encoding,
+ {transport,
+ client_service,
+ client_encoding,
client_dict0,
+ client_strings,
+ server_service,
server_encoding,
- server_container}).
+ server_container,
+ server_strings}).
%% Not really what we should be setting unless the message is sent in
%% the common application but diameter doesn't care.
@@ -163,7 +179,7 @@
?answer_message(_, ResultCode)).
%% Config for diameter:start_service/2.
--define(SERVICE(Name),
+-define(SERVICE(Name, Decode),
[{'Origin-Host', Name ++ "." ++ ?REALM},
{'Origin-Realm', ?REALM},
{'Host-IP-Address', [?ADDR]},
@@ -172,6 +188,8 @@
{'Auth-Application-Id', [?DIAMETER_APP_ID_COMMON]},
{'Acct-Application-Id', [?DIAMETER_APP_ID_ACCOUNTING]},
{restrict_connections, false},
+ {string_decode, Decode},
+ {incoming_maxlen, 1 bsl 21},
{spawn_opt, [{min_heap_size, 5000}]}
| [{application, [{dictionary, D},
{module, ?MODULE},
@@ -221,37 +239,78 @@
%% ===========================================================================
suite() ->
- [{timetrap, {seconds, 60}}].
+ [{timetrap, {seconds, 10}}].
all() ->
- [start, start_services, add_transports, result_codes]
- ++ [{group, ?util:name([R,D,A,C]), P} || R <- ?ENCODINGS,
- D <- ?RFCS,
- A <- ?ENCODINGS,
- C <- ?CONTAINERS,
- P <- [[], [parallel]]]
- ++ [outstanding, remove_transports, empty, stop_services, stop].
+ [start, result_codes, {group, traffic}, outstanding, empty, stop].
groups() ->
Ts = tc(),
- [{?util:name([R,D,A,C]), [], Ts} || R <- ?ENCODINGS,
- D <- ?RFCS,
- A <- ?ENCODINGS,
- C <- ?CONTAINERS].
+ Sctp = ?util:have_sctp(),
+ [{?util:name([R,D,A,C]), [parallel], Ts} || R <- ?ENCODINGS,
+ D <- ?RFCS,
+ A <- ?ENCODINGS,
+ C <- ?CONTAINERS]
+ ++
+ [{?util:name([T,R,D,A,C,SD,CD]),
+ [],
+ [start_services,
+ add_transports,
+ result_codes,
+ {group, ?util:name([R,D,A,C])},
+ remove_transports,
+ stop_services]}
+ || T <- ?TRANSPORTS,
+ T /= sctp orelse Sctp,
+ R <- ?ENCODINGS,
+ D <- ?RFCS,
+ A <- ?ENCODINGS,
+ C <- ?CONTAINERS,
+ SD <- ?STRING_DECODES,
+ CD <- ?STRING_DECODES]
+ ++
+ [{traffic, [parallel], [{group, ?util:name([T,R,D,A,C,SD,CD])}
+ || T <- ?TRANSPORTS,
+ T /= sctp orelse Sctp,
+ R <- ?ENCODINGS,
+ D <- ?RFCS,
+ A <- ?ENCODINGS,
+ C <- ?CONTAINERS,
+ SD <- ?STRING_DECODES,
+ CD <- ?STRING_DECODES]}].
init_per_group(Name, Config) ->
- [R,D,A,C] = ?util:name(Name),
- G = #group{client_encoding = R,
- client_dict0 = dict0(D),
- server_encoding = A,
- server_container = C},
- [{group, G} | Config].
+ case ?util:name(Name) of
+ [T,R,D,A,C,SD,CD] ->
+ G = #group{transport = T,
+ client_service = [$C|?util:unique_string()],
+ client_encoding = R,
+ client_dict0 = dict0(D),
+ client_strings = CD,
+ server_service = [$S|?util:unique_string()],
+ server_encoding = A,
+ server_container = C,
+ server_strings = SD},
+ [{group, G} | Config];
+ _ ->
+ Config
+ end.
end_per_group(_, _) ->
ok.
+%% Skip testcases that can reasonably fail under SCTP.
init_per_testcase(Name, Config) ->
- [{testcase, Name} | Config].
+ case [skip || #group{transport = sctp}
+ <- [proplists:get_value(group, Config)],
+ send_maxlen == Name
+ orelse send_long == Name]
+ of
+ [skip] ->
+ {skip, sctp};
+ [] ->
+ [{testcase, Name} | Config]
+ end.
end_per_testcase(_, _) ->
ok.
@@ -264,10 +323,14 @@ tc() ->
send_eval,
send_bad_answer,
send_protocol_error,
+ send_experimental_result,
send_arbitrary,
send_unknown,
+ send_unknown_short,
send_unknown_mandatory,
+ send_unknown_short_mandatory,
send_noreply,
+ send_grouped_error,
send_unsupported,
send_unsupported_app,
send_error_bit,
@@ -277,8 +340,10 @@ tc() ->
send_zero_avp_length,
send_invalid_avp_length,
send_invalid_reject,
- send_unrecognized_mandatory,
+ send_unexpected_mandatory_decode,
+ send_unexpected_mandatory,
send_long,
+ send_maxlen,
send_nopeer,
send_noapp,
send_discard,
@@ -313,19 +378,29 @@ tc() ->
start(_Config) ->
ok = diameter:start().
-start_services(_Config) ->
- ok = diameter:start_service(?SERVER, ?SERVICE(?SERVER)),
- ok = diameter:start_service(?CLIENT, [{sequence, ?CLIENT_MASK}
- | ?SERVICE(?CLIENT)]).
+start_services(Config) ->
+ #group{client_service = CN,
+ client_strings = CD,
+ server_service = SN,
+ server_strings = SD}
+ = group(Config),
+ ok = diameter:start_service(SN, ?SERVICE(SN, SD)),
+ ok = diameter:start_service(CN, [{sequence, ?CLIENT_MASK}
+ | ?SERVICE(CN, CD)]).
add_transports(Config) ->
- LRef = ?util:listen(?SERVER,
- tcp,
+ #group{transport = T,
+ client_service = CN,
+ server_service = SN}
+ = group(Config),
+ LRef = ?util:listen(SN,
+ T,
[{capabilities_cb, fun capx/2},
+ {pool_size, 8},
{spawn_opt, [{min_heap_size, 8096}]},
{applications, apps(rfc3588)}]),
- Cs = [?util:connect(?CLIENT,
- tcp,
+ Cs = [?util:connect(CN,
+ T,
LRef,
[{id, Id},
{capabilities, [{'Origin-State-Id', origin(Id)}]},
@@ -348,12 +423,18 @@ outstanding(_Config) ->
is_atom(element(1,T))].
remove_transports(Config) ->
+ #group{client_service = CN,
+ server_service = SN}
+ = group(Config),
[LRef | Cs] = ?util:read_priv(Config, "transport"),
- [?util:disconnect(?CLIENT, C, ?SERVER, LRef) || C <- Cs].
+ [?util:disconnect(CN, C, SN, LRef) || C <- Cs].
-stop_services(_Config) ->
- ok = diameter:stop_service(?CLIENT),
- ok = diameter:stop_service(?SERVER).
+stop_services(Config) ->
+ #group{client_service = CN,
+ server_service = SN}
+ = group(Config),
+ ok = diameter:stop_service(CN),
+ ok = diameter:stop_service(SN).
%% Ensure even transports have been removed from request table.
empty(_Config) ->
@@ -388,7 +469,7 @@ send_ok(Config) ->
Req = ['ACR', {'Accounting-Record-Type', ?EVENT_RECORD},
{'Accounting-Record-Number', 1}],
- ['ACA', _SessionId, {'Result-Code', ?SUCCESS} | _]
+ ['ACA', {'Session-Id', _}, {'Result-Code', ?SUCCESS} | _]
= call(Config, Req).
%% Send an accounting ACR that the server answers badly to.
@@ -404,16 +485,17 @@ send_eval(Config) ->
Req = ['ACR', {'Accounting-Record-Type', ?EVENT_RECORD},
{'Accounting-Record-Number', 3}],
- ['ACA', _SessionId, {'Result-Code', ?SUCCESS} | _]
+ ['ACA', {'Session-Id', _}, {'Result-Code', ?SUCCESS} | _]
= call(Config, Req).
%% Send an accounting ACR that the server tries to answer with an
-%% inappropriate header, resulting in no answer being sent and the
-%% request timing out.
+%% inappropriate header. That the error is detected is coded in
+%% handle_answer.
send_bad_answer(Config) ->
Req = ['ACR', {'Accounting-Record-Type', ?EVENT_RECORD},
{'Accounting-Record-Number', 2}],
- {timeout, _} = call(Config, Req).
+ ?answer_message(?SUCCESS)
+ = call(Config, Req).
%% Send an ACR that the server callback answers explicitly with a
%% protocol error.
@@ -424,35 +506,62 @@ send_protocol_error(Config) ->
?answer_message(?TOO_BUSY)
= call(Config, Req).
+%% Send a 3xxx Experimental-Result in an answer not setting the E-bit
+%% and missing a Result-Code.
+send_experimental_result(Config) ->
+ Req = ['ACR', {'Accounting-Record-Type', ?EVENT_RECORD},
+ {'Accounting-Record-Number', 5}],
+ ['ACA', {'Session-Id', _} | _]
+ = call(Config, Req).
+
%% Send an ASR with an arbitrary non-mandatory AVP and expect success
%% and the same AVP in the reply.
send_arbitrary(Config) ->
Req = ['ASR', {'AVP', [#diameter_avp{name = 'Product-Name',
value = "XXX"}]}],
- ['ASA', _SessionId, {'Result-Code', ?SUCCESS} | Avps]
+ ['ASA', {'Session-Id', _}, {'Result-Code', ?SUCCESS} | Avps]
= call(Config, Req),
{'AVP', [#diameter_avp{name = 'Product-Name',
- value = "XXX"}]}
- = lists:last(Avps).
+ value = V}]}
+ = lists:last(Avps),
+ "XXX" = string(V, Config).
%% Send an unknown AVP (to some client) and check that it comes back.
send_unknown(Config) ->
Req = ['ASR', {'AVP', [#diameter_avp{code = 999,
is_mandatory = false,
data = <<17>>}]}],
- ['ASA', _SessionId, {'Result-Code', ?SUCCESS} | Avps]
+ ['ASA', {'Session-Id', _}, {'Result-Code', ?SUCCESS} | Avps]
= call(Config, Req),
{'AVP', [#diameter_avp{code = 999,
is_mandatory = false,
data = <<17>>}]}
= lists:last(Avps).
+%% Ditto, and point the AVP length past the end of the message. Expect
+%% 5014.
+send_unknown_short(Config) ->
+ send_unknown_short(Config, false, ?INVALID_AVP_LENGTH).
+
+send_unknown_short(Config, M, RC) ->
+ Req = ['ASR', {'AVP', [#diameter_avp{code = 999,
+ is_mandatory = M,
+ data = <<17>>}]}],
+ ['ASA', {'Session-Id', _}, {'Result-Code', RC} | Avps]
+ = call(Config, Req),
+ [#'diameter_base_Failed-AVP'{'AVP' = As}]
+ = proplists:get_value('Failed-AVP', Avps),
+ [#diameter_avp{code = 999,
+ is_mandatory = M,
+ data = <<17, _/binary>>}] %% extra bits from padding
+ = As.
+
%% Ditto but set the M flag.
send_unknown_mandatory(Config) ->
Req = ['ASR', {'AVP', [#diameter_avp{code = 999,
is_mandatory = true,
data = <<17>>}]}],
- ['ASA', _SessionId, {'Result-Code', ?AVP_UNSUPPORTED} | Avps]
+ ['ASA', {'Session-Id', _}, {'Result-Code', ?AVP_UNSUPPORTED} | Avps]
= call(Config, Req),
[#'diameter_base_Failed-AVP'{'AVP' = As}]
= proplists:get_value('Failed-AVP', Avps),
@@ -461,6 +570,46 @@ send_unknown_mandatory(Config) ->
data = <<17>>}]
= As.
+%% Ditto, and point the AVP length past the end of the message. Expect
+%% 5014 instead of 5001.
+send_unknown_short_mandatory(Config) ->
+ send_unknown_short(Config, true, ?INVALID_AVP_LENGTH).
+
+%% Send an ASR containing an unexpected mandatory Session-Timeout.
+%% Expect 5001, and check that the value in Failed-AVP was decoded.
+send_unexpected_mandatory_decode(Config) ->
+ Req = ['ASR', {'AVP', [#diameter_avp{code = 27, %% Session-Timeout
+ is_mandatory = true,
+ data = <<12:32>>}]}],
+ ['ASA', {'Session-Id', _}, {'Result-Code', ?AVP_UNSUPPORTED} | Avps]
+ = call(Config, Req),
+ [#'diameter_base_Failed-AVP'{'AVP' = As}]
+ = proplists:get_value('Failed-AVP', Avps),
+ [#diameter_avp{code = 27,
+ is_mandatory = true,
+ value = 12,
+ data = <<12:32>>}]
+ = As.
+
+%% Send an containing a faulty Grouped AVP (empty Proxy-Host in
+%% Proxy-Info) and expect that only the faulty AVP is sent in
+%% Failed-AVP. The encoded values of Proxy-Host and Proxy-State are
+%% swapped in prepare_request since an empty Proxy-Host is an encode
+%% error.
+send_grouped_error(Config) ->
+ Req = ['ASR', {'Proxy-Info', [[{'Proxy-Host', "abcd"},
+ {'Proxy-State', ""}]]}],
+ ['ASA', {'Session-Id', _}, {'Result-Code', ?INVALID_AVP_LENGTH} | Avps]
+ = call(Config, Req),
+ [#'diameter_base_Failed-AVP'{'AVP' = As}]
+ = proplists:get_value('Failed-AVP', Avps),
+ [#diameter_avp{name = 'Proxy-Info',
+ value = #'diameter_base_Proxy-Info'
+ {'Proxy-Host' = Empty,
+ 'Proxy-State' = undefined}}]
+ = As,
+ <<0>> = iolist_to_binary(Empty).
+
%% Send an STR that the server ignores.
send_noreply(Config) ->
Req = ['STR', {'Termination-Cause', ?BAD_ANSWER}],
@@ -487,7 +636,7 @@ send_error_bit(Config) ->
%% Send a bad version and check that we get 5011.
send_unsupported_version(Config) ->
Req = ['STR', {'Termination-Cause', ?LOGOUT}],
- ['STA', _SessionId, {'Result-Code', ?UNSUPPORTED_VERSION} | _]
+ ['STA', {'Session-Id', _}, {'Result-Code', ?UNSUPPORTED_VERSION} | _]
= call(Config, Req).
%% Send a request containing an AVP length > data size.
@@ -507,14 +656,14 @@ send_zero_avp_length(Config) ->
send_invalid_avp_length(Config) ->
Req = ['STR', {'Termination-Cause', ?LOGOUT}],
- ['STA', _SessionId,
+ ['STA', {'Session-Id', _},
{'Result-Code', ?INVALID_AVP_LENGTH},
- _OriginHost,
- _OriginRealm,
- _UserName,
- _Class,
- _ErrorMessage,
- _ErrorReportingHost,
+ {'Origin-Host', _},
+ {'Origin-Realm', _},
+ {'User-Name', _},
+ {'Class', _},
+ {'Error-Message', _},
+ {'Error-Reporting-Host', _},
{'Failed-AVP', [#'diameter_base_Failed-AVP'{'AVP' = [_]}]}
| _]
= call(Config, Req).
@@ -527,30 +676,38 @@ send_invalid_reject(Config) ->
?answer_message(?TOO_BUSY)
= call(Config, Req).
-%% Send an STR containing a known AVP, but one that's not allowed and
-%% sets the M-bit.
-send_unrecognized_mandatory(Config) ->
+%% Send an STR containing a known AVP, but one that's not expected and
+%% that sets the M-bit.
+send_unexpected_mandatory(Config) ->
Req = ['STR', {'Termination-Cause', ?LOGOUT}],
- ['STA', _SessionId, {'Result-Code', ?AVP_UNSUPPORTED} | _]
+ ['STA', {'Session-Id', _}, {'Result-Code', ?AVP_UNSUPPORTED} | _]
= call(Config, Req).
%% Send something long that will be fragmented by TCP.
send_long(Config) ->
Req = ['STR', {'Termination-Cause', ?LOGOUT},
{'User-Name', [lists:duplicate(1 bsl 20, $X)]}],
- ['STA', _SessionId, {'Result-Code', ?SUCCESS} | _]
+ ['STA', {'Session-Id', _}, {'Result-Code', ?SUCCESS} | _]
= call(Config, Req).
+%% Send something longer than the configure incoming_maxlen.
+send_maxlen(Config) ->
+ Req = ['STR', {'Termination-Cause', ?LOGOUT},
+ {'User-Name', [lists:duplicate(1 bsl 21, $X)]}],
+ {timeout, _} = call(Config, Req).
+
%% Send something for which pick_peer finds no suitable peer.
send_nopeer(Config) ->
Req = ['STR', {'Termination-Cause', ?LOGOUT}],
{error, no_connection} = call(Config, Req, [{extra, [?EXTRA]}]).
%% Send something on an unconfigured application.
-send_noapp(_Config) ->
+send_noapp(Config) ->
+ #group{client_service = CN}
+ = group(Config),
Req = ['STR', {'Termination-Cause', ?LOGOUT}],
- {error, no_connection} = diameter:call(?CLIENT, unknown_alias, Req).
+ {error, no_connection} = diameter:call(CN, unknown_alias, Req).
%% Send something that's discarded by prepare_request.
send_discard(Config) ->
@@ -562,21 +719,26 @@ send_any_1(Config) ->
Req = ['STR', {'Termination-Cause', ?LOGOUT}],
{error, no_connection} = call(Config, Req, [{filter, {any, []}}]).
send_any_2(Config) ->
+ #group{server_service = SN}
+ = group(Config),
Req = ['STR', {'Termination-Cause', ?LOGOUT},
- {'Destination-Host', [?HOST(?SERVER, "unknown.org")]}],
+ {'Destination-Host', [?HOST(SN, "unknown.org")]}],
?answer_message(?UNABLE_TO_DELIVER)
- = call(Config, Req, [{filter, {any, [host, realm]}}]).
+ = call(Config, Req, [{filter, {first, [{all, [host, realm]},
+ realm]}}]).
%% Send with a conjunctive filter.
send_all_1(Config) ->
Req = ['STR', {'Termination-Cause', ?LOGOUT}],
Realm = lists:foldr(fun(C,A) -> [C,A] end, [], ?REALM),
- ['STA', _SessionId, {'Result-Code', ?SUCCESS} | _]
+ ['STA', {'Session-Id', _}, {'Result-Code', ?SUCCESS} | _]
= call(Config, Req, [{filter, {all, [{host, any},
{realm, Realm}]}}]).
send_all_2(Config) ->
+ #group{server_service = SN}
+ = group(Config),
Req = ['STR', {'Termination-Cause', ?LOGOUT},
- {'Destination-Host', [?HOST(?SERVER, "unknown.org")]}],
+ {'Destination-Host', [?HOST(SN, "unknown.org")]}],
{error, no_connection}
= call(Config, Req, [{filter, {all, [host, realm]}}]).
@@ -589,9 +751,8 @@ send_timeout(Config) ->
%% received the Session-Id.
send_error(Config) ->
Req = ['RAR', {'Re-Auth-Request-Type', ?AUTHORIZE_AUTHENTICATE}],
- ?answer_message(SId, ?TOO_BUSY)
- = call(Config, Req),
- true = undefined /= SId.
+ ?answer_message([_], ?TOO_BUSY)
+ = call(Config, Req).
%% Send a request with the detached option and receive it as a message
%% from handle_answer instead.
@@ -600,7 +761,7 @@ send_detach(Config) ->
Ref = make_ref(),
ok = call(Config, Req, [{extra, [{self(), Ref}]}, detach]),
Ans = receive {Ref, T} -> T end,
- ['STA', _SessionId, {'Result-Code', ?SUCCESS} | _]
+ ['STA', {'Session-Id', _}, {'Result-Code', ?SUCCESS} | _]
= Ans.
%% Send a request which can't be encoded and expect {error, encode}.
@@ -609,13 +770,15 @@ send_encode_error(Config) ->
%% Send with filtering and expect success.
send_destination_1(Config) ->
+ #group{server_service = SN}
+ = group(Config),
Req = ['STR', {'Termination-Cause', ?LOGOUT},
- {'Destination-Host', [?HOST(?SERVER, ?REALM)]}],
- ['STA', _SessionId, {'Result-Code', ?SUCCESS} | _]
+ {'Destination-Host', [?HOST(SN, ?REALM)]}],
+ ['STA', {'Session-Id', _}, {'Result-Code', ?SUCCESS} | _]
= call(Config, Req, [{filter, {all, [host, realm]}}]).
send_destination_2(Config) ->
Req = ['STR', {'Termination-Cause', ?LOGOUT}],
- ['STA', _SessionId, {'Result-Code', ?SUCCESS} | _]
+ ['STA', {'Session-Id', _}, {'Result-Code', ?SUCCESS} | _]
= call(Config, Req, [{filter, {all, [host, realm]}}]).
%% Send with filtering on and expect failure when specifying an
@@ -626,8 +789,10 @@ send_destination_3(Config) ->
{error, no_connection}
= call(Config, Req, [{filter, {all, [host, realm]}}]).
send_destination_4(Config) ->
+ #group{server_service = SN}
+ = group(Config),
Req = ['STR', {'Termination-Cause', ?LOGOUT},
- {'Destination-Host', [?HOST(?SERVER, "unknown.org")]}],
+ {'Destination-Host', [?HOST(SN, "unknown.org")]}],
{error, no_connection}
= call(Config, Req, [{filter, {all, [host, realm]}}]).
@@ -639,8 +804,10 @@ send_destination_5(Config) ->
?answer_message(?REALM_NOT_SERVED)
= call(Config, Req).
send_destination_6(Config) ->
+ #group{server_service = SN}
+ = group(Config),
Req = ['STR', {'Termination-Cause', ?LOGOUT},
- {'Destination-Host', [?HOST(?SERVER, "unknown.org")]}],
+ {'Destination-Host', [?HOST(SN, "unknown.org")]}],
?answer_message(?UNABLE_TO_DELIVER)
= call(Config, Req).
@@ -675,7 +842,7 @@ send_bad_filter(Config, F) ->
%% Specify multiple filter options and expect them be conjunctive.
send_multiple_filters_1(Config) ->
Fun = fun(#diameter_caps{}) -> true end,
- ['STA', _SessionId, {'Result-Code', ?SUCCESS} | _]
+ ['STA', {'Session-Id', _}, {'Result-Code', ?SUCCESS} | _]
= send_multiple_filters(Config, [host, {eval, Fun}]).
send_multiple_filters_2(Config) ->
E = {erlang, is_tuple, []},
@@ -686,7 +853,7 @@ send_multiple_filters_3(Config) ->
E2 = {erlang, is_tuple, []},
E3 = {erlang, is_record, [diameter_caps]},
E4 = [{erlang, is_record, []}, diameter_caps],
- ['STA', _SessionId, {'Result-Code', ?SUCCESS} | _]
+ ['STA', {'Session-Id', _}, {'Result-Code', ?SUCCESS} | _]
= send_multiple_filters(Config, [{eval, E} || E <- [E1,E2,E3,E4]]).
send_multiple_filters(Config, Fs) ->
@@ -697,21 +864,36 @@ send_multiple_filters(Config, Fs) ->
%% only the return value from the prepare_request callback being
%% significant.
send_anything(Config) ->
- ['STA', _SessionId, {'Result-Code', ?SUCCESS} | _]
+ ['STA', {'Session-Id', _}, {'Result-Code', ?SUCCESS} | _]
= call(Config, anything).
%% ===========================================================================
+group(Config) ->
+ #group{} = proplists:get_value(group, Config).
+
+string(V, Config) ->
+ #group{client_strings = B} = group(Config),
+ decode(V,B).
+
+decode(S, true)
+ when is_list(S) ->
+ S;
+decode(B, false)
+ when is_binary(B) ->
+ binary_to_list(B).
+
call(Config, Req) ->
call(Config, Req, []).
call(Config, Req, Opts) ->
Name = proplists:get_value(testcase, Config),
- #group{client_encoding = ReqEncoding,
+ #group{client_service = CN,
+ client_encoding = ReqEncoding,
client_dict0 = Dict0}
= Group
- = proplists:get_value(group, Config),
- diameter:call(?CLIENT,
+ = group(Config),
+ diameter:call(CN,
dict(Req, Dict0),
msg(Req, ReqEncoding, Dict0),
[{extra, [{Name, Group}, now()]} | Opts]).
@@ -798,35 +980,38 @@ peer_down(_SvcName, _Peer, State) ->
%% pick_peer/6-7
-pick_peer(Peers, _, ?CLIENT, _State, {Name, Group}, _)
+pick_peer(Peers, _, [$C|_], _State, {Name, Group}, _)
when Name /= send_detach ->
find(Group, Peers).
-pick_peer(_Peers, _, ?CLIENT, _State, {send_nopeer, _}, _, ?EXTRA) ->
+pick_peer(_Peers, _, [$C|_], _State, {send_nopeer, _}, _, ?EXTRA) ->
false;
-pick_peer(Peers, _, ?CLIENT, _State, {send_detach, Group}, _, {_,_}) ->
+pick_peer(Peers, _, [$C|_], _State, {send_detach, Group}, _, {_,_}) ->
find(Group, Peers).
-find(#group{server_encoding = A, server_container = C}, Peers) ->
+find(#group{client_service = CN,
+ server_encoding = A,
+ server_container = C},
+ Peers) ->
Id = {A,C},
- [P] = [P || P <- Peers, id(Id, P)],
+ [P] = [P || P <- Peers, id(Id, P, CN)],
{ok, P}.
-id(Id, {Pid, _Caps}) ->
+id(Id, {Pid, _Caps}, SvcName) ->
[{ref, _}, {type, _}, {options, Opts} | _]
- = diameter:service_info(?CLIENT, Pid),
+ = diameter:service_info(SvcName, Pid),
lists:member({id, Id}, Opts).
%% prepare_request/5-6
-prepare_request(_Pkt, ?CLIENT, {_Ref, _Caps}, {send_discard, _}, _) ->
+prepare_request(_Pkt, [$C|_], {_Ref, _Caps}, {send_discard, _}, _) ->
{discard, unprepared};
-prepare_request(Pkt, ?CLIENT, {_Ref, Caps}, {Name, Group}, _) ->
+prepare_request(Pkt, [$C|_], {_Ref, Caps}, {Name, Group}, _) ->
{send, prepare(Pkt, Caps, Name, Group)}.
-prepare_request(Pkt, ?CLIENT, {_Ref, Caps}, {send_detach, Group}, _, _) ->
+prepare_request(Pkt, [$C|_], {_Ref, Caps}, {send_detach, Group}, _, _) ->
{eval_packet, {send, prepare(Pkt, Caps, Group)}, [fun log/2, detach]}.
log(#diameter_packet{bin = Bin} = P, T)
@@ -836,6 +1021,26 @@ log(#diameter_packet{bin = Bin} = P, T)
%% prepare/4
prepare(Pkt, Caps, N, #group{client_dict0 = Dict0} = Group)
+ when N == send_unknown_short_mandatory;
+ N == send_unknown_short ->
+ Req = prepare(Pkt, Caps, Group),
+
+ #diameter_packet{header = #diameter_header{length = L},
+ bin = Bin}
+ = E
+ = diameter_codec:encode(Dict0, Pkt#diameter_packet{msg = Req}),
+
+ %% Find the unknown AVP data at the end of the message and alter
+ %% its length header.
+
+ {Padding, [17|_]} = lists:splitwith(fun(C) -> C == 0 end,
+ lists:reverse(binary_to_list(Bin))),
+
+ Offset = L - length(Padding) - 4,
+ <<H:Offset/binary, Len:24, T/binary>> = Bin,
+ E#diameter_packet{bin = <<H/binary, (Len+9):24, T/binary>>};
+
+prepare(Pkt, Caps, N, #group{client_dict0 = Dict0} = Group)
when N == send_long_avp_length;
N == send_short_avp_length;
N == send_zero_avp_length ->
@@ -876,8 +1081,8 @@ prepare(Pkt, Caps, N, #group{client_dict0 = Dict0} = Group)
<<V, L:24, H/binary>> = H0, %% assert
E#diameter_packet{bin = <<V, (L+4):24, H/binary, 16:24, 0:32, T/binary>>};
-prepare(Pkt, Caps, send_unrecognized_mandatory, #group{client_dict0 = Dict0}
- = Group) ->
+prepare(Pkt, Caps, send_unexpected_mandatory, #group{client_dict0 = Dict0}
+ = Group) ->
Req = prepare(Pkt, Caps, Group),
#diameter_packet{bin = <<V, Len:24, T/binary>>}
= E
@@ -886,6 +1091,38 @@ prepare(Pkt, Caps, send_unrecognized_mandatory, #group{client_dict0 = Dict0}
Avp = <<Code:32, Flags, 8:24>>,
E#diameter_packet{bin = <<V, (Len+8):24, T/binary, Avp/binary>>};
+prepare(Pkt, Caps, send_grouped_error, #group{client_dict0 = Dict0}
+ = Group) ->
+ Req = prepare(Pkt, Caps, Group),
+ #diameter_packet{bin = Bin}
+ = E
+ = diameter_codec:encode(Dict0, Pkt#diameter_packet{msg = Req}),
+ {Code, Flags, undefined} = Dict0:avp_header('Proxy-Info'),
+ %% Find Proxy-Info by looking for its header.
+ Pattern = <<Code:32, Flags, 28:24>>,
+ {Offset, 8} = binary:match(Bin, Pattern),
+
+ %% Extract and swap Proxy-Host/State payloads.
+
+ <<H:Offset/binary,
+ PI:8/binary,
+ PH:5/binary,
+ 12:24,
+ Payload:4/binary,
+ PS:5/binary,
+ 8:24,
+ T/binary>>
+ = Bin,
+
+ E#diameter_packet{bin = <<H/binary,
+ PI/binary,
+ PH/binary,
+ 8:24,
+ PS:5/binary,
+ 12:24,
+ Payload/binary,
+ T/binary>>};
+
prepare(Pkt, Caps, send_unsupported, #group{client_dict0 = Dict0} = Group) ->
Req = prepare(Pkt, Caps, Group),
#diameter_packet{bin = <<H:5/binary, _CmdCode:3/binary, T/binary>>}
@@ -977,10 +1214,10 @@ prepare_retransmit(_Pkt, false, _Peer, _Name, _Group) ->
%% handle_answer/6-7
-handle_answer(Pkt, Req, ?CLIENT, Peer, {Name, Group}, _) ->
+handle_answer(Pkt, Req, [$C|_], Peer, {Name, Group}, _) ->
answer(Pkt, Req, Peer, Name, Group).
-handle_answer(Pkt, Req, ?CLIENT, Peer, {send_detach = Name, Group}, _, X) ->
+handle_answer(Pkt, Req, [$C|_], Peer, {send_detach = Name, Group}, _, X) ->
{Pid, Ref} = X,
Pid ! {Ref, answer(Pkt, Req, Peer, Name, Group)}.
@@ -992,13 +1229,19 @@ answer(Pkt, Req, _Peer, Name, #group{client_dict0 = Dict0}) ->
[R | Vs] = Dict:'#get-'(answer(Ans, Es, Name)),
[Dict:rec2msg(R) | Vs].
-answer(Rec, [_|_], N)
- when N == send_long_avp_length;
- N == send_short_avp_length;
- N == send_zero_avp_length;
- N == send_invalid_avp_length;
- N == send_invalid_reject ->
+%% Missing Result-Code and inappropriate Experimental-Result-Code.
+answer(Rec, Es, send_experimental_result) ->
+ [{5004, #diameter_avp{name = 'Experimental-Result'}},
+ {5005, #diameter_avp{name = 'Result-Code'}}]
+ = Es,
+ Rec;
+
+%% An inappropriate E-bit results in a decode error ...
+answer(Rec, Es, send_bad_answer) ->
+ [{5004, #diameter_avp{name = 'Result-Code'}} | _] = Es,
Rec;
+
+%% ... while other errors are reflected in Failed-AVP.
answer(Rec, [], _) ->
Rec.
@@ -1010,11 +1253,11 @@ app(Req, _, Dict0) ->
%% handle_error/6
-handle_error(timeout = Reason, _Req, ?CLIENT, _Peer, _, Time) ->
+handle_error(timeout = Reason, _Req, [$C|_], _Peer, _, Time) ->
Now = now(),
{Reason, {Time, Now, timer:now_diff(Now, Time)}};
-handle_error(Reason, _Req, ?CLIENT, _Peer, _, _Time) ->
+handle_error(Reason, _Req, [$C|_], _Peer, _, _Time) ->
{error, Reason}.
%% handle_request/3
@@ -1022,7 +1265,9 @@ handle_error(Reason, _Req, ?CLIENT, _Peer, _, _Time) ->
%% Note that diameter will set Result-Code and Failed-AVPs if
%% #diameter_packet.errors is non-null.
-handle_request(#diameter_packet{header = H, msg = M}, ?SERVER, {_Ref, Caps}) ->
+handle_request(#diameter_packet{header = H, msg = M, avps = As},
+ _,
+ {_Ref, Caps}) ->
#diameter_header{end_to_end_id = EI,
hop_by_hop_id = HI}
= H,
@@ -1030,10 +1275,12 @@ handle_request(#diameter_packet{header = H, msg = M}, ?SERVER, {_Ref, Caps}) ->
V = EI bsr B, %% assert
V = HI bsr B, %%
#diameter_caps{origin_state_id = {_,[Id]}} = Caps,
- answer(origin(Id), request(M, Caps)).
+ answer(origin(Id), request(M, [H|As], Caps)).
answer(T, {Tag, Action, Post}) ->
{Tag, answer(T, Action), Post};
+answer(_, {reply, [#diameter_header{} | _]} = T) ->
+ T;
answer({A,C}, {reply, Ans}) ->
answer(C, {reply, msg(Ans, A, diameter_gen_base_rfc3588)});
answer(pkt, {reply, Ans})
@@ -1042,6 +1289,41 @@ answer(pkt, {reply, Ans})
answer(_, T) ->
T.
+%% request/3
+
+%% send_experimental_result
+request(#diameter_base_accounting_ACR{'Accounting-Record-Number' = 5},
+ [Hdr | Avps],
+ #diameter_caps{origin_host = {OH, _},
+ origin_realm = {OR, _}}) ->
+ [H,R|T] = [A || N <- ['Origin-Host',
+ 'Origin-Realm',
+ 'Session-Id',
+ 'Accounting-Record-Type',
+ 'Accounting-Record-Number'],
+ #diameter_avp{} = A
+ <- [lists:keyfind(N, #diameter_avp.name, Avps)]],
+ Ans = [Hdr#diameter_header{is_request = false},
+ H#diameter_avp{data = OH},
+ R#diameter_avp{data = OR},
+ #diameter_avp{name = 'Experimental-Result',
+ code = 297,
+ need_encryption = false,
+ data = [#diameter_avp{data = {?DIAMETER_DICT_COMMON,
+ 'Vendor-Id',
+ 123}},
+ #diameter_avp{data
+ = {?DIAMETER_DICT_COMMON,
+ 'Experimental-Result-Code',
+ 3987}}]}
+ | T],
+ {reply, Ans};
+
+request(Msg, _Avps, Caps) ->
+ request(Msg, Caps).
+
+%% request/2
+
%% send_nok
request(#diameter_base_accounting_ACR{'Accounting-Record-Number' = 0},
_) ->
diff --git a/lib/diameter/test/diameter_transport_SUITE.erl b/lib/diameter/test/diameter_transport_SUITE.erl
index 97f4cec11f..40f713a550 100644
--- a/lib/diameter/test/diameter_transport_SUITE.erl
+++ b/lib/diameter/test/diameter_transport_SUITE.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -64,7 +64,7 @@
= #diameter_caps{host_ip_address
= Addrs}}).
-%% The term we register after open a listening port with gen_tcp.
+%% The term we register after open a listening port with gen_{tcp,sctp}.
-define(TEST_LISTENER(Ref, PortNr),
{?MODULE, listen, Ref, PortNr}).
@@ -85,7 +85,7 @@
%% ===========================================================================
suite() ->
- [{timetrap, {minutes, 2}}].
+ [{timetrap, {seconds, 15}}].
all() ->
[start,
@@ -104,7 +104,7 @@ tc() ->
reconnect].
init_per_suite(Config) ->
- [{sctp, have_sctp()} | Config].
+ [{sctp, ?util:have_sctp()} | Config].
end_per_suite(_Config) ->
ok.
@@ -127,7 +127,10 @@ tcp_accept(_) ->
accept(tcp).
sctp_accept(Config) ->
- if_sctp(fun accept/1, Config).
+ case lists:member({sctp, true}, Config) of
+ true -> accept(sctp);
+ false -> {skip, no_sctp}
+ end.
%% Start multiple accepting transport processes that are connected to
%% with an equal number of connecting processes using gen_tcp/sctp
@@ -157,7 +160,10 @@ tcp_connect(_) ->
connect(tcp).
sctp_connect(Config) ->
- if_sctp(fun connect/1, Config).
+ case lists:member({sctp, true}, Config) of
+ true -> connect(sctp);
+ false -> {skip, no_sctp}
+ end.
connect(Prot) ->
T = {Prot, make_ref()},
@@ -180,12 +186,13 @@ reconnect({listen, Ref}) ->
[_] = diameter_reg:wait({diameter_tcp, listener, {LRef, '_'}}),
true = diameter_reg:add_new({?MODULE, Ref, LRef}),
- %% Wait for partner to request transport death: kill to force the
- %% peer to reconnect.
+ %% Wait for partner to request transport death.
TPid = abort(SvcName, LRef, Ref),
+ %% Kill transport to force the peer to reconnect.
exit(TPid, kill),
+ %% Wait for the partner again.
abort(SvcName, LRef, Ref);
reconnect({connect, Ref}) ->
@@ -193,14 +200,14 @@ reconnect({connect, Ref}) ->
true = diameter:subscribe(SvcName),
ok = start_service(SvcName),
[{{_, _, LRef}, Pid}] = diameter_reg:wait({?MODULE, Ref, '_'}),
- CRef = ?util:connect(SvcName, tcp, LRef, [{reconnect_timer, 2000},
+ CRef = ?util:connect(SvcName, tcp, LRef, [{connect_timer, 2000},
{watchdog_timer, 6000}]),
%% Tell partner to kill transport after seeing that there are no
%% reconnection attempts.
abort(SvcName, Pid, Ref),
- %% Transport does down and is reestablished.
+ %% Transport goes down and is reestablished.
?RECV(#diameter_event{service = SvcName, info = {down, CRef, _, _}}),
?RECV(#diameter_event{service = SvcName, info = {reconnect, CRef, _}}),
?RECV(#diameter_event{service = SvcName, info = {up, CRef, _, _, _}}),
@@ -218,7 +225,7 @@ reconnect(_) ->
|| T <- [listen, connect]]).
start_service(SvcName) ->
- OH = io_lib:format("~p-~p-~p", tuple_to_list(now())),
+ OH = diameter_util:unique_string(),
Opts = [{application, [{dictionary, diameter_gen_base_rfc6733},
{module, diameter_callback}]},
{'Origin-Host', OH},
@@ -250,28 +257,6 @@ abort(SvcName, LRef, Ref)
%% ===========================================================================
%% ===========================================================================
-%% have_sctp/0
-
-have_sctp() ->
- case gen_sctp:open() of
- {ok, Sock} ->
- gen_sctp:close(Sock),
- true;
- {error, E} when E == eprotonosupport;
- E == esocktnosupport -> %% fail on any other reason
- false
- end.
-
-%% if_sctp/2
-
-if_sctp(F, Config) ->
- case proplists:get_value(sctp, Config) of
- true ->
- F(sctp);
- false ->
- {skip, no_sctp}
- end.
-
%% init/2
init(accept, {Prot, Ref}) ->
@@ -380,37 +365,14 @@ start_connect(tcp, T, Svc, Opts) ->
diameter_tcp:start(T, Svc, Opts).
%% start_accept/2
-%%
-%% Start transports sequentially by having each wait for a message
-%% from a job in a queue before commencing. Only one transport with a
-%% pending accept is started at a time since diameter_{tcp,sctp}
-%% currently assume (and diameter currently implements) this.
start_accept(Prot, Ref) ->
- Pid = sync(accept, Ref),
{Mod, Opts} = tmod(Prot),
-
- try
- {ok, TPid, [?ADDR]} = Mod:start({accept, Ref},
- ?SVC([?ADDR]),
- [{port, 0} | Opts]),
- ?RECV(?TMSG({TPid, connected})),
- TPid
- after
- Pid ! Ref
- end.
-
-sync(What, Ref) ->
- ok = diameter_sync:cast({?MODULE, What, Ref},
- [fun lock/2, Ref, self()],
- infinity,
- infinity),
- receive {start, Ref, Pid} -> Pid end.
-
-lock(Ref, Pid) ->
- Pid ! {start, Ref, self()},
- erlang:monitor(process, Pid),
- Ref = receive T -> T end.
+ {ok, TPid, [?ADDR]} = Mod:start({accept, Ref},
+ ?SVC([?ADDR]),
+ [{port, 0} | Opts]),
+ ?RECV(?TMSG({TPid, connected})),
+ TPid.
tmod(sctp) ->
{diameter_sctp, [{sctp_initmsg, ?SCTP_INIT}]};
@@ -439,12 +401,13 @@ gen_listen(tcp) ->
%% gen_accept/2
gen_accept(sctp, Sock) ->
- Assoc = ?RECV(?SCTP(Sock, {_, #sctp_assoc_change{state = comm_up,
- outbound_streams = O,
- inbound_streams = I,
- assoc_id = A}}),
- {O, I, A}),
- putr(assoc, Assoc),
+ #sctp_assoc_change{state = comm_up,
+ outbound_streams = OS,
+ inbound_streams = IS,
+ assoc_id = Id}
+ = ?RECV(?SCTP(Sock, {_, #sctp_assoc_change{} = S}), S),
+
+ putr(assoc, {OS, IS, Id}),
{ok, Sock};
gen_accept(tcp, LSock) ->
gen_tcp:accept(LSock).
@@ -462,7 +425,11 @@ gen_send(tcp, Sock, Bin) ->
gen_recv(sctp, Sock) ->
{_OS, _IS, Id} = getr(assoc),
- ?RECV(?SCTP(Sock, {[#sctp_sndrcvinfo{assoc_id = Id}], Bin}), Bin);
+ receive
+ ?SCTP(Sock, {[#sctp_sndrcvinfo{assoc_id = Id}], Bin})
+ when is_binary(Bin) ->
+ Bin
+ end;
gen_recv(tcp, Sock) ->
tcp_recv(Sock, <<>>).
diff --git a/lib/diameter/test/diameter_util.erl b/lib/diameter/test/diameter_util.erl
index 92c72c84e7..e8fab18a45 100644
--- a/lib/diameter/test/diameter_util.erl
+++ b/lib/diameter/test/diameter_util.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -29,7 +29,9 @@
run/1,
fold/3,
foldl/3,
- scramble/1]).
+ scramble/1,
+ unique_string/0,
+ have_sctp/0]).
%% diameter-specific
-export([lport/2,
@@ -184,6 +186,32 @@ s(Acc, L) ->
s([T|Acc], H ++ Rest).
%% ---------------------------------------------------------------------------
+%% unique_string/0
+
+unique_string() ->
+ try erlang:unique_integer() of
+ N ->
+ integer_to_list(N)
+ catch
+ error: undef -> %% OTP < 18
+ {M,S,U} = now(),
+ tl(lists:append(["-" ++ integer_to_list(N) || N <- [M,S,U]]))
+ end.
+
+%% ---------------------------------------------------------------------------
+%% have_sctp/0
+
+have_sctp() ->
+ case gen_sctp:open() of
+ {ok, Sock} ->
+ gen_sctp:close(Sock),
+ true;
+ {error, E} when E == eprotonosupport;
+ E == esocktnosupport -> %% fail on any other reason
+ false
+ end.
+
+%% ---------------------------------------------------------------------------
%% eval/1
%%
%% Evaluate a function in one of a number of forms.
@@ -254,13 +282,12 @@ path(Config, Name) ->
%%
%% Lookup the port number of a tcp/sctp listening transport.
-lport(M, {Node, Ref}) ->
- rpc:call(Node, ?MODULE, lport, [M, Ref]);
+lport(Prot, {Node, Ref}) ->
+ rpc:call(Node, ?MODULE, lport, [Prot, Ref]);
lport(Prot, Ref) ->
- Mod = tmod(Prot),
[_] = diameter_reg:wait({'_', listener, {Ref, '_'}}),
- [N || {listen, N, _} <- Mod:ports(Ref)].
+ [N || M <- tmod(Prot), {listen, N, _} <- M:ports(Ref)].
%% ---------------------------------------------------------------------------
%% listen/2-3
@@ -292,13 +319,17 @@ connect(Client, Prot, LRef, Opts) ->
Ref = add_transport(Client, {connect, opts(Prot, PortNr) ++ Opts}),
true = transport(Client, Ref), %% assert
- ok = receive
- {diameter_event, Client, {up, Ref, _, _, _}} -> ok
- after 10000 ->
- {Client, Prot, PortNr, process_info(self(), messages)}
- end,
+ diameter_lib:for_n(fun(_) -> ok = up(Client, Ref, Prot, PortNr) end,
+ proplists:get_value(pool_size, Opts, 1)),
Ref.
+up(Client, Ref, Prot, PortNr) ->
+ receive
+ {diameter_event, Client, {up, Ref, _, _, _}} -> ok
+ after 10000 ->
+ {Client, Prot, PortNr, process_info(self(), messages)}
+ end.
+
transport(SvcName, Ref) ->
[Ref] == [R || [{ref, R} | _] <- diameter:service_info(SvcName, transport),
R == Ref].
@@ -327,13 +358,15 @@ add_transport(SvcName, T) ->
Ref.
tmod(tcp) ->
- diameter_tcp;
+ [diameter_tcp];
tmod(sctp) ->
- diameter_sctp.
+ [diameter_sctp];
+tmod(any) ->
+ [diameter_sctp, diameter_tcp].
opts(Prot, T) ->
- [{transport_module, tmod(Prot)},
- {transport_config, [{ip, ?ADDR}, {port, 0} | opts(T)]}].
+ [{transport_module, M} || M <- tmod(Prot)]
+ ++ [{transport_config, [{ip, ?ADDR}, {port, 0} | opts(T)]}].
opts(listen) ->
[{accept, M} || M <- [{256,0,0,1}, ["256.0.0.1", ["^.+$"]]]];
diff --git a/lib/diameter/test/diameter_watchdog_SUITE.erl b/lib/diameter/test/diameter_watchdog_SUITE.erl
index b6e8730ec2..2520f3bc4c 100644
--- a/lib/diameter/test/diameter_watchdog_SUITE.erl
+++ b/lib/diameter/test/diameter_watchdog_SUITE.erl
@@ -1,7 +1,7 @@
%%
%% %CopyrightBegin%
%%
-%% Copyright Ericsson AB 2010-2013. All Rights Reserved.
+%% Copyright Ericsson AB 2010-2015. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
@@ -48,7 +48,8 @@
accept/1,
connect/3,
send/2,
- setopts/2]).
+ setopts/2,
+ close/1]).
-include("diameter.hrl").
-include("diameter_ct.hrl").
@@ -544,6 +545,9 @@ setopts(Sock, Opts) ->
send(Sock, Bin) ->
send(getr(config), Sock, Bin).
+close(Sock) ->
+ gen_tcp:close(Sock).
+
%% send/3
%% First outgoing message from a new transport process is CER/CEA.
@@ -672,7 +676,7 @@ jitter(T,D) ->
%% Generate a unique hostname for the faked peer.
hostname() ->
- lists:flatten(io_lib:format("~p-~p-~p", tuple_to_list(now()))).
+ ?util:unique_string().
putr(Key, Val) ->
put({?MODULE, Key}, Val).
diff --git a/lib/diameter/test/modules.mk b/lib/diameter/test/modules.mk
index 4fea62461c..6da96bd676 100644
--- a/lib/diameter/test/modules.mk
+++ b/lib/diameter/test/modules.mk
@@ -1,8 +1,7 @@
-#-*-makefile-*- ; force emacs to enter makefile-mode
# %CopyrightBegin%
#
-# Copyright Ericsson AB 2010-2013. All Rights Reserved.
+# Copyright Ericsson AB 2010-2015. All Rights Reserved.
#
# The contents of this file are subject to the Erlang Public License,
# Version 1.1, (the "License"); you may not use this file except in
@@ -40,6 +39,7 @@ MODULES = \
diameter_gen_sctp_SUITE \
diameter_gen_tcp_SUITE \
diameter_length_SUITE \
+ diameter_pool_SUITE \
diameter_reg_SUITE \
diameter_relay_SUITE \
diameter_stats_SUITE \
diff --git a/lib/diameter/vsn.mk b/lib/diameter/vsn.mk
index f7462c3916..24107a5bdc 100644
--- a/lib/diameter/vsn.mk
+++ b/lib/diameter/vsn.mk
@@ -1,8 +1,6 @@
-#-*-makefile-*- ; force emacs to enter makefile-mode
-
# %CopyrightBegin%
#
-# Copyright Ericsson AB 2010-2013. All Rights Reserved.
+# Copyright Ericsson AB 2010-2016. All Rights Reserved.
#
# The contents of this file are subject to the Erlang Public License,
# Version 1.1, (the "License"); you may not use this file except in
@@ -18,5 +16,5 @@
# %CopyrightEnd%
APPLICATION = diameter
-DIAMETER_VSN = 1.4.2
+DIAMETER_VSN = 1.9.2.4
APP_VSN = $(APPLICATION)-$(DIAMETER_VSN)$(PRE_VSN)