diff options
Diffstat (limited to 'lib/diameter')
163 files changed, 19810 insertions, 16074 deletions
diff --git a/lib/diameter/.gitignore b/lib/diameter/.gitignore index 5afcbedc23..8b13789179 100644 --- a/lib/diameter/.gitignore +++ b/lib/diameter/.gitignore @@ -1,58 +1 @@ -# Match at any level. -*~ -autom4te.cache - -# Compiler derivatives -# -# Do not use too creative wildcards. -# Those might ignore files that should not be ignored. - -i686-pc-linux-gnu -x86_64-unknown-linux-gnu -i386-apple-darwin[0-9]*.[0-9]*.[0-9]* -sparc-sun-solaris[0-9]*.[0-9]* -i386-pc-solaris[0-9]*.[0-9]* -i386-unknown-freebsd[0-9]*.[0-9]* -tile-tilera-linux-gnu -powerpc-unknown-linux-gnu - -# Mac OS X -a.out.dSYM/ - -# Anchored from $DIAMETER_TOP -/config.log -/config.status - -/Makefile -/configure - - -# General patterns for applications in lib. -# -# Assume that all test/Emakefiles are generated. -# -# Any application with a checked-in test/Emakefile should -# use a negative pattern in its own .gitignore. - -# -# Files generated by configure. -# - -/configure -/config.log -/config.status - - -# -# Generated documentation. (ie. not doc/src) -# - -/doc/[^s]* - - -# -# Files generated when building/running tests -# - -/test/*.log diff --git a/lib/diameter/src/app/depend.sed b/lib/diameter/Makefile index 9df0133960..9961d627cf 100644 --- a/lib/diameter/src/app/depend.sed +++ b/lib/diameter/Makefile @@ -1,7 +1,7 @@ -# +# # %CopyrightBegin% # -# Copyright Ericsson AB 2010-2011. All Rights Reserved. +# Copyright Ericsson AB 2010-2012. 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 @@ -15,17 +15,18 @@ # under the License. # # %CopyrightEnd% -# -# -# Extract include dependencies from .erl files. The output is massaged -# further in Makefile. -# +include $(ERL_TOP)/make/target.mk +include $(ERL_TOP)/make/$(TARGET)/otp.mk +include vsn.mk +include subdirs.mk + +SUB_DIRECTORIES = $(SUB_DIRS) doc/src +SPECIAL_TARGETS = + +include $(ERL_TOP)/make/otp_subdir.mk -/^-include/!d -/"diameter/!d +info: + @echo "APP_VSN = $(APP_VSN)" -s@^-include_lib("[^/]*@$(DIAMETER_TOP)@ -s@^-include("@@ -s@".*@@ -s@^@$(EBIN)/.$(EMULATOR): @ +.PHONY: info diff --git a/lib/diameter/Makefile.in b/lib/diameter/Makefile.in deleted file mode 100644 index cf38c26045..0000000000 --- a/lib/diameter/Makefile.in +++ /dev/null @@ -1,88 +0,0 @@ -# -# %CopyrightBegin% -# -# Copyright Ericsson AB 2010-2011. 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% - -ifneq ($(ERL_TOP),) -include $(ERL_TOP)/make/target.mk -include $(ERL_TOP)/make/$(TARGET)/otp.mk -else -include $(DIAMETER_TOP)/make/target.mk -include $(DIAMETER_TOP)/make/$(TARGET)/rules.mk -endif - -# ---------------------------------------------------- -# Application version -# ---------------------------------------------------- -include vsn.mk -VSN=$(DIAMETER_VSN) - -DIAMETER_TOP = @DIAMETER_TOP@ - - -# ---------------------------------------------------- -# Common Macros -# ---------------------------------------------------- - -include subdirs.mk - -SUB_DIRECTORIES = $(SUB_DIRS) doc/src - -SPECIAL_TARGETS = - -ifneq ($(ERL_TOP),) -ifneq ($(PREFIX),) -CONFIGURE_OPTS += --prefix=$(PREFIX) -endif -endif - - -# ---------------------------------------------------- -# Default Subdir Targets -# ---------------------------------------------------- -ifneq ($(ERL_TOP),) -include $(ERL_TOP)/make/otp_subdir.mk -else -include $(DIAMETER_TOP)/make/subdir.mk -endif - -.PHONY: reconf conf info version dialyzer - -reconf: - autoconf - -conf: do_configure - -do_configure: configure - ./configure $(CONFIGURE_OPTS) - -configure: configure.in - autoconf - -info: - @echo "APP_VSN: $(APP_VSN)" - @echo "DIAMETER_VSN: $(DIAMETER_VSN)" - -version: - @echo "$(VSN)" - - -dialyzer: - (cd ./ebin; \ - dialyzer --build_plt \ - --output_plt ../priv/diameter.plt \ - -r ../../diameter/ebin \ - --verbose) diff --git a/lib/diameter/aclocal.m4 b/lib/diameter/aclocal.m4 deleted file mode 100644 index 2abb47dba2..0000000000 --- a/lib/diameter/aclocal.m4 +++ /dev/null @@ -1,65 +0,0 @@ -dnl -dnl %CopyrightBegin% -dnl -dnl Copyright Ericsson AB 1998-2011. All Rights Reserved. -dnl -dnl The contents of this file are subject to the Erlang Public License, -dnl Version 1.1, (the "License"); you may not use this file except in -dnl compliance with the License. You should have received a copy of the -dnl Erlang Public License along with this software. If not, it can be -dnl retrieved online at http://www.erlang.org/. -dnl -dnl Software distributed under the License is distributed on an "AS IS" -dnl basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See -dnl the License for the specific language governing rights and limitations -dnl under the License. -dnl -dnl %CopyrightEnd% -dnl - -dnl -dnl aclocal.m4 -dnl -dnl Local macros used in configure.in. The Local Macros which -dnl could/should be part of autoconf are prefixed LM_, macros specific -dnl to the Erlang system are prefixed ERL_. -dnl - -dnl ---------------------------------------------------------------------- -dnl -dnl LM_PROG_INSTALL_DIR -dnl -dnl Figure out how to create directories with parents. -dnl (In my opinion INSTALL_DIR is a bad name, MKSUBDIRS or something is better) -dnl -dnl We prefer 'install -d', but use 'mkdir -p' if it exists. -dnl If none of these methods works, we give up. -dnl - - -AC_DEFUN(LM_PROG_INSTALL_DIR, -[AC_CACHE_CHECK(how to create a directory including parents, -ac_cv_prog_mkdir_p, -[ -temp_name_base=config.$$ -temp_name=$temp_name_base/x/y/z -$INSTALL -d $temp_name >/dev/null 2>&1 -ac_cv_prog_mkdir_p=none -if test -d $temp_name; then - ac_cv_prog_mkdir_p="$INSTALL -d" -else - mkdir -p $temp_name >/dev/null 2>&1 - if test -d $temp_name; then - ac_cv_prog_mkdir_p="mkdir -p" - fi -fi -rm -fr $temp_name_base -]) - -case "${ac_cv_prog_mkdir_p}" in - none) AC_MSG_ERROR(don't know how create directories with parents) ;; - *) INSTALL_DIR="$ac_cv_prog_mkdir_p" AC_SUBST(INSTALL_DIR) ;; -esac -]) - - diff --git a/lib/diameter/autoconf/config.guess b/lib/diameter/autoconf/config.guess deleted file mode 100755 index 38a833903b..0000000000 --- a/lib/diameter/autoconf/config.guess +++ /dev/null @@ -1,1519 +0,0 @@ -#! /bin/sh -# Attempt to guess a canonical system name. -# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, -# 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, -# Inc. - -timestamp='2007-05-17' - -# This file is free software; you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA -# 02110-1301, USA. -# -# As a special exception to the GNU General Public License, if you -# distribute this file as part of a program that contains a -# configuration script generated by Autoconf, you may include it under -# the same distribution terms that you use for the rest of that program. - - -# Originally written by Per Bothner <[email protected]>. -# Please send patches to <[email protected]>. Submit a context -# diff and a properly formatted ChangeLog entry. -# -# This script attempts to guess a canonical system name similar to -# config.sub. If it succeeds, it prints the system name on stdout, and -# exits with 0. Otherwise, it exits with 1. -# -# The plan is that this can be called by configure scripts if you -# don't specify an explicit build system type. - -me=`echo "$0" | sed -e 's,.*/,,'` - -usage="\ -Usage: $0 [OPTION] - -Output the configuration name of the system \`$me' is run on. - -Operation modes: - -h, --help print this help, then exit - -t, --time-stamp print date of last modification, then exit - -v, --version print version number, then exit - -Report bugs and patches to <[email protected]>." - -version="\ -GNU config.guess ($timestamp) - -Originally written by Per Bothner. -Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 -Free Software Foundation, Inc. - -This is free software; see the source for copying conditions. There is NO -warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." - -help=" -Try \`$me --help' for more information." - -# Parse command line -while test $# -gt 0 ; do - case $1 in - --time-stamp | --time* | -t ) - echo "$timestamp" ; exit ;; - --version | -v ) - echo "$version" ; exit ;; - --help | --h* | -h ) - echo "$usage"; exit ;; - -- ) # Stop option processing - shift; break ;; - - ) # Use stdin as input. - break ;; - -* ) - echo "$me: invalid option $1$help" >&2 - exit 1 ;; - * ) - break ;; - esac -done - -if test $# != 0; then - echo "$me: too many arguments$help" >&2 - exit 1 -fi - -trap 'exit 1' 1 2 15 - -# CC_FOR_BUILD -- compiler used by this script. Note that the use of a -# compiler to aid in system detection is discouraged as it requires -# temporary files to be created and, as you can see below, it is a -# headache to deal with in a portable fashion. - -# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still -# use `HOST_CC' if defined, but it is deprecated. - -# Portable tmp directory creation inspired by the Autoconf team. - -set_cc_for_build=' -trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ; -trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; -: ${TMPDIR=/tmp} ; - { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || - { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } || - { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } || - { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ; -dummy=$tmp/dummy ; -tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ; -case $CC_FOR_BUILD,$HOST_CC,$CC in - ,,) echo "int x;" > $dummy.c ; - for c in cc gcc c89 c99 ; do - if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then - CC_FOR_BUILD="$c"; break ; - fi ; - done ; - if test x"$CC_FOR_BUILD" = x ; then - CC_FOR_BUILD=no_compiler_found ; - fi - ;; - ,,*) CC_FOR_BUILD=$CC ;; - ,*,*) CC_FOR_BUILD=$HOST_CC ;; -esac ; set_cc_for_build= ;' - -# This is needed to find uname on a Pyramid OSx when run in the BSD universe. -# ([email protected] 1994-08-24) -if (test -f /.attbin/uname) >/dev/null 2>&1 ; then - PATH=$PATH:/.attbin ; export PATH -fi - -UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown -UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown -UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown -UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown - -# Note: order is significant - the case branches are not exclusive. - -case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in - *:NetBSD:*:*) - # NetBSD (nbsd) targets should (where applicable) match one or - # more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*, - # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently - # switched to ELF, *-*-netbsd* would select the old - # object file format. This provides both forward - # compatibility and a consistent mechanism for selecting the - # object file format. - # - # Note: NetBSD doesn't particularly care about the vendor - # portion of the name. We always set it to "unknown". - sysctl="sysctl -n hw.machine_arch" - UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \ - /usr/sbin/$sysctl 2>/dev/null || echo unknown)` - case "${UNAME_MACHINE_ARCH}" in - armeb) machine=armeb-unknown ;; - arm*) machine=arm-unknown ;; - sh3el) machine=shl-unknown ;; - sh3eb) machine=sh-unknown ;; - sh5el) machine=sh5le-unknown ;; - *) machine=${UNAME_MACHINE_ARCH}-unknown ;; - esac - # The Operating System including object format, if it has switched - # to ELF recently, or will in the future. - case "${UNAME_MACHINE_ARCH}" in - arm*|i386|m68k|ns32k|sh3*|sparc|vax) - eval $set_cc_for_build - if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ - | grep __ELF__ >/dev/null - then - # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). - # Return netbsd for either. FIX? - os=netbsd - else - os=netbsdelf - fi - ;; - *) - os=netbsd - ;; - esac - # The OS release - # Debian GNU/NetBSD machines have a different userland, and - # thus, need a distinct triplet. However, they do not need - # kernel version information, so it can be replaced with a - # suitable tag, in the style of linux-gnu. - case "${UNAME_VERSION}" in - Debian*) - release='-gnu' - ;; - *) - release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` - ;; - esac - # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: - # contains redundant information, the shorter form: - # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. - echo "${machine}-${os}${release}" - exit ;; - *:OpenBSD:*:*) - UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` - echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE} - exit ;; - *:ekkoBSD:*:*) - echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE} - exit ;; - *:SolidBSD:*:*) - echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE} - exit ;; - macppc:MirBSD:*:*) - echo powerpc-unknown-mirbsd${UNAME_RELEASE} - exit ;; - *:MirBSD:*:*) - echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE} - exit ;; - alpha:OSF1:*:*) - case $UNAME_RELEASE in - *4.0) - UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` - ;; - *5.*) - UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` - ;; - esac - # According to Compaq, /usr/sbin/psrinfo has been available on - # OSF/1 and Tru64 systems produced since 1995. I hope that - # covers most systems running today. This code pipes the CPU - # types through head -n 1, so we only detect the type of CPU 0. - ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` - case "$ALPHA_CPU_TYPE" in - "EV4 (21064)") - UNAME_MACHINE="alpha" ;; - "EV4.5 (21064)") - UNAME_MACHINE="alpha" ;; - "LCA4 (21066/21068)") - UNAME_MACHINE="alpha" ;; - "EV5 (21164)") - UNAME_MACHINE="alphaev5" ;; - "EV5.6 (21164A)") - UNAME_MACHINE="alphaev56" ;; - "EV5.6 (21164PC)") - UNAME_MACHINE="alphapca56" ;; - "EV5.7 (21164PC)") - UNAME_MACHINE="alphapca57" ;; - "EV6 (21264)") - UNAME_MACHINE="alphaev6" ;; - "EV6.7 (21264A)") - UNAME_MACHINE="alphaev67" ;; - "EV6.8CB (21264C)") - UNAME_MACHINE="alphaev68" ;; - "EV6.8AL (21264B)") - UNAME_MACHINE="alphaev68" ;; - "EV6.8CX (21264D)") - UNAME_MACHINE="alphaev68" ;; - "EV6.9A (21264/EV69A)") - UNAME_MACHINE="alphaev69" ;; - "EV7 (21364)") - UNAME_MACHINE="alphaev7" ;; - "EV7.9 (21364A)") - UNAME_MACHINE="alphaev79" ;; - esac - # A Pn.n version is a patched version. - # A Vn.n version is a released version. - # A Tn.n version is a released field test version. - # A Xn.n version is an unreleased experimental baselevel. - # 1.2 uses "1.2" for uname -r. - echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - exit ;; - Alpha\ *:Windows_NT*:*) - # How do we know it's Interix rather than the generic POSIX subsystem? - # Should we change UNAME_MACHINE based on the output of uname instead - # of the specific Alpha model? - echo alpha-pc-interix - exit ;; - 21064:Windows_NT:50:3) - echo alpha-dec-winnt3.5 - exit ;; - Amiga*:UNIX_System_V:4.0:*) - echo m68k-unknown-sysv4 - exit ;; - *:[Aa]miga[Oo][Ss]:*:*) - echo ${UNAME_MACHINE}-unknown-amigaos - exit ;; - *:[Mm]orph[Oo][Ss]:*:*) - echo ${UNAME_MACHINE}-unknown-morphos - exit ;; - *:OS/390:*:*) - echo i370-ibm-openedition - exit ;; - *:z/VM:*:*) - echo s390-ibm-zvmoe - exit ;; - *:OS400:*:*) - echo powerpc-ibm-os400 - exit ;; - arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) - echo arm-acorn-riscix${UNAME_RELEASE} - exit ;; - arm:riscos:*:*|arm:RISCOS:*:*) - echo arm-unknown-riscos - exit ;; - SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) - echo hppa1.1-hitachi-hiuxmpp - exit ;; - Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) - # [email protected] (Earle F. Ake) contributed MIS and NILE. - if test "`(/bin/universe) 2>/dev/null`" = att ; then - echo pyramid-pyramid-sysv3 - else - echo pyramid-pyramid-bsd - fi - exit ;; - NILE*:*:*:dcosx) - echo pyramid-pyramid-svr4 - exit ;; - DRS?6000:unix:4.0:6*) - echo sparc-icl-nx6 - exit ;; - DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) - case `/usr/bin/uname -p` in - sparc) echo sparc-icl-nx7; exit ;; - esac ;; - sun4H:SunOS:5.*:*) - echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` - exit ;; - sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) - echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` - exit ;; - i86pc:SunOS:5.*:* | ix86xen:SunOS:5.*:*) - echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` - exit ;; - sun4*:SunOS:6*:*) - # According to config.sub, this is the proper way to canonicalize - # SunOS6. Hard to guess exactly what SunOS6 will be like, but - # it's likely to be more like Solaris than SunOS4. - echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` - exit ;; - sun4*:SunOS:*:*) - case "`/usr/bin/arch -k`" in - Series*|S4*) - UNAME_RELEASE=`uname -v` - ;; - esac - # Japanese Language versions have a version number like `4.1.3-JL'. - echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` - exit ;; - sun3*:SunOS:*:*) - echo m68k-sun-sunos${UNAME_RELEASE} - exit ;; - sun*:*:4.2BSD:*) - UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` - test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3 - case "`/bin/arch`" in - sun3) - echo m68k-sun-sunos${UNAME_RELEASE} - ;; - sun4) - echo sparc-sun-sunos${UNAME_RELEASE} - ;; - esac - exit ;; - aushp:SunOS:*:*) - echo sparc-auspex-sunos${UNAME_RELEASE} - exit ;; - # The situation for MiNT is a little confusing. The machine name - # can be virtually everything (everything which is not - # "atarist" or "atariste" at least should have a processor - # > m68000). The system name ranges from "MiNT" over "FreeMiNT" - # to the lowercase version "mint" (or "freemint"). Finally - # the system name "TOS" denotes a system which is actually not - # MiNT. But MiNT is downward compatible to TOS, so this should - # be no problem. - atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) - echo m68k-atari-mint${UNAME_RELEASE} - exit ;; - atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) - echo m68k-atari-mint${UNAME_RELEASE} - exit ;; - *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) - echo m68k-atari-mint${UNAME_RELEASE} - exit ;; - milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) - echo m68k-milan-mint${UNAME_RELEASE} - exit ;; - hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) - echo m68k-hades-mint${UNAME_RELEASE} - exit ;; - *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) - echo m68k-unknown-mint${UNAME_RELEASE} - exit ;; - m68k:machten:*:*) - echo m68k-apple-machten${UNAME_RELEASE} - exit ;; - powerpc:machten:*:*) - echo powerpc-apple-machten${UNAME_RELEASE} - exit ;; - RISC*:Mach:*:*) - echo mips-dec-mach_bsd4.3 - exit ;; - RISC*:ULTRIX:*:*) - echo mips-dec-ultrix${UNAME_RELEASE} - exit ;; - VAX*:ULTRIX*:*:*) - echo vax-dec-ultrix${UNAME_RELEASE} - exit ;; - 2020:CLIX:*:* | 2430:CLIX:*:*) - echo clipper-intergraph-clix${UNAME_RELEASE} - exit ;; - mips:*:*:UMIPS | mips:*:*:RISCos) - eval $set_cc_for_build - sed 's/^ //' << EOF >$dummy.c -#ifdef __cplusplus -#include <stdio.h> /* for printf() prototype */ - int main (int argc, char *argv[]) { -#else - int main (argc, argv) int argc; char *argv[]; { -#endif - #if defined (host_mips) && defined (MIPSEB) - #if defined (SYSTYPE_SYSV) - printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0); - #endif - #if defined (SYSTYPE_SVR4) - printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0); - #endif - #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) - printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0); - #endif - #endif - exit (-1); - } -EOF - $CC_FOR_BUILD -o $dummy $dummy.c && - dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` && - SYSTEM_NAME=`$dummy $dummyarg` && - { echo "$SYSTEM_NAME"; exit; } - echo mips-mips-riscos${UNAME_RELEASE} - exit ;; - Motorola:PowerMAX_OS:*:*) - echo powerpc-motorola-powermax - exit ;; - Motorola:*:4.3:PL8-*) - echo powerpc-harris-powermax - exit ;; - Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) - echo powerpc-harris-powermax - exit ;; - Night_Hawk:Power_UNIX:*:*) - echo powerpc-harris-powerunix - exit ;; - m88k:CX/UX:7*:*) - echo m88k-harris-cxux7 - exit ;; - m88k:*:4*:R4*) - echo m88k-motorola-sysv4 - exit ;; - m88k:*:3*:R3*) - echo m88k-motorola-sysv3 - exit ;; - AViiON:dgux:*:*) - # DG/UX returns AViiON for all architectures - UNAME_PROCESSOR=`/usr/bin/uname -p` - if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] - then - if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ - [ ${TARGET_BINARY_INTERFACE}x = x ] - then - echo m88k-dg-dgux${UNAME_RELEASE} - else - echo m88k-dg-dguxbcs${UNAME_RELEASE} - fi - else - echo i586-dg-dgux${UNAME_RELEASE} - fi - exit ;; - M88*:DolphinOS:*:*) # DolphinOS (SVR3) - echo m88k-dolphin-sysv3 - exit ;; - M88*:*:R3*:*) - # Delta 88k system running SVR3 - echo m88k-motorola-sysv3 - exit ;; - XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) - echo m88k-tektronix-sysv3 - exit ;; - Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) - echo m68k-tektronix-bsd - exit ;; - *:IRIX*:*:*) - echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` - exit ;; - ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. - echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id - exit ;; # Note that: echo "'`uname -s`'" gives 'AIX ' - i*86:AIX:*:*) - echo i386-ibm-aix - exit ;; - ia64:AIX:*:*) - if [ -x /usr/bin/oslevel ] ; then - IBM_REV=`/usr/bin/oslevel` - else - IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} - fi - echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} - exit ;; - *:AIX:2:3) - if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then - eval $set_cc_for_build - sed 's/^ //' << EOF >$dummy.c - #include <sys/systemcfg.h> - - main() - { - if (!__power_pc()) - exit(1); - puts("powerpc-ibm-aix3.2.5"); - exit(0); - } -EOF - if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` - then - echo "$SYSTEM_NAME" - else - echo rs6000-ibm-aix3.2.5 - fi - elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then - echo rs6000-ibm-aix3.2.4 - else - echo rs6000-ibm-aix3.2 - fi - exit ;; - *:AIX:*:[45]) - IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` - if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then - IBM_ARCH=rs6000 - else - IBM_ARCH=powerpc - fi - if [ -x /usr/bin/oslevel ] ; then - IBM_REV=`/usr/bin/oslevel` - else - IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} - fi - echo ${IBM_ARCH}-ibm-aix${IBM_REV} - exit ;; - *:AIX:*:*) - echo rs6000-ibm-aix - exit ;; - ibmrt:4.4BSD:*|romp-ibm:BSD:*) - echo romp-ibm-bsd4.4 - exit ;; - ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and - echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to - exit ;; # report: romp-ibm BSD 4.3 - *:BOSX:*:*) - echo rs6000-bull-bosx - exit ;; - DPX/2?00:B.O.S.:*:*) - echo m68k-bull-sysv3 - exit ;; - 9000/[34]??:4.3bsd:1.*:*) - echo m68k-hp-bsd - exit ;; - hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) - echo m68k-hp-bsd4.4 - exit ;; - 9000/[34678]??:HP-UX:*:*) - HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` - case "${UNAME_MACHINE}" in - 9000/31? ) HP_ARCH=m68000 ;; - 9000/[34]?? ) HP_ARCH=m68k ;; - 9000/[678][0-9][0-9]) - if [ -x /usr/bin/getconf ]; then - sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` - sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` - case "${sc_cpu_version}" in - 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 - 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 - 532) # CPU_PA_RISC2_0 - case "${sc_kernel_bits}" in - 32) HP_ARCH="hppa2.0n" ;; - 64) HP_ARCH="hppa2.0w" ;; - '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20 - esac ;; - esac - fi - if [ "${HP_ARCH}" = "" ]; then - eval $set_cc_for_build - sed 's/^ //' << EOF >$dummy.c - - #define _HPUX_SOURCE - #include <stdlib.h> - #include <unistd.h> - - int main () - { - #if defined(_SC_KERNEL_BITS) - long bits = sysconf(_SC_KERNEL_BITS); - #endif - long cpu = sysconf (_SC_CPU_VERSION); - - switch (cpu) - { - case CPU_PA_RISC1_0: puts ("hppa1.0"); break; - case CPU_PA_RISC1_1: puts ("hppa1.1"); break; - case CPU_PA_RISC2_0: - #if defined(_SC_KERNEL_BITS) - switch (bits) - { - case 64: puts ("hppa2.0w"); break; - case 32: puts ("hppa2.0n"); break; - default: puts ("hppa2.0"); break; - } break; - #else /* !defined(_SC_KERNEL_BITS) */ - puts ("hppa2.0"); break; - #endif - default: puts ("hppa1.0"); break; - } - exit (0); - } -EOF - (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` - test -z "$HP_ARCH" && HP_ARCH=hppa - fi ;; - esac - if [ ${HP_ARCH} = "hppa2.0w" ] - then - eval $set_cc_for_build - - # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating - # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler - # generating 64-bit code. GNU and HP use different nomenclature: - # - # $ CC_FOR_BUILD=cc ./config.guess - # => hppa2.0w-hp-hpux11.23 - # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess - # => hppa64-hp-hpux11.23 - - if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | - grep __LP64__ >/dev/null - then - HP_ARCH="hppa2.0w" - else - HP_ARCH="hppa64" - fi - fi - echo ${HP_ARCH}-hp-hpux${HPUX_REV} - exit ;; - ia64:HP-UX:*:*) - HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` - echo ia64-hp-hpux${HPUX_REV} - exit ;; - 3050*:HI-UX:*:*) - eval $set_cc_for_build - sed 's/^ //' << EOF >$dummy.c - #include <unistd.h> - int - main () - { - long cpu = sysconf (_SC_CPU_VERSION); - /* The order matters, because CPU_IS_HP_MC68K erroneously returns - true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct - results, however. */ - if (CPU_IS_PA_RISC (cpu)) - { - switch (cpu) - { - case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; - case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; - case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; - default: puts ("hppa-hitachi-hiuxwe2"); break; - } - } - else if (CPU_IS_HP_MC68K (cpu)) - puts ("m68k-hitachi-hiuxwe2"); - else puts ("unknown-hitachi-hiuxwe2"); - exit (0); - } -EOF - $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` && - { echo "$SYSTEM_NAME"; exit; } - echo unknown-hitachi-hiuxwe2 - exit ;; - 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) - echo hppa1.1-hp-bsd - exit ;; - 9000/8??:4.3bsd:*:*) - echo hppa1.0-hp-bsd - exit ;; - *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) - echo hppa1.0-hp-mpeix - exit ;; - hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) - echo hppa1.1-hp-osf - exit ;; - hp8??:OSF1:*:*) - echo hppa1.0-hp-osf - exit ;; - i*86:OSF1:*:*) - if [ -x /usr/sbin/sysversion ] ; then - echo ${UNAME_MACHINE}-unknown-osf1mk - else - echo ${UNAME_MACHINE}-unknown-osf1 - fi - exit ;; - parisc*:Lites*:*:*) - echo hppa1.1-hp-lites - exit ;; - C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) - echo c1-convex-bsd - exit ;; - C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) - if getsysinfo -f scalar_acc - then echo c32-convex-bsd - else echo c2-convex-bsd - fi - exit ;; - C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) - echo c34-convex-bsd - exit ;; - C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) - echo c38-convex-bsd - exit ;; - C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) - echo c4-convex-bsd - exit ;; - CRAY*Y-MP:*:*:*) - echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' - exit ;; - CRAY*[A-Z]90:*:*:*) - echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ - | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ - -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ - -e 's/\.[^.]*$/.X/' - exit ;; - CRAY*TS:*:*:*) - echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' - exit ;; - CRAY*T3E:*:*:*) - echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' - exit ;; - CRAY*SV1:*:*:*) - echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' - exit ;; - *:UNICOS/mp:*:*) - echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' - exit ;; - F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) - FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` - FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` - echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" - exit ;; - 5000:UNIX_System_V:4.*:*) - FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` - FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'` - echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" - exit ;; - i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) - echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} - exit ;; - sparc*:BSD/OS:*:*) - echo sparc-unknown-bsdi${UNAME_RELEASE} - exit ;; - *:BSD/OS:*:*) - echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} - exit ;; - *:FreeBSD:*:*) - case ${UNAME_MACHINE} in - pc98) - echo i386-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; - amd64) - echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; - *) - echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; - esac - exit ;; - i*:CYGWIN*:*) - echo ${UNAME_MACHINE}-pc-cygwin - exit ;; - *:MINGW*:*) - echo ${UNAME_MACHINE}-pc-mingw32 - exit ;; - i*:windows32*:*) - # uname -m includes "-pc" on this system. - echo ${UNAME_MACHINE}-mingw32 - exit ;; - i*:PW*:*) - echo ${UNAME_MACHINE}-pc-pw32 - exit ;; - *:Interix*:[3456]*) - case ${UNAME_MACHINE} in - x86) - echo i586-pc-interix${UNAME_RELEASE} - exit ;; - EM64T | authenticamd) - echo x86_64-unknown-interix${UNAME_RELEASE} - exit ;; - esac ;; - [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*) - echo i${UNAME_MACHINE}-pc-mks - exit ;; - i*:Windows_NT*:* | Pentium*:Windows_NT*:*) - # How do we know it's Interix rather than the generic POSIX subsystem? - # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we - # UNAME_MACHINE based on the output of uname instead of i386? - echo i586-pc-interix - exit ;; - i*:UWIN*:*) - echo ${UNAME_MACHINE}-pc-uwin - exit ;; - amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) - echo x86_64-unknown-cygwin - exit ;; - p*:CYGWIN*:*) - echo powerpcle-unknown-cygwin - exit ;; - prep*:SunOS:5.*:*) - echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` - exit ;; - *:GNU:*:*) - # the GNU system - echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` - exit ;; - *:GNU/*:*:*) - # other systems with GNU libc and userland - echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu - exit ;; - i*86:Minix:*:*) - echo ${UNAME_MACHINE}-pc-minix - exit ;; - arm*:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - avr32*:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - cris:Linux:*:*) - echo cris-axis-linux-gnu - exit ;; - crisv32:Linux:*:*) - echo crisv32-axis-linux-gnu - exit ;; - frv:Linux:*:*) - echo frv-unknown-linux-gnu - exit ;; - ia64:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - m32r*:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - m68*:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - mips:Linux:*:*) - eval $set_cc_for_build - sed 's/^ //' << EOF >$dummy.c - #undef CPU - #undef mips - #undef mipsel - #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) - CPU=mipsel - #else - #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) - CPU=mips - #else - CPU= - #endif - #endif -EOF - eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n ' - /^CPU/{ - s: ::g - p - }'`" - test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; } - ;; - mips64:Linux:*:*) - eval $set_cc_for_build - sed 's/^ //' << EOF >$dummy.c - #undef CPU - #undef mips64 - #undef mips64el - #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) - CPU=mips64el - #else - #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) - CPU=mips64 - #else - CPU= - #endif - #endif -EOF - eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n ' - /^CPU/{ - s: ::g - p - }'`" - test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; } - ;; - or32:Linux:*:*) - echo or32-unknown-linux-gnu - exit ;; - ppc:Linux:*:*) - echo powerpc-unknown-linux-gnu - exit ;; - ppc64:Linux:*:*) - echo powerpc64-unknown-linux-gnu - exit ;; - alpha:Linux:*:*) - case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in - EV5) UNAME_MACHINE=alphaev5 ;; - EV56) UNAME_MACHINE=alphaev56 ;; - PCA56) UNAME_MACHINE=alphapca56 ;; - PCA57) UNAME_MACHINE=alphapca56 ;; - EV6) UNAME_MACHINE=alphaev6 ;; - EV67) UNAME_MACHINE=alphaev67 ;; - EV68*) UNAME_MACHINE=alphaev68 ;; - esac - objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null - if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi - echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC} - exit ;; - parisc:Linux:*:* | hppa:Linux:*:*) - # Look for CPU level - case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in - PA7*) echo hppa1.1-unknown-linux-gnu ;; - PA8*) echo hppa2.0-unknown-linux-gnu ;; - *) echo hppa-unknown-linux-gnu ;; - esac - exit ;; - parisc64:Linux:*:* | hppa64:Linux:*:*) - echo hppa64-unknown-linux-gnu - exit ;; - s390:Linux:*:* | s390x:Linux:*:*) - echo ${UNAME_MACHINE}-ibm-linux - exit ;; - sh64*:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - sh*:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - sparc:Linux:*:* | sparc64:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - tile:Linux:*:*) - echo tile-unknown-linux-gnu - exit ;; - vax:Linux:*:*) - echo ${UNAME_MACHINE}-dec-linux-gnu - exit ;; - x86_64:Linux:*:*) - echo x86_64-unknown-linux-gnu - exit ;; - xtensa:Linux:*:*) - echo xtensa-unknown-linux-gnu - exit ;; - i*86:Linux:*:*) - # The BFD linker knows what the default object file format is, so - # first see if it will tell us. cd to the root directory to prevent - # problems with other programs or directories called `ld' in the path. - # Set LC_ALL=C to ensure ld outputs messages in English. - ld_supported_targets=`cd /; LC_ALL=C ld --help 2>&1 \ - | sed -ne '/supported targets:/!d - s/[ ][ ]*/ /g - s/.*supported targets: *// - s/ .*// - p'` - case "$ld_supported_targets" in - elf32-i386) - TENTATIVE="${UNAME_MACHINE}-pc-linux-gnu" - ;; - a.out-i386-linux) - echo "${UNAME_MACHINE}-pc-linux-gnuaout" - exit ;; - coff-i386) - echo "${UNAME_MACHINE}-pc-linux-gnucoff" - exit ;; - "") - # Either a pre-BFD a.out linker (linux-gnuoldld) or - # one that does not give us useful --help. - echo "${UNAME_MACHINE}-pc-linux-gnuoldld" - exit ;; - esac - # Determine whether the default compiler is a.out or elf - eval $set_cc_for_build - sed 's/^ //' << EOF >$dummy.c - #include <features.h> - #ifdef __ELF__ - # ifdef __GLIBC__ - # if __GLIBC__ >= 2 - LIBC=gnu - # else - LIBC=gnulibc1 - # endif - # else - LIBC=gnulibc1 - # endif - #else - #if defined(__INTEL_COMPILER) || defined(__PGI) || defined(__SUNPRO_C) || defined(__SUNPRO_CC) - LIBC=gnu - #else - LIBC=gnuaout - #endif - #endif - #ifdef __dietlibc__ - LIBC=dietlibc - #endif -EOF - eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n ' - /^LIBC/{ - s: ::g - p - }'`" - test x"${LIBC}" != x && { - echo "${UNAME_MACHINE}-pc-linux-${LIBC}" - exit - } - test x"${TENTATIVE}" != x && { echo "${TENTATIVE}"; exit; } - ;; - i*86:DYNIX/ptx:4*:*) - # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. - # earlier versions are messed up and put the nodename in both - # sysname and nodename. - echo i386-sequent-sysv4 - exit ;; - i*86:UNIX_SV:4.2MP:2.*) - # Unixware is an offshoot of SVR4, but it has its own version - # number series starting with 2... - # I am not positive that other SVR4 systems won't match this, - # I just have to hope. -- rms. - # Use sysv4.2uw... so that sysv4* matches it. - echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} - exit ;; - i*86:OS/2:*:*) - # If we were able to find `uname', then EMX Unix compatibility - # is probably installed. - echo ${UNAME_MACHINE}-pc-os2-emx - exit ;; - i*86:XTS-300:*:STOP) - echo ${UNAME_MACHINE}-unknown-stop - exit ;; - i*86:atheos:*:*) - echo ${UNAME_MACHINE}-unknown-atheos - exit ;; - i*86:syllable:*:*) - echo ${UNAME_MACHINE}-pc-syllable - exit ;; - i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*) - echo i386-unknown-lynxos${UNAME_RELEASE} - exit ;; - i*86:*DOS:*:*) - echo ${UNAME_MACHINE}-pc-msdosdjgpp - exit ;; - i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) - UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` - if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then - echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} - else - echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} - fi - exit ;; - i*86:*:5:[678]*) - # UnixWare 7.x, OpenUNIX and OpenServer 6. - case `/bin/uname -X | grep "^Machine"` in - *486*) UNAME_MACHINE=i486 ;; - *Pentium) UNAME_MACHINE=i586 ;; - *Pent*|*Celeron) UNAME_MACHINE=i686 ;; - esac - echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} - exit ;; - i*86:*:3.2:*) - if test -f /usr/options/cb.name; then - UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name` - echo ${UNAME_MACHINE}-pc-isc$UNAME_REL - elif /bin/uname -X 2>/dev/null >/dev/null ; then - UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` - (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 - (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ - && UNAME_MACHINE=i586 - (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ - && UNAME_MACHINE=i686 - (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ - && UNAME_MACHINE=i686 - echo ${UNAME_MACHINE}-pc-sco$UNAME_REL - else - echo ${UNAME_MACHINE}-pc-sysv32 - fi - exit ;; - pc:*:*:*) - # Left here for compatibility: - # uname -m prints for DJGPP always 'pc', but it prints nothing about - # the processor, so we play safe by assuming i386. - echo i386-pc-msdosdjgpp - exit ;; - Intel:Mach:3*:*) - echo i386-pc-mach3 - exit ;; - paragon:*:*:*) - echo i860-intel-osf1 - exit ;; - i860:*:4.*:*) # i860-SVR4 - if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then - echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 - else # Add other i860-SVR4 vendors below as they are discovered. - echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 - fi - exit ;; - mini*:CTIX:SYS*5:*) - # "miniframe" - echo m68010-convergent-sysv - exit ;; - mc68k:UNIX:SYSTEM5:3.51m) - echo m68k-convergent-sysv - exit ;; - M680?0:D-NIX:5.3:*) - echo m68k-diab-dnix - exit ;; - M68*:*:R3V[5678]*:*) - test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; - 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) - OS_REL='' - test -r /etc/.relid \ - && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` - /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ - && { echo i486-ncr-sysv4.3${OS_REL}; exit; } - /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ - && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; - 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) - /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ - && { echo i486-ncr-sysv4; exit; } ;; - m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) - echo m68k-unknown-lynxos${UNAME_RELEASE} - exit ;; - mc68030:UNIX_System_V:4.*:*) - echo m68k-atari-sysv4 - exit ;; - TSUNAMI:LynxOS:2.*:*) - echo sparc-unknown-lynxos${UNAME_RELEASE} - exit ;; - rs6000:LynxOS:2.*:*) - echo rs6000-unknown-lynxos${UNAME_RELEASE} - exit ;; - PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*) - echo powerpc-unknown-lynxos${UNAME_RELEASE} - exit ;; - SM[BE]S:UNIX_SV:*:*) - echo mips-dde-sysv${UNAME_RELEASE} - exit ;; - RM*:ReliantUNIX-*:*:*) - echo mips-sni-sysv4 - exit ;; - RM*:SINIX-*:*:*) - echo mips-sni-sysv4 - exit ;; - *:SINIX-*:*:*) - if uname -p 2>/dev/null >/dev/null ; then - UNAME_MACHINE=`(uname -p) 2>/dev/null` - echo ${UNAME_MACHINE}-sni-sysv4 - else - echo ns32k-sni-sysv - fi - exit ;; - PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort - # says <[email protected]> - echo i586-unisys-sysv4 - exit ;; - *:UNIX_System_V:4*:FTX*) - # From Gerald Hewes <[email protected]>. - # How about differentiating between stratus architectures? -djm - echo hppa1.1-stratus-sysv4 - exit ;; - *:*:*:FTX*) - # From [email protected]. - echo i860-stratus-sysv4 - exit ;; - i*86:VOS:*:*) - # From [email protected]. - echo ${UNAME_MACHINE}-stratus-vos - exit ;; - *:VOS:*:*) - # From [email protected]. - echo hppa1.1-stratus-vos - exit ;; - mc68*:A/UX:*:*) - echo m68k-apple-aux${UNAME_RELEASE} - exit ;; - news*:NEWS-OS:6*:*) - echo mips-sony-newsos6 - exit ;; - R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) - if [ -d /usr/nec ]; then - echo mips-nec-sysv${UNAME_RELEASE} - else - echo mips-unknown-sysv${UNAME_RELEASE} - fi - exit ;; - BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. - echo powerpc-be-beos - exit ;; - BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. - echo powerpc-apple-beos - exit ;; - BePC:BeOS:*:*) # BeOS running on Intel PC compatible. - echo i586-pc-beos - exit ;; - SX-4:SUPER-UX:*:*) - echo sx4-nec-superux${UNAME_RELEASE} - exit ;; - SX-5:SUPER-UX:*:*) - echo sx5-nec-superux${UNAME_RELEASE} - exit ;; - SX-6:SUPER-UX:*:*) - echo sx6-nec-superux${UNAME_RELEASE} - exit ;; - SX-7:SUPER-UX:*:*) - echo sx7-nec-superux${UNAME_RELEASE} - exit ;; - SX-8:SUPER-UX:*:*) - echo sx8-nec-superux${UNAME_RELEASE} - exit ;; - SX-8R:SUPER-UX:*:*) - echo sx8r-nec-superux${UNAME_RELEASE} - exit ;; - Power*:Rhapsody:*:*) - echo powerpc-apple-rhapsody${UNAME_RELEASE} - exit ;; - *:Rhapsody:*:*) - echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} - exit ;; - *:Darwin:*:*) - UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown - case $UNAME_PROCESSOR in - unknown) UNAME_PROCESSOR=powerpc ;; - esac - echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} - exit ;; - *:procnto*:*:* | *:QNX:[0123456789]*:*) - UNAME_PROCESSOR=`uname -p` - if test "$UNAME_PROCESSOR" = "x86"; then - UNAME_PROCESSOR=i386 - UNAME_MACHINE=pc - fi - echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE} - exit ;; - *:QNX:*:4*) - echo i386-pc-qnx - exit ;; - NSE-?:NONSTOP_KERNEL:*:*) - echo nse-tandem-nsk${UNAME_RELEASE} - exit ;; - NSR-?:NONSTOP_KERNEL:*:*) - echo nsr-tandem-nsk${UNAME_RELEASE} - exit ;; - *:NonStop-UX:*:*) - echo mips-compaq-nonstopux - exit ;; - BS2000:POSIX*:*:*) - echo bs2000-siemens-sysv - exit ;; - DS/*:UNIX_System_V:*:*) - echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} - exit ;; - *:Plan9:*:*) - # "uname -m" is not consistent, so use $cputype instead. 386 - # is converted to i386 for consistency with other x86 - # operating systems. - if test "$cputype" = "386"; then - UNAME_MACHINE=i386 - else - UNAME_MACHINE="$cputype" - fi - echo ${UNAME_MACHINE}-unknown-plan9 - exit ;; - *:TOPS-10:*:*) - echo pdp10-unknown-tops10 - exit ;; - *:TENEX:*:*) - echo pdp10-unknown-tenex - exit ;; - KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) - echo pdp10-dec-tops20 - exit ;; - XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) - echo pdp10-xkl-tops20 - exit ;; - *:TOPS-20:*:*) - echo pdp10-unknown-tops20 - exit ;; - *:ITS:*:*) - echo pdp10-unknown-its - exit ;; - SEI:*:*:SEIUX) - echo mips-sei-seiux${UNAME_RELEASE} - exit ;; - *:DragonFly:*:*) - echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` - exit ;; - *:*VMS:*:*) - UNAME_MACHINE=`(uname -p) 2>/dev/null` - case "${UNAME_MACHINE}" in - A*) echo alpha-dec-vms ; exit ;; - I*) echo ia64-dec-vms ; exit ;; - V*) echo vax-dec-vms ; exit ;; - esac ;; - *:XENIX:*:SysV) - echo i386-pc-xenix - exit ;; - i*86:skyos:*:*) - echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//' - exit ;; - i*86:rdos:*:*) - echo ${UNAME_MACHINE}-pc-rdos - exit ;; -esac - -#echo '(No uname command or uname output not recognized.)' 1>&2 -#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2 - -eval $set_cc_for_build -cat >$dummy.c <<EOF -#ifdef _SEQUENT_ -# include <sys/types.h> -# include <sys/utsname.h> -#endif -main () -{ -#if defined (sony) -#if defined (MIPSEB) - /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, - I don't know.... */ - printf ("mips-sony-bsd\n"); exit (0); -#else -#include <sys/param.h> - printf ("m68k-sony-newsos%s\n", -#ifdef NEWSOS4 - "4" -#else - "" -#endif - ); exit (0); -#endif -#endif - -#if defined (__arm) && defined (__acorn) && defined (__unix) - printf ("arm-acorn-riscix\n"); exit (0); -#endif - -#if defined (hp300) && !defined (hpux) - printf ("m68k-hp-bsd\n"); exit (0); -#endif - -#if defined (NeXT) -#if !defined (__ARCHITECTURE__) -#define __ARCHITECTURE__ "m68k" -#endif - int version; - version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; - if (version < 4) - printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); - else - printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); - exit (0); -#endif - -#if defined (MULTIMAX) || defined (n16) -#if defined (UMAXV) - printf ("ns32k-encore-sysv\n"); exit (0); -#else -#if defined (CMU) - printf ("ns32k-encore-mach\n"); exit (0); -#else - printf ("ns32k-encore-bsd\n"); exit (0); -#endif -#endif -#endif - -#if defined (__386BSD__) - printf ("i386-pc-bsd\n"); exit (0); -#endif - -#if defined (sequent) -#if defined (i386) - printf ("i386-sequent-dynix\n"); exit (0); -#endif -#if defined (ns32000) - printf ("ns32k-sequent-dynix\n"); exit (0); -#endif -#endif - -#if defined (_SEQUENT_) - struct utsname un; - - uname(&un); - - if (strncmp(un.version, "V2", 2) == 0) { - printf ("i386-sequent-ptx2\n"); exit (0); - } - if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ - printf ("i386-sequent-ptx1\n"); exit (0); - } - printf ("i386-sequent-ptx\n"); exit (0); - -#endif - -#if defined (vax) -# if !defined (ultrix) -# include <sys/param.h> -# if defined (BSD) -# if BSD == 43 - printf ("vax-dec-bsd4.3\n"); exit (0); -# else -# if BSD == 199006 - printf ("vax-dec-bsd4.3reno\n"); exit (0); -# else - printf ("vax-dec-bsd\n"); exit (0); -# endif -# endif -# else - printf ("vax-dec-bsd\n"); exit (0); -# endif -# else - printf ("vax-dec-ultrix\n"); exit (0); -# endif -#endif - -#if defined (alliant) && defined (i860) - printf ("i860-alliant-bsd\n"); exit (0); -#endif - - exit (1); -} -EOF - -$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` && - { echo "$SYSTEM_NAME"; exit; } - -# Apollos put the system type in the environment. - -test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; } - -# Convex versions that predate uname can use getsysinfo(1) - -if [ -x /usr/convex/getsysinfo ] -then - case `getsysinfo -f cpu_type` in - c1*) - echo c1-convex-bsd - exit ;; - c2*) - if getsysinfo -f scalar_acc - then echo c32-convex-bsd - else echo c2-convex-bsd - fi - exit ;; - c34*) - echo c34-convex-bsd - exit ;; - c38*) - echo c38-convex-bsd - exit ;; - c4*) - echo c4-convex-bsd - exit ;; - esac -fi - -cat >&2 <<EOF -$0: unable to guess system type - -This script, last modified $timestamp, has failed to recognize -the operating system you are using. It is advised that you -download the most up to date version of the config scripts from - - http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.guess -and - http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.sub - -If the version you run ($0) is already up to date, please -send the following data and any information you think might be -pertinent to <[email protected]> in order to provide the needed -information to handle your system. - -config.guess timestamp = $timestamp - -uname -m = `(uname -m) 2>/dev/null || echo unknown` -uname -r = `(uname -r) 2>/dev/null || echo unknown` -uname -s = `(uname -s) 2>/dev/null || echo unknown` -uname -v = `(uname -v) 2>/dev/null || echo unknown` - -/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` -/bin/uname -X = `(/bin/uname -X) 2>/dev/null` - -hostinfo = `(hostinfo) 2>/dev/null` -/bin/universe = `(/bin/universe) 2>/dev/null` -/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` -/bin/arch = `(/bin/arch) 2>/dev/null` -/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` -/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` - -UNAME_MACHINE = ${UNAME_MACHINE} -UNAME_RELEASE = ${UNAME_RELEASE} -UNAME_SYSTEM = ${UNAME_SYSTEM} -UNAME_VERSION = ${UNAME_VERSION} -EOF - -exit 1 - -# Local variables: -# eval: (add-hook 'write-file-hooks 'time-stamp) -# time-stamp-start: "timestamp='" -# time-stamp-format: "%:y-%02m-%02d" -# time-stamp-end: "'" -# End: diff --git a/lib/diameter/autoconf/config.sub b/lib/diameter/autoconf/config.sub deleted file mode 100755 index f43233b104..0000000000 --- a/lib/diameter/autoconf/config.sub +++ /dev/null @@ -1,1630 +0,0 @@ -#! /bin/sh -# Configuration validation subroutine script. -# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, -# 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, -# Inc. - -timestamp='2007-04-29' - -# This file is (in principle) common to ALL GNU software. -# The presence of a machine in this file suggests that SOME GNU software -# can handle that machine. It does not imply ALL GNU software can. -# -# This file is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA -# 02110-1301, USA. -# -# As a special exception to the GNU General Public License, if you -# distribute this file as part of a program that contains a -# configuration script generated by Autoconf, you may include it under -# the same distribution terms that you use for the rest of that program. - - -# Please send patches to <[email protected]>. Submit a context -# diff and a properly formatted ChangeLog entry. -# -# Configuration subroutine to validate and canonicalize a configuration type. -# Supply the specified configuration type as an argument. -# If it is invalid, we print an error message on stderr and exit with code 1. -# Otherwise, we print the canonical config type on stdout and succeed. - -# This file is supposed to be the same for all GNU packages -# and recognize all the CPU types, system types and aliases -# that are meaningful with *any* GNU software. -# Each package is responsible for reporting which valid configurations -# it does not support. The user should be able to distinguish -# a failure to support a valid configuration from a meaningless -# configuration. - -# The goal of this file is to map all the various variations of a given -# machine specification into a single specification in the form: -# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM -# or in some cases, the newer four-part form: -# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM -# It is wrong to echo any other type of specification. - -me=`echo "$0" | sed -e 's,.*/,,'` - -usage="\ -Usage: $0 [OPTION] CPU-MFR-OPSYS - $0 [OPTION] ALIAS - -Canonicalize a configuration name. - -Operation modes: - -h, --help print this help, then exit - -t, --time-stamp print date of last modification, then exit - -v, --version print version number, then exit - -Report bugs and patches to <[email protected]>." - -version="\ -GNU config.sub ($timestamp) - -Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 -Free Software Foundation, Inc. - -This is free software; see the source for copying conditions. There is NO -warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." - -help=" -Try \`$me --help' for more information." - -# Parse command line -while test $# -gt 0 ; do - case $1 in - --time-stamp | --time* | -t ) - echo "$timestamp" ; exit ;; - --version | -v ) - echo "$version" ; exit ;; - --help | --h* | -h ) - echo "$usage"; exit ;; - -- ) # Stop option processing - shift; break ;; - - ) # Use stdin as input. - break ;; - -* ) - echo "$me: invalid option $1$help" - exit 1 ;; - - *local*) - # First pass through any local machine types. - echo $1 - exit ;; - - * ) - break ;; - esac -done - -case $# in - 0) echo "$me: missing argument$help" >&2 - exit 1;; - 1) ;; - *) echo "$me: too many arguments$help" >&2 - exit 1;; -esac - -# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any). -# Here we must recognize all the valid KERNEL-OS combinations. -maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` -case $maybe_os in - nto-qnx* | linux-gnu* | linux-dietlibc | linux-newlib* | linux-uclibc* | \ - uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* | \ - storm-chaos* | os2-emx* | rtmk-nova*) - os=-$maybe_os - basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` - ;; - *) - basic_machine=`echo $1 | sed 's/-[^-]*$//'` - if [ $basic_machine != $1 ] - then os=`echo $1 | sed 's/.*-/-/'` - else os=; fi - ;; -esac - -### Let's recognize common machines as not being operating systems so -### that things like config.sub decstation-3100 work. We also -### recognize some manufacturers as not being operating systems, so we -### can provide default operating systems below. -case $os in - -sun*os*) - # Prevent following clause from handling this invalid input. - ;; - -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \ - -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \ - -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \ - -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\ - -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \ - -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \ - -apple | -axis | -knuth | -cray) - os= - basic_machine=$1 - ;; - -sim | -cisco | -oki | -wec | -winbond) - os= - basic_machine=$1 - ;; - -scout) - ;; - -wrs) - os=-vxworks - basic_machine=$1 - ;; - -chorusos*) - os=-chorusos - basic_machine=$1 - ;; - -chorusrdb) - os=-chorusrdb - basic_machine=$1 - ;; - -hiux*) - os=-hiuxwe2 - ;; - -sco6) - os=-sco5v6 - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` - ;; - -sco5) - os=-sco3.2v5 - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` - ;; - -sco4) - os=-sco3.2v4 - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` - ;; - -sco3.2.[4-9]*) - os=`echo $os | sed -e 's/sco3.2./sco3.2v/'` - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` - ;; - -sco3.2v[4-9]*) - # Don't forget version if it is 3.2v4 or newer. - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` - ;; - -sco5v6*) - # Don't forget version if it is 3.2v4 or newer. - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` - ;; - -sco*) - os=-sco3.2v2 - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` - ;; - -udk*) - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` - ;; - -isc) - os=-isc2.2 - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` - ;; - -clix*) - basic_machine=clipper-intergraph - ;; - -isc*) - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` - ;; - -lynx*) - os=-lynxos - ;; - -ptx*) - basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` - ;; - -windowsnt*) - os=`echo $os | sed -e 's/windowsnt/winnt/'` - ;; - -psos*) - os=-psos - ;; - -mint | -mint[0-9]*) - basic_machine=m68k-atari - os=-mint - ;; -esac - -# Decode aliases for certain CPU-COMPANY combinations. -case $basic_machine in - # Recognize the basic CPU types without company name. - # Some are omitted here because they have special meanings below. - 1750a | 580 \ - | a29k \ - | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ - | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \ - | am33_2.0 \ - | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr | avr32 \ - | bfin \ - | c4x | clipper \ - | d10v | d30v | dlx | dsp16xx \ - | fido | fr30 | frv \ - | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ - | i370 | i860 | i960 | ia64 \ - | ip2k | iq2000 \ - | m32c | m32r | m32rle | m68000 | m68k | m88k \ - | maxq | mb | microblaze | mcore | mep \ - | mips | mipsbe | mipseb | mipsel | mipsle \ - | mips16 \ - | mips64 | mips64el \ - | mips64vr | mips64vrel \ - | mips64orion | mips64orionel \ - | mips64vr4100 | mips64vr4100el \ - | mips64vr4300 | mips64vr4300el \ - | mips64vr5000 | mips64vr5000el \ - | mips64vr5900 | mips64vr5900el \ - | mipsisa32 | mipsisa32el \ - | mipsisa32r2 | mipsisa32r2el \ - | mipsisa64 | mipsisa64el \ - | mipsisa64r2 | mipsisa64r2el \ - | mipsisa64sb1 | mipsisa64sb1el \ - | mipsisa64sr71k | mipsisa64sr71kel \ - | mipstx39 | mipstx39el \ - | mn10200 | mn10300 \ - | mt \ - | msp430 \ - | nios | nios2 \ - | ns16k | ns32k \ - | or32 \ - | pdp10 | pdp11 | pj | pjl \ - | powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \ - | pyramid \ - | score \ - | sh | sh[1234] | sh[24]a | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \ - | sh64 | sh64le \ - | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \ - | sparcv8 | sparcv9 | sparcv9b | sparcv9v \ - | spu | strongarm \ - | tahoe | thumb | tic4x | tic80 | tron \ - | v850 | v850e \ - | we32k \ - | x86 | xc16x | xscale | xscalee[bl] | xstormy16 | xtensa \ - | z8k) - basic_machine=$basic_machine-unknown - ;; - m6811 | m68hc11 | m6812 | m68hc12) - # Motorola 68HC11/12. - basic_machine=$basic_machine-unknown - os=-none - ;; - m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k) - ;; - ms1) - basic_machine=mt-unknown - ;; - - # We use `pc' rather than `unknown' - # because (1) that's what they normally are, and - # (2) the word "unknown" tends to confuse beginning users. - i*86 | x86_64) - basic_machine=$basic_machine-pc - ;; - # Object if more than one company name word. - *-*-*) - echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 - exit 1 - ;; - # Recognize the basic CPU types with company name. - 580-* \ - | a29k-* \ - | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ - | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \ - | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \ - | arm-* | armbe-* | armle-* | armeb-* | armv*-* \ - | avr-* | avr32-* \ - | bfin-* | bs2000-* \ - | c[123]* | c30-* | [cjt]90-* | c4x-* | c54x-* | c55x-* | c6x-* \ - | clipper-* | craynv-* | cydra-* \ - | d10v-* | d30v-* | dlx-* \ - | elxsi-* \ - | f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \ - | h8300-* | h8500-* \ - | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ - | i*86-* | i860-* | i960-* | ia64-* \ - | ip2k-* | iq2000-* \ - | m32c-* | m32r-* | m32rle-* \ - | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \ - | m88110-* | m88k-* | maxq-* | mcore-* \ - | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \ - | mips16-* \ - | mips64-* | mips64el-* \ - | mips64vr-* | mips64vrel-* \ - | mips64orion-* | mips64orionel-* \ - | mips64vr4100-* | mips64vr4100el-* \ - | mips64vr4300-* | mips64vr4300el-* \ - | mips64vr5000-* | mips64vr5000el-* \ - | mips64vr5900-* | mips64vr5900el-* \ - | mipsisa32-* | mipsisa32el-* \ - | mipsisa32r2-* | mipsisa32r2el-* \ - | mipsisa64-* | mipsisa64el-* \ - | mipsisa64r2-* | mipsisa64r2el-* \ - | mipsisa64sb1-* | mipsisa64sb1el-* \ - | mipsisa64sr71k-* | mipsisa64sr71kel-* \ - | mipstx39-* | mipstx39el-* \ - | mmix-* \ - | mt-* \ - | msp430-* \ - | nios-* | nios2-* \ - | none-* | np1-* | ns16k-* | ns32k-* \ - | orion-* \ - | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ - | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \ - | pyramid-* \ - | romp-* | rs6000-* \ - | sh-* | sh[1234]-* | sh[24]a-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \ - | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \ - | sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \ - | sparclite-* \ - | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | strongarm-* | sv1-* | sx?-* \ - | tahoe-* | thumb-* \ - | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \ - | tron-* \ - | v850-* | v850e-* | vax-* \ - | we32k-* \ - | x86-* | x86_64-* | xc16x-* | xps100-* | xscale-* | xscalee[bl]-* \ - | xstormy16-* | xtensa-* \ - | ymp-* \ - | z8k-*) - ;; - # Recognize the various machine names and aliases which stand - # for a CPU type and a company and sometimes even an OS. - 386bsd) - basic_machine=i386-unknown - os=-bsd - ;; - 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) - basic_machine=m68000-att - ;; - 3b*) - basic_machine=we32k-att - ;; - a29khif) - basic_machine=a29k-amd - os=-udi - ;; - abacus) - basic_machine=abacus-unknown - ;; - adobe68k) - basic_machine=m68010-adobe - os=-scout - ;; - alliant | fx80) - basic_machine=fx80-alliant - ;; - altos | altos3068) - basic_machine=m68k-altos - ;; - am29k) - basic_machine=a29k-none - os=-bsd - ;; - amd64) - basic_machine=x86_64-pc - ;; - amd64-*) - basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - amdahl) - basic_machine=580-amdahl - os=-sysv - ;; - amiga | amiga-*) - basic_machine=m68k-unknown - ;; - amigaos | amigados) - basic_machine=m68k-unknown - os=-amigaos - ;; - amigaunix | amix) - basic_machine=m68k-unknown - os=-sysv4 - ;; - apollo68) - basic_machine=m68k-apollo - os=-sysv - ;; - apollo68bsd) - basic_machine=m68k-apollo - os=-bsd - ;; - aux) - basic_machine=m68k-apple - os=-aux - ;; - balance) - basic_machine=ns32k-sequent - os=-dynix - ;; - c90) - basic_machine=c90-cray - os=-unicos - ;; - convex-c1) - basic_machine=c1-convex - os=-bsd - ;; - convex-c2) - basic_machine=c2-convex - os=-bsd - ;; - convex-c32) - basic_machine=c32-convex - os=-bsd - ;; - convex-c34) - basic_machine=c34-convex - os=-bsd - ;; - convex-c38) - basic_machine=c38-convex - os=-bsd - ;; - cray | j90) - basic_machine=j90-cray - os=-unicos - ;; - craynv) - basic_machine=craynv-cray - os=-unicosmp - ;; - cr16c) - basic_machine=cr16c-unknown - os=-elf - ;; - crds | unos) - basic_machine=m68k-crds - ;; - crisv32 | crisv32-* | etraxfs*) - basic_machine=crisv32-axis - ;; - cris | cris-* | etrax*) - basic_machine=cris-axis - ;; - crx) - basic_machine=crx-unknown - os=-elf - ;; - da30 | da30-*) - basic_machine=m68k-da30 - ;; - decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn) - basic_machine=mips-dec - ;; - decsystem10* | dec10*) - basic_machine=pdp10-dec - os=-tops10 - ;; - decsystem20* | dec20*) - basic_machine=pdp10-dec - os=-tops20 - ;; - delta | 3300 | motorola-3300 | motorola-delta \ - | 3300-motorola | delta-motorola) - basic_machine=m68k-motorola - ;; - delta88) - basic_machine=m88k-motorola - os=-sysv3 - ;; - djgpp) - basic_machine=i586-pc - os=-msdosdjgpp - ;; - dpx20 | dpx20-*) - basic_machine=rs6000-bull - os=-bosx - ;; - dpx2* | dpx2*-bull) - basic_machine=m68k-bull - os=-sysv3 - ;; - ebmon29k) - basic_machine=a29k-amd - os=-ebmon - ;; - elxsi) - basic_machine=elxsi-elxsi - os=-bsd - ;; - encore | umax | mmax) - basic_machine=ns32k-encore - ;; - es1800 | OSE68k | ose68k | ose | OSE) - basic_machine=m68k-ericsson - os=-ose - ;; - fx2800) - basic_machine=i860-alliant - ;; - genix) - basic_machine=ns32k-ns - ;; - gmicro) - basic_machine=tron-gmicro - os=-sysv - ;; - go32) - basic_machine=i386-pc - os=-go32 - ;; - h3050r* | hiux*) - basic_machine=hppa1.1-hitachi - os=-hiuxwe2 - ;; - h8300hms) - basic_machine=h8300-hitachi - os=-hms - ;; - h8300xray) - basic_machine=h8300-hitachi - os=-xray - ;; - h8500hms) - basic_machine=h8500-hitachi - os=-hms - ;; - harris) - basic_machine=m88k-harris - os=-sysv3 - ;; - hp300-*) - basic_machine=m68k-hp - ;; - hp300bsd) - basic_machine=m68k-hp - os=-bsd - ;; - hp300hpux) - basic_machine=m68k-hp - os=-hpux - ;; - hp3k9[0-9][0-9] | hp9[0-9][0-9]) - basic_machine=hppa1.0-hp - ;; - hp9k2[0-9][0-9] | hp9k31[0-9]) - basic_machine=m68000-hp - ;; - hp9k3[2-9][0-9]) - basic_machine=m68k-hp - ;; - hp9k6[0-9][0-9] | hp6[0-9][0-9]) - basic_machine=hppa1.0-hp - ;; - hp9k7[0-79][0-9] | hp7[0-79][0-9]) - basic_machine=hppa1.1-hp - ;; - hp9k78[0-9] | hp78[0-9]) - # FIXME: really hppa2.0-hp - basic_machine=hppa1.1-hp - ;; - hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) - # FIXME: really hppa2.0-hp - basic_machine=hppa1.1-hp - ;; - hp9k8[0-9][13679] | hp8[0-9][13679]) - basic_machine=hppa1.1-hp - ;; - hp9k8[0-9][0-9] | hp8[0-9][0-9]) - basic_machine=hppa1.0-hp - ;; - hppa-next) - os=-nextstep3 - ;; - hppaosf) - basic_machine=hppa1.1-hp - os=-osf - ;; - hppro) - basic_machine=hppa1.1-hp - os=-proelf - ;; - i370-ibm* | ibm*) - basic_machine=i370-ibm - ;; -# I'm not sure what "Sysv32" means. Should this be sysv3.2? - i*86v32) - basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` - os=-sysv32 - ;; - i*86v4*) - basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` - os=-sysv4 - ;; - i*86v) - basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` - os=-sysv - ;; - i*86sol2) - basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` - os=-solaris2 - ;; - i386mach) - basic_machine=i386-mach - os=-mach - ;; - i386-vsta | vsta) - basic_machine=i386-unknown - os=-vsta - ;; - iris | iris4d) - basic_machine=mips-sgi - case $os in - -irix*) - ;; - *) - os=-irix4 - ;; - esac - ;; - isi68 | isi) - basic_machine=m68k-isi - os=-sysv - ;; - m88k-omron*) - basic_machine=m88k-omron - ;; - magnum | m3230) - basic_machine=mips-mips - os=-sysv - ;; - merlin) - basic_machine=ns32k-utek - os=-sysv - ;; - mingw32) - basic_machine=i386-pc - os=-mingw32 - ;; - mingw32ce) - basic_machine=arm-unknown - os=-mingw32ce - ;; - miniframe) - basic_machine=m68000-convergent - ;; - *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*) - basic_machine=m68k-atari - os=-mint - ;; - mips3*-*) - basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'` - ;; - mips3*) - basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown - ;; - monitor) - basic_machine=m68k-rom68k - os=-coff - ;; - morphos) - basic_machine=powerpc-unknown - os=-morphos - ;; - msdos) - basic_machine=i386-pc - os=-msdos - ;; - ms1-*) - basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'` - ;; - mvs) - basic_machine=i370-ibm - os=-mvs - ;; - ncr3000) - basic_machine=i486-ncr - os=-sysv4 - ;; - netbsd386) - basic_machine=i386-unknown - os=-netbsd - ;; - netwinder) - basic_machine=armv4l-rebel - os=-linux - ;; - news | news700 | news800 | news900) - basic_machine=m68k-sony - os=-newsos - ;; - news1000) - basic_machine=m68030-sony - os=-newsos - ;; - news-3600 | risc-news) - basic_machine=mips-sony - os=-newsos - ;; - necv70) - basic_machine=v70-nec - os=-sysv - ;; - next | m*-next ) - basic_machine=m68k-next - case $os in - -nextstep* ) - ;; - -ns2*) - os=-nextstep2 - ;; - *) - os=-nextstep3 - ;; - esac - ;; - nh3000) - basic_machine=m68k-harris - os=-cxux - ;; - nh[45]000) - basic_machine=m88k-harris - os=-cxux - ;; - nindy960) - basic_machine=i960-intel - os=-nindy - ;; - mon960) - basic_machine=i960-intel - os=-mon960 - ;; - nonstopux) - basic_machine=mips-compaq - os=-nonstopux - ;; - np1) - basic_machine=np1-gould - ;; - nsr-tandem) - basic_machine=nsr-tandem - ;; - op50n-* | op60c-*) - basic_machine=hppa1.1-oki - os=-proelf - ;; - openrisc | openrisc-*) - basic_machine=or32-unknown - ;; - os400) - basic_machine=powerpc-ibm - os=-os400 - ;; - OSE68000 | ose68000) - basic_machine=m68000-ericsson - os=-ose - ;; - os68k) - basic_machine=m68k-none - os=-os68k - ;; - pa-hitachi) - basic_machine=hppa1.1-hitachi - os=-hiuxwe2 - ;; - paragon) - basic_machine=i860-intel - os=-osf - ;; - pbd) - basic_machine=sparc-tti - ;; - pbb) - basic_machine=m68k-tti - ;; - pc532 | pc532-*) - basic_machine=ns32k-pc532 - ;; - pc98) - basic_machine=i386-pc - ;; - pc98-*) - basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - pentium | p5 | k5 | k6 | nexgen | viac3) - basic_machine=i586-pc - ;; - pentiumpro | p6 | 6x86 | athlon | athlon_*) - basic_machine=i686-pc - ;; - pentiumii | pentium2 | pentiumiii | pentium3) - basic_machine=i686-pc - ;; - pentium4) - basic_machine=i786-pc - ;; - pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*) - basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - pentiumpro-* | p6-* | 6x86-* | athlon-*) - basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*) - basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - pentium4-*) - basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - pn) - basic_machine=pn-gould - ;; - power) basic_machine=power-ibm - ;; - ppc) basic_machine=powerpc-unknown - ;; - ppc-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - ppcle | powerpclittle | ppc-le | powerpc-little) - basic_machine=powerpcle-unknown - ;; - ppcle-* | powerpclittle-*) - basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - ppc64) basic_machine=powerpc64-unknown - ;; - ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - ppc64le | powerpc64little | ppc64-le | powerpc64-little) - basic_machine=powerpc64le-unknown - ;; - ppc64le-* | powerpc64little-*) - basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - ps2) - basic_machine=i386-ibm - ;; - pw32) - basic_machine=i586-unknown - os=-pw32 - ;; - rdos) - basic_machine=i386-pc - os=-rdos - ;; - rom68k) - basic_machine=m68k-rom68k - os=-coff - ;; - rm[46]00) - basic_machine=mips-siemens - ;; - rtpc | rtpc-*) - basic_machine=romp-ibm - ;; - s390 | s390-*) - basic_machine=s390-ibm - ;; - s390x | s390x-*) - basic_machine=s390x-ibm - ;; - sa29200) - basic_machine=a29k-amd - os=-udi - ;; - sb1) - basic_machine=mipsisa64sb1-unknown - ;; - sb1el) - basic_machine=mipsisa64sb1el-unknown - ;; - sde) - basic_machine=mipsisa32-sde - os=-elf - ;; - sei) - basic_machine=mips-sei - os=-seiux - ;; - sequent) - basic_machine=i386-sequent - ;; - sh) - basic_machine=sh-hitachi - os=-hms - ;; - sh5el) - basic_machine=sh5le-unknown - ;; - sh64) - basic_machine=sh64-unknown - ;; - sparclite-wrs | simso-wrs) - basic_machine=sparclite-wrs - os=-vxworks - ;; - sps7) - basic_machine=m68k-bull - os=-sysv2 - ;; - spur) - basic_machine=spur-unknown - ;; - st2000) - basic_machine=m68k-tandem - ;; - stratus) - basic_machine=i860-stratus - os=-sysv4 - ;; - sun2) - basic_machine=m68000-sun - ;; - sun2os3) - basic_machine=m68000-sun - os=-sunos3 - ;; - sun2os4) - basic_machine=m68000-sun - os=-sunos4 - ;; - sun3os3) - basic_machine=m68k-sun - os=-sunos3 - ;; - sun3os4) - basic_machine=m68k-sun - os=-sunos4 - ;; - sun4os3) - basic_machine=sparc-sun - os=-sunos3 - ;; - sun4os4) - basic_machine=sparc-sun - os=-sunos4 - ;; - sun4sol2) - basic_machine=sparc-sun - os=-solaris2 - ;; - sun3 | sun3-*) - basic_machine=m68k-sun - ;; - sun4) - basic_machine=sparc-sun - ;; - sun386 | sun386i | roadrunner) - basic_machine=i386-sun - ;; - sv1) - basic_machine=sv1-cray - os=-unicos - ;; - symmetry) - basic_machine=i386-sequent - os=-dynix - ;; - t3e) - basic_machine=alphaev5-cray - os=-unicos - ;; - t90) - basic_machine=t90-cray - os=-unicos - ;; - tic54x | c54x*) - basic_machine=tic54x-unknown - os=-coff - ;; - tic55x | c55x*) - basic_machine=tic55x-unknown - os=-coff - ;; - tic6x | c6x*) - basic_machine=tic6x-unknown - os=-coff - ;; - tx39) - basic_machine=mipstx39-unknown - ;; - tx39el) - basic_machine=mipstx39el-unknown - ;; - tile*) - basic_machine=tile-tilera - os=-linux-gnu - ;; - toad1) - basic_machine=pdp10-xkl - os=-tops20 - ;; - tower | tower-32) - basic_machine=m68k-ncr - ;; - tpf) - basic_machine=s390x-ibm - os=-tpf - ;; - udi29k) - basic_machine=a29k-amd - os=-udi - ;; - ultra3) - basic_machine=a29k-nyu - os=-sym1 - ;; - v810 | necv810) - basic_machine=v810-nec - os=-none - ;; - vaxv) - basic_machine=vax-dec - os=-sysv - ;; - vms) - basic_machine=vax-dec - os=-vms - ;; - vpp*|vx|vx-*) - basic_machine=f301-fujitsu - ;; - vxworks960) - basic_machine=i960-wrs - os=-vxworks - ;; - vxworks68) - basic_machine=m68k-wrs - os=-vxworks - ;; - vxworks29k) - basic_machine=a29k-wrs - os=-vxworks - ;; - w65*) - basic_machine=w65-wdc - os=-none - ;; - w89k-*) - basic_machine=hppa1.1-winbond - os=-proelf - ;; - xbox) - basic_machine=i686-pc - os=-mingw32 - ;; - xps | xps100) - basic_machine=xps100-honeywell - ;; - ymp) - basic_machine=ymp-cray - os=-unicos - ;; - z8k-*-coff) - basic_machine=z8k-unknown - os=-sim - ;; - none) - basic_machine=none-none - os=-none - ;; - -# Here we handle the default manufacturer of certain CPU types. It is in -# some cases the only manufacturer, in others, it is the most popular. - w89k) - basic_machine=hppa1.1-winbond - ;; - op50n) - basic_machine=hppa1.1-oki - ;; - op60c) - basic_machine=hppa1.1-oki - ;; - romp) - basic_machine=romp-ibm - ;; - mmix) - basic_machine=mmix-knuth - ;; - rs6000) - basic_machine=rs6000-ibm - ;; - vax) - basic_machine=vax-dec - ;; - pdp10) - # there are many clones, so DEC is not a safe bet - basic_machine=pdp10-unknown - ;; - pdp11) - basic_machine=pdp11-dec - ;; - we32k) - basic_machine=we32k-att - ;; - sh[1234] | sh[24]a | sh[34]eb | sh[1234]le | sh[23]ele) - basic_machine=sh-unknown - ;; - sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v) - basic_machine=sparc-sun - ;; - cydra) - basic_machine=cydra-cydrome - ;; - orion) - basic_machine=orion-highlevel - ;; - orion105) - basic_machine=clipper-highlevel - ;; - mac | mpw | mac-mpw) - basic_machine=m68k-apple - ;; - pmac | pmac-mpw) - basic_machine=powerpc-apple - ;; - *-unknown) - # Make sure to match an already-canonicalized machine name. - ;; - *) - echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 - exit 1 - ;; -esac - -# Here we canonicalize certain aliases for manufacturers. -case $basic_machine in - *-digital*) - basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'` - ;; - *-commodore*) - basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'` - ;; - *) - ;; -esac - -# Decode manufacturer-specific aliases for certain operating systems. - -if [ x"$os" != x"" ] -then -case $os in - # First match some system type aliases - # that might get confused with valid system types. - # -solaris* is a basic system type, with this one exception. - -solaris1 | -solaris1.*) - os=`echo $os | sed -e 's|solaris1|sunos4|'` - ;; - -solaris) - os=-solaris2 - ;; - -svr4*) - os=-sysv4 - ;; - -unixware*) - os=-sysv4.2uw - ;; - -gnu/linux*) - os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` - ;; - # First accept the basic system types. - # The portable systems comes first. - # Each alternative MUST END IN A *, to match a version number. - # -sysv* is not here because it comes later, after sysvr4. - -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ - | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\ - | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \ - | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ - | -aos* \ - | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ - | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ - | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \ - | -openbsd* | -solidbsd* \ - | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \ - | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ - | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ - | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ - | -chorusos* | -chorusrdb* \ - | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ - | -mingw32* | -linux-gnu* | -linux-newlib* | -linux-uclibc* \ - | -uxpv* | -beos* | -mpeix* | -udk* \ - | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \ - | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ - | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \ - | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \ - | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \ - | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \ - | -skyos* | -haiku* | -rdos* | -toppers* | -drops*) - # Remember, each alternative MUST END IN *, to match a version number. - ;; - -qnx*) - case $basic_machine in - x86-* | i*86-*) - ;; - *) - os=-nto$os - ;; - esac - ;; - -nto-qnx*) - ;; - -nto*) - os=`echo $os | sed -e 's|nto|nto-qnx|'` - ;; - -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ - | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \ - | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) - ;; - -mac*) - os=`echo $os | sed -e 's|mac|macos|'` - ;; - -linux-dietlibc) - os=-linux-dietlibc - ;; - -linux*) - os=`echo $os | sed -e 's|linux|linux-gnu|'` - ;; - -sunos5*) - os=`echo $os | sed -e 's|sunos5|solaris2|'` - ;; - -sunos6*) - os=`echo $os | sed -e 's|sunos6|solaris3|'` - ;; - -opened*) - os=-openedition - ;; - -os400*) - os=-os400 - ;; - -wince*) - os=-wince - ;; - -osfrose*) - os=-osfrose - ;; - -osf*) - os=-osf - ;; - -utek*) - os=-bsd - ;; - -dynix*) - os=-bsd - ;; - -acis*) - os=-aos - ;; - -atheos*) - os=-atheos - ;; - -syllable*) - os=-syllable - ;; - -386bsd) - os=-bsd - ;; - -ctix* | -uts*) - os=-sysv - ;; - -nova*) - os=-rtmk-nova - ;; - -ns2 ) - os=-nextstep2 - ;; - -nsk*) - os=-nsk - ;; - # Preserve the version number of sinix5. - -sinix5.*) - os=`echo $os | sed -e 's|sinix|sysv|'` - ;; - -sinix*) - os=-sysv4 - ;; - -tpf*) - os=-tpf - ;; - -triton*) - os=-sysv3 - ;; - -oss*) - os=-sysv3 - ;; - -svr4) - os=-sysv4 - ;; - -svr3) - os=-sysv3 - ;; - -sysvr4) - os=-sysv4 - ;; - # This must come after -sysvr4. - -sysv*) - ;; - -ose*) - os=-ose - ;; - -es1800*) - os=-ose - ;; - -xenix) - os=-xenix - ;; - -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) - os=-mint - ;; - -aros*) - os=-aros - ;; - -kaos*) - os=-kaos - ;; - -zvmoe) - os=-zvmoe - ;; - -none) - ;; - *) - # Get rid of the `-' at the beginning of $os. - os=`echo $os | sed 's/[^-]*-//'` - echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2 - exit 1 - ;; -esac -else - -# Here we handle the default operating systems that come with various machines. -# The value should be what the vendor currently ships out the door with their -# machine or put another way, the most popular os provided with the machine. - -# Note that if you're going to try to match "-MANUFACTURER" here (say, -# "-sun"), then you have to tell the case statement up towards the top -# that MANUFACTURER isn't an operating system. Otherwise, code above -# will signal an error saying that MANUFACTURER isn't an operating -# system, and we'll never get to this point. - -case $basic_machine in - score-*) - os=-elf - ;; - spu-*) - os=-elf - ;; - *-acorn) - os=-riscix1.2 - ;; - arm*-rebel) - os=-linux - ;; - arm*-semi) - os=-aout - ;; - c4x-* | tic4x-*) - os=-coff - ;; - # This must come before the *-dec entry. - pdp10-*) - os=-tops20 - ;; - pdp11-*) - os=-none - ;; - *-dec | vax-*) - os=-ultrix4.2 - ;; - m68*-apollo) - os=-domain - ;; - i386-sun) - os=-sunos4.0.2 - ;; - m68000-sun) - os=-sunos3 - # This also exists in the configure program, but was not the - # default. - # os=-sunos4 - ;; - m68*-cisco) - os=-aout - ;; - mep-*) - os=-elf - ;; - mips*-cisco) - os=-elf - ;; - mips*-*) - os=-elf - ;; - or32-*) - os=-coff - ;; - *-tti) # must be before sparc entry or we get the wrong os. - os=-sysv3 - ;; - sparc-* | *-sun) - os=-sunos4.1.1 - ;; - *-be) - os=-beos - ;; - *-haiku) - os=-haiku - ;; - *-ibm) - os=-aix - ;; - *-knuth) - os=-mmixware - ;; - *-wec) - os=-proelf - ;; - *-winbond) - os=-proelf - ;; - *-oki) - os=-proelf - ;; - *-hp) - os=-hpux - ;; - *-hitachi) - os=-hiux - ;; - i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent) - os=-sysv - ;; - *-cbm) - os=-amigaos - ;; - *-dg) - os=-dgux - ;; - *-dolphin) - os=-sysv3 - ;; - m68k-ccur) - os=-rtu - ;; - m88k-omron*) - os=-luna - ;; - *-next ) - os=-nextstep - ;; - *-sequent) - os=-ptx - ;; - *-crds) - os=-unos - ;; - *-ns) - os=-genix - ;; - i370-*) - os=-mvs - ;; - *-next) - os=-nextstep3 - ;; - *-gould) - os=-sysv - ;; - *-highlevel) - os=-bsd - ;; - *-encore) - os=-bsd - ;; - *-sgi) - os=-irix - ;; - *-siemens) - os=-sysv4 - ;; - *-masscomp) - os=-rtu - ;; - f30[01]-fujitsu | f700-fujitsu) - os=-uxpv - ;; - *-rom68k) - os=-coff - ;; - *-*bug) - os=-coff - ;; - *-apple) - os=-macos - ;; - *-atari*) - os=-mint - ;; - *) - os=-none - ;; -esac -fi - -# Here we handle the case where we know the os, and the CPU type, but not the -# manufacturer. We pick the logical manufacturer. -vendor=unknown -case $basic_machine in - *-unknown) - case $os in - -riscix*) - vendor=acorn - ;; - -sunos*) - vendor=sun - ;; - -aix*) - vendor=ibm - ;; - -beos*) - vendor=be - ;; - -hpux*) - vendor=hp - ;; - -mpeix*) - vendor=hp - ;; - -hiux*) - vendor=hitachi - ;; - -unos*) - vendor=crds - ;; - -dgux*) - vendor=dg - ;; - -luna*) - vendor=omron - ;; - -genix*) - vendor=ns - ;; - -mvs* | -opened*) - vendor=ibm - ;; - -os400*) - vendor=ibm - ;; - -ptx*) - vendor=sequent - ;; - -tpf*) - vendor=ibm - ;; - -vxsim* | -vxworks* | -windiss*) - vendor=wrs - ;; - -aux*) - vendor=apple - ;; - -hms*) - vendor=hitachi - ;; - -mpw* | -macos*) - vendor=apple - ;; - -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) - vendor=atari - ;; - -vos*) - vendor=stratus - ;; - esac - basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"` - ;; -esac - -echo $basic_machine$os -exit - -# Local variables: -# eval: (add-hook 'write-file-hooks 'time-stamp) -# time-stamp-start: "timestamp='" -# time-stamp-format: "%:y-%02m-%02d" -# time-stamp-end: "'" -# End: diff --git a/lib/diameter/autoconf/configure.vxworks b/lib/diameter/autoconf/configure.vxworks deleted file mode 100755 index 33aa497680..0000000000 --- a/lib/diameter/autoconf/configure.vxworks +++ /dev/null @@ -1,147 +0,0 @@ -#!/bin/sh -# -# %CopyrightBegin% -# -# Copyright Ericsson AB 1997-2011. 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% -# -# Author: -# Patrik Winroth -# - - -# vxworks_ppc860 vxworks_ppc603 vxworks_ppc603_longcall vxworks_cpu32 vxworks_sparc -# vxworks_ppc750 vxworks_simso - -case $# in -1) host=$1 ;; -*) echo "usage: configure.vxworks host-configuration"; exit 1 ;; -esac - -case $1 in -vxworks_cpu32) ;; -vxworks_ppc750) ;; -vxworks_ppc860) ;; -vxworks_ppc603) ;; -vxworks_ppc603_nolongcall) ;; -vxworks_sparc) ;; -vxworks_simso) ;; -vxworks_simlinux) ;; -vxworks_ppc32) ;; -*) echo "usage: configure.vxworks TARGET"; - echo "where TARGET is one of vxworks_cpu32, vxworks_ppc750, vxworks_ppc860, vxworks_ppc603, vxworks_ppc603_nolongcall, vxworks_sparc, vxworks_simso, vxworks_simlinux, vxworks_ppc32"; exit 1;; -esac - -if [ "x$ERL_TOP" = x ]; then - echo "You need to set ERL_TOP!" - exit 1 -fi - - -target=$host - -# Find out the HOST and WIND_BASE environment -HOST_TYPE=${HOST_TYPE:=sun4-solaris2} -case $1 in -vxworks_ppc750) VXTOP=Tornado2.2 ;; -vxworks_simso) VXTOP=WindRiver ;; -vxworks_simlinux) VXTOP=WindRiver ;; -vxworks_ppc32) VXTOP=WindRiver ;; -*) VXTOP=wind ;; -esac - -WIND_BASE=${WIND_BASE:=`ypmatch tornado passwd | awk -F: '{print $6}'`/$VXTOP} - -# These are created by autoconf. -MKDIRS="${ERL_TOP}/lib/os_mon/priv/bin/$target - ${ERL_TOP}/lib/os_mon/priv/obj/$target - ${ERL_TOP}/lib/orber/priv/obj/$target - ${ERL_TOP}/lib/orber/priv/bin/$target - ${ERL_TOP}/lib/ic/priv/lib/$target - ${ERL_TOP}/lib/ic/priv/obj/$target - ${ERL_TOP}/lib/asn1/priv/lib/$target - ${ERL_TOP}/lib/asn1/priv/obj/$target - ${ERL_TOP}/lib/erl_interface/obj/$target - ${ERL_TOP}/lib/erl_interface/obj.debug/$target - ${ERL_TOP}/lib/erl_interface/bin/$target - ${ERL_TOP}/lib/runtime_tools/priv/lib/$target - ${ERL_TOP}/lib/runtime_tools/priv/obj/$target - ${ERL_TOP}/erts/obj/$target - ${ERL_TOP}/erts/obj.debug/$target - ${ERL_TOP}/bin/$target" - -for dir in $MKDIRS; do - test ! -d "$dir" && mkdir -p "$dir" -done - -# -# Create Makefiles for vxWorks. -# -my_root=${ERL_TOP}/erts/emulator -emu_test=$my_root/test -beam=$my_root/beam -erts_lib_src=${ERL_TOP}/erts/lib_src -erts_incl=${ERL_TOP}/erts/include -erts_incl_intrnl=${ERL_TOP}/erts/include/internal -etcdir=${ERL_TOP}/erts/etc/common -erlint_dir=${ERL_TOP}/lib/erl_interface/src -epmd_dir=${ERL_TOP}/erts/epmd/src -os_mon_dir=${ERL_TOP}/lib/os_mon/c_src -orber_dir=${ERL_TOP}/lib/orber/c_src -ic_dir=${ERL_TOP}/lib/ic/c_src -asn1_dir=${ERL_TOP}/lib/asn1/c_src -internal_tools_dir=${ERL_TOP} -libdir=${ERL_TOP}/lib -tsdir=$libdir/test_server/src -zlibdir=${ERL_TOP}/erts/emulator/zlib -runtime_tools_dir=${ERL_TOP}/lib/runtime_tools/c_src -tools_dir=${ERL_TOP}/lib/tools/c_src - -CONFIG_FILES="${ERL_TOP}/erts/emulator/$host/Makefile - $erts_lib_src/$host/Makefile - $erts_incl/$host/erl_int_sizes_config.h - $erts_incl_intrnl/$host/ethread.mk - $erts_incl_intrnl/$host/ethread_header_config.h - $etcdir/$host/Makefile - $erlint_dir/$host/Makefile - $erlint_dir/$host/eidefs.mk - $epmd_dir/$host/Makefile - $internal_tools_dir/make/$host/otp.mk - $os_mon_dir/$host/Makefile - $zlibdir/$host/Makefile - $ic_dir/$host/Makefile - $asn1_dir/$host/Makefile - $runtime_tools_dir/$host/Makefile - $tools_dir/$host/Makefile - $orber_dir/$host/Makefile" - -for file in $CONFIG_FILES; do - new_name=`echo $file|sed "s%/$host/%/$target/%"` - dir=`echo $new_name|sed 's%/[^/][^/]*$%%'` - if test "$dir" != "$new_name" && test "$dir" != .; then - test ! -d "$dir" && mkdir "$dir" - fi - - sole_name=`echo $file|sed "s%.*$target/%%"` - in_file=`echo $dir|sed "s%/[^/][^/]*$%/$sole_name.in%"` - echo "creating $new_name" - sed -f vxworks/sed.$target -f vxworks/sed.general \ - -e "s,@HOST_TYPE@,$HOST_TYPE,g" \ - -e "s,@WIND_BASE@,$WIND_BASE,g" \ - -e "s,@TARGET@,$target,g" \ - $in_file > $new_name -done - - diff --git a/lib/diameter/autoconf/install-sh b/lib/diameter/autoconf/install-sh deleted file mode 100755 index a5897de6ea..0000000000 --- a/lib/diameter/autoconf/install-sh +++ /dev/null @@ -1,519 +0,0 @@ -#!/bin/sh -# install - install a program, script, or datafile - -scriptversion=2006-12-25.00 - -# This originates from X11R5 (mit/util/scripts/install.sh), which was -# later released in X11R6 (xc/config/util/install.sh) with the -# following copyright and license. -# -# Copyright (C) 1994 X Consortium -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN -# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC- -# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -# -# Except as contained in this notice, the name of the X Consortium shall not -# be used in advertising or otherwise to promote the sale, use or other deal- -# ings in this Software without prior written authorization from the X Consor- -# tium. -# -# -# FSF changes to this file are in the public domain. -# -# Calling this script install-sh is preferred over install.sh, to prevent -# `make' implicit rules from creating a file called install from it -# when there is no Makefile. -# -# This script is compatible with the BSD install script, but was written -# from scratch. - -nl=' -' -IFS=" "" $nl" - -# set DOITPROG to echo to test this script - -# Don't use :- since 4.3BSD and earlier shells don't like it. -doit=${DOITPROG-} -if test -z "$doit"; then - doit_exec=exec -else - doit_exec=$doit -fi - -# Put in absolute file names if you don't have them in your path; -# or use environment vars. - -chgrpprog=${CHGRPPROG-chgrp} -chmodprog=${CHMODPROG-chmod} -chownprog=${CHOWNPROG-chown} -cmpprog=${CMPPROG-cmp} -cpprog=${CPPROG-cp} -mkdirprog=${MKDIRPROG-mkdir} -mvprog=${MVPROG-mv} -rmprog=${RMPROG-rm} -stripprog=${STRIPPROG-strip} - -posix_glob='?' -initialize_posix_glob=' - test "$posix_glob" != "?" || { - if (set -f) 2>/dev/null; then - posix_glob= - else - posix_glob=: - fi - } -' - -posix_mkdir= - -# Desired mode of installed file. -mode=0755 - -chgrpcmd= -chmodcmd=$chmodprog -chowncmd= -mvcmd=$mvprog -rmcmd="$rmprog -f" -stripcmd= - -src= -dst= -dir_arg= -dst_arg= - -copy_on_change=false -no_target_directory= - -usage="\ -Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE - or: $0 [OPTION]... SRCFILES... DIRECTORY - or: $0 [OPTION]... -t DIRECTORY SRCFILES... - or: $0 [OPTION]... -d DIRECTORIES... - -In the 1st form, copy SRCFILE to DSTFILE. -In the 2nd and 3rd, copy all SRCFILES to DIRECTORY. -In the 4th, create DIRECTORIES. - -Options: - --help display this help and exit. - --version display version info and exit. - - -c (ignored) - -C install only if different (preserve the last data modification time) - -d create directories instead of installing files. - -g GROUP $chgrpprog installed files to GROUP. - -m MODE $chmodprog installed files to MODE. - -o USER $chownprog installed files to USER. - -s $stripprog installed files. - -t DIRECTORY install into DIRECTORY. - -T report an error if DSTFILE is a directory. - -Environment variables override the default commands: - CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG - RMPROG STRIPPROG -" - -while test $# -ne 0; do - case $1 in - -c) ;; - - -C) copy_on_change=true;; - - -d) dir_arg=true;; - - -g) chgrpcmd="$chgrpprog $2" - shift;; - - --help) echo "$usage"; exit $?;; - - -m) mode=$2 - case $mode in - *' '* | *' '* | *' -'* | *'*'* | *'?'* | *'['*) - echo "$0: invalid mode: $mode" >&2 - exit 1;; - esac - shift;; - - -o) chowncmd="$chownprog $2" - shift;; - - -s) stripcmd=$stripprog;; - - -t) dst_arg=$2 - shift;; - - -T) no_target_directory=true;; - - --version) echo "$0 $scriptversion"; exit $?;; - - --) shift - break;; - - -*) echo "$0: invalid option: $1" >&2 - exit 1;; - - *) break;; - esac - shift -done - -if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then - # When -d is used, all remaining arguments are directories to create. - # When -t is used, the destination is already specified. - # Otherwise, the last argument is the destination. Remove it from $@. - for arg - do - if test -n "$dst_arg"; then - # $@ is not empty: it contains at least $arg. - set fnord "$@" "$dst_arg" - shift # fnord - fi - shift # arg - dst_arg=$arg - done -fi - -if test $# -eq 0; then - if test -z "$dir_arg"; then - echo "$0: no input file specified." >&2 - exit 1 - fi - # It's OK to call `install-sh -d' without argument. - # This can happen when creating conditional directories. - exit 0 -fi - -if test -z "$dir_arg"; then - trap '(exit $?); exit' 1 2 13 15 - - # Set umask so as not to create temps with too-generous modes. - # However, 'strip' requires both read and write access to temps. - case $mode in - # Optimize common cases. - *644) cp_umask=133;; - *755) cp_umask=22;; - - *[0-7]) - if test -z "$stripcmd"; then - u_plus_rw= - else - u_plus_rw='% 200' - fi - cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;; - *) - if test -z "$stripcmd"; then - u_plus_rw= - else - u_plus_rw=,u+rw - fi - cp_umask=$mode$u_plus_rw;; - esac -fi - -for src -do - # Protect names starting with `-'. - case $src in - -*) src=./$src;; - esac - - if test -n "$dir_arg"; then - dst=$src - dstdir=$dst - test -d "$dstdir" - dstdir_status=$? - else - - # Waiting for this to be detected by the "$cpprog $src $dsttmp" command - # might cause directories to be created, which would be especially bad - # if $src (and thus $dsttmp) contains '*'. - if test ! -f "$src" && test ! -d "$src"; then - echo "$0: $src does not exist." >&2 - exit 1 - fi - - if test -z "$dst_arg"; then - echo "$0: no destination specified." >&2 - exit 1 - fi - - dst=$dst_arg - # Protect names starting with `-'. - case $dst in - -*) dst=./$dst;; - esac - - # If destination is a directory, append the input filename; won't work - # if double slashes aren't ignored. - if test -d "$dst"; then - if test -n "$no_target_directory"; then - echo "$0: $dst_arg: Is a directory" >&2 - exit 1 - fi - dstdir=$dst - dst=$dstdir/`basename "$src"` - dstdir_status=0 - else - # Prefer dirname, but fall back on a substitute if dirname fails. - dstdir=` - (dirname "$dst") 2>/dev/null || - expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$dst" : 'X\(//\)[^/]' \| \ - X"$dst" : 'X\(//\)$' \| \ - X"$dst" : 'X\(/\)' \| . 2>/dev/null || - echo X"$dst" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ - s//\1/ - q - } - /^X\(\/\/\)[^/].*/{ - s//\1/ - q - } - /^X\(\/\/\)$/{ - s//\1/ - q - } - /^X\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q' - ` - - test -d "$dstdir" - dstdir_status=$? - fi - fi - - obsolete_mkdir_used=false - - if test $dstdir_status != 0; then - case $posix_mkdir in - '') - # Create intermediate dirs using mode 755 as modified by the umask. - # This is like FreeBSD 'install' as of 1997-10-28. - umask=`umask` - case $stripcmd.$umask in - # Optimize common cases. - *[2367][2367]) mkdir_umask=$umask;; - .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;; - - *[0-7]) - mkdir_umask=`expr $umask + 22 \ - - $umask % 100 % 40 + $umask % 20 \ - - $umask % 10 % 4 + $umask % 2 - `;; - *) mkdir_umask=$umask,go-w;; - esac - - # With -d, create the new directory with the user-specified mode. - # Otherwise, rely on $mkdir_umask. - if test -n "$dir_arg"; then - mkdir_mode=-m$mode - else - mkdir_mode= - fi - - posix_mkdir=false - case $umask in - *[123567][0-7][0-7]) - # POSIX mkdir -p sets u+wx bits regardless of umask, which - # is incompatible with FreeBSD 'install' when (umask & 300) != 0. - ;; - *) - tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$ - trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0 - - if (umask $mkdir_umask && - exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1 - then - if test -z "$dir_arg" || { - # Check for POSIX incompatibilities with -m. - # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or - # other-writeable bit of parent directory when it shouldn't. - # FreeBSD 6.1 mkdir -m -p sets mode of existing directory. - ls_ld_tmpdir=`ls -ld "$tmpdir"` - case $ls_ld_tmpdir in - d????-?r-*) different_mode=700;; - d????-?--*) different_mode=755;; - *) false;; - esac && - $mkdirprog -m$different_mode -p -- "$tmpdir" && { - ls_ld_tmpdir_1=`ls -ld "$tmpdir"` - test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1" - } - } - then posix_mkdir=: - fi - rmdir "$tmpdir/d" "$tmpdir" - else - # Remove any dirs left behind by ancient mkdir implementations. - rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null - fi - trap '' 0;; - esac;; - esac - - if - $posix_mkdir && ( - umask $mkdir_umask && - $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir" - ) - then : - else - - # The umask is ridiculous, or mkdir does not conform to POSIX, - # or it failed possibly due to a race condition. Create the - # directory the slow way, step by step, checking for races as we go. - - case $dstdir in - /*) prefix='/';; - -*) prefix='./';; - *) prefix='';; - esac - - eval "$initialize_posix_glob" - - oIFS=$IFS - IFS=/ - $posix_glob set -f - set fnord $dstdir - shift - $posix_glob set +f - IFS=$oIFS - - prefixes= - - for d - do - test -z "$d" && continue - - prefix=$prefix$d - if test -d "$prefix"; then - prefixes= - else - if $posix_mkdir; then - (umask=$mkdir_umask && - $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break - # Don't fail if two instances are running concurrently. - test -d "$prefix" || exit 1 - else - case $prefix in - *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;; - *) qprefix=$prefix;; - esac - prefixes="$prefixes '$qprefix'" - fi - fi - prefix=$prefix/ - done - - if test -n "$prefixes"; then - # Don't fail if two instances are running concurrently. - (umask $mkdir_umask && - eval "\$doit_exec \$mkdirprog $prefixes") || - test -d "$dstdir" || exit 1 - obsolete_mkdir_used=true - fi - fi - fi - - if test -n "$dir_arg"; then - { test -z "$chowncmd" || $doit $chowncmd "$dst"; } && - { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } && - { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false || - test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1 - else - - # Make a couple of temp file names in the proper directory. - dsttmp=$dstdir/_inst.$$_ - rmtmp=$dstdir/_rm.$$_ - - # Trap to clean up those temp files at exit. - trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0 - - # Copy the file name to the temp name. - (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") && - - # and set any options; do chmod last to preserve setuid bits. - # - # If any of these fail, we abort the whole thing. If we want to - # ignore errors from any of these, just make sure not to ignore - # errors from the above "$doit $cpprog $src $dsttmp" command. - # - { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } && - { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } && - { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } && - { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } && - - # If -C, don't bother to copy if it wouldn't change the file. - if $copy_on_change && - old=`LC_ALL=C ls -dlL "$dst" 2>/dev/null` && - new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` && - - eval "$initialize_posix_glob" && - $posix_glob set -f && - set X $old && old=:$2:$4:$5:$6 && - set X $new && new=:$2:$4:$5:$6 && - $posix_glob set +f && - - test "$old" = "$new" && - $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1 - then - rm -f "$dsttmp" - else - # Rename the file to the real destination. - $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null || - - # The rename failed, perhaps because mv can't rename something else - # to itself, or perhaps because mv is so ancient that it does not - # support -f. - { - # Now remove or move aside any old file at destination location. - # We try this two ways since rm can't unlink itself on some - # systems and the destination file might be busy for other - # reasons. In this case, the final cleanup might fail but the new - # file should still install successfully. - { - test ! -f "$dst" || - $doit $rmcmd -f "$dst" 2>/dev/null || - { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null && - { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; } - } || - { echo "$0: cannot unlink or rename $dst" >&2 - (exit 1); exit 1 - } - } && - - # Now rename the file to the real destination. - $doit $mvcmd "$dsttmp" "$dst" - } - fi || exit 1 - - trap '' 0 - fi -done - -# Local variables: -# eval: (add-hook 'write-file-hooks 'time-stamp) -# time-stamp-start: "scriptversion=" -# time-stamp-format: "%:y-%02m-%02d.%02H" -# time-stamp-end: "$" -# End: diff --git a/lib/diameter/autoconf/vxworks/sed.general b/lib/diameter/autoconf/vxworks/sed.general deleted file mode 100644 index 77b306aa0a..0000000000 --- a/lib/diameter/autoconf/vxworks/sed.general +++ /dev/null @@ -1,125 +0,0 @@ -# -# %CopyrightBegin% -# -# Copyright Ericsson AB 1997-2011. 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% -# -# Author: Patrik Winroth -# -# This sed program file is intended to be used when creating Makefiles -# for vxworks from the generic Makefile.in that is found in a number -# of directories (see configure.vxworks). -# -# This is the general part that is common for all architectures. -# - -# Size of data types. -s|^#undef SIZEOF_CHAR|#define SIZEOF_CHAR 1| -s|^#undef SIZEOF_SHORT|#define SIZEOF_SHORT 2| -s|^#undef SIZEOF_INT|#define SIZEOF_INT 4| -s|^#undef SIZEOF_LONG_LONG|#define SIZEOF_LONG_LONG 8| -s|^#undef SIZEOF_LONG$|#define SIZEOF_LONG 4| - -# General stuff. -s|@erts_rootdir@|/clearcase/otp/erts| - -s|@LIBOBJS@|$(OBJDIR)/elib_malloc.o| -s|@DLOAD_LIB@|| -s|@LDFLAGS@|| -# FIXME: A bit strange to clear out remaining DED_* -s|@DED_LDFLAGS@|| -s|@DED_CFLAGS@|| -s|@STATIC_CFLAGS@|| -s|@GCCLIB@|libgcc.a| -s|@DEFS@|| -s|@DEXPORT@|| -s|@DCFLAGS@|| -s|@THR_DEFS@|| -s|@THR_LIBS@|| -s|@THR_LIB_NAME@|| -s|@THR_X_LIBS@|| -s|@ETHR_X_LIBS@|| -s|@ETHR_LIBS@|| -s|@ETHR_LIB_NAME@|| -s|@ETHR_DEFS@|| -s|@ETHR_THR_LIB_BASE@|| -s|@EMU_THR_DEFS@|| -s|@EMU_THR_LIBS@|| -s|@EMU_THR_LIB_NAME@|ethread| -s|@ERTS_ENABLE_KERNEL_POLL@|no| -s|@cc_root@|/clearcase/otp/| -# Define VxWorks even though cross-compiling. -s|@HCFLAGS@|-DVXWORKS| -s|@HCLIBS@|| -s|@ENABLE_ALLOC_TYPE_VARS@|| -s|@TERMCAP_LIB@|| -s|@ERTS_BUILD_SMP_EMU@|no| -s|@ERTS_BUILD_HYBRID_EMU@|no| -s|@HAVE_VALGRIND@|no| -s|@EXEEXT@|| -s|@WITH_SCTP@|| - -# HiPE -s|@HIPE_ENABLED@|| -s|@PERFCTR_PATH@|| -s|@USE_PERFCTR@|| - -# m4 -s|@OPSYS@|noopsys| - -# Conditional inclusion of applications -s|@HIPE_APP@|| -s|@SSL_APP@|ssl| -s|@CRYPTO_APP@|crypto| -s|@SSH_APP@|ssh| - -# The target tools prefix, prepended to all cc,ld,as etc commands -s|@TTPREFIX@|GCC_EXEC_PREFIX=@WIND_BASE@/host/@HOST_TYPE@/lib/gcc-lib/ @WIND_BASE@/host/@HOST_TYPE@/bin/| - -# Install programs etc -s|@PERL@|perl| -s|@INSTALL@|/usr/ucb/install -c| -s|@INSTALL_PROGRAM@|${INSTALL}| -s|@INSTALL_SCRIPT@|${INSTALL}| -s|@INSTALL_DATA@|${INSTALL} -m 644| -s|@INSTALL_DIR@|$(INSTALL) -d| -s|@RM@|/bin/rm| -s|@MKDIR@|/bin/mkdir| -s|@ERLANG_OSTYPE@|vxworks| -s|@vxworks_reclaim@|reclaim.h| -s|@os_mon_programs@|| -s|@erlexec@|erl.exec| -s|@EMU_LIBOBJS@|| - -# General CFLAGS -s|@GENERAL_CFLAGS@|-DHAVE_LOCALTIME_R -DHAVE_GMTIME_R -DENABLE_ELIB_MALLOC -DELIB_HEAP_USER -DELIB_SORTED_BLOCKS -DWORDS_BIGENDIAN -DELIB_DONT_INITIALIZE -DSIZEOF_CHAR=1 -DSIZEOF_SHORT=2 -DSIZEOF_INT=4 -DSIZEOF_LONG=4 -DSIZEOF_LONG_LONG=8 -DSIZEOF_VOID_P=4 -DERTS_USE_PORT_TASKS=1|g -s|@WFLAGS@|| - -# Thread flags for eidefs.mk (erl_interface) -s|@EI_THREADS@|false| - -# Make java code compile although we don't test it on VxWorks (no license) -s|@JAVAC@|javac| - -# What is this anyway? -# Disable it and see what breaks. -#s|@ded_soname@|| - -# Only variable substituted directly -s|$(LDFLAGS)|-r -d| -s|@LIBRT@|| -# XXX What is EFFLAGS? Not used in the emulator Makefile.in anyway. -s|$(EFLAGS)|-DENABLE_ELIB_MALLOC -DELIB_HEAP_USER -DELIB_SORTED_BLOCKS| - diff --git a/lib/diameter/autoconf/vxworks/sed.vxworks_cpu32 b/lib/diameter/autoconf/vxworks/sed.vxworks_cpu32 deleted file mode 100644 index 5a1590e786..0000000000 --- a/lib/diameter/autoconf/vxworks/sed.vxworks_cpu32 +++ /dev/null @@ -1,45 +0,0 @@ -# -# %CopyrightBegin% -# -# Copyright Ericsson AB 1997-2011. 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% -# -# Author: Patrik Winroth -# -# This sed program file is intended to be used when creating Makefiles for vxworks -# from the generic Makefile.in that is found in a number of directories (see configure.vxworks) -# -# -# -s|@host@|vxworks_cpu32| -s|@system_type@|vxworks_cpu32| -s|@CC@|@TTPREFIX@cc68k| -s|@HCC@|gcc| -s|@LD@|@TTPREFIX@ld68k| -s|@LIBS@|| -s|@DED_LD@|@TTPREFIX@ld68k| -s|@DED_CFLAGS@|@CFLAGS@| -s|@DEBUG_FLAGS@|-g| -s|@GCCLIB_PATH@|@WIND_BASE@/host/@HOST_TYPE@/lib/gcc-lib/m68k-wrs-vxworks/cygnus-2.7.2-960126/m68000/msoft-float/libgcc.a| -s|@RANLIB@|@TTPREFIX@ranlib68k| -s|@AR@|@TTPREFIX@ar68k| -s|@STRIP@|@TTPREFIX@strip68k| -s|@SYMPREFIX@|_| -s|@GCCLIBFLAGS@|-L@WIND_BASE@/host/@HOST_TYPE@/lib/gcc-lib/m68k-wrs-vxworks/cygnus-2.7.2-960126/m68000/msoft-float -lgcc| - -s|@LIB_CFLAGS@|@CFLAGS@| - -s|@CFLAGS@|@GENERAL_CFLAGS@ -DCPU=CPU32 -mnobitfield -DWANT_NONBLOCKING -DHAVE_MEMMOVE -DVXWORKS -I@WIND_BASE@/target/h -fno-builtin -nostdinc -fvolatile -msoft-float| -#s|@LIB_CFLAGS@|@GENERAL_CFLAGS@ -DCPU=CPU32 -mnobitfield -DWANT_NONBLOCKING -DHAVE_MEMMOVE -DVXWORKS -I@WIND_BASE@/target/h -fno-builtin -nostdinc -fvolatile -msoft-float| diff --git a/lib/diameter/autoconf/vxworks/sed.vxworks_ppc32 b/lib/diameter/autoconf/vxworks/sed.vxworks_ppc32 deleted file mode 100644 index 9104b24ed3..0000000000 --- a/lib/diameter/autoconf/vxworks/sed.vxworks_ppc32 +++ /dev/null @@ -1,52 +0,0 @@ -# -# %CopyrightBegin% -# -# Copyright Ericsson AB 2006-2011. 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% -# -# Author: Peter Andersson -# -# This sed program file is intended to be used when creating Makefiles for vxworks -# from the generic Makefile.in that is found in a number of directories (see configure.vxworks) -# -# -# -s|@host@|vxworks_ppc32| -s|@system_type@|vxworks_ppc32| -s|@ARCH@|ppc32| -s|@CC@|GCC_EXEC_PREFIX=@WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/lib/gcc-lib/ @WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/bin/ccppc -mlongcall| -s|@HCC@|gcc| -s|@LD@|GCC_EXEC_PREFIX=@WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/lib/gcc-lib/ @WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/bin/ldppc| -s|@STRIP@|GCC_EXEC_PREFIX=@WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/lib/gcc-lib/ @WIND_BASE@/workbench-2.3/@HOST_TYPE@/bin/stripppc| -s|@SYMPREFIX@|| -s|@LIBS@|| -s|@GCCLIBFLAGS@|-L@WIND_BASE@/vxworks-6.3/target/lib/ppc/PPC32/common -lgcc| -s|@DED_LD@|GCC_EXEC_PREFIX=@WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/lib/gcc-lib/ @WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/bin/ldppc| -s|@DED_CFLAGS@|@CFLAGS@| -s|@DEBUG_CFLAGS@|@CFLAGS@| -# generate dwarf debug code on PPC .. -s|@DEBUG_FLAGS@|-gdwarf| -# remove -g option -s|TYPE_FLAGS = -g |TYPE_FLAGS = | -s|@GCCLIB_PATH@|@WIND_BASE@/vxworks-6.3/target/lib/ppc/PPC32/common/libgcc.a| -s|@RANLIB@|GCC_EXEC_PREFIX=@WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/lib/gcc-lib/ @WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/bin/ranlibppc| -s|@AR@|GCC_EXEC_PREFIX=@WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/lib/gcc-lib/ @WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/bin/arppc| -# -Dasm(X)= is for beam - -s|@LIB_CFLAGS@|@CFLAGS@| - -s|@CFLAGS@|@GENERAL_CFLAGS@ -DCPU=PPC32 -DTOOL_FAMILY=gnu -DTOOL=gnu -DWANT_NONBLOCKING -DHAVE_SENS -DHAVE_MEMMOVE -DVXWORKS -I@WIND_BASE@/vxworks-6.3/target/h -I@WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/lib/gcc/powerpc-wrs-vxworks/3.4.4/include -I@WIND_BASE@/vxworks-6.3/target/h/wrn/coreip -mstrict-align -fvolatile -fno-builtin | - -#s|@LIB_CFLAGS@|@GENERAL_CFLAGS@ -DCPU=PPC32 -DTOOL_FAMILY=gnu -DTOOL=gnu -DWANT_NONBLOCKING -DHAVE_SENS -DHAVE_MEMMOVE -DVXWORKS -I@WIND_BASE@/vxworks-6.3/target/h/wrn/coreip -I@WIND_BASE@/vxworks-6.3/target/h -mstrict-align -fvolatile -fno-builtin | diff --git a/lib/diameter/autoconf/vxworks/sed.vxworks_ppc603 b/lib/diameter/autoconf/vxworks/sed.vxworks_ppc603 deleted file mode 100644 index e1dd7c5afd..0000000000 --- a/lib/diameter/autoconf/vxworks/sed.vxworks_ppc603 +++ /dev/null @@ -1,51 +0,0 @@ -# -# %CopyrightBegin% -# -# Copyright Ericsson AB 2000-2011. 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% -# -# Author: Patrik Winroth -# -# This sed program file is intended to be used when creating Makefiles for vxworks -# from the generic Makefile.in that is found in a number of directories (see configure.vxworks) -# -# -# -s|@host@|vxworks_ppc603| -s|@system_type@|vxworks_ppc603| -s|@ARCH@|ppc603| -s|@CC@|@TTPREFIX@ccppc -mlongcall| -s|@HCC@|gcc| -s|@LD@|@TTPREFIX@ldppc| -s|@STRIP@|@TTPREFIX@stripppc| -s|@SYMPREFIX@|| -s|@LIBS@|| -s|@GCCLIBFLAGS@|-L@WIND_BASE@/host/@HOST_TYPE@/lib/gcc-lib/powerpc-wrs-vxworks/cygnus-2.7.2-960126 -lgcc| -s|@DED_LD@|@TTPREFIX@ldppc| -s|@DED_CFLAGS@|@CFLAGS@| -s|@DEBUG_CFLAGS@|@CFLAGS@| -# generate dwarf debug code on PPC .. -s|@DEBUG_FLAGS@|-gdwarf| -# remove -g option -s|TYPE_FLAGS = -g |TYPE_FLAGS = | -s|@GCCLIB_PATH@|@WIND_BASE@/host/@HOST_TYPE@/lib/gcc-lib/powerpc-wrs-vxworks/cygnus-2.7.2-960126/libgcc.a| -s|@RANLIB@|@TTPREFIX@ranlibppc| -s|@AR@|@TTPREFIX@arppc| -# -Dasm(X)= is for beam - -s|@LIB_CFLAGS@|@CFLAGS@| - -s|@CFLAGS@|@GENERAL_CFLAGS@ -DCPU=PPC603 -DWANT_NONBLOCKING -DHAVE_MEMMOVE -DVXWORKS -I@WIND_BASE@/target/h -mstrict-align -fvolatile -fno-builtin -fno-for-scope -D_GNU_TOOL| -#s|@LIB_CFLAGS@|@GENERAL_CFLAGS@ -DCPU=PPC603 -DWANT_NONBLOCKING -DHAVE_MEMMOVE -DVXWORKS -I@WIND_BASE@/target/h -mstrict-align -fvolatile -fno-builtin -fno-for-scope -D_GNU_TOOL| diff --git a/lib/diameter/autoconf/vxworks/sed.vxworks_ppc603_nolongcall b/lib/diameter/autoconf/vxworks/sed.vxworks_ppc603_nolongcall deleted file mode 100644 index 5d7673d323..0000000000 --- a/lib/diameter/autoconf/vxworks/sed.vxworks_ppc603_nolongcall +++ /dev/null @@ -1,51 +0,0 @@ -# -# %CopyrightBegin% -# -# Copyright Ericsson AB 1997-2011. 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% -# -# Author: Patrik Winroth -# -# This sed program file is intended to be used when creating Makefiles for vxworks -# from the generic Makefile.in that is found in a number of directories (see configure.vxworks) -# -# -# -s|@host@|vxworks_ppc603| -s|@system_type@|vxworks_ppc603| -s|@ARCH@|ppc603| -s|@CC@|@TTPREFIX@ccppc| -s|@HCC@|gcc| -s|@LD@|@TTPREFIX@ldppc| -s|@STRIP@|@TTPREFIX@stripppc| -s|@SYMPREFIX@|| -s|@LIBS@|| -s|@GCCLIBFLAGS@|-L@WIND_BASE@/host/@HOST_TYPE@/lib/gcc-lib/powerpc-wrs-vxworks/cygnus-2.7.2-960126 -lgcc| -s|@DED_LD@|@TTPREFIX@ldppc| -s|@DED_CFLAGS@|@CFLAGS@| -# generate dwarf debug code on PPC .. -s|@DEBUG_FLAGS@|-gdwarf| -# remove -g option -s|TYPE_FLAGS = -g |TYPE_FLAGS = | -s|@GCCLIB_PATH@|@WIND_BASE@/host/@HOST_TYPE@/lib/gcc-lib/powerpc-wrs-vxworks/cygnus-2.7.2-960126/libgcc.a| -s|@RANLIB@|@TTPREFIX@ranlibppc| -s|@AR@|@TTPREFIX@arppc| -# -Dasm(X)= is for beam - -s|@LIB_CFLAGS@|@CFLAGS@| - -s|@CFLAGS@|@GENERAL_CFLAGS@ -DCPU=PPC603 -DWANT_NONBLOCKING -DHAVE_MEMMOVE -DVXWORKS -I@WIND_BASE@/target/h -mstrict-align -fvolatile -fno-builtin -fno-for-scope -D_GNU_TOOL| -#s|@LIB_CFLAGS@|@GENERAL_CFLAGS@ -DCPU=PPC603 -DWANT_NONBLOCKING -DHAVE_MEMMOVE -DVXWORKS -I@WIND_BASE@/target/h -mstrict-align -fvolatile -fno-builtin -fno-for-scope -D_GNU_TOOL| - diff --git a/lib/diameter/autoconf/vxworks/sed.vxworks_ppc860 b/lib/diameter/autoconf/vxworks/sed.vxworks_ppc860 deleted file mode 100644 index 7a3c32df5b..0000000000 --- a/lib/diameter/autoconf/vxworks/sed.vxworks_ppc860 +++ /dev/null @@ -1,50 +0,0 @@ -# -# %CopyrightBegin% -# -# Copyright Ericsson AB 1997-2011. 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% -# -# Author: Patrik Winroth -# -# This sed program file is intended to be used when creating Makefiles for vxworks -# from the generic Makefile.in that is found in a number of directories (see configure.vxworks) -# -# -# -s|@host@|vxworks_ppc860| -s|@system_type@|vxworks_ppc860| -s|@ARCH@|ppc860| -s|@CC@|@TTPREFIX@ccppc -mlongcall| -s|@HCC@|gcc| -s|@LD@|@TTPREFIX@ldppc| -s|@STRIP@|@TTPREFIX@stripppc| -s|@SYMPREFIX@|| -s|@LIBS@|| -s|@GCCLIBFLAGS@|-L@WIND_BASE@/host/@HOST_TYPE@/lib/gcc-lib/powerpc-wrs-vxworks/cygnus-2.7.2-960126/soft-float -lgcc| -s|@DED_LD@|@TTPREFIX@ldppc| -s|@DED_CFLAGS@|@CFLAGS@| -s|@DEBUG_CFLAGS@|@CFLAGS@| -# generate dwarf debug code on PPC .. -s|@DEBUG_FLAGS@|-gdwarf| -# remove -g option (go for dwarf) -s|TYPE_FLAGS = -g |TYPE_FLAGS = | -s|@GCCLIB_PATH@|@WIND_BASE@/host/@HOST_TYPE@/lib/gcc-lib/powerpc-wrs-vxworks/cygnus-2.7.2-960126/soft-float/libgcc.a| -s|@RANLIB@|@TTPREFIX@ranlibppc| -s|@AR@|@TTPREFIX@arppc| - -s|@LIB_CFLAGS@|@CFLAGS@| - -s|@CFLAGS@|@GENERAL_CFLAGS@ -DCPU=PPC860 -DWANT_NONBLOCKING -DHAVE_MEMMOVE -DVXWORKS -I@WIND_BASE@/target/h -mcpu=860 -fvolatile -fno-builtin -fno-for-scope -msoft-float -D_GNU_TOOL -nostdinc| -#s|@LIB_CFLAGS@|@GENERAL_CFLAGS@ -DCPU=PPC860 -DWANT_NONBLOCKING -DHAVE_MEMMOVE -DVXWORKS -I@WIND_BASE@/target/h -mcpu=powerpc -fvolatile -fno-builtin -fno-for-scope -msoft-float -D_GNU_TOOL -nostdinc| diff --git a/lib/diameter/autoconf/vxworks/sed.vxworks_simlinux b/lib/diameter/autoconf/vxworks/sed.vxworks_simlinux deleted file mode 100644 index 56eae6507c..0000000000 --- a/lib/diameter/autoconf/vxworks/sed.vxworks_simlinux +++ /dev/null @@ -1,59 +0,0 @@ -# -# %CopyrightBegin% -# -# Copyright Ericsson AB 2008-2011. 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% -# -# Author: Peter Andersson -# -# This sed program file is intended to be used when creating Makefiles for vxworks -# from the generic Makefile.in that is found in a number of directories (see configure.vxworks) -# -# -# -s|@host@|vxworks_simlinux| -s|@system_type@|vxworks_simlinux| -s|@ARCH@|simlinux| - -s|@CC@|GCC_EXEC_PREFIX=@WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/lib/gcc-lib/ @WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/bin/ccpentium| - -s|@HCC@|gcc| - -s|@LD@|GCC_EXEC_PREFIX=@WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/lib/gcc-lib/ @WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/bin/ldpentium| - -#s|@STRIP@|GCC_EXEC_PREFIX=@WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/lib/gcc-lib/ @WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/bin/strip| -s|@STRIP@|| - -s|@SYMPREFIX@|| -s|@LIBS@|| -s|@GCCLIBFLAGS@|-L@WIND_BASE@/vxworks-6.3/target/lib/simlinux/SIMLINUX/common -lgcc| - -s|@DED_LD@|GCC_EXEC_PREFIX=@WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/lib/gcc-lib/ @WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/bin/ldpentium| - -s|@DED_CFLAGS@|@CFLAGS@| -s|@DEBUG_CFLAGS@|@CFLAGS@| -# remove -g option -s|TYPE_FLAGS = -g |TYPE_FLAGS = | -s|@GCCLIB_PATH@|@WIND_BASE@/vxworks-6.3/target/lib/simlinux/SIMLINUX/common/libgcc.a| - -s|@RANLIB@|GCC_EXEC_PREFIX=@WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/lib/gcc-lib/ @WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/bin/ranlibpentium| - -s|@AR@|GCC_EXEC_PREFIX=@WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/lib/gcc-lib/ @WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/bin/arpentium| - -# -Dasm(X)= is for beam -s|@LIB_CFLAGS@|@CFLAGS@| - -s|@CFLAGS@|@GENERAL_CFLAGS@ -DCPU=SIMLINUX -DTOOL_FAMILY=gnu -DTOOL=gnu -DWANT_NONBLOCKING -DHAVE_SENS -DHAVE_MEMMOVE -DVXWORKS -DDEBUG -I@WIND_BASE@/vxworks-6.3/target/h -I@WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/lib/gcc/i586-wrs-vxworks/3.4.4/include -I@WIND_BASE@/vxworks-6.3/target/h/wrn/coreip -fvolatile -fno-builtin | -#s|@LIB_CFLAGS@|@GENERAL_CFLAGS@ -DCPU=SIMLINUX -DTOOL_FAMILY=gnu -DTOOL=gnu -DWANT_NONBLOCKING -DHAVE_SENS -DHAVE_MEMMOVE -DVXWORKS -DDEBUG -I@WIND_BASE@/vxworks-6.3/target/h -I@WIND_BASE@/vxworks-6.3/target/h/wrn/coreip -mstrict-align -fvolatile -fno-builtin | diff --git a/lib/diameter/autoconf/vxworks/sed.vxworks_simso b/lib/diameter/autoconf/vxworks/sed.vxworks_simso deleted file mode 100644 index 6b845d31de..0000000000 --- a/lib/diameter/autoconf/vxworks/sed.vxworks_simso +++ /dev/null @@ -1,64 +0,0 @@ -# -# %CopyrightBegin% -# -# Copyright Ericsson AB 2005-2011. 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% -# -# Author: Peter Andersson -# -# This sed program file is intended to be used when creating Makefiles for vxworks -# from the generic Makefile.in that is found in a number of directories (see configure.vxworks) -# -# -# -s|@host@|vxworks_simso| -s|@system_type@|vxworks_simso| -s|@ARCH@|simso| - -# Tornado2.2: s|@CC@|@TTPREFIX@ccsimso| -s|@CC@|GCC_EXEC_PREFIX=@WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/lib/gcc-lib/ @WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/bin/ccsparc| - -s|@HCC@|gcc| - -# Tornado2.2: s|@LD@|@TTPREFIX@ldsimso| -s|@LD@|GCC_EXEC_PREFIX=@WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/lib/gcc-lib/ @WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/bin/ldsparc| - -# Tornado2.2: s|@STRIP@|@TTPREFIX@stripsimso| -s|@STRIP@|GCC_EXEC_PREFIX=@WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/lib/gcc-lib/ @WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/bin/stripsparc| - -s|@SYMPREFIX@|| -s|@LIBS@|| -s|@GCCLIBFLAGS@|-L@WIND_BASE@/vxworks-6.3/target/lib/simso/SIMSPARCSOLARIS/common -lgcc| - -# Tornado2.2: s|@DED_LD@|@TTPREFIX@ldsimso| -s|@DED_LD@|GCC_EXEC_PREFIX=@WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/lib/gcc-lib/ @WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/bin/ldsparc| - -s|@DED_CFLAGS@|@CFLAGS@| -s|@DEBUG_CFLAGS@|@CFLAGS@| -# remove -g option -s|TYPE_FLAGS = -g |TYPE_FLAGS = | -s|@GCCLIB_PATH@|@WIND_BASE@/vxworks-6.3/target/lib/simso/SIMSPARCSOLARIS/common/libgcc.a| - -# Tornado2.2: s|@RANLIB@|@TTPREFIX@ranlibsimso| -s|@RANLIB@|GCC_EXEC_PREFIX=@WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/lib/gcc-lib/ @WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/bin/ranlibsparc| - -# Tornado2.2: s|@AR@|arsimso| -s|@AR@|GCC_EXEC_PREFIX=@WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/lib/gcc-lib/ @WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/bin/arsparc| - -# -Dasm(X)= is for beam -s|@LIB_CFLAGS@|@CFLAGS@| - -s|@CFLAGS@|@GENERAL_CFLAGS@ -DCPU=SIMSPARCSOLARIS -DTOOL_FAMILY=gnu -DTOOL=gnu -DWANT_NONBLOCKING -DHAVE_SENS -DHAVE_MEMMOVE -DVXWORKS -DDEBUG -I@WIND_BASE@/vxworks-6.3/target/h -I@WIND_BASE@/gnu/3.4.4-vxworks-6.3/@HOST_TYPE@/lib/gcc/sparc-wrs-vxworks/3.4.4/include -I@WIND_BASE@/vxworks-6.3/target/h/wrn/coreip -fvolatile -fno-builtin | -#s|@LIB_CFLAGS@|@GENERAL_CFLAGS@ -DCPU=SIMSPARCSOLARIS -DTOOL_FAMILY=gnu -DTOOL=gnu -DWANT_NONBLOCKING -DHAVE_SENS -DHAVE_MEMMOVE -DVXWORKS -DDEBUG -I@WIND_BASE@/vxworks-6.3/target/h -I@WIND_BASE@/vxworks-6.3/target/h/wrn/coreip -mstrict-align -fvolatile -fno-builtin | diff --git a/lib/diameter/autoconf/vxworks/sed.vxworks_sparc b/lib/diameter/autoconf/vxworks/sed.vxworks_sparc deleted file mode 100644 index 6f637d8746..0000000000 --- a/lib/diameter/autoconf/vxworks/sed.vxworks_sparc +++ /dev/null @@ -1,38 +0,0 @@ -# -# %CopyrightBegin% -# -# Copyright Ericsson AB 1997-2011. 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% -# -# Author: Patrik Winroth -# -# This sed program file is intended to be used when creating Makefiles for vxworks -# from the generic Makefile.in that is found in a number of directories (see configure.vxworks) -# - -# ccsparc -O2 doesn't work when compiling "rundir"/gc.c - signal 11 is generated when trying -# therefore it is compiled with -O1 instead, which works - get a new ccsparc ! -s/\$(COMPILE\.emu) -o \$@ -c gc\.c/$(CC) @CFLAGS@ @DEFS@ -O1 $(BEAM_MODE) -I$(SYSDIR) -I$(EMUDIR) -I. $(CPPFLAGS) -c -o $@ -c gc.c/ -s/@host@/vxworks_sparc/ -s/@system_type@/vxworks_sparc/ -s/@CC@/\/home\/gandalf\/bsproj\/tools\/vw-gnu\/solaris.sparc\/bin\/ccsparc/ -s/@HCC@/gcc/ -s/@LD@/\/home\/gandalf\/bsproj\/tools\/vw-gnu\/solaris.sparc\/bin\/ldsparc/ -s/@DEBUG_FLAGS@/-g/ -s/@GCCLIB_PATH@/\/home\/gandalf\/bsproj\/tools\/vw-gnu\/solaris.sparc\/lib\/gcc-lib\/sparc-wrs-vxworks\/cygnus-2.2.3.1\/libgcc.a/ -s/@RANLIB@/ranlibsparc/ -s/@AR@/arsparc/ -s/@CFLAGS@/-I\/home\/gandalf\/bsproj\/BS.2\/UOS\/vw\/5.2\/h -DWANT_NONBLOCKING -DHAVE_MEMMOVE -DCPU=SPARC -DVXWORKS -fno-builtin -nostdinc/ - diff --git a/lib/diameter/bin/diameterc b/lib/diameter/bin/diameterc index f5cf3ebc10..a72ba2d75c 100755 --- a/lib/diameter/bin/diameterc +++ b/lib/diameter/bin/diameterc @@ -33,19 +33,24 @@ usage() -> io:format( - "~w [options] file~n" + "~w [options] dict~n" "~n" " Compile a diameter dictionary file (.dia) to Erlang source (.erl)~n" " and/or header (.hrl) files.~n" "~n" " options:~n" - " -h = print this message~n" - " -v = verbose output~n" - " -o dir = set the output directory (default .)~n" - " -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", + "~n" + " --name name = set @name~n" + " --prefix prefix = set @prefix~n" + " --inherits dict|- = set/clear @inherits~n" + "~n" + " -h = print this message~n" + " -v = verbose output~n" + " -o dir = set the output directory (default .)~n" + " -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", [?MODULE]). main(Args) -> @@ -68,24 +73,30 @@ gen(Args) -> end. compile(#argv{file = File, options = Opts} = A) -> - try - Spec = diameter_spec_util:parse(File, Opts), - 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 - 0 + 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 + 0; + {error, Reason} -> + error_msg(diameter_dict_util:format_error(Reason), []), + 1 catch error: Reason -> - error_msg({"ERROR: ~p~n ~p", [Reason, erlang:get_stacktrace()]}), + error_msg("ERROR: ~p~n ~p", [Reason, erlang:get_stacktrace()]), 2 end. maybe_output(#argv{file = File, output = Output}, Spec, Opts, Mode) -> lists:member(Mode, Output) - andalso diameter_codegen:from_spec(File, Spec, Opts, Mode). + andalso diameter_codegen:from_dict(File, Spec, Opts, Mode). error_msg({Fmt, Args}) -> - io:format(standard_error, Fmt ++ "~n", Args). + error_msg(Fmt, Args). + +error_msg(Fmt, Args) -> + io:format(standard_error, "** " ++ Fmt ++ "~n", Args). norm({_,_} = T) -> T; @@ -109,9 +120,17 @@ arg(["-o", Dir | Args], #argv{options = Opts} = A) -> arg(Args, A#argv{options = [{outdir, Dir} | Opts]}); arg(["-i", Dir | Args], #argv{options = Opts} = A) -> - true = dir_exists(Dir), arg(Args, A#argv{options = Opts ++ [{include, Dir}]}); +arg(["--name", Name | Args], #argv{options = Opts} = A) -> + arg(Args, A#argv{options = [{name, Name} | Opts]}); + +arg(["--prefix", Name | Args], #argv{options = Opts} = A) -> + arg(Args, A#argv{options = [{prefix, Name} | Opts]}); + +arg(["--inherits", Dict | Args], #argv{options = Opts} = A) -> + arg(Args, A#argv{options = Opts ++ [{inherits, Dict}]}); + arg(["-E" | Args], #argv{output = Output} = A) -> arg(Args, A#argv{output = lists:delete(erl, Output)}); @@ -120,10 +139,10 @@ arg(["-H" | Args], #argv{output = Output} = A) -> arg(["-d" | Args], #argv{options = Opts, output = Output} = A) -> arg(Args, A#argv{options = [debug | Opts], - output = [spec | Output]}); + output = [spec | Output]}); arg([[$- = M, C, H | T] | Args], A) %% clustered options - when C /= $i, C /= $o -> + when C /= $i, C /= $o, C /= $- -> arg([[M,C], [M,H|T] | Args], A); arg([File], A) -> diff --git a/lib/diameter/configure.in b/lib/diameter/configure.in deleted file mode 100644 index 9aca3859c5..0000000000 --- a/lib/diameter/configure.in +++ /dev/null @@ -1,138 +0,0 @@ -dnl Process this file with autoconf to produce a configure script. - -dnl %CopyrightBegin% -dnl -dnl Copyright Ericsson AB 1998-2011. All Rights Reserved. -dnl -dnl The contents of this file are subject to the Erlang Public License, -dnl Version 1.1, (the "License"); you may not use this file except in -dnl compliance with the License. You should have received a copy of the -dnl Erlang Public License along with this software. If not, it can be -dnl retrieved online at http://www.erlang.org/. -dnl -dnl Software distributed under the License is distributed on an "AS IS" -dnl basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See -dnl the License for the specific language governing rights and limitations -dnl under the License. -dnl -dnl %CopyrightEnd% - -if test "x$no_recursion" != "xyes" -a "x$OVERRIDE_CONFIG_CACHE" = "x"; then - # We do not want to use a common cache! - cache_file=/dev/null -fi - -AC_INIT(vsn.mk) - -dnl <STANDALONE DIAMETER> -dnl This is needed for diameters own environment to rock, -dnl but since we are now integrated into OTP, we skip it. -dnl In order to build stand-alone we need atleast 2.63... -dnl AC_PREREQ(2.63) -dnl </STANDALONE DIAMETER> - -dnl LM_PRECIOUS_VARS - - -dnl The OTP source tree is the default "top", -dnl but we can also define our own top: DIAMETER_TOP - -if test -n "$ERL_TOP" || test -d $ERL_TOP ; then - erl_top=${ERL_TOP} - AC_CONFIG_AUX_DIRS($erl_top/erts/autoconf) - DIAMETER_TOP=${ERL_TOP}/lib/diameter -else - AC_ARG_VAR(DIAMETER_TOP, [Diameter top source directory]) - if test -n "$DIAMETER_TOP" || test -d $DIAMETER_TOP ; then - AC_CONFIG_AUX_DIRS(autoconf) - fi - - dnl <STANDALONE DIAMETER> - dnl AC_ERLANG_SUBST_ROOT_DIR - dnl AC_ERLANG_SUBST_LIB_DIR - dnl AC_ERLANG_CHECK_LIB([erl_docgen], - dnl [echo "erl_docgen version \"$ERLANG_LIB_VER_erl_docgen\"" - dnl echo "is installed in \"$ERLANG_LIB_DIR_erl_docgen\""], - dnl [AC_MSG_ERROR([erl_docgen was not found!])]) - dnl AC_ERLANG_CHECK_LIB([test_server], - dnl [echo "test_server version \"$ERLANG_LIB_VER_test_server\"" - dnl echo "is installed in \"$ERLANG_LIB_DIR_test_server\""], - dnl [AC_MSG_ERROR([test_server was not found!])]) - dnl </STANDALONE DIAMETER> - -fi - -AC_SUBST(DIAMETER_TOP) -export DIAMETER_TOP - -if test "X$host" != "Xfree_source" -a "X$host" != "Xwin32"; then - AC_CANONICAL_HOST -fi - -TARGET=$host -AC_SUBST(TARGET) - -if test "x$erl_top" = "x"; then - dnl STANDALONE DIAMETER - AC_CHECK_PROGS(XSLTPROC, xsltproc) - if test -z "$XSLTPROC"; then - echo "xsltproc" >> doc/CONF_INFO - AC_MSG_WARN([No 'xsltproc' command found: the documentation can not be built]) - fi - - AC_CHECK_PROGS(FOP, fop) - if test -z "$FOP"; then - AC_MSG_ERROR([No 'fop' command found: the documentation can not be built]) - fi -fi - -dnl -dnl We can live with Solaris /usr/ucb/install -dnl -case $host in - *-*-solaris*|free_source) - if test -x /usr/ucb/install; then - INSTALL="/usr/ucb/install -c" - fi - ;; - *) - ;; -esac -AC_PROG_INSTALL -LM_PROG_INSTALL_DIR - -case $host_os in - darwin*) - dnl Need to preserve modification time on archives; - dnl otherwise, ranlib has to be run on archives - dnl again after installation. - INSTALL_DATA="$INSTALL_DATA -p";; - *) - ;; -esac - -dnl -dnl Fix for Tilera install permissions -dnl - -case $build in - *tile*) - INSTALL_PROGRAM="$INSTALL_PROGRAM -m755" - INSTALL_SCRIPT="$INSTALL_SCRIPT -m755" - ;; - *) - ;; -esac - - -dnl <STANDALONE DIAMETER> -dnl AC_ERLANG_NEED_ERL([$PATH]) -dnl AC_ERLANG_NEED_ERLC([$PATH]) -dnl </STANDALONE DIAMETER> - -AC_OUTPUT( - Makefile:Makefile.in - src/app/diameter.mk:src/app/diameter.mk.in - make/$host/rules.mk:make/rules.mk.in - ) - diff --git a/lib/diameter/doc/.gitignore b/lib/diameter/doc/.gitignore new file mode 100644 index 0000000000..b634bdd7ba --- /dev/null +++ b/lib/diameter/doc/.gitignore @@ -0,0 +1,4 @@ + +/html/ +/man*/ +/pdf/ diff --git a/lib/diameter/doc/src/.gitignore b/lib/diameter/doc/src/.gitignore index feeb378fd8..5776e1cc76 100644 --- a/lib/diameter/doc/src/.gitignore +++ b/lib/diameter/doc/src/.gitignore @@ -1,2 +1,3 @@ /depend.mk +/seehere.ent diff --git a/lib/diameter/doc/src/Makefile b/lib/diameter/doc/src/Makefile index 1453138cb6..8ad38ba0d5 100644 --- a/lib/diameter/doc/src/Makefile +++ b/lib/diameter/doc/src/Makefile @@ -1,7 +1,7 @@ # # %CopyrightBegin% # -# Copyright Ericsson AB 2010-2011. All Rights Reserved. +# Copyright Ericsson AB 2010-2012. 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 @@ -16,13 +16,8 @@ # # %CopyrightEnd% -ifneq ($(ERL_TOP),) include $(ERL_TOP)/make/target.mk include $(ERL_TOP)/make/$(TARGET)/otp.mk -else -include $(DIAMETER_TOP)/make/target.mk -include $(DIAMETER_TOP)/make/$(TARGET)/rules.mk -endif include ../../vsn.mk @@ -39,7 +34,8 @@ XML_REF_FILES = $(XML_REF1_FILES) $(XML_REF3_FILES) $(XML_REF4_FILES) XML_FILES = $(BOOK_FILES) $(XML_APPLICATION_FILES) \ $(XML_REF_FILES) \ - $(XML_PART_FILES) $(XML_CHAPTER_FILES) + $(XML_PART_FILES) $(XML_CHAPTER_FILES) \ + seealso.ent INTERNAL_HTML_FILES = $(TECHNICAL_DESCR_FILES:%.xml=$(HTMLDIR)/%.html) @@ -98,7 +94,7 @@ html: gifs $(HTML_REF_MAN_FILE) clean clean_docs: clean_pdf clean_html clean_man rm -f errs core *~ - rm -f depend.mk + rm -f depend.mk seehere.ent clean_pdf: rm -f $(PDFDIR)/* @@ -126,8 +122,6 @@ debug opt: info: @echo "->Makefile<-" @echo "" - @echo "DOCSUPPORT = $(DOCSUPPORT)" - @echo "" @echo "INDEX_FILE = $(INDEX_FILE)" @echo "INDEX_SRC = $(INDEX_SRC)" @echo "INDEX_TARGET = $(INDEX_TARGET)" @@ -141,10 +135,6 @@ info: @echo "" @echo "GIF_FILES = $(GIF_FILES)" @echo "" - @echo "TEX_FILES_USERS_GUIDE = $(TEX_FILES_USERS_GUIDE)" - @echo "TEX_FILES_REF_MAN = $(TEX_FILES_REF_MAN)" - @echo "TEX_FILES_BOOK = $(TEX_FILES_BOOK)" - @echo "" @echo "MAN1_FILES = $(MAN1_FILES)" @echo "MAN3_FILES = $(MAN3_FILES)" @echo "MAN4_FILES = $(MAN4_FILES)" @@ -161,30 +151,29 @@ info: # ---------------------------------------------------- # Release Target # ---------------------------------------------------- -ifneq ($(ERL_TOP),) + include $(ERL_TOP)/make/otp_release_targets.mk -else -include $(DIAMETER_TOP)/make/release_targets.mk -endif release_docs_spec: $(LOCAL)docs - $(INSTALL_DIR) $(RELSYSDIR)/doc/pdf - $(INSTALL_DIR) $(RELSYSDIR)/doc/html - $(INSTALL_DIR) $(RELEASE_PATH)/man/man1 - $(INSTALL_DIR) $(RELEASE_PATH)/man/man3 - $(INSTALL_DIR) $(RELEASE_PATH)/man/man4 - $(INSTALL_DATA) $(TOP_PDF_FILE) $(RELSYSDIR)/doc/pdf - $(INSTALL_DATA) $(HTMLDIR)/*.* $(RELSYSDIR)/doc/html - $(INSTALL_DATA) $(INFO_FILE) $(RELSYSDIR) - $(INSTALL_DATA) $(MAN1_FILES) $(RELEASE_PATH)/man/man1 - $(INSTALL_DATA) $(MAN3_FILES) $(RELEASE_PATH)/man/man3 - $(INSTALL_DATA) $(MAN4_FILES) $(RELEASE_PATH)/man/man4 - [ -z "$(LOCAL)" ] || cp -r $(HTMLDIR)/js $(RELSYSDIR)/doc/html + $(INSTALL_DIR) "$(RELSYSDIR)/doc/pdf" + $(INSTALL_DIR) "$(RELSYSDIR)/doc/html" + $(INSTALL_DIR) "$(RELEASE_PATH)/man/man1" + $(INSTALL_DIR) "$(RELEASE_PATH)/man/man3" + $(INSTALL_DIR) "$(RELEASE_PATH)/man/man4" + $(INSTALL_DATA) $(TOP_PDF_FILE) "$(RELSYSDIR)/doc/pdf" + $(INSTALL_DATA) $(HTMLDIR)/*.* "$(RELSYSDIR)/doc/html" + $(INSTALL_DATA) $(INFO_FILE) "$(RELSYSDIR)" + $(INSTALL_DATA) $(MAN1_FILES) "$(RELEASE_PATH)/man/man1" + $(INSTALL_DATA) $(MAN3_FILES) "$(RELEASE_PATH)/man/man3" + $(INSTALL_DATA) $(MAN4_FILES) "$(RELEASE_PATH)/man/man4" + [ -z "$(LOCAL)" ] || cp -r $(HTMLDIR)/js "$(RELSYSDIR)/doc/html" echo $(LOCAL) release_spec: -depend.mk: depend.sed $(XML_REF_FILES) $(XML_CHAPTER_FILES) Makefile +depend.mk: depend.sed Makefile seealso.ent \ + $(XML_REF_FILES) $(XML_CHAPTER_FILES) + sed -f seehere.sed seealso.ent > seehere.ent (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/depend.sed b/lib/diameter/doc/src/depend.sed index 5973c4586e..42de597f15 100644 --- a/lib/diameter/doc/src/depend.sed +++ b/lib/diameter/doc/src/depend.sed @@ -21,14 +21,18 @@ # massaged in Makefile. # -/^<com>\([^<]*\)<\/com>/b rf -/^<module>\([^<]*\)<\/module>/b rf +/^<com>/b c +/^<module>/b c /^<chapter>/!d +# Chapter: html basename is same as xml. s@@$(HTMLDIR)/%FILE%.html: %FILE%.xml@ q -:rf -s@@$(HTMLDIR)/\1.html: %FILE%.xml@ +# Reference: html basename is from contents of com/module element. +:c +s@^[^>]*>@@ +s@<.*@@ +s@.*@$(HTMLDIR)/&.html: %FILE%.xml@ q diff --git a/lib/diameter/doc/src/diameter.xml b/lib/diameter/doc/src/diameter.xml index 2cad70e3bc..b7669b760b 100644 --- a/lib/diameter/doc/src/diameter.xml +++ b/lib/diameter/doc/src/diameter.xml @@ -1,11 +1,22 @@ <?xml version="1.0" encoding="latin1" ?> -<!DOCTYPE erlref SYSTEM "erlref.dtd"> +<!DOCTYPE erlref SYSTEM "erlref.dtd" [ + <!ENTITY make_ref + '<seealso marker="erts:erlang#make_ref-0">erlang:make_ref/0</seealso>'> + <!ENTITY transport_module + '<seealso marker="diameter_transport">transport module</seealso>'> + <!ENTITY dictionary + '<seealso marker="diameter_dict">dictionary</seealso>'> + <!ENTITY % also SYSTEM "seealso.ent" > + <!ENTITY % here SYSTEM "seehere.ent" > + %also; + %here; +]> <erlref> <header> <copyright> -<year>2011</year> +<year>2011</year><year>2012</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -43,35 +54,30 @@ under the License. <description> <p> -This module provides the interface with which a user -creates a service that sends and receives messages using the -Diameter protocol as defined in RFC 3588.</p> +This module provides the interface with which a user can +implement a Diameter node that sends and receives messages using the +Diameter protocol as defined in &the_rfc;.</p> <p> Basic usage consists of creating a representation of a -locally implemented Diameter peer and its capabilities with <seealso -marker="#start_service">start_service/2</seealso>, adding transport -capability using <seealso -marker="#add_transport">add_transport/2</seealso> and sending Diameter -requests and receiving Diameter answers with <seealso -marker="#call">call/4</seealso>. +locally implemented Diameter node and its capabilities with +&start_service;, adding transport capability using +&add_transport; and sending Diameter +requests and receiving Diameter answers with &call;. Incoming Diameter requests are communicated as callbacks to a -<seealso -marker="diameter_app">diameter_app(3)</seealso> callback modules as +&man_app; callback modules as specified in the service configuration.</p> <p> -Beware the difference between <em>diameter application</em> and -<em>Diameter application</em>. +Beware the difference between <em>diameter</em> (not capitalised) and +<em>Diameter</em> (capitalised). The former refers to the Erlang application named diameter whose main -api is defined here, the latter to an application of the Diameter -protocol in the sense of RFC 3588. -More generally, capitalized Diameter refers to the RFC -and diameter to this implementation.</p> +api is defined here, the latter to Diameter protocol in the sense of +&the_rfc;.</p> <p> -The diameter application must be started before calling functions in -this module.</p> +The diameter application must be started before calling most functions +in this module.</p> </description> @@ -84,13 +90,15 @@ this module.</p> <tag><c>Address()</c></tag> <tag><c>DiameterIdentity()</c></tag> +<tag><c>Grouped()</c></tag> +<tag><c>OctetString()</c></tag> <tag><c>Time()</c></tag> <tag><c>Unsigned32()</c></tag> <tag><c>UTF8String()</c></tag> <item> <p> -Types corresponding to RFC 3588 AVP Data Formats. -Defined in <seealso marker="diameter_dict">diameter_dict(4)</seealso>.</p> +Types corresponding to &the_rfc; AVP Data Formats. +Defined in &dict_data_types;.</p> <marker id="application_alias"/> </item> @@ -99,31 +107,34 @@ Defined in <seealso marker="diameter_dict">diameter_dict(4)</seealso>.</p> <item> <p> A name identifying a Diameter application in -service configuration passed to <seealso -marker="#start_service">start_service/2</seealso> and passed to -<seealso marker="#call">call/4</seealso> when sending requests -belonging to the application.</p> +service configuration. +Passed to &call; when sending requests +defined by the application.</p> <marker id="application_module"/> </item> -<tag><c>application_module() = Mod | [Mod | ExtraArgs]</c></tag> +<tag><c>application_module() = Mod + | [Mod | ExtraArgs] + | #diameter_callback{}</c></tag> <item> -<code> +<pre> Mod = atom() ExtraArgs = list() -</code> +</pre> <p> -A module implementing the callback interface defined in <seealso -marker="diameter_app">diameter_app(3)</seealso>, along with any +A module implementing the callback interface defined in &man_app;, +along with any extra arguments to be appended to those documented for the interface. -Any extra arguments are appended to the documented list of arguments for -each function. -Note that additional arguments specific to an outgoing request be -specified to <seealso marker="#call">call/4</seealso>, in which case -the call-specific arguments are appended to any specified with the -callback module.</p> +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> + +<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> <marker id="application_opt"/> </item> @@ -132,18 +143,18 @@ callback module.</p> <item> <p> -Options defining a Diameter application as configured in an -<c>application</c> option passed to -<seealso marker="#start_service">start_service/2</seealso>.</p> +Options defining a Diameter application. +Has one the following types.</p> <taglist> -<tag><c>{alias, application_alias()}</c></tag> +<tag><c>{alias, &application_alias;}</c></tag> <item> <p> An unique identifier for the application in the scope of the service. -Optional, defaults to the value of the <c>dictionary</c> option.</p> +Defaults to the value of the <c>dictionary</c> option if +unspecified.</p> </item> <tag><c>{dictionary, atom()}</c></tag> @@ -152,47 +163,43 @@ Optional, defaults to the value of the <c>dictionary</c> option.</p> The 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 <seealso -marker="diameter_dict">diameter_dict(4)</seealso>.</p> +documented in &man_dict;.</p> </item> -<tag><c>{module, application_module()}</c></tag> +<tag><c>{module, &application_module;}</c></tag> <item> <p> -A callback module with which messages of the Diameter application are +The callback module with which messages of the Diameter application are handled. -See <seealso marker="diameter_app">diameter_app(3)</seealso> for -information on the required interface and semantics.</p> +See &man_app; for the required interface and semantics.</p> </item> <tag><c>{state, term()}</c></tag> <item> <p> The initial callback state. -Defaults to the value of the <c>alias</c> option if unspecified. -The prevailing state is passed to certain -<seealso marker="diameter_app">diameter_app(3)</seealso> -callbacks, which can then return a new state.</p> +The prevailing state is passed to some +&man_app; +callbacks, which can then return a new state. +Defaults to the value of the <c>alias</c> option if unspecified.</p> </item> <tag><c>{call_mutates_state, true|false}</c></tag> <item> <p> -Specifies whether or not the <seealso -marker="diameter_app#pick_peer">pick_peer/4</seealso> -application callback (following from a call to -<seealso marker="#call">call/4</seealso>) -can modifiy state, +Specifies whether or not the &app_pick_peer; +application callback can modify the application state, Defaults to <c>false</c> if unspecified.</p> +<note> <p> -Note that <seealso -marker="diameter_app#pick_peer">pick_peer</seealso> callbacks are -serialized when these are allowed to modify state, which is a +&app_pick_peer; callbacks +are serialized when these are allowed to modify state, 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 but -sending its own requests should probably avoid it.</p> +state but a server or agent that responds to incoming request should +probably avoid it.</p> +</note> </item> <tag><c>{answer_errors, callback|report|discard}</c></tag> @@ -200,18 +207,16 @@ sending its own requests should probably avoid it.</p> <p> Determines the manner in which incoming answer messages containing decode errors are handled. -If <c>callback</c> then errors result in a <seealso -marker="diameter_app#handle_answer">handle_answer/4</seealso> -callback in the same fashion as for <seealso -marker="diameter_app#handle_request">handle_request/3</seealso>, in the -<c>errors</c> field of the <c>diameter_packet</c> record passed into -the callback. +If <c>callback</c> then errors result in a &app_handle_answer; +callback in the same fashion as for &app_handle_request;, with +errors communicated in the <c>errors</c> field of the +<c>#diameter_packet{}</c> record passed to the callback. If <c>report</c> then an answer containing errors is discarded without a callback and a warning report is written to the log. If <c>discard</c> then an answer containing errors is silently discarded without a callback. In both the <c>report</c> and <c>discard</c> cases the return value -for the <seealso marker="#call">call/4</seealso> invocation in +for the &call; invocation in question is as if a callback had taken place and returned <c>{error, failure}</c>.</p> @@ -228,8 +233,9 @@ Defaults to <c>report</c> if unspecified.</p> <item> <p> -Options available to <seealso marker="#call">call/4</seealso> when -sending an outgoing Diameter request.</p> +Options available to &call; when +sending an outgoing Diameter request. +Has one of the following types.</p> <taglist> @@ -238,23 +244,23 @@ sending an outgoing Diameter request.</p> <p> Extra arguments to append to callbacks to the callback module in question. -These are appended to any extra arguments configured with the callback +These are appended to any extra arguments configured on the callback itself. Multiple options append to the argument list.</p> </item> -<tag><c>{filter, peer_filter()}</c></tag> +<tag><c>{filter, &peer_filter;}</c></tag> <item> <p> A filter to apply to the list of available peers before passing them to -the <seealso marker="diameter_app#pick_peer">pick_peer/4</seealso> +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> </item> -<tag><c>{timeout, Unsigned32()}</c></tag> +<tag><c>{timeout, &dict_Unsigned32;}</c></tag> <item> <p> The number of milliseconds after which the request should @@ -265,21 +271,17 @@ Defaults to 5000.</p> <tag><c>detach</c></tag> <item> <p> -Causes <seealso marker="#call">call/4</seealso> to return <c>ok</c> as +Causes &call; to return <c>ok</c> as soon as the request in question has been encoded instead of waiting for and returning -the result from a subsequent -<seealso marker="diameter_app#handle_answer">handle_answer/4</seealso> -or <seealso -marker="diameter_app#handle_error">handle_error/4</seealso> -callback.</p> +the result from a subsequent &app_handle_answer; or +&app_handle_error; callback.</p> </item> </taglist> <p> -An invalid option will cause <seealso marker="#call">call/4</seealso> -to fail.</p> +An invalid option will cause &call; to fail.</p> <marker id="capability"/> </item> @@ -288,108 +290,54 @@ to fail.</p> <item> <p> -AVP values used in outgoing CER/CEA messages during capabilities exchange. -Can be configured both on a service and a transport, the latter taking -precedence over the former.</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. +Has one of the following types.</p> <taglist> -<tag><c>{'Origin-Host', DiameterIdentity()}</c></tag> -<item> -<p> -Value of the Origin-Host AVP in outgoing messages.</p> -</item> - -<tag><c>{'Origin-Realm', DiameterIdentity()}</c></tag> +<tag><c>{'Origin-Host', &dict_DiameterIdentity;}</c></tag> +<tag><c>{'Origin-Realm', &dict_DiameterIdentity;}</c></tag> +<tag><c>{'Host-IP-Address', [&dict_Address;]}</c></tag> <item> <p> -Value of the Origin-Realm AVP in outgoing messages.</p> +An address list is available to the start function of a +&transport_module;, which +can return a new list for use in the subsequent CER or CEA. +Host-IP-Address need not be specified if the transport start function +returns an address list.</p> </item> -<tag><c>{'Host-IP-Address', [Address()]}</c></tag> +<tag><c>{'Vendor-Id', &dict_Unsigned32;}</c></tag> +<tag><c>{'Product-Name', &dict_UTF8String;}</c></tag> +<tag><c>{'Origin-State-Id', &dict_Unsigned32;}</c></tag> <item> <p> -Values of Host-IP-Address AVPs. -Optional.</p> - -<p> -The list of addresses is available to the start function of a -transport module, which either uses them as is or returns a new list -(typically as configured as <c>transport_config()</c> on the -transport module in question) in order for the correct list of -addresses to be sent in capabilities exchange messages.</p> -</item> - -<tag><c>{'Vendor-Id', Unsigned32()}</c></tag> -<item> -<p> -Value of the Vendor-Id AVP sent in an outgoing capabilities -exchange message.</p> -</item> - -<tag><c>{'Product-Name', UTF8String()}</c></tag> -<item> -<p> -Value of the Product-Name AVP sent in an outgoing capabilities -exchange message.</p> -</item> - -<tag><c>{'Origin-State-Id', Unsigned32()}</c></tag> -<item> -<p> -Value of Origin-State-Id to be included in outgoing messages sent by -diameter itself. -In particular, the AVP will be included in CER/CEA and DWR/DWA messages. -Optional.</p> - -<p> +Origin-State-Id is optional but will be included in outgoing messages +sent by diameter itself: CER/CEA, DWR/DWA and DPR/DPA. Setting a value of <c>0</c> (zero) is equivalent to not setting a -value as documented in RFC 3588. -The function <seealso -marker="#origin_state_id">origin_state_id/0</seealso> -can be used as to retrieve a value that is set when the diameter +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> </item> -<tag><c>{'Supported-Vendor-Id', [Unsigned32()]}</c></tag> +<tag><c>{'Supported-Vendor-Id', [&dict_Unsigned32;]}</c></tag> +<tag><c>{'Auth-Application-Id', [&dict_Unsigned32;]}</c></tag> +<tag><c>{'Inband-Security-Id', [&dict_Unsigned32;]}</c></tag> <item> <p> -Values of Supported-Vendor-Id AVPs sent in an outgoing -capabilities exchange message. -Optional, defaults to the empty list.</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 +from the peer offers it.</p> </item> -<tag><c>{'Auth-Application-Id', [Unsigned32()]}</c></tag> -<item> -<p> -Values of Auth-Application-Id AVPs sent in an outgoing -capabilities exchange message. -Optional, defaults to the empty list.</p> -</item> - -<tag><c>{'Acct-Application-Id', [Unsigned32()]}</c></tag> -<item> -<p> -Values of Acct-Application-Id AVPs sent in an outgoing -capabilities exchange message. -Optional, defaults to the empty list.</p> -</item> - -<tag><c>{'Vendor-Specific-Application-Id', [Grouped()]}</c></tag> -<item> -<p> -Values of Vendor-Specific-Application-Id AVPs sent in -an outgoing capabilities exchange message. -Optional, defaults to the empty list.</p> -</item> - -<tag><c>{'Firmware-Revision', Unsigned32()}</c></tag> -<item> -<p> -Value of the Firmware-Revision AVP sent in an outgoing capabilities -exchange message. -Optional.</p> -</item> +<tag><c>{'Acct-Application-Id', [&dict_Unsigned32;]}</c></tag> +<tag><c>{'Vendor-Specific-Application-Id', [&dict_Grouped;]}</c></tag> +<tag><c>{'Firmware-Revision', &dict_Unsigned32;}</c></tag> </taglist> @@ -406,7 +354,7 @@ It is an error to specify duplicate tuples.</p> An expression that can be evaluated as a function in the following sense.</p> -<code> +<pre> eval([{M,F,A} | T]) -> apply(M, F, T ++ A); eval([[F|A] | T]) -> @@ -415,17 +363,22 @@ eval([F|A]) -> apply(F, A); eval(F) -> eval([F]). -</code> +</pre> <p> -Evaluating an evaluable() <c>E</c> on an argument list <c>A</c> +Applying an <c>&evaluable;</c> +<c>E</c> to an argument list <c>A</c> is meant in the sense of <c>eval([E|A])</c>.</p> +<warning> <p> -Beware of using local funs (that is, fun expressions not of the -form <c>fun Module:Name/Arity</c>) in situations in which the fun is -not short-lived and code is to be upgraded at runtime since any -processes retaining such a fun will have a reference to old code.</p> +Beware of using fun expressions of the form <c>fun Name/Arity</c> in +situations in which the fun is not short-lived +and code is to be upgraded at runtime since any processes retaining +such a fun will have a reference to old code. +In particular, such a value is typically inappropriate in +configuration passed to &start_service; or &add_transport;.</p> +</warning> <marker id="peer_filter"/> </item> @@ -433,10 +386,8 @@ processes retaining such a fun will have a reference to old code.</p> <tag><c>peer_filter() = term()</c></tag> <item> <p> -A filter passed to <seealso marker="#call">call/4</seealso> -in order to select candidate peers for a -<seealso marker="diameter_app#pick_peer">pick_peer/4</seealso> -callback. +A filter passed to &call; in order to select candidate peers for a +&app_pick_peer; callback. Has one of the following types.</p> <taglist> @@ -467,63 +418,73 @@ or any peer if the request does not contain a <c>Destination-Realm</c> AVP.</p> </item> -<tag><c>{host, any|DiameterIdentity()}</c></tag> +<tag><c>{host, any|&dict_DiameterIdentity;}</c></tag> <item> <p> Matches only those peers whose <c>Origin-Host</c> has the specified value, or all peers if the atom <c>any</c>.</p> </item> -<tag><c>{realm, any|DiameterIdentity()</c></tag> +<tag><c>{realm, any|&dict_DiameterIdentity;</c></tag> <item> <p> Matches only those peers whose <c>Origin-Realm</c> has the -value, or all peers if the atom <c>any</c>.</p> +specified value, or all peers if the atom <c>any</c>.</p> </item> -<tag><c>{eval, evaluable()}</c></tag> +<tag><c>{eval, &evaluable;}</c></tag> <item> <p> -Matches only those peers for which the specified evaluable() returns +Matches only those peers for which the specified +<c>&evaluable;</c> returns <c>true</c> on the connection's <c>diameter_caps</c> record. Any other return value or exception is equivalent to <c>false</c>.</p> </item> -<tag><c>{neg, peer_filter()}</c></tag> +<tag><c>{neg, &peer_filter;}</c></tag> <item> <p> Matches only those peers not matched by the specified filter.</p> </item> -<tag><c>{all, [peer_filter()]}</c></tag> +<tag><c>{all, [&peer_filter;]}</c></tag> <item> <p> -Matches only those peers matched by each filter of the specified list.</p> +Matches only those peers matched by each filter in the specified list.</p> </item> -<tag><c>{any, [peer_filter()]}</c></tag> +<tag><c>{any, [&peer_filter;]}</c></tag> <item> <p> -Matches only those peers matched by at least one filter of the +Matches only those peers matched by at least one filter in the specified list.</p> </item> </taglist> <p> -Note that the <c>host</c> and <c>realm</c> filters examine the -outgoing request as passed to <seealso marker="#call">call/4</seealso>, -assuming that this is a record- or list-valued message() as documented -in <seealso marker="diameter_app">diameter_app(3)</seealso>, and that -the message contains at most one of each AVP. -If this is not the case then the <c>{host|realm, DiameterIdentity()}</c> +An invalid filter is equivalent to <c>{any,[]}</c>, a filter +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. +If this is not the case then the <c>{host|realm, &dict_DiameterIdentity;}</c> filters must be used to achieve the desired result. -Note also that an empty host/realm (which should not be typical) -is equivalent to an unspecified one for the purposes of filtering.</p> +An empty <c>&dict_DiameterIdentity;</c> +(which should not be typical) +matches all hosts/realms for the purposes of filtering.</p> +</note> +<warning> <p> -An invalid filter is equivalent to <c>{any, []}</c>, a filter -that matches no peer.</p> +A <c>host</c> filter is not typically desirable when setting +Destination-Host since it will remove peer agents from the +candidates list.</p> +</warning> <marker id="service_event"/> </item> @@ -531,41 +492,52 @@ that matches no peer.</p> <tag><c>service_event() = #diameter_event{}</c></tag> <item> <p> -Event message sent to processes that have subscribed using <seealso -marker="#subscribe">subscribe/1</seealso>.</p> +An event message sent to processes that have subscribed to these using +&subscribe;.</p> <p> -The <c>info</c> field of the event record can be one of the -following.</p> +The <c>info</c> field of the event record can have one of the +following types.</p> <taglist> +<tag><c>start</c></tag> +<tag><c>stop</c></tag> + +<item> +<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 +implies the termination of all transport processes.</p> +</item> + <tag><c>{up, Ref, Peer, Config, Pkt}</c></tag> <tag><c>{up, Ref, Peer, Config}</c></tag> <tag><c>{down, Ref, Peer, Config}</c></tag> <item> -<code> -Ref = transport_ref() -Peer = diameter_app:peer() -Config = {connect|listen, [transport_opt()]} +<pre> +Ref = &transport_ref; +Peer = &app_peer; +Config = {connect|listen, [&transport_opt;]} Pkt = #diameter_packet{} -</code> +</pre> <p> -Reports that the RFC 3539 watchdog state machine has -transitioned into (<c>up</c>) or out of (<c>down</c>) the open +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> record is present in an <c>up</c> tuple -then there has been an exchange of capabilities exchange messages and -the record contains the received CER or CEA, otherwise the -connection has reestablished without the loss or transport +If a <c>#diameter_packet{}</c> record 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> <p> -Note that a single up/down event for a given peer corresponds to -as many peer_up/down callbacks as there are Diameter -applications shared by the peer, as determined during capablilities -exchange. +Note that a single <c>up</c>/<c>down</c> event for a given peer +corresponds to one &app_peer_up;/&app_peer_down; +callback for each of the Diameter applications negotiated during +capablilities 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> @@ -573,23 +545,133 @@ respect to individual Diameter applications.</p> <tag><c>{reconnect, Ref, Opts}</c></tag> <item> -<code> -Ref = transport_ref() -Opts = [transport_opt()] -</code> +<pre> +Ref = &transport_ref; +Opts = [&transport_opt;] +</pre> <p> A connecting transport is attempting to establish/reestablish a -transport connection with a peer following <c>reconnect_timer</c> or -<c>watchdog_timer</c> expiry.</p> +transport connection with a peer following &reconnect_timer; or +&watchdog_timer; expiry.</p> +</item> + +<tag><c>{closed, Ref, Reason, Config}</c></tag> +<item> +<pre> +Ref = &transport_ref; +Config = {connect|listen, [&transport_opt;]} +</pre> + +<p> +Capabilities exchange has failed. +<c>Reason</c> can have one of the following types.</p> + +<taglist> + +<tag><c>{'CER', Result, Caps, Pkt}</c></tag> +<item> +<pre> +Result = ResultCode | {capabilities_cb, CB, ResultCode|discard} +Caps = #diameter_caps{} +Pkt = #diameter_packet{} +ResultCode = integer() +CB = &evaluable; +</pre> + +<p> +An incoming CER has been answered with the indicated result code or +discarded. +<c>Caps</c> contains pairs of values for the the local node and remote +peer. +<c>Pkt</c> contains the CER in question. +In the case of rejection by a capabilities callback, the tuple +contains the rejecting callback.</p> +</item> + +<tag><c>{'CER', Caps, {ResultCode, Pkt}}</c></tag> +<item> +<pre> +ResultCode = integer() +Caps = #diameter_caps{} +Pkt = #diameter_packet{} +</pre> + +<p> +An incoming CER contained errors and has been answered with the +indicated result code. +<c>Caps</c> contains only values for the the local node. +<c>Pkt</c> contains the CER in question.</p> +</item> + +<tag><c>{'CER', timeout}</c></tag> +<item> +<p> +An expected CER was not received within &capx_timeout; of +connection establishment.</p> +</item> + +<tag><c>{'CEA', Result, Caps, Pkt}</c></tag> +<item> +<pre> +Result = integer() | atom() | {capabilities_cb, CB, ResultCode|discard} +Caps = #diameter_caps{} +Pkt = #diameter_packet{} +ResultCode = integer() +</pre> + +<p> +An incoming CEA has been rejected for the indicated reason. +An integer-valued <c>Result</c> indicates the result code sent +by the peer. +<c>Caps</c> contains pairs of values for the the local node and remote +peer. +<c>Pkt</c> contains the CEA in question. +In the case of rejection by a capabilities callback, the tuple +contains the rejecting callback.</p> +</item> + +<tag><c>{'CEA', Caps, Pkt}</c></tag> +<item> +<pre> +Caps = #diameter_caps{} +Pkt = #diameter_packet{} +</pre> + +<p> +An incoming CEA contained errors and has been rejected. +<c>Caps</c> contains only values for the the local node. +<c>Pkt</c> contains the CEA in question.</p> +</item> + +<tag><c>{'CEA', timeout}</c></tag> +<item> +<p> +An expected CEA was not received within &capx_timeout; +of connection establishment.</p> +</item> + +</taglist> +</item> + +<tag><c>{watchdog, Ref, PeerRef, {From, To}, Config}</c></tag> +<item> +<pre> +Ref = &transport_ref; +PeerRef = &app_peer_ref; +From, To = initial | okay | suspect | down | reopen +Config = {connect|listen, [transport_opt()]} +</pre> + +<p> +An RFC 3539 watchdog state machine has changed state.</p> </item> </taglist> <p> For forward compatibility, a subscriber should be prepared to receive -<c>diameter_event.info</c> of forms other than those documented -above.</p> +info fields of forms other than the above.</p> <marker id="service_name"/> </item> @@ -597,12 +679,11 @@ above.</p> <tag><c>service_name() = term()</c></tag> <item> <p> -The name of a service as passed to <seealso -marker="#start_service">start_service/2</seealso> and with which the +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 <c>erlang:make_ref/0</c> can be used to generate a service name -that is somewhat unique.</p> +Note that &make_ref; +can be used to generate a service name that is somewhat unique.</p> <marker id="service_opt"/> </item> @@ -610,29 +691,80 @@ that is somewhat unique.</p> <tag><c>service_opt()</c></tag> <item> <p> -Options accepted by <seealso -marker="#start_service">start_service/2</seealso>. -Can be any <c>capability()</c> tuple as -well as the following.</p> +An option passed to &start_service;. +Can be any <c>&capability;</c> as well as the following.</p> <taglist> -<tag><c>{application, [application_opt()]}</c></tag> +<tag><c>{application, [&application_opt;]}</c></tag> <item> <p> Defines a Diameter application supported by the service.</p> <p> -A service must define one application for each Diameter application it -intends to support. -For an outgoing Diameter request, the application is specified by -passing the desired application's <c>application_alias()</c> to -<seealso marker="#call">call/4</seealso>, while for an +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 +passed to &call;, while for an incoming request the application identifier in the message -header determines the application (and callback module), the -application identifier being specified in the <seealso -marker="diameter_dict">dictionary</seealso> file defining the -application.</p> +header determines the application, the identifier being specified in +the application's &dictionary; file.</p> +</item> + +<tag><c>{restrict_connections, false + | node + | nodes + | [node()] + | evaluable()}</c></tag> +<item> +<p> +Specifies the degree to which multiple transport connections to the +same peer are accepted by the service.</p> + +<p> +If type <c>[node()]</c> then a connection is rejected if another already +exists on any of the specified nodes. +Values of type <c>false</c>, <c>node</c>, <c>nodes</c> or +&evaluable; are equivalent to +values <c>[]</c>, <c>[node()]</c>, <c>[node()|nodes()]</c> and the +evaluated value, respectively, evaluation of each expression taking +place whenever a new connection is to be established. +Note that <c>false</c> allows an unlimited number of connections to be +established with the same peer.</p> + +<p> +Multiple connections are independent and governed +by their own peer and watchdog state machines.</p> + +<p> +Defaults to <c>nodes</c>.</p> +</item> + +<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 +to be evaluated at &start_service;. +In particular, an identifier <c>Id</c> is mapped to a new identifier +as follows.</p> +<pre> +(H bsl N) bor (Id band ((1 bsl N) - 1)) +</pre> +<p> +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 +the bound is <c>4*R*60 =< 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 +non-negative integer less than <c>1 bsl (32-N)</c>.</p> + +<p> +Defaults to <c>{0,32}</c>.</p> </item> </taglist> @@ -643,126 +775,312 @@ application.</p> <tag><c>transport_opt()</c></tag> <item> <p> -Options accepted by <seealso -marker="#add_transport">add_transport/2</seealso>.</p> +An option passed to &add_transport;. +Has one of the following types.</p> <taglist> -<tag><c>{transport_module, atom()}</c></tag> +<marker id="applications"/> +<tag><c>{applications, [&application_alias;]}</c></tag> <item> <p> -A module implementing a transport process as defined in <seealso -marker="diameter_transport">diameter_transport(3)</seealso>. -Defaults to <c>diameter_tcp</c> if unspecified.</p> +The list of 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> +</item> + +<marker id="capabilities"/> +<tag><c>{capabilities, [&capability;]}</c></tag> +<item> +<p> +AVP's used to construct outgoing CER/CEA messages. +Values take precedence over any specified on the service in +question.</p> <p> -The interface required of a transport module is documented in <seealso -marker="diameter_transport">diameter_transport(3)</seealso>.</p> +Specifying a capability as a transport option +may be particularly appropriate for Inband-Security-Id, in case +TLS is desired over TCP as implemented by &man_tcp;.</p> </item> -<tag><c>{transport_config, term()}</c></tag> +<marker id="capabilities_cb"/> +<tag><c>{capabilities_cb, &evaluable;}</c></tag> <item> <p> -A term passed as the third argument to the <seealso -marker="diameter_transport#start">start/3</seealso> function of -the relevant <c>transport_module</c> in order to start a transport process. -Defaults to the empty list if unspecified.</p> +A 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 +<c>#diameter_caps{}</c> record of the connection.</p> + +<p> +The return value can have one of the following types.</p> + +<taglist> +<tag><c>ok</c></tag> +<item> +<p> +Accept the connection.</p> </item> -<tag><c>{applications, [application_alias()]}</c></tag> +<tag><c>integer()</c></tag> <item> <p> -The list of Diameter applications to which usage of the transport -should be restricted. -Defaults to all applications configured on the service -in question.</p> +Causes an incoming CER to be answered with the specified Result-Code.</p> </item> -<tag><c>{capabilities, [capability()]}</c></tag> +<tag><c>discard</c></tag> <item> <p> -AVP's used to construct outgoing CER/CEA messages. -Any AVP specified takes precedence over a corresponding value specified -for the service in question.</p> +Causes an incoming CER to be discarded without CEA being sent.</p> </item> -<tag><c>{watchdog_timer, TwInit}</c></tag> +<tag><c>unknown</c></tag> <item> -<code> -TwInit = Unsigned32() - | {M,F,A} -</code> +<p> +Equivalent to returning <c>3010</c>, DIAMETER_UNKNOWN_PEER.</p> +</item> +</taglist> <p> -The RFC 3539 watchdog timer. -An integer value is interpreted as the RFC's TwInit in milliseconds, -a jitter of ± 2 seconds being added at each rearming of the -timer to compute the RFC's Tw. -An MFA is expected to return the RFC's Tw directly, with jitter -applied, allowing the jitter calculation to be performed by -the callback.</p> +Returning anything but <c>ok</c> or a 2xxx series result +code causes the transport connection to be broken. +Multiple &capabilities_cb; +options can be specified, in which +case the corresponding callbacks are applied until either all return +<c>ok</c> or one does not.</p> +</item> +<marker id="capx_timeout"/> +<tag><c>{capx_timeout, &dict_Unsigned32;}</c></tag> +<item> <p> -An integer value must be at least 6000 as required by RFC 3539. -Defaults to 30000 if unspecified.</p> +The 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 reconnection attempts is +governed by &watchdog_timer; or +&reconnect_timer; expiry. +For a listening transport, the peer determines the timing.</p> + +<p> +Defaults to 10000.</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 +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 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> + +<p> +The return value can have one of the following types.</p> + +<taglist> +<tag><c>{dpr, [option()]}</c></tag> +<item> +<p> +Causes Disconnect-Peer-Request to be sent 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> + +<taglist> +<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 +<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> +</item> + +<tag><c>{timeout, &dict_Unsigned32;}</c></tag> +<item> +<p> +The number of milliseconds after which the transport process is +terminated if DPA has not been received. +Defaults to 1000.</p> +</item> +</taglist> +</item> + +<tag><c>dpr</c></tag> +<item> +<p> +Equivalent to <c>{dpr, []}</c>.</p> +</item> + +<tag><c>close</c></tag> +<item> +<p> +Causes the transport process to be terminated without +Disconnect-Peer-Request being sent to the peer.</p> </item> +<tag><c>ignore</c></tag> +<item> +<p> +Equivalent to not having configured the callback.</p> +</item> +</taglist> + +<p> +Multiple &disconnect_cb; +options can be specified, in which +case the corresponding callbacks are applied until one of them returns +a value other than <c>ignore</c>. +All callbacks returning <c>ignore</c> is equivalent to not having +configured them.</p> + +<p> +Defaults to a single callback returning <c>dpr</c>.</p> +</item> + +<marker id="reconnect_timer"/> <tag><c>{reconnect_timer, Tc}</c></tag> <item> -<code> -Tc = Unsigned32() -</code> +<pre> +Tc = &dict_Unsigned32; +</pre> <p> -For a connecting transport, the RFC 3588 Tc timer, in milliseconds. -Note that this timer determines the frequency with which the transport +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> +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 OPEN rather than +causing the RFC 3539 state machine to pass to state OKAY rather than REOPEN. -Note that these semantics are not goverened by the RFC and -that a listening transport's reconnect_timer should be greater than its -peers's Tc plus jitter.</p> +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> <p> Defaults to 30000 for a connecting transport and 60000 for a listening transport.</p> </item> +<marker id="transport_config"/> +<tag><c>{transport_config, term()}</c></tag> +<tag><c>{transport_config, term(), &dict_Unsigned32;}</c></tag> +<item> +<p> +A 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> + +<p> +The 3-tuple form additionally specifies an interval, in milliseconds, +after which a started transport process should be terminated if it has +not yet established a connection. +For example, the following options on a connecting transport +request a connection with one peer over SCTP or another +(typically the same) over TCP.</p> + +<pre> +{transport_module, diameter_sctp} +{transport_config, SctpOpts, 5000} +{transport_module, diameter_tcp} +{transport_config, TcpOpts} +</pre> + +<p> +To listen on both SCTP and TCP, define one transport for each.</p> +</item> + +<marker id="transport_module"/> +<tag><c>{transport_module, atom()}</c></tag> +<item> +<p> +A module implementing a transport process as defined in &man_transport;. +Defaults to <c>diameter_tcp</c> if unspecified.</p> + +<p> +Multiple <c>transport_module</c> and &transport_config; +options are allowed. +The order of these is significant in this case (and only in this case), +a <c>transport_module</c> being paired with the first +&transport_config; +following it in the options list, or the default value for trailing +modules. +Transport starts will be attempted with each of the +modules in order until one establishes a connection within the +corresponding timeout (see below) or all fail.</p> +</item> + +<marker id="watchdog_timer"/> +<tag><c>{watchdog_timer, TwInit}</c></tag> +<item> +<pre> +TwInit = &dict_Unsigned32; + | {M,F,A} +</pre> + +<p> +The RFC 3539 watchdog timer. +An integer value is interpreted as the RFC's TwInit in milliseconds, +a jitter of ± 2 seconds being added at each rearming of the +timer to compute the RFC's Tw. +An MFA is expected to return the RFC's Tw directly, with jitter +applied, allowing the jitter calculation to be performed by +the callback.</p> + +<p> +An integer value must be at least 6000 as required by RFC 3539. +Defaults to 30000 if unspecified.</p> +</item> + </taglist> <p> Unrecognized options are silently ignored but are returned unmodified -by <seealso -marker="#service_info">service_info/2</seealso> and can be referred to -in predicate functions passed to <seealso -marker="#remove_transport">remove_transport/2</seealso>.</p> +by &service_info; and can be referred to +in predicate functions passed to &remove_transport;.</p> + +<marker id="transport_ref"/> +</item> +<tag><c>transport_ref() = reference()</c></tag> +<item> +<p> +An reference returned by &add_transport; that +identifies the configuration.</p> </item> </taglist> </section> -<marker id="add_transport"/> <funcs> <!-- ===================================================================== --> <func> -<name>add_transport(SvcName, {connect|listen, Options}) +<name>add_transport(SvcName, {connect|listen, [Opt]}) -> {ok, Ref} | {error, Reason}</name> <fsummary>Add transport capability to a service.</fsummary> <type> -<v>SvcName = service_name()</v> -<v>Options = [transport_opt()]</v> -<v>Ref = ref()</v> +<v>SvcName = &service_name;</v> +<v>Opt = &transport_opt;</v> +<v>Ref = &transport_ref;</v> <v>Reason = term()</v> </type> <desc> @@ -770,8 +1088,8 @@ marker="#remove_transport">remove_transport/2</seealso>.</p> Add transport capability to a service.</p> <p> -The service will start a transport process(es) in order to establish a -connection with the peer, either by connecting to the peer +The service will start transport processes as required in order to +establish a connection with the peer, either by connecting to the peer (<c>connect</c>) or by accepting incoming connection requests (<c>listen</c>). A connecting transport establishes transport connections with at most @@ -781,84 +1099,77 @@ one peer, an listening transport potentially with many.</p> The diameter application takes responsibility for exchanging CER/CEA with the peer. Upon successful completion of capabilities exchange the service -calls each relevant application module's <seealso -marker="diameter_app#peer_up">peer_up/3</seealso> callback +calls each relevant application module's &app_peer_up; callback after which the caller can exchange Diameter messages with the peer over the transport. In addition to CER/CEA, the service takes responsibility for the -handling of DWR/DWA and required by RFC 3539 as well as for DPR/DPA.</p> +handling of DWR/DWA and required by RFC 3539, as well as for DPR/DPA.</p> <p> The returned reference uniquely identifies the transport within the scope of the service. Note that the function returns before a transport connection has been -established. +established.</p> + +<note> +<p> It is not an error to add a transport to a service that has not yet been configured: a service can be started after configuring -transports.</p> +its transports.</p> +</note> -<marker id="call"/> </desc> </func> <!-- ===================================================================== --> <func> -<name>call(SvcName, App, Request, Options) -> ok | Answer | {error, Reason}</name> +<name>call(SvcName, App, Request, [Opt]) -> Answer | ok | {error, Reason}</name> <fsummary>Send a Diameter request message.</fsummary> <type> -<v>SvcName = service_name()</v> -<v>App = application_alias()</v> -<v>Request = diameter_app:message() | term()</v> +<v>SvcName = &service_name;</v> +<v>App = &application_alias;</v> +<v>Request = &codec_message;</v> <v>Answer = term()</v> -<v>Options = [call_opt()]</v> +<v>Opt = &call_opt;</v> </type> <desc> <p> -Send a Diameter request message and possibly return the answer or error.</p> +Send a Diameter request message.</p> <p> -<c>App</c> identifies the Diameter application in which the request is +<c>App</c> specifies the Diameter application in which the request is defined and callbacks to the corresponding callback module -will follow as described below and in <seealso -marker="diameter_app">diameter_app(3)</seealso>. -Unless the <c>detach</c> option has been specified to cause an earlier -return, the call returns either when an answer message is received -from the peer or an error occurs. -In the case of an answer, the return value is as returned by a -<seealso -marker="diameter_app#handle_answer">handle_answer/4</seealso> -callback. -In the case of an error, whether or not the error is returned directly -by diameter or from a <seealso -marker="diameter_app#handle_error">handle_error/4</seealso> +will follow as described below and in &man_app;. +Unless the <c>detach</c> option is specified, the call returns either +when an answer message is received from the peer or an error occurs. +In the answer case, the return value is as returned by a +&app_handle_answer; callback. +In the error case, whether or not the error is returned directly +by diameter or from a &app_handle_error; callback depends on whether or not the outgoing request is -successfully encoded for transmission from the peer, the cases being +successfully encoded for transmission to the peer, the cases being documented below.</p> <p> If there are no suitable peers, or if -<seealso marker="diameter_app#pick_peer">pick_peer/4</seealso> -rejects them by returning 'false', then <c>{error, no_connection}</c> +&app_pick_peer; +rejects them by returning <c>false</c>, then <c>{error,no_connection}</c> is returned. -Otherwise <seealso marker="diameter_app#pick_peer">pick_peer/4</seealso> -is followed by a -<seealso -marker="diameter_app#prepare_request">prepare_request/3</seealso> -callback, the message is encoded and sent.</p> +Otherwise &app_pick_peer; is followed by a +&app_prepare_request; callback, the message is encoded and then sent.</p> <p> There are several error cases which may prevent an answer from being received and passed to a -<seealso marker="diameter_app#handle_answer">handle_answer/4</seealso> -callback:</p> +&app_handle_answer; callback:</p> <list> <item> <p> If the initial encode of the outgoing request -fails, then the request process fails and <c>{error, encode}</c> +fails, then the request process fails and <c>{error,encode}</c> is returned.</p> </item> @@ -866,16 +1177,14 @@ is returned.</p> <p> If the request is successfully encoded and sent but the answer times out then a -<seealso marker="diameter_app#handle_error">handle_error/4</seealso> -callback takes place with <c>Reason = timeout</c>.</p> +&app_handle_error; callback takes place with <c>Reason = timeout</c>.</p> </item> <item> <p> If the request is successfully encoded and sent but the service in question is stopped before an answer is received then a -<seealso marker="diameter_app#handle_error">handle_error/4</seealso> -callback takes place <c>Reason = cancel</c>.</p> +&app_handle_error; callback takes place with <c>Reason = cancel</c>.</p> </item> <item> @@ -884,25 +1193,18 @@ If the transport connection with the peer goes down after the request has been sent but before an answer has been received then an attempt is made to resend the request to an alternate peer. If no such peer is available, or if the subsequent -<seealso marker="diameter_app#pick_peer">pick_peer/4</seealso> -callback rejects the candidates, then a -<seealso marker="diameter_app#handle_error">handle_error/4</seealso> -callback takes place with <c>Reason = failover</c>. -If a peer is selected then a -<seealso -marker="diameter_app#prepare_retransmit">prepare_retransmit/3</seealso> +&app_pick_peer; callback rejects the candidates, then a +&app_handle_error; callback takes place with <c>Reason = failover</c>. +If a peer is selected then a &app_prepare_retransmit; callback takes place, after which the semantics are the same as -following an initial -<seealso marker="diameter_app#prepare_request"> -prepare_request/3</seealso> -callback.</p> +following an initial &app_prepare_request; callback.</p> </item> <item> <p> If an encode error takes place during retransmission then the request process fails and -<c>{error, failure}</c> is returned.</p> +<c>{error,failure}</c> is returned.</p> </item> <item> @@ -910,7 +1212,7 @@ retransmission then the request process fails and If an application callback made in processing the request fails (pick_peer, prepare_request, prepare_retransmit, handle_answer or handle_error) then either -<c>{error, encode}</c> or <c>{error, failure}</c> +<c>{error,encode}</c> or <c>{error,failure}</c> is returned depending on whether or not there has been an attempt to send the request over the transport.</p> </item> @@ -918,18 +1220,17 @@ attempt to send the request over the transport.</p> </list> <p> -Note that <c>{error, encode}</c> is the only return value which +Note that <c>{error,encode}</c> is the only return value which guarantees that the request has <em>not</em> been sent over the -transport.</p> +transport connection.</p> -<marker id="origin_state_id"/> </desc> </func> <!-- ===================================================================== --> <func> -<name>origin_state_id() -> Unsigned32()</name> +<name>origin_state_id() -> &dict_Unsigned32;</name> <fsummary>Returns a reasonable Origin-State-Id.</fsummary> <desc> <p> @@ -938,26 +1239,26 @@ outgoing messages.</p> <p> The value returned is the number of seconds since 19680120T031408Z, -the first value that can be encoded as a Diameter Time(), +the first value that can be encoded as a Diameter <c>&dict_Time;</c>, at the time the diameter application was started.</p> -<marker id="remove_transport"/> </desc> </func> <!-- ===================================================================== --> <func> -<name>remove_transport(SvcName, Pred) -> ok</name> +<name>remove_transport(SvcName, Pred) -> ok | {error, Reason}</name> <fsummary>Remove previously added transports.</fsummary> <type> -<v>SvcName = service_name()</v> -<v>Pred = Fun | MFA | ref() | list() | true | false</v> +<v>SvcName = &service_name;</v> +<v>Pred = Fun | MFA | &transport_ref; | list() | true | false</v> <v></v> -<v>Fun = fun((reference(), connect|listen, list()) -> boolean())</v> -<v> | fun((reference(), list()) -> boolean())</v> +<v>Fun = fun((&transport_ref;, connect|listen, list()) -> boolean())</v> +<v> | fun((&transport_ref;, list()) -> boolean())</v> <v> | fun((list()) -> boolean())</v> <v>MFA = {atom(), atom(), list()}</v> +<v>Reason = term()</v> </type> <desc> <p> @@ -967,50 +1268,329 @@ Remove previously added transports.</p> <c>Pred</c> determines which transports to remove. An arity-3-valued <c>Pred</c> removes all transports for which <c>Pred(Ref, Type, Opts)</c> returns <c>true</c>, where <c>Type</c> and -<c>Opts</c> are as passed to <seealso -marker="#add_transport">add_transport/2</seealso> and <c>Ref</c> is -as returned by the corresponding call. +<c>Opts</c> are as passed to &add_transport; and <c>Ref</c> is +as returned by it. The remaining forms are equivalent to an arity-3 fun as follows.</p> -<code> -Pred = fun(reference(), list()): fun(Ref, _, Opts) -> Pred(Ref, Opts) end -Pred = fun(list()): fun(_, _, Opts) -> Pred(Opts) end -Pred = reference(): fun(Ref, _, _) -> Pred == Ref end -Pred = list(): fun(_, _, Opts) -> [] == Pred -- Opts end -Pred = true: fun(_, _, _) -> true end -Pred = false: fun(_, _, _) -> false end +<pre> +Pred = fun(transport_ref(), list()): fun(Ref, _, Opts) -> Pred(Ref, Opts) end +Pred = fun(list()): fun(_, _, Opts) -> Pred(Opts) end +Pred = transport_ref(): fun(Ref, _, _) -> Pred == Ref end +Pred = list(): fun(_, _, Opts) -> [] == Pred -- Opts end +Pred = true: fun(_, _, _) -> true end +Pred = false: fun(_, _, _) -> false end Pred = {M,F,A}: fun(Ref, Type, Opts) -> apply(M, F, [Ref, Type, Opts | A]) end -</code> +</pre> <p> -Removing a transport causes all associated transport connections to -be broken. -A base application DPR message with -Disconnect-Cause <c>DO_NOT_WANT_TO_TALK_TO_YOU</c> will be sent -to each connected peer before disassociating the transport configuration -from the service and terminating the transport upon reception of -DPA or timeout.</p> - -<!-- TODO: document the timeout value, possibly make configurable. --> +Removing a transport causes the corresponding transport processes to +be terminated. +Whether or not a DPR message is sent to a peer is +controlled by value of &disconnect_cb; +configured on the transport.</p> -<marker id="service_info"/> </desc> </func> <!-- ===================================================================== --> <func> -<name>service_info(SvcName, Item) -> Value</name> -<fsummary>Return specific information about a started service.</fsummary> +<name>service_info(SvcName, Info) -> term()</name> +<fsummary>Return information about a started service.</fsummary> <type> -<v>SvcName = service_name()</v> -<v>Value = term()</v> +<v>SvcName = &service_name;</v> +<v>Info = Item | [Info]</v> +<v>Item = atom()</v> </type> <desc> <p> -Return information about a started service.</p> +Return information about a started service. +Requesting info for an unknown service causes <c>undefined</c> to be +returned. +Requesting a list of items causes a tagged list to be +returned.</p> + +<p> +<c>Item</c> can be one of the following.</p> + +<taglist> + +<tag><c>'Origin-Host'</c></tag> +<tag><c>'Origin-Realm'</c></tag> +<tag><c>'Vendor-Id'</c></tag> +<tag><c>'Product-Name'</c></tag> +<tag><c>'Origin-State-Id'</c></tag> +<tag><c>'Host-IP-Address'</c></tag> +<tag><c>'Supported-Vendor'</c></tag> +<tag><c>'Auth-Application-Id'</c></tag> +<tag><c>'Inband-Security-Id'</c></tag> +<tag><c>'Acct-Application-Id'</c></tag> +<tag><c>'Vendor-Specific-Application-Id'</c></tag> +<tag><c>'Firmware-Revision'</c></tag> +<item> +<p> +Return a capability value as configured with &start_service;.</p> +</item> + +<tag><c>applications</c></tag> +<item> +<p> +Return the list of applications as configured with &start_service;. +</p> +</item> + +<tag><c>capabilities</c></tag> +<item> +<p> +Return a tagged list of all capabilities values as configured with +&start_service;.</p> +</item> + +<tag><c>transport</c></tag> +<item> +<p> +Return a list containing one entry for each of the service's transport +as configured with &add_transport;. +Each entry is a tagged list containing both configuration and +information about established peer connections. +An example return value with for a client service with Origin-Host +"client.example.com" configured with a single transport connected to +"server.example.com" might look as follows.</p> + +<pre> +[[{ref,#Ref<0.0.0.93>}, + {type,connect}, + {options,[{transport_module,diameter_tcp}, + {transport_config,[{ip,{127,0,0,1}}, + {raddr,{127,0,0,1}}, + {rport,3868}, + {reuseaddr,true}]}]}, + {watchdog,{<0.66.0>,{1346,171491,996448},okay}}, + {peer,{<0.67.0>,{1346,171491,999906}}}, + {apps,[{0,common}]}, + {caps,[{origin_host,{"client.example.com","server.example.com"}}, + {origin_realm,{"example.com","example.com"}}, + {host_ip_address,{[{127,0,0,1}],[{127,0,0,1}]}}, + {vendor_id,{0,193}}, + {product_name,{"Client","Server"}}, + {origin_state_id,{[],[]}}, + {supported_vendor_id,{[],[]}}, + {auth_application_id,{[0],[0]}}, + {inband_security_id,{[],[0]}}, + {acct_application_id,{[],[]}}, + {vendor_specific_application_id,{[],[]}}, + {firmware_revision,{[],[]}}, + {avp,{[],[]}}]}, + {port,[{owner,<0.69.0>}, + {module,diameter_tcp}, + {socket,{{127,0,0,1},48758}}, + {peer,{{127,0,0,1},3868}}, + {statistics,[{recv_oct,656}, + {recv_cnt,6}, + {recv_max,148}, + {recv_avg,109}, + {recv_dvi,19}, + {send_oct,836}, + {send_cnt,6}, + {send_max,184}, + {send_avg,139}, + {send_pend,0}]}]}, + {statistics,[{{{0,258,0},recv},3}, + {{{0,258,1},send},3}, + {{{0,257,0},recv},1}, + {{{0,257,1},send},1}, + {{{0,258,0},recv,{'Result-Code',2001}},3}, + {{{0,280,1},recv},2}, + {{{0,280,0},send},2}]}]] +</pre> + +<p> +Here <c>ref</c> is a <c>&transport_ref;</c> and <c>options</c> +the corresponding <c>&transport_opt;</c> list passed to +&add_transport;. +The <c>watchdog</c> entry shows the state of a connection's RFC 3539 watchdog +state machine. +The <c>peer</c> entry identifies the <c>&app_peer_ref;</c> for +which there will have been &app_peer_up; callbacks for the +Diameter applications identified by the <c>apps</c> entry, +<c>common</c> being the <c>&application_alias;</c>. +The <c>caps</c> entry identifies the capabilities sent by the local +node and received from the peer during capabilities exchange. +The <c>port</c> entry displays socket-level information about the +transport connection. +The <c>statistics</c> entry presents Diameter-level counters, +an entry like <c>{{{0,280,1},recv},2}</c> saying that the client has +received 2 DWR messages: <c>{0,280,1} = {Application_Id, Command_Code, +R_Flag}</c>.</p> + +<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 +during the lifetime of the transport configuration.</p> + +<p> +A listening transport presents its information slightly differently +since there may be multiple accepted connections for the same +<c>&transport_ref;</c>. +The <c>transport</c> info returned by a server with a single client +connection might look as follows.</p> + +<pre> +[[{ref,#Ref<0.0.0.61>}, + {type,listen}, + {options,[{transport_module,diameter_tcp}, + {transport_config,[{reuseaddr,true}, + {ip,{127,0,0,1}}, + {port,3868}]}]}, + {accept,[[{watchdog,{<0.56.0>,{1346,171481,226895},okay}}, + {peer,{<0.58.0>,{1346,171491,999511}}}, + {apps,[{0,common}]}, + {caps,[{origin_host,{"server.example.com","client.example.com"}}, + {origin_realm,{"example.com","example.com"}}, + {host_ip_address,{[{127,0,0,1}],[{127,0,0,1}]}}, + {vendor_id,{193,0}}, + {product_name,{"Server","Client"}}, + {origin_state_id,{[],[]}}, + {supported_vendor_id,{[],[]}}, + {auth_application_id,{[0],[0]}}, + {inband_security_id,{[],[]}}, + {acct_application_id,{[],[]}}, + {vendor_specific_application_id,{[],[]}}, + {firmware_revision,{[],[]}}, + {avp,{[],[]}}]}, + {port,[{owner,<0.62.0>}, + {module,diameter_tcp}, + {socket,{{127,0,0,1},3868}}, + {peer,{{127,0,0,1},48758}}, + {statistics,[{recv_oct,1576}, + {recv_cnt,16}, + {recv_max,184}, + {recv_avg,98}, + {recv_dvi,26}, + {send_oct,1396}, + {send_cnt,16}, + {send_max,148}, + {send_avg,87}, + {send_pend,0}]}]}], + [{watchdog,{<0.72.0>,{1346,171491,998404},initial}}]]}, + {statistics,[{{{0,280,0},recv},7}, + {{{0,280,1},send},7}, + {{{0,258,0},send,{'Result-Code',2001}},3}, + {{{0,258,1},recv},3}, + {{{0,258,0},send},3}, + {{{0,280,1},recv},5}, + {{{0,280,0},send},5}, + {{{0,257,1},recv},1}, + {{{0,257,0},send},1}]}]] +</pre> + +<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> + +</item> + +<tag><c>connections</c></tag> +<item> +<p> +Return a list containing one entry for every established transport +connection whose watchdog state machine is not in the <c>down</c> +state. +This is a flat view of <c>transport</c> info which lists only active +connections and for which Diameter-level statistics are accumulated +only for the lifetime of the transport connection. +A return value for the server above might look as follows.</p> + +<pre> +[[{ref,#Ref<0.0.0.61>}, + {type,accept}, + {options,[{transport_module,diameter_tcp}, + {transport_config,[{reuseaddr,true}, + {ip,{127,0,0,1}}, + {port,3868}]}]}, + {watchdog,{<0.56.0>,{1346,171481,226895},okay}}, + {peer,{<0.58.0>,{1346,171491,999511}}}, + {apps,[{0,common}]}, + {caps,[{origin_host,{"server.example.com","client.example.com"}}, + {origin_realm,{"example.com","example.com"}}, + {host_ip_address,{[{127,0,0,1}],[{127,0,0,1}]}}, + {vendor_id,{193,0}}, + {product_name,{"Server","Client"}}, + {origin_state_id,{[],[]}}, + {supported_vendor_id,{[],[]}}, + {auth_application_id,{[0],[0]}}, + {inband_security_id,{[],[]}}, + {acct_application_id,{[],[]}}, + {vendor_specific_application_id,{[],[]}}, + {firmware_revision,{[],[]}}, + {avp,{[],[]}}]}, + {port,[{owner,<0.62.0>}, + {module,diameter_tcp}, + {socket,{{127,0,0,1},3868}}, + {peer,{{127,0,0,1},48758}}, + {statistics,[{recv_oct,10124}, + {recv_cnt,132}, + {recv_max,184}, + {recv_avg,76}, + {recv_dvi,9}, + {send_oct,10016}, + {send_cnt,132}, + {send_max,148}, + {send_avg,75}, + {send_pend,0}]}]}, + {statistics,[{{{0,280,0},recv},62}, + {{{0,280,1},send},62}, + {{{0,258,0},send,{'Result-Code',2001}},3}, + {{{0,258,1},recv},3}, + {{{0,258,0},send},3}, + {{{0,280,1},recv},66}, + {{{0,280,0},send},66}, + {{{0,257,1},recv},1}, + {{{0,257,0},send},1}]}]] +</pre> + +<p> +Note that there may be multiple entries with the same <c>ref</c>, in +contrast to <c>transport</c> info.</p> +</item> + +<tag><c>statistics</c></tag> +<item> +<p> +Return a <c>{{Counter, Ref}, non_neg_integer()}</c> list of counter values. +<c>Ref</c> can be either a <c>&transport_ref;</c> +or a <c>&app_peer_ref;</c>. +Entries for the latter are folded into corresponding entries for the +former as peer connections go down. +Entries for both are removed at &remove_transport;. +The Diameter-level statistics returned by <c>transport</c> and +<c>connections</c> info are based upon these entries.</p> +</item> + +<tag><c>&app_peer_ref;</c></tag> +<item> +<p> +Return transport configuration associated with a single peer, as +passed to &add_transport;. +The returned list is empty if the peer is unknown. +Otherwise it contains the <c>ref</c>, <c>type</c> and <c>options</c> +tuples as in <c>transport</c> and <c>connections</c> info above. +For example:</p> + +<pre> +[{ref,#Ref<0.0.0.61>}, + {type,accept}, + {options,[{transport_module,diameter_tcp}, + {transport_config,[{reuseaddr,true}, + {ip,{127,0,0,1}}, + {port,3868}]}]}] +</pre> +</item> + +</taglist> -<marker id="services"/> </desc> </func> @@ -1020,34 +1600,32 @@ Return information about a started service.</p> <name>services() -> [SvcName]</name> <fsummary>Return the list of started services.</fsummary> <type> -<v>SvcName = service_name()</v> +<v>SvcName = &service_name;</v> </type> <desc> <p> Return the list of started services.</p> -<marker id="session_id"/> </desc> </func> <!-- ===================================================================== --> <func> -<name>session_id(Ident) -> OctetString()</name> +<name>session_id(Ident) -> &dict_OctetString;</name> <fsummary>Return a value for a Session-Id AVP.</fsummary> <type> -<v>Ident = DiameterIdentity()</v> +<v>Ident = &dict_DiameterIdentity;</v> </type> <desc> <p> Return a value for a Session-Id AVP.</p> <p> -The value has the form required by section 8.8 of RFC 3588. +The value has the form required by section 8.8 of &the_rfc;. Ident should be the Origin-Host of the peer from which the message containing the returned value will be sent.</p> -<marker id="start"/> </desc> </func> @@ -1061,10 +1639,9 @@ Start the diameter application.</p> <p> The diameter application must be started before starting a service. -In a production system this will typically be accomplished by a boot +In a production system this is typically accomplished by a boot file, not by calling <c>start/0</c> explicitly.</p> -<marker id="start_service"/> </desc> </func> @@ -1073,8 +1650,8 @@ file, not by calling <c>start/0</c> explicitly.</p> <name>start_service(SvcName, Options) -> ok | {error, Reason}</name> <fsummary>Start a Diameter service.</fsummary> <type> -<v>SvcName = service_name()</v> -<v>Options = [service_opt()]</v> +<v>SvcName = &service_name;</v> +<v>Options = [&service_opt;]</v> <v>Reason = term()</v> </type> <desc> @@ -1082,13 +1659,19 @@ file, not by calling <c>start/0</c> explicitly.</p> Start a diameter service.</p> <p> -A service defines a locally-implemented Diameter peer, specifying the -capabilities of the peer to be used during capabilities exchange and -the Diameter applications that it supports. -Transports are added to a service using <seealso -marker="#add_transport">add_transport/2</seealso>.</p> +A service defines a locally-implemented Diameter node, specifying the +capabilities to be advertised during capabilities exchange. +Transports are added to a service using &add_transport;. +</p> + +<note> +<p> +A transport can both override its service's +capabilities and restrict its supported Diameter applications so +"service = Diameter node as identified by Origin-Host" is not +necessarily the case.</p> +</note> -<marker id="stop_service"/> </desc> </func> @@ -1103,7 +1686,6 @@ Stop the diameter application.</p> <p> </p> -<marker id="stop_service"/> </desc> </func> @@ -1112,14 +1694,25 @@ Stop the diameter application.</p> <name>stop_service(SvcName) -> ok | {error, Reason}</name> <fsummary>Stop a Diameter service.</fsummary> <type> -<v>SvcName = service_name()</v> +<v>SvcName = &service_name;</v> <v>Reason = term()</v> </type> <desc> <p> Stop a diameter service.</p> -<marker id="subscribe"/> +<p> +Stopping a service causes all associated transport connections to be +broken. +A DPR message with be sent as in the case of &remove_transport;.</p> + +<note> +<p> +Stopping a service does not remove any associated transports: +&remove_transport; must +be called to remove transport configuration.</p> +</note> + </desc> </func> @@ -1129,17 +1722,19 @@ Stop a diameter service.</p> <name>subscribe(SvcName) -> true</name> <fsummary>Subscribe to event messages.</fsummary> <type> -<v>SvcName = service_name()</v> +<v>SvcName = &service_name;</v> </type> <desc> <p> -Subscribe to <c>service_event()</c> messages from a service.</p> +Subscribe to <c>&service_event;</c> messages from +a service.</p> <p> It is not an error to subscribe to events from a service -that does not yet exist.</p> +that does not yet exist. +Doing so before adding transports is required to guarantee the +reception of all related events.</p> -<marker id="unsubscribe"/> </desc> </func> @@ -1149,7 +1744,7 @@ that does not yet exist.</p> <name>unsubscribe(SvcName) -> true</name> <fsummary>Unsubscribe to event messages.</fsummary> <type> -<v>SvcName = service_name()</v> +<v>SvcName = &service_name;</v> </type> <desc> <p> @@ -1166,9 +1761,7 @@ Unsubscribe to event messages from a service.</p> <title>SEE ALSO</title> <p> -<seealso marker="diameter_app">diameter_app(3)</seealso>, -<seealso marker="diameter_transport">diameter_transport(3)</seealso>, -<seealso marker="diameter_dict">diameter_dict(4)</seealso></p> +&man_app;, &man_transport;, &man_dict;</p> </section> diff --git a/lib/diameter/doc/src/diameter_app.xml b/lib/diameter/doc/src/diameter_app.xml index a9ae0ebbec..f4db625c71 100644 --- a/lib/diameter/doc/src/diameter_app.xml +++ b/lib/diameter/doc/src/diameter_app.xml @@ -1,11 +1,19 @@ <?xml version="1.0" encoding="latin1" ?> -<!DOCTYPE erlref SYSTEM "erlref.dtd"> +<!DOCTYPE erlref SYSTEM "erlref.dtd" [ + <!ENTITY message '<seealso marker="#message">message()</seealso>'> + <!ENTITY dict + '<seealso marker="diameter_dict#MESSAGE_RECORDS">diameter_dict(4)</seealso>'> + <!ENTITY % also SYSTEM "seealso.ent" > + <!ENTITY % here SYSTEM "seehere.ent" > + %also; + %here; +]> <erlref> <header> <copyright> -<year>2011</year> +<year>2011</year><year>2012</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -41,15 +49,13 @@ Callback module of a Diameter application.</modulesummary> <description> <p> -A diameter service as started by <seealso -marker="diameter#start_service">diameter:start_service/2</seealso> +A diameter service as started by &mod_start_service; configures one of more Diameter applications, each of whose configuration specifies a callback that handles messages specific to -its application. -The messages and AVPs of the Diameter application are defined in a +the application. +The messages and AVPs of the application are defined in a dictionary file whose format is documented in -<seealso marker="diameter_dict">diameter_dict(4)</seealso> -while the callback module is documented here. +&man_dict; while the callback module is documented here. The callback module implements the Diameter application-specific functionality of a service.</p> @@ -60,26 +66,24 @@ The functions themselves are of three distinct flavours:</p> <list> <item> <p> -<seealso marker="#peer_up">peer_up/3</seealso> and -<seealso marker="#peer_down">peer_down/3</seealso> signal the +&peer_up; and &peer_down; signal the attainment or loss of connectivity with a Diameter peer.</p> </item> <item> <p> -<seealso marker="#pick_peer">pick_peer/4</seealso>, -<seealso marker="#prepare_request">prepare_request/3</seealso>, -<seealso marker="#prepare_retransmit">prepare_retransmit/3</seealso>, -<seealso marker="#handle_answer">handle_answer/4</seealso> -and <seealso marker="#handle_error">handle_error/4</seealso> are (or may -be) called as a consequence of a call to <seealso -marker="diameter#call">diameter:call/4</seealso> to send an outgoing +&pick_peer;, +&prepare_request;, +&prepare_retransmit;, +&handle_answer; +and &handle_error; are (or may be) called as a consequence of a call +to &mod_call; to send an outgoing Diameter request message.</p> </item> <item> <p> -<seealso marker="#handle_request">handle_request/3</seealso> +&handle_request; is called in response to an incoming Diameter request message.</p> </item> @@ -92,10 +96,9 @@ is called in response to an incoming Diameter request message.</p> The arities given for the the callback functions here assume no extra arguments. All functions will also be passed any extra arguments configured with -the callback module itself when calling <seealso -marker="diameter#start_service">diameter:start_service/2</seealso> +the callback module itself when calling &mod_start_service; and, for the call-specific callbacks, any extra arguments passed to -<seealso marker="diameter#call">diameter:call/4</seealso>.</p> +&mod_call;.</p> </note> <!-- ===================================================================== --> @@ -106,11 +109,14 @@ and, for the call-specific callbacks, any extra arguments passed to <taglist> +<marker id="capabilities"/> + <tag><c>capabilities() = #diameter_caps{}</c></tag> <item> <p> A record containing the identities of -the local and remote Diameter peers having an established transport +the local Diameter node and the remote Diameter peer having an +established transport connection, as well as the capabilities as determined by capabilities exchange. Each field of the record is a 2-tuple consisting of @@ -119,78 +125,51 @@ Optional or possibly multiple values are encoded as lists of values, mandatory values as the bare value.</p> </item> -<tag><c>message() = record() | list()</c></tag> +<marker id="message"/> + +<tag><c>message() = &codec_message;</c></tag> <item> <p> The representation of a Diameter message as passed to -<seealso marker="diameter#call">diameter:call/4</seealso>. -The record representation is as outlined in -<seealso -marker="diameter_dict#MESSAGE_RECORDS">diameter_dict(4)</seealso>: -a message as defined in a dictionary file is encoded as a record with -one field for each component AVP. -Equivalently, a message can also be encoded as a list whose head is -the atom-valued message name (the record name minus any -prefix specified in the relevant dictionary file) and whose tail is a -list of <c>{FieldName, FieldValue}</c> pairs.</p> - -<p> -A third representation allows a message to be specified as a list -whose head is a <c>diameter_header</c> record and whose tail is a list -of <c>diameter_avp</c> records. -This representation is used by diameter itself when relaying requests -as directed by the return value of a -<seealso marker="#handle_request">handle_request/3</seealso> -callback. -It differs from the other other two in that it bypasses the checks for -messages that do not agree with their definitions in the dictionary in -question (since relays agents must handle arbitrary request): messages -are sent exactly as specified.</p> +&mod_call; or returned from a &handle_request; callback.</p> </item> -<tag><c>packet() = #diameter_packet{}</c></tag> +<marker id="packet"/> + +<tag><c>packet() = &codec_packet;</c></tag> <item> <p> -A container for incoming and outgoing Diameters message that's passed +A container for incoming and outgoing Diameter messages that's passed through encode/decode and transport. -Fields of a packet() record should not be set in return values except -as documented.</p> +Fields should not be set in return values except as documented.</p> </item> +<marker id="peer_ref"/> + <tag><c>peer_ref() = term()</c></tag> <item> <p> -A term identifying a transport connection with a Diameter peer. -Should be treated opaquely.</p> +A term identifying a transport connection with a Diameter peer.</p> </item> -<tag><c>peer() = {peer_ref(), capabilities()}</c></tag> +<marker id="peer"/> + +<tag><c>peer() = {&peer_ref;, &capabilities;}</c></tag> <item> <p> A tuple representing a Diameter peer connection.</p> </item> -<tag><c>service_name() = term()</c></tag> -<item> -<p> -The service supporting the Diameter application. -Specified to <seealso -marker="diameter#start_service">diameter:start_service/2</seealso> -when starting the service.</p> -</item> +<marker id="state"/> <tag><c>state() = term()</c></tag> <item> <p> The state maintained by the application callback functions -<seealso marker="#peer_up">peer_up/3</seealso>, -<seealso marker="#peer_down">peer_down/3</seealso> and (optionally) -<seealso marker="#pick_peer">pick_peer/4</seealso>. +&peer_up;, &peer_down; and (optionally) &pick_peer;. The initial state is configured in the call to -<seealso -marker="diameter#start_service">diameter:start_service/2</seealso> -that configures the application on a service. +&mod_start_service; that configures the application on a service. Callback functions returning a state are evaluated in a common service-specific process while those not returning state are evaluated in a request-specific @@ -211,18 +190,33 @@ process.</p> <name>Mod:peer_up(SvcName, Peer, State) -> NewState</name> <fsummary>Invoked when a transport connection has been established</fsummary> <type> -<v>SvcName = service_name()</v> -<v>Peer = peer()</v> -<v>State = NewState = state()</v> +<v>SvcName = &mod_service_name;</v> +<v>Peer = &peer;</v> +<v>State = NewState = &state;</v> </type> <desc> <p> -Invoked when a transport connection has been established -and a successful capabilities exchange has indicated that the peer -supports the Diameter application of the application on which -the callback module in question has been configured.</p> +Invoked to signal the availability of a peer connection. +In particular, capabilities exchange with the peer has indicated +support for the application in question, the RFC 3539 watchdog state +machine for the connection has reached state <c>OKAY</c> and Diameter +messages can be both sent and received.</p> + +<note> +<p> +A watchdog state machine can reach state <c>OKAY</c> from state +<c>SUSPECT</c> without a new capabilities exchange taking place. +A new transport connection (and capabilities exchange) results in a +new peer_ref().</p> +</note> + +<note> +<p> +There is no requirement that a callback return before incoming +requests are received: &handle_request; callbacks must be +handled independently of &peer_up; and &peer_down;.</p> +</note> -<marker id="peer_down"/> </desc> </func> @@ -230,78 +224,87 @@ the callback module in question has been configured.</p> <name>Mod:peer_down(SvcName, Peer, State) -> NewState</name> <fsummary>Invoked when a transport connection has been lost.</fsummary> <type> -<v>SvcName = service_name()</v> -<v>Peer = peer()</v> -<v>State = NewState = state()</v> +<v>SvcName = &mod_service_name;</v> +<v>Peer = &peer;</v> +<v>State = NewState = &state;</v> </type> <desc> <p> -Invoked when a transport connection has been lost following a previous -call to <seealso marker="#peer_up">peer_up/3</seealso>.</p> +Invoked to signal that a peer connection is no longer available +following a previous call to &peer_up;. +In particular, that the RFC 3539 watchdog state machine for the +connection has left state <c>OKAY</c> and the peer will no longer be a +candidate in &pick_peer; callbacks.</p> -<marker id="pick_peer"/> </desc> </func> <func> -<name>Mod:pick_peer(Candidates, Reserved, SvcName, State) - -> {ok, Peer} | {Peer, NewState} | false</name> +<name>Mod:pick_peer(Candidates, _Reserved, SvcName, State) + -> Selection | false</name> <fsummary>Select a target peer for an outgoing request.</fsummary> <type> -<v>Candidates = [peer()]</v> -<v>Peer = peer() | false</v> -<v>SvcName = service_name()</v> -<v>State = NewState = state()</v> +<v>Candidates = [&peer;]</v> +<v>SvcName = &mod_service_name;</v> +<v>State = NewState = &state;</v> +<v>Selection = {ok, Peer} | {Peer, NewState}</v> +<v>Peer = &peer; | false</v> </type> <desc> <p> -Invoked as a consequence of a call to <seealso -marker="diameter#call">diameter:call/4</seealso> to select a destination -peer for an outgoing request, the return value indicating the selected peer. -A new application state can also be returned but only if the Diameter -application in question was -configured with the option <c>call_mutates_state</c> set to -<c>true</c>, as documented for <seealso -marker="diameter#start_service">diameter:start_service/2</seealso>.</p> - -<p> -The candidate peers list will only include those -which are selected by any <c>filter</c> option specified in the call to -<seealso marker="diameter#call">diameter:call/4</seealso>, and only -those which have indicated support for the Diameter application in -question. +Invoked as a consequence of a call to &mod_call; to select a destination +peer for an outgoing request. +The return value indicates the selected peer.</p> + +<p> +The candidate list contains only those peers that have advertised +support for the Diameter application in question during capabilities +exchange, that have not be excluded by a <c>filter</c> option in +the call to &mod_call; +and whose watchdog state machine is in the <c>OKAY</c> state. The order of the elements is unspecified except that any peers whose Origin-Host and Origin-Realm matches that of the outgoing request (in the sense of a <c>{filter, {all, [host, realm]}}</c> -option to <seealso marker="diameter#call">diameter:call/4</seealso>) +option to &mod_call;) will be placed at the head of the list.</p> <p> -The return values <c>false</c> and <c>{false, State}</c> are -equivalent when callback state is mutable, as are -<c>{ok, Peer}</c> and <c>{Peer, State}</c>. -Returning a peer as <c>false</c> causes <c>{error, no_connection}</c> -to be returned from <seealso marker="diameter#call">diameter:call/4</seealso>. -Returning a peer() from an initial pick_peer/4 callback will result in a -<seealso marker="#prepare_request">prepare_request/3</seealso> callback -followed by either <seealso -marker="#handle_answer">handle_answer/4</seealso> -or <seealso marker="#handle_error">handle_error/4</seealso> depending +A callback that returns a peer() will be followed by a +&prepare_request; +callback and, if the latter indicates that the request should be sent, +by either &handle_answer; +or &handle_error; depending on whether or not an answer message is received from the peer. -If transport with the peer is lost before this then a new <seealso -marker="#pick_peer">pick_peer/4</seealso> callback takes place to -select an alternate peer.</p> - -<p> -Note that there is no guarantee that a <seealso -marker="#pick_peer">pick_peer/4</seealso> callback to select -an alternate peer will be followed by any additional callbacks, only -that the initial <seealso -marker="#pick_peer">pick_peer/4</seealso> will be, since a +If the transport becomes unavailable after &prepare_request; then a +new &pick_peer; callback may take place to +failover to an alternate peer, after which &prepare_retransmit; takes the +place of &prepare_request; in resending the +request. +There is no guarantee that a &pick_peer; callback to select +an alternate peer will be followed by any additional callbacks since a retransmission to an alternate peer is abandoned if an answer is received from a previously selected peer.</p> -<marker id="prepare_request"/> +<p> +Returning <c>false</c> or <c>{false, NewState}</c> causes <c>{error, +no_connection}</c> to be returned from &mod_call;.</p> + +<p> +The return values <c>false</c> and <c>{false, State}</c> (that is, +<c>NewState = State</c>) are equivalent, as are <c>{ok, Peer}</c> and +<c>{Peer, State}</c>.</p> + +<note> +<p> +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 +value returned by a &peer_up; +or &peer_down; callback.</p> +</note> + </desc> </func> @@ -310,74 +313,81 @@ received from a previously selected peer.</p> <name>Mod:prepare_request(Packet, SvcName, Peer) -> Action</name> <fsummary>Return a request for encoding and transport.</fsummary> <type> -<v>Packet = packet()</v> -<v>SvcName = service_name()</v> -<v>Peer = peer()</v> -<v>Action = {send, packet() | message()} | {discard, Reason} | discard</v> +<v>Packet = &packet;</v> +<v>SvcName = &mod_service_name;</v> +<v>Peer = &peer;</v> +<v>Action = Send | Discard | {eval_packet, Action, PostF}</v> +<v>Send = {send, &packet; | &message;}</v> +<v>Discard = {discard, Reason} | discard</v> +<v>PostF = &mod_evaluable;}</v> </type> <desc> <p> Invoked to return a request for encoding and transport. -Allows the sender to access the selected peer's capabilities -in order to set (for example) <c>Destination-Host</c> and/or -<c>Destination-Realm</c> in the outgoing request, although the -callback need not be limited to this usage. +Allows the sender to use the selected peer's capabilities +to modify the outgoing request. Many implementations may simply want to return <c>{send, Packet}</c></p> <p> -A returned packet() should set the request to be encoded in its +A returned &packet; should set the +request to be encoded in its <c>msg</c> field and can set the <c>transport_data</c> field in order -to pass information to the transport module. -Extra arguments passed to <seealso -marker="diameter#call">diameter:call/4</seealso> can be used to -communicate transport data to the callback. -A returned packet() can also set the <c>header</c> field to a -<c>diameter_header</c> record in order to specify values that should -be preserved in the outgoing request, although this should typically -not be necessary and allows the callback to set header values -inappropriately. +to pass information to the transport process. +Extra arguments passed to &mod_call; can be used to +communicate transport (or any other) data to the callback.</p> + +<p> +A returned &packet; can set +the <c>header</c> field to a +<c>#diameter_header{}</c> to specify values that should +be preserved in the outgoing request, values otherwise being those in +the header record contained in <c>Packet</c>. A returned <c>length</c>, <c>cmd_code</c> or <c>application_id</c> is ignored.</p> <p> +A returned <c>PostF</c> will be evaluated on any encoded +<c>#diameter_packet{}</c> prior to transmission, the <c>bin</c> field +containing the encoded binary. +The return value is ignored.</p> + +<p> Returning <c>{discard, Reason}</c> causes the request to be aborted -and the <seealso -marker="diameter#call">diameter:call/4</seealso> for which the +and the &mod_call; for which the callback has taken place to return <c>{error, Reason}</c>. Returning <c>discard</c> is equivalent to returning <c>{discard, discarded}</c>.</p> -<marker id="prepare_retransmit"/> </desc> </func> <func> -<name>Mod:prepare_retransmit(Packet, SvcName, Peer) -> Result</name> +<name>Mod:prepare_retransmit(Packet, SvcName, Peer) -> Action</name> <fsummary>Return a request for encoding and retransmission.</fsummary> <type> -<v>Packet = packet()</v> -<v>SvcName = service_name()</v> -<v>Peer = peer()</v> -<v>Result = {send, packet() | message()} | {discard, Reason} | discard</v> +<v>Packet = &packet;</v> +<v>SvcName = &mod_service_name;</v> +<v>Peer = &peer;</v> +<v>Action = Send | Discard | {eval_packet, Action, PostF}</v> +<v>Send = {send, &packet; | &message;}</v> +<v>Discard = {discard, Reason} | discard</v> +<v>PostF = &mod_evaluable;}</v> </type> <desc> <p> Invoked to return a request for encoding and retransmission. -Has the same role as <seealso -marker="#prepare_request">prepare_request/3</seealso> in the case that +Has the same role as &prepare_request; in the case that a peer connection is lost an an alternate peer selected but the -argument packet() is as returned by the initial -<c>prepare_request/3</c>.</p> +argument &packet; is as returned +by the initial &prepare_request;.</p> <p> Returning <c>{discard, Reason}</c> causes the request to be aborted -and a <seealso -marker="#handle_error">handle_error/4</seealso> callback to +and a &handle_error; callback to take place with <c>Reason</c> as initial argument. Returning <c>discard</c> is equivalent to returning <c>{discard, discarded}</c>.</p> -<marker id="handle_answer"/> </desc> </func> @@ -385,51 +395,43 @@ discarded}</c>.</p> <name>Mod:handle_answer(Packet, Request, SvcName, Peer) -> Result</name> <fsummary>Receive an answer message from a peer.</fsummary> <type> -<v>Packet = packet()</v> -<v>Request = message()</v> -<v>SvcName = service_name()</v> -<v>Peer = peer()</v> +<v>Packet = &packet;</v> +<v>Request = &message;</v> +<v>SvcName = &mod_service_name;</v> +<v>Peer = &peer;</v> <v>Result = term()</v> </type> <desc> <p> Invoked when an answer message is received from a peer. -The return value is returned from the call to <seealso -marker="diameter#call">diameter:call/4</seealso> for which the -callback takes place unless the <c>detach</c> option was -specified.</p> +The return value is returned from &mod_call; unless the +<c>detach</c> option was specified.</p> <p> -The decoded answer record is in the <c>msg</c> field of the argument -packet(), -the undecoded binary in the <c>packet</c> field. +The decoded answer record and undecoded binary are in the <c>msg</c> +and <c>bin</c> fields of the argument +&packet; respectively. <c>Request</c> is the outgoing request message as was returned from -<seealso marker="#prepare_request">prepare_request/3</seealso> or -<seealso marker="#prepare_retransmit">prepare_retransmit/3</seealso> -before the request was passed to the transport.</p> +&prepare_request; or &prepare_retransmit;.</p> <p> -For any given call to <seealso -marker="diameter#call">diameter:call/4</seealso> there is at most one -call to the handle_answer callback of the application in question: any +For any given call to &mod_call; there is at most one +&handle_answer; callback: any duplicate answer (due to retransmission or otherwise) is discarded. -Similarly, only one of <c>handle_answer/4</c> or <c>handle_error/4</c> is -called for any given request.</p> +Similarly, only one of &handle_answer; or +&handle_error; is called.</p> <p> By default, an incoming answer message that cannot be successfully -decoded causes the request process in question to fail, causing the -relevant call to <seealso -marker="diameter#call">diameter:call/4</seealso> -to return <c>{error, failure} (unless the <c>detach</c> option was -specified)</c>. -In particular, there is no <c>handle_error/4</c> callback in this +decoded causes the request process to fail, causing +&mod_call; +to return <c>{error, failure}</c> unless the <c>detach</c> option was +specified. +In particular, there is no &handle_error; callback in this case. -Application configuration may change this behaviour as described for -<seealso -marker="diameter#start_service">diameter:start_service/2</seealso>.</p> +The &mod_application_opt; +<c>answer_errors</c> can be set to change this behaviour.</p> -<marker id="handle_error"/> </desc> </func> @@ -438,30 +440,26 @@ marker="diameter#start_service">diameter:start_service/2</seealso>.</p> <fsummary>Return an error from a outgoing request.</fsummary> <type> <v>Reason = timeout | failover | term()</v> -<v>Request = message()</v> -<v>SvcName = service_name()</v> -<v>Peer = peer()</v> +<v>Request = &message;</v> +<v>SvcName = &mod_service_name;</v> +<v>Peer = &peer;</v> <v>Result = term()</v> </type> <desc> <p> -Invoked when an error occurs before an answer message is received from -a peer in response to an outgoing request. -The return value is returned from the call to <seealso -marker="diameter#call">diameter:call/4</seealso> for which the -callback takes place (unless the <c>detach</c> option was -specified).</p> +Invoked when an error occurs before an answer message is received +in response to an outgoing request. +The return value is returned from &mod_call; unless the +<c>detach</c> option was specified.</p> <p> Reason <c>timeout</c> indicates that an answer message has not been -received within the required time. +received within the time specified with the corresponding &mod_call_opt;. Reason <c>failover</c> indicates that the transport connection to the peer to which the request has -been sent has been lost but that not alternate node was available, -possibly because a <seealso marker="#pick_peer">pick_peer/4</seealso> -callback returned false.</p> +been sent has become unavailable and that not alternate peer was +not selected.</p> -<marker id="handle_request"/> </desc> </func> @@ -469,54 +467,54 @@ callback returned false.</p> <name>Mod:handle_request(Packet, SvcName, Peer) -> Action</name> <fsummary>Receive an incoming request.</fsummary> <type> -<v>Packet = packet()</v> +<v>Packet = &packet;</v> <v>SvcName = term()</v> -<v>Peer = peer()</v> -<v>Action = Reply | {relay, Opts} | discard | {eval, Action, PostF}</v> -<v>Reply = {reply, message()} +<v>Peer = &peer;</v> +<v>Action = Reply + | {relay, [Opt]} + | discard + | {eval|eval_packet, Action, PostF}</v> +<v>Reply = {reply, &packet; | &message;} | {protocol_error, 3000..3999}</v> -<v>Opts = diameter:call_opts()</v> -<v>PostF = diameter:evaluable()</v> +<v>Opt = &mod_call_opt;</v> +<v>PostF = &mod_evaluable;</v> </type> <desc> <p> Invoked when a request message is received from a peer. The application in which the callback takes place (that is, the -callback module as configured with <seealso -marker="diameter#start_service">diameter:start_service/2</seealso>) +callback module as configured with &mod_start_service;) is determined by the Application Identifier in the header of the incoming request message, the selected module being the one -whose corresponding <seealso -marker="diameter_dict#MESSAGE_RECORDS">dictionary</seealso> declares +whose corresponding dictionary declares itself as defining either the application in question or the Relay application.</p> <p> -The argument packet() has the following signature.</p> +The argument &packet; has the following signature.</p> -<code> +<pre> #diameter_packet{header = #diameter_header{}, avps = [#diameter_avp{}], msg = record() | undefined, - errors = ['Unsigned32'() | {'Unsigned32'(), #diameter_avp{}}], + errors = [&dict_Unsigned32; | {&dict_Unsigned32;, #diameter_avp{}}], bin = binary(), transport_data = term()} -</code> +</pre> <p> -The <c>msg</c> field will be <c>undefined</c> only in case the request has +The <c>msg</c> field will be <c>undefined</c> in case the request has been received in the relay application. Otherwise it contains the record representing the request as outlined -in <seealso -marker="diameter_dict#MESSAGE_RECORDS">diameter_dict(4)</seealso>.</p> +in &dict;.</p> <p> The <c>errors</c> field specifies any Result-Code's identifying errors that were encountered in decoding the request. In this case diameter will set both Result-Code and Failed-AVP AVP's in a returned -answer message() before sending it to the peer: -the returned message() need only set any other required AVP's. +answer &message; before sending it to the peer: +the returned &message; need only set any other required AVP's. Note that the errors detected by diameter are all of the 5xxx series (Permanent Failures). The <c>errors</c> list is empty if the request has been received in @@ -526,19 +524,24 @@ the relay application.</p> The <c>transport_data</c> field contains an arbitrary term passed into diameter from the transport module in question, or the atom <c>undefined</c> if the transport specified no data. -The term is preserved in the packet() containing any answer message -sent back to the transport process unless another value is explicitly -specified.</p> +The term is preserved if a &message; is returned but must be set +explicitly in a returned &packet;.</p> <p> The semantics of each of the possible return values are as follows.</p> <taglist> -<tag><c>{reply, message()}</c></tag> +<tag><c>{reply, &packet; | &message;}</c></tag> <item> <p> -Send the specified answer message to the peer.</p> +Send the specified answer message to the peer. +In the case of a &packet;, the +message to be sent must be set in the +<c>msg</c> field and the <c>header</c> field can be set to a +<c>#diameter_header{}</c> to specify values that should be +preserved in the outgoing answer, appropriate values otherwise +being set by diameter.</p> </item> <tag><c>{protocol_error, 3000..3999}</c></tag> @@ -547,15 +550,15 @@ Send the specified answer message to the peer.</p> Send an answer message to the peer containing the specified protocol error. Equivalent to</p> -<code> +<pre> {reply, ['answer-message' | Avps] -</code> +</pre> <p> where <c>Avps</c> sets the Origin-Host, Origin-Realm, the specified Result-Code and (if the request sent one) Session-Id AVP's.</p> <p> -Note that RFC 3588 mandates that only answers with a 3xxx series +Note that &the_rfc; mandates that only answers with a 3xxx series Result-Code (protocol errors) may set the E bit. Returning a non-3xxx value in a <c>protocol_error</c> tuple will cause the request process in question to fail.</p> @@ -568,37 +571,47 @@ Relay a request to another peer in the role of a Diameter relay agent. If a routing loop is detected then the request is answered with 3005 (DIAMETER_LOOP_DETECTED). Otherwise a Route-Record AVP (containing the sending peer's Origin-Host) is -added to the request and <seealso marker="#pick_peer">pick_peer/4</seealso> -and subsequent callbacks take place just as if <seealso -marker="diameter#call">diameter:call/4</seealso> had been called +added to the request and &pick_peer; +and subsequent callbacks take place just as if &mod_call; had been called explicitly. The End-to-End Identifier of the incoming request is preserved in the header of the relayed request.</p> <p> The returned <c>Opts</c> should not specify <c>detach</c>. -A subsequent <seealso marker="#handle_answer">handle_answer/4</seealso> +A subsequent &handle_answer; callback for the relayed request must return its first -argument, the <c>diameter_packet</c> record containing the answer +argument, the <c>#diameter_packet{}</c> record containing the answer message. Note that the <c>extra</c> option can be specified to supply arguments that can distinguish the relay case from others if so desired. Any other return value (for example, from a -<seealso marker="#handle_error">handle_error/4</seealso> callback) +&handle_error; callback) causes the request to be answered with 3002 (DIAMETER_UNABLE_TO_DELIVER).</p> </item> <tag><c>discard</c></tag> <item> <p> -Discard the request.</p> +Discard the request. +No answer message is sent to the peer.</p> </item> <tag><c>{eval, Action, PostF}</c></tag> <item> <p> Handle the request as if <c>Action</c> has been returned and then -evaluate <c>PostF</c> in the request process.</p> +evaluate <c>PostF</c> in the request process. +The return value is ignored.</p> +</item> + +<tag><c>{eval_packet, Action, PostF}</c></tag> +<item> +<p> +Like <c>eval</c> but evaluate <c>PostF</c> on any encoded +<c>#diameter_packet{}</c> prior to transmission, the <c>bin</c> field +containing the encoded binary. +The return value is ignored.</p> </item> </taglist> diff --git a/lib/diameter/doc/src/diameter_codec.xml b/lib/diameter/doc/src/diameter_codec.xml new file mode 100644 index 0000000000..4a77d5435b --- /dev/null +++ b/lib/diameter/doc/src/diameter_codec.xml @@ -0,0 +1,389 @@ +<?xml version="1.0" encoding="latin1" ?> +<!DOCTYPE erlref SYSTEM "erlref.dtd" [ + <!ENTITY records + '<seealso marker="diameter_dict#MESSAGE_RECORDS">diameter_dict(4)</seealso>'> + <!ENTITY types + '<seealso marker="diameter_dict#DATA_TYPES">diameter_dict(4)</seealso>'> + <!ENTITY % also SYSTEM "seealso.ent" > + <!ENTITY % here SYSTEM "seehere.ent" > + %also; + %here; +]> + +<erlref> +<header> +<copyright> +<year>2012</year> +<holder>Ericsson AB. All Rights Reserved.</holder> +</copyright> +<legalnotice> +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. + +</legalnotice> + +<title>diameter_codec(3)</title> +<prepared>Anders Svensson</prepared> +<responsible></responsible> +<docno></docno> +<approved></approved> +<checked></checked> +<date></date> +<rev></rev> +<file>diameter_codec.xml</file> +</header> + +<module>diameter_codec</module> +<modulesummary>Decode and encode of Diameter messages.</modulesummary> + +<description> + +<p> +Incoming Diameter messages are decoded from binary() before being +communicated to &man_app; callbacks. +Similarly, outgoing Diameter messages are encoded into binary() before +being passed to the appropriate &man_transport; module for +transmission. +The functions in this module implement this encode/decode.</p> + +<note> +<p> +Calls to this module are made by diameter itself as a consequence of +configuration passed to &mod_start_service;. +The encode/decode functions may also be useful for other purposes (eg. +test) but the diameter user does not need to call them explicitly when +sending and receiving messages using &mod_call; and the callback +interface documented in &man_app;.</p> +</note> + +<p> +The &header; and &packet; records below +are defined in diameter.hrl, which can be included as follows.</p> + +<pre> +-include_lib("diameter/include/diameter.hrl"). +</pre> + +<p> +Application-specific records are definied in the hrl +files resulting from dictionary file compilation.</p> + +</description> + +<!-- ===================================================================== --> + +<section> +<title>DATA TYPES</title> + +<p></p> + +<taglist> + +<marker id="integers"/> + +<tag><c>uint8() = 0..255</c></tag> +<tag><c>uint24() = 0..16777215</c></tag> +<tag><c>uint32() = 0..4294967295</c></tag> +<item> +<p> +8-bit, 24-bit and 32-bit integers occurring in Diameter and AVP +headers.</p> +</item> + +<marker id="avp"/> + +<tag><c>avp() = #diameter_avp{}</c></tag> +<item> +<p> +The application-neutral representation of an AVP. +Primarily intended for use by relay applications that need to handle +arbitrary Diameter applications. +A service implementing a specific Diameter application +(for which it configures a dictionary) can manipulate values of type +&message; instead.</p> + +<p> +Fields have the following types.</p> + +<taglist> + +<tag><c>code = uint32()</c></tag> +<tag><c>is_mandatory = boolean()</c></tag> +<tag><c>need_encryption = boolean()</c></tag> +<tag><c>vendor_id = uint32() | undefined</c></tag> +<item> +<p> +Values in the AVP header, corresponding to AVP Code, the M flag, P +flags and Vendor-ID respectivelty. +A Vendor-ID other than <c>undefined</c> implies a set V flag.</p> +</item> + +<tag><c>data = iolist()</c></tag> +<item> +<p> +The data bytes of the AVP.</p> +</item> + +<tag><c>name = atom()</c></tag> +<item> +<p> +The name of the AVP as defined in the dictionary file in question, or +<c>undefined</c> if the AVP is unknown to the dictionary file in +question.</p> +</item> + +<tag><c>value = term()</c></tag> +<item> +<p> +The decoded value of an AVP. +Will be <c>undefined</c> on decode if the data bytes could +not be decoded or the AVP is unknown. +The type of a decoded value is as document in &types;.</p> +</item> + +<tag><c>type = atom()</c></tag> +<item> +<p> +The type of the AVP as specified in the dictionary file in question +(or one it inherits). +Possible types are <c>undefined</c> and the Diameter types: +<c>OctetString</c>, <c>Integer32</c>, <c>Integer64</c>, +<c>Unsigned32</c>, <c>Unsigned64</c>, <c>Float32</c>, <c>Float64</c>, +<c>Grouped</c>, <c>Enumerated</c>, <c>Address</c>, <c>Time</c>, +<c>UTF8String</c>, <c>DiameterIdentity</c>, <c>DiameterURI</c>, +<c>IPFilterRule</c> and <c>QoSFilterRule</c>.</p> +</item> + +</taglist> + +</item> + +<marker id="dictionary"/> + +<tag><c>dictionary() = module()</c></tag> +<item> + +<p> +The name of a generated dictionary module as generated by &man_compile; +or &make_codec;. +The interface provided by a dictionary module is an +implementation detail that may change.</p> +</item> + +<marker id="header"/> + +<tag><c>header() = #diameter_header{}</c></tag> +<item> +<p> +The record representation of the Diameter header. +Values in a &packet; returned by &decode; are as extracted from the +incoming message. +Values set in an &packet; passed to &encode; are preserved in the +encoded binary(), with the exception of <c>length</c>, <c>cmd_code</c> +and <c>application_id</c>, all of which are determined by the +&dictionary; in question.</p> + +<note> +<p> +It is not necessary to set header fields explicitly in outgoing +messages as diameter itself will set appropriate values. +Setting inappropriate values can be useful for test purposes.</p> +</note> + +<p> +Fields have the following types.</p> + +<taglist> + +<tag><c>version = uint8()</c></tag> +<tag><c>length = uint24()</c></tag> +<tag><c>cmd_code = uint24()</c></tag> +<tag><c>application_id = uint32()</c></tag> +<tag><c>hop_by_hop_id = uint32()</c></tag> +<tag><c>end_to_end_id = uint32()</c></tag> +<item> +<p> +Values of the Version, Message Length, Command-Code, Application-ID, +Hop-by-Hop Identifier and End-to-End Identifier fields of the Diameter +header.</p> +</item> + +<tag><c>is_request = boolean()</c></tag> +<tag><c>is_proxiable = boolean()</c></tag> +<tag><c>is_error = boolean()</c></tag> +<tag><c>is_retransmitted = boolean()</c></tag> +<item> +<p> +Values correspoding to the R(equest), P(roxiable), E(rror) +and T(Potentially re-transmitted message) flags of the Diameter +header.</p> +</item> + +</taglist> + +</item> + +<marker id="message"/> + +<tag><c>message() = record() | list()</c></tag> +<item> +<p> +The representation of a Diameter message as passed to +&mod_call; or returned from a &app_handle_request; callback. +The record representation is as outlined in &records;: +a message as defined in a dictionary file is encoded as a record with +one field for each component AVP. +Equivalently, a message can also be encoded as a list whose head is +the atom-valued message name (as specified in the relevant dictionary +file) and whose tail is a list of <c>{AvpName, AvpValue}</c> pairs.</p> + +<p> +Another list-valued representation allows a message to be specified +as a list whose head is a &header; and whose tail is an &avp; list. +This representation is used by diameter itself when relaying requests +as directed by the return value of a &app_handle_request; callback. +It differs from the other other two in that it bypasses the checks for +messages that do not agree with their definitions in the dictionary in +question: messages are sent exactly as specified.</p> + +</item> + +<marker id="packet"/> + +<tag><c>packet() = #diameter_packet{}</c></tag> +<item> +<p> +A container for incoming and outgoing Diameter messages. +Fields have the following types.</p> + +<taglist> + +<tag><c>header = &header; | undefined</c></tag> +<item> +<p> +The Diameter header of the message. +Can be (and typically should be) <c>undefined</c> for an outgoing +message in a non-relay application, in which case diameter provides +appropriate values.</p> +</item> + +<tag><c>avps = [&avp;] | undefined</c></tag> +<item> +<p> +The AVPs of the message. +Ignored for an outgoing message if the <c>msg</c> field is set to a +value other than <c>undefined</c>.</p> +</item> + +<tag><c>msg = &message; | undefined</c></tag> +<item> +<p> +The incoming/outgoing message. +For an incoming message, a record if the message can be +decoded in a non-relay application, <c>undefined</c> otherwise. +For an outgoing message, setting a <c>[&header; | &avp;]</c> list is +equivalent to setting the <c>header</c> and <c>avps</c> fields to the +corresponding values.</p> + +<warning> +<p> +A record-valued <c>msg</c> field does <b>not</b> imply an absence of +decode errors. +The <c>errors</c> field should also be examined.</p> +</warning> + +</item> + +<tag><c>bin = binary()</c></tag> +<item> +<p> +The incoming message prior to encode or the outgoing message after +encode.</p> +</item> + +<tag><c>errors = [5000..5999 | {5000..5999, avp()}]</c></tag> +<item> +<p> +Errors detected at decode of an incoming message, as identified by +a corresponding 5xxx series Result-Code (Permanent Failures). +For an incoming request, these should be used to formulate an +appropriate answer as documented for the &app_handle_request; +callback in &man_app;. +For an incoming answer, the &mod_application_opt; +<c>answer_errors</c> determines the behaviour.</p> +</item> + +<tag><c>transport_data = term()</c></tag> +<item> +<p> +An arbitrary term of meaning only to the transport process in +question, as documented in &man_transport;.</p> +</item> + +</taglist> + +</item> + +</taglist> + +</section> + +<!-- ===================================================================== --> + +<funcs> + +<func> +<name>decode(Mod, Bin) -> Pkt</name> +<fsummary>Decode a Diameter message.</fsummary> +<type> +<v>Mod = &dictionary;</v> +<v>Bin = binary()</v> +<v>Pkt = &packet;</v> +</type> +<desc> + +<p> +Decode a Diameter message.</p> + +</desc> +</func> + +<func> +<name>encode(Mod, Msg) -> Pkt</name> +<fsummary>Encode a Diameter message.</fsummary> +<type> +<v>Mod = &dictionary;</v> +<v>Msg = &message; | &packet;</v> +<v>Pkt = &packet;</v> +</type> +<desc> + +<p> +Encode a Diameter message. +</p> + +</desc> +</func> + +</funcs> + +<!-- ===================================================================== --> +<!-- ===================================================================== --> + +<section> +<title>SEE ALSO</title> + +<p> +&man_compile;, &man_app;, &man_dict;, &man_make;</p> + +</section> + +</erlref> diff --git a/lib/diameter/doc/src/diameter_compile.xml b/lib/diameter/doc/src/diameter_compile.xml index 72bac30709..0bd7ad1789 100644 --- a/lib/diameter/doc/src/diameter_compile.xml +++ b/lib/diameter/doc/src/diameter_compile.xml @@ -1,10 +1,17 @@ <?xml version="1.0" encoding="iso-8859-1" ?> -<!DOCTYPE comref SYSTEM "comref.dtd"> +<!DOCTYPE comref SYSTEM "comref.dtd" [ + <!ENTITY dictionary + '<seealso marker="diameter_dict">dictionary file</seealso>'> + <!ENTITY % also SYSTEM "seealso.ent" > + <!ENTITY % here SYSTEM "seehere.ent" > + %also; + %here; +]> <comref> <header> <copyright> -<year>2011</year> +<year>2011</year><year>2012</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -31,12 +38,14 @@ supplied. <description> <p> -The diameterc utility is used to transform diameter -<seealso marker="diameter_dict">dictionary files</seealso> -into Erlang source. -The resulting source implements the interface diameter requires +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> +<p> +The module &man_make; provides an alternate compilation interface.</p> + </description> <section> @@ -47,41 +56,55 @@ to encode and decode the dictionary's messages and AVP's.</p> <tag><![CDATA[diameterc [<options>] <file>]]></tag> <item> <p> -Transforms a single dictionary file. Valid options are as follows.</p> +Compile a single dictionary file to Erlang source. +Valid options are as follows.</p> -<!-- Leave -h/d/v undocumented, except for the usage message from the - utility itself. --> +<tag><![CDATA[-i <dir>]]></tag> +<item> +<p> +Prepend the specified directory to the code path. +Use to point at beam files compiled from inherited dictionaries, +<c>&dict_inherits;</c> in a dictionary file creating a beam +dependency, not an erl/hrl dependency.</p> + +<p> +Multiple <c>-i</c> options can be specified.</p> +</item> <taglist> <tag><![CDATA[-o <dir>]]></tag> <item> <p> -Specifies the directory into which the generated source should be written. +Write generated source to the specified directory. Defaults to the current working directory.</p> </item> -<tag><![CDATA[-i <dir>]]></tag> +<tag><![CDATA[-E]]></tag> +<tag><![CDATA[-H]]></tag> <item> <p> -Specifies a directory to add to the code path. -Typically used to point at beam files corresponding to dictionaries -included by the one being compiled (using the <c>@includes</c> directive): -inclusion is a beam dependency, not an erl/hrl dependency.</p> - -<p> -Multiple <c>-i</c> options can be specified.</p> +Supress erl and hrl generation, respectively.</p> </item> -<tag><![CDATA[-E]]></tag> +<tag><![CDATA[--name <name>]]></tag> +<tag><![CDATA[--prefix <prefix>]]></tag> <item> <p> -Supresses erl generation.</p> +Set <c>&dict_name;</c> or <c>&dict_prefix;</c> to the specified +string. +Overrides any setting in the file itself.</p> </item> -<tag><![CDATA[-H]]></tag> +<tag><![CDATA[--inherits <dict>]]></tag> <item> <p> -Supresses hrl generation.</p> +Append &dict_inherits; of the specified module. +Specifying <c>"-"</c> has the effect of discarding clearing any +previous inherits, both in the dictionary file and on the options +list.</p> + +<p> +Multiple <c>--inherits</c> options can be specified.</p> </item> </taglist> @@ -104,20 +127,10 @@ Returns 0 on success, non-zero on failure.</p> <!-- ===================================================================== --> <section> -<title>BUGS</title> - -<p> -The identification of errors in the source file is poor.</p> - -</section> - -<!-- ===================================================================== --> - -<section> <title>SEE ALSO</title> <p> -<seealso marker="diameter_dict">diameter_dict(4)</seealso></p> +&man_make;, &man_dict;</p> </section> diff --git a/lib/diameter/doc/src/diameter_dict.xml b/lib/diameter/doc/src/diameter_dict.xml index e7c530f1b8..8b0687a22e 100644 --- a/lib/diameter/doc/src/diameter_dict.xml +++ b/lib/diameter/doc/src/diameter_dict.xml @@ -1,11 +1,22 @@ <?xml version="1.0" encoding="latin1" ?> -<!DOCTYPE erlref SYSTEM "fileref.dtd"> +<!DOCTYPE erlref SYSTEM "fileref.dtd" [ + <!ENTITY format + '<seealso marker="#FILE_FORMAT">FILE FORMAT</seealso>'> + <!ENTITY records + '<seealso marker="#MESSAGE_RECORDS">MESSAGE RECORDS</seealso>'> + <!ENTITY types + '<seealso marker="#DATA_TYPES">DATA TYPES</seealso>'> + <!ENTITY % also SYSTEM "seealso.ent" > + <!ENTITY % here SYSTEM "seehere.ent" > + %also; + %here; +]> <fileref> <header> <copyright> -<year>2011</year> +<year>2011</year><year>2012</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -36,52 +47,49 @@ under the License. <!-- ===================================================================== --> <file>diameter_dict</file> -<filesummary>Dictionary inteface of the diameter application.</filesummary> +<filesummary>Dictionary interface of the diameter application.</filesummary> <description> <p> -A diameter service as configured with <seealso -marker="diameter#start_service">diameter:start_service/2</seealso> +A diameter service, as configured with &mod_start_service;, specifies one or more supported Diameter applications. Each Diameter application specifies a dictionary module that knows how -to encode and decode its messages and AVP's. +to encode and decode its messages and AVPs. The dictionary module is in turn generated from a file that defines -these messages and AVP's. -The format of such a file is defined in -<seealso marker="#FILE_FORMAT">FILE FORMAT</seealso> below. +these messages and AVPs. +The format of such a file is defined in &format; below. Users add support for their specific applications by creating dictionary files, compiling them to Erlang modules using -<seealso marker="diameterc">diameterc</seealso> and configuring the +either &man_compile; or &man_make; and configuring the resulting dictionaries modules on a service.</p> <p> -The codec generation also results in a hrl file that defines records -for the messages and grouped AVP's defined for the application, these -records being what a user of the diameter application sends and receives. -(Modulo other available formats as discussed in <seealso -marker="diameter_app">diameter_app(3)</seealso>.) +Dictionary module generation also results in a hrl file that defines +records for the messages and Grouped AVPs defined by the +dictionary, these records being what a user of the diameter +application sends and receives, modulo other possible formats as +discussed in &man_app;. These records and the underlying Erlang data types corresponding to -Diameter data formats are discussed in <seealso -marker="#MESSAGE_RECORDS">MESSAGE RECORDS</seealso> and <seealso -marker="#DATA_TYPES">DATA TYPES</seealso> respectively. -The generated hrl also contains defines for the possible values of +Diameter data formats are discussed in &records; and &types; +respectively. +The generated hrl also contains macro definitions for the possible values of AVPs of type Enumerated.</p> <p> The diameter application includes three dictionary modules -corresponding to applications defined in section 2.4 of RFC 3588: +corresponding to applications defined in section 2.4 of &the_rfc;: <c>diameter_gen_base_rfc3588</c> for the Diameter Common Messages application with application identifier 0, <c>diameter_gen_accounting</c> for the Diameter Base Accounting application with application identifier 3 and -<c>diameter_gen_relay</c>the Relay application with application +<c>diameter_gen_relay</c> the Relay application with application identifier 0xFFFFFFFF. The Common Message and Relay applications are the only applications that diameter itself has any specific knowledge of. The Common Message application is used for messages that diameter itself handles: CER/CEA, DWR/DWA and DPR/DPA. The Relay application is given special treatment with regard to -encode/decode since the messages and AVP's it handles are not specifically +encode/decode since the messages and AVPs it handles are not specifically defined.</p> <marker id="FILE_FORMAT"/> @@ -94,28 +102,29 @@ defined.</p> <p> A dictionary file consists of distinct sections. -Each section starts with a line consisting of a tag -followed by zero or more arguments. -Each section ends at the the start of the next section or end of file. +Each section starts with a tag followed by zero or more arguments +and ends at the the start of the next section or end of file. Tags consist of an ampersand character followed by a keyword and are separated from their arguments by whitespace. -Whitespace within a section separates individual tokens but its -quantity is insignificant.</p> +Whitespace separates individual tokens but is otherwise insignificant.</p> <p> The tags, their arguments and the contents of each corresponding section are as follows. -Each section can occur at most once unless otherwise specified. +Each section can occur multiple times unless otherwise specified. The order in which sections are specified is unimportant.</p> <taglist> +<marker id="id"/> + <tag><c>@id Number</c></tag> <item> <p> Defines the integer Number as the Diameter Application Id of the application in question. -Required if the dictionary defines <c>@messages</c>. +Can occur at most once and is required if the dictionary defines +<c>@messages</c>. The section has empty content.</p> <p> @@ -126,119 +135,143 @@ is used to identify the relevant dictionary module.</p> <p> Example:</p> -<code> +<pre> @id 16777231 -</code> +</pre> </item> +<marker id="name"/> + <tag><c>@name Mod</c></tag> <item> <p> Defines the name of the generated dictionary module. -The section has empty content. -Mod must match the regular expression '^[a-zA-Z0-9][-_a-zA-Z0-9]*$'; -that is, contains only alphanumerics, hyphens and underscores begin with an -alphanumeric.</p> +Can occur at most once and defaults to the name of the dictionary file +minus any extension if unspecified. +The section has empty content.</p> <p> -A name is optional and defaults to the name of the dictionary file -minus any extension. -Note that a generated module must have a unique name an not colide -with another module in the system.</p> +Note that a dictionary module should have a unique name so as not collide +with existing modules in the system.</p> <p> Example:</p> -<code> +<pre> @name etsi_e2 -</code> +</pre> </item> +<marker id="prefix"/> + <tag><c>@prefix Name</c></tag> <item> <p> -Defines Name as the prefix to be added to record and constant names in -the generated dictionary module and hrl. -The section has empty content. -Name must be of the same form as a @name.</p> +Defines Name as the prefix to be added to record and constant names +(followed by a <c>'_'</c> character) in the generated dictionary +module and hrl. +Can occur at most once. +The section has empty content.</p> <p> -A prefix is optional but can -be used to disambiguate record and constant names -resulting from similarly named messages and AVP's in different -Diameter applications.</p> +A prefix is optional but can be be used to disambiguate between record +and constant names resulting from similarly named messages and AVPs in +different Diameter applications.</p> <p> Example:</p> -<code> -@prefix etsi_e2_ -</code> +<pre> +@prefix etsi_e2 +</pre> </item> +<marker id="vendor"/> + <tag><c>@vendor Number Name</c></tag> <item> <p> -Defines the integer Number as the the default Vendor-ID of AVP's for +Defines the integer Number as the the default Vendor-Id of AVPs for which the V flag is set. Name documents the owner of the application but is otherwise unused. +Can occur at most once and is required if an AVP sets the V flag and +is not otherwise assigned a Vendor-Id. The section has empty content.</p> <p> Example:</p> -<code> +<pre> @vendor 13019 ETSI -</code> +</pre> </item> +<marker id="avp_vendor_id"/> + <tag><c>@avp_vendor_id Number</c></tag> <item> <p> -Defines the integer Number as the Vendor-ID of the AVP's listed in the +Defines the integer Number as the Vendor-Id of the AVPs listed in the section content, overriding the <c>@vendor</c> default. -The section content consists of AVP names. -Can occur zero or more times (with different values of Number).</p> +The section content consists of AVP names.</p> <p> Example:</p> -<code> +<pre> @avp_vendor_id 2937 WWW-Auth Domain-Index Region-Set -</code> +</pre> </item> +<marker id="inherits"/> + <tag><c>@inherits Mod</c></tag> <item> <p> -Defines the name of a generated dictionary module containing AVP -definitions referenced by the dictionary but not defined by it. -The section content is empty.</p> +Defines the name of a dictionary module containing AVP +definitions that should be imported into the current dictionary. +The section content consists of the names of those AVPs whose +definitions should be imported from the dictionary, an empty list +causing all to be imported. +Any listed AVPs must not be defined in the current dictionary and +it is an error to inherit the same AVP from more than one +dictionary.</p> <p> -Can occur 0 or more times (with different values of Mod) but all -dictionaries should typically inherit RFC3588 AVPs from +Note that an inherited AVP that sets the V flag takes its Vendor-Id +from either <c>@avp_vendor_id</c> in the inheriting dictionary or +<c>@vendor</c> in the inherited dictionary. +In particular, <c>@avp_vendor_id</c> in the inherited dictionary is +ignored. +Inheriting from a dictionary that specifies the required <c>@vendor</c> +is equivalent to using <c>@avp_vendor_id</c> with a copy of the +dictionary's definitions but the former makes for easier reuse.</p> + +<p> +All dictionaries should typically inherit &the_rfc; AVPs from <c>diameter_gen_base_rfc3588</c>.</p> <p> Example:</p> -<code> +<pre> @inherits diameter_gen_base_rfc3588 -</code> +</pre> </item> +<marker id="avp_types"/> + <tag><c>@avp_types</c></tag> <item> <p> @@ -248,63 +281,82 @@ The section consists of definitions of the form</p> <p><c>Name Code Type Flags</c></p> <p> -where Code is the integer AVP code, Flags is a string of V, -M and P characters indicating the flags to be -set on an outgoing AVP or a single - (minus) character if none are to -be set. -Type identifies either an AVP Data Format as defined in <seealso -marker="#DATA_TYPES">DATA TYPES</seealso> below or a -type as defined by a <c>@custom_types</c> tag.</p> +where Code is the integer AVP code, Type identifies an AVP Data Format +as defined in section &types; below, +and Flags is a string of V, M and P characters indicating the flags to be +set on an outgoing AVP or a single <c>'-'</c> (minus) character if +none are to be set.</p> <p> Example:</p> -<code> +<pre> @avp_types -Location-Information 350 Grouped VM -Requested-Information 353 Enumerated V -</code> +Location-Information 350 Grouped MV +Requested-Information 353 Enumerated V +</pre> +<warning> <p> -Note that the P flag has been deprecated by the Diameter Maintenance -and Extensions Working Group of the IETF: diameter will set the P flag -to 0 as mandated by the current draft standard.</p> +The P flag has been deprecated by &the_rfc;.</p> +</warning> </item> +<marker id="custom_types"/> + <tag><c>@custom_types Mod</c></tag> <item> <p> -Defines AVPs for which module Mod provides encode/decode. -The section contents consists of type names. -For each AVP Name defined with custom type Type, Mod should export the -function Name/3 with arguments encode|decode, Type and Data, -the latter being the term to be encoded/decoded. -The function returns the encoded/decoded value.</p> +Specifies AVPs for which module Mod provides encode/decode functions. +The section contents consists of AVP names. +For each such name, <c>Mod:Name(encode|decode, Type, Data)</c> is +expected to provide encode/decode for values of the AVP, where Name is +the name of the AVP, Type is it's type as declared in the +<c>@avp_types</c> section of the dictionary and Data is the value to +encode/decode.</p> <p> -Can occur 0 or more times (with different values of Mod).</p> +Example:</p> + +<pre> +@custom_types rfc4005_avps + +Framed-IP-Address +</pre> +</item> + +<marker id="codecs"/> + +<tag><c>@codecs Mod</c></tag> +<item> +<p> +Like <c>@custom_types</c> but requires the specified module to export +<c>Mod:Type(encode|decode, Name, Data)</c> rather than +<c>Mod:Name(encode|decode, Type, Data)</c>.</p> <p> Example:</p> -<code> -@custom_types rfc4005_types +<pre> +@codecs rfc4005_avps Framed-IP-Address -</code> +</pre> </item> +<marker id="messages"/> + <tag><c>@messages</c></tag> <item> <p> Defines the messages of the application. The section content consists of definitions of the form specified in -section 3.2 of RFC 3588, "Command Code ABNF specification".</p> +section 3.2 of &the_rfc;, "Command Code Format Specification".</p> <!-- RFC 4740 RTR/RTA --> -<code> +<pre> @messages RTR ::= < Diameter Header: 287, REQ, PXY > @@ -337,31 +389,39 @@ RTA ::= < Diameter Header: 287, PXY > * [ Proxy-Info ] * [ Route-Record ] * [ AVP ] -</code> +</pre> </item> +<marker id="grouped"/> + <tag><c>@grouped</c></tag> <item> <p> Defines the contents of the AVPs of the application having type Grouped. The section content consists of definitions of the form specified in -section 4.4 of RFC 3588, "Grouped AVP Values".</p> +section 4.4 of &the_rfc;, "Grouped AVP Values".</p> <p> Example:</p> -<code> +<pre> @grouped SIP-Deregistration-Reason ::= < AVP Header: 383 > { SIP-Reason-Code } [ SIP-Reason-Info ] * [ AVP ] -</code> +</pre> + +<p> +Specifying a Vendor-Id in the definition of a grouped AVP is +equivalent to specifying it with <c>@avp_vendor_id</c>.</p> </item> +<marker id="enum"/> + <tag><c>@enum Name</c></tag> <item> <p> @@ -371,30 +431,37 @@ Integer values can be prefixed with 0x to be interpreted as hexidecimal.</p> <p> -Can occur 0 or more times (with different values of Name). -The AVP in question can be defined in an inherited dictionary in order -to introduce additional values. -An AVP so extended must be referenced by in a <c>@messages</c> or -<c>@grouped</c> section.</p> +Note that the AVP in question can be defined in an inherited +dictionary in order to introduce additional values to an enumeration +otherwise defined in another dictionary.</p> <p> Example:</p> -<code> +<pre> @enum SIP-Reason-Code PERMANENT_TERMINATION 0 NEW_SIP_SERVER_ASSIGNED 1 SIP_SERVER_CHANGE 2 REMOVE_SIP_SERVER 3 -</code> +</pre> +</item> + +<marker id="end"/> + +<tag><c>@end</c></tag> +<item> +<p> +Causes parsing of the dictionary to terminate: +any remaining content is ignored.</p> </item> </taglist> <p> Comments can be included in a dictionary file using semicolon: -text from a semicolon to end of line is ignored.</p> +characters from a semicolon to end of line are ignored.</p> <marker id="MESSAGE_RECORDS"/> </section> @@ -409,28 +476,28 @@ The hrl generated from a dictionary specification defines records for the messages and grouped AVPs defined in <c>@messages</c> and <c>@grouped</c> sections. For each message or grouped AVP definition, a record is defined whose -name is the message or AVP name prefixed with any dictionary prefix -defined with <c>@prefix</c> and whose fields are the names of the AVPs +name is the message or AVP name, prefixed with any dictionary prefix +defined with <c>@prefix</c>, and whose fields are the names of the AVPs contained in the message or grouped AVP in the order specified in the definition in question. For example, the grouped AVP</p> -<code> +<pre> SIP-Deregistration-Reason ::= < AVP Header: 383 > { SIP-Reason-Code } [ SIP-Reason-Info ] * [ AVP ] -</code> +</pre> <p> will result in the following record definition given an empty prefix.</p> -<code> +<pre> -record('SIP-Deregistration-Reason' {'SIP-Reason-Code', 'SIP-Reason-Info', 'AVP'}). -</code> +</pre> <p> The values encoded in the fields of generated records depends on the @@ -438,7 +505,7 @@ type and number of times the AVP can occur. In particular, an AVP which is specified as occurring exactly once is encoded as a value of the AVP's type while an AVP with any other specification is encoded as a list of values of the AVP's type. -The AVP's type is as specified in the AVP definition, the RFC 3588 +The AVP's type is as specified in the AVP definition, the &the_rfc; types being described below.</p> <marker id="DATA_TYPES"/> @@ -451,13 +518,11 @@ types being described below.</p> <p> The data formats defined in sections 4.2 ("Basic AVP Data -Formats") and 4.3 ("Derived AVP Data Formats") of RFC 3588 are encoded +Formats") and 4.3 ("Derived AVP Data Formats") of &the_rfc; are encoded as values of the types defined here. -Values are passed to <seealso -marker="diameter#call">diameter:call/4</seealso> +Values are passed to &mod_call; in a request record when sending a request, returned in a resulting -answer record and passed to a <seealso -marker="diameter_app#handle_request">handle_request</seealso> +answer record and passed to a &app_handle_request; callback upon reception of an incoming request.</p> <p> @@ -472,7 +537,7 @@ callback upon reception of an incoming request.</p> <marker id="Float64"/> <marker id="Grouped"/> -<code> +<pre> OctetString() = [0..255] Integer32() = -2147483647..2147483647 Integer64() = -9223372036854775807..9223372036854775807 @@ -481,7 +546,7 @@ Unsigned64() = 0..18446744073709551615 Float32() = '-infinity' | float() | infinity Float64() = '-infinity' | float() | infinity Grouped() = record() -</code> +</pre> <p> On encode, an OctetString() can be specified as an iolist(), @@ -495,10 +560,10 @@ section.</p> <em>Derived AVP Data Formats</em></p> <marker id="Address"/> -<code> +<pre> Address() = OctetString() | tuple() -</code> +</pre> <p> On encode, an OctetString() IPv4 address is parsed in the usual @@ -510,7 +575,7 @@ An IPv6 tuple() has length 8 and contains values of type 0..65535. The tuple representation is used on decode.</p> <marker id="Time"/> -<code> +<pre> Time() = {date(), time()} where @@ -524,19 +589,19 @@ where Hour = 0..23 Minute = 0..59 Second = 0..59 -</code> +</pre> <p> Additionally, values that can be encoded are -limited by way of their encoding as four octets as required by RFC -3588 with the required extension from RFC 2030. +limited by way of their encoding as four octets as required by +&the_rfc; with the required extension from RFC 2030. In particular, only values between <c>{{1968,1,20},{3,14,8}}</c> and <c>{{2104,2,26},{9,42,23}}</c> (both inclusive) can be encoded.</p> <marker id="UTF8String"/> -<code> +<pre> UTF8String() = [integer()] -</code> +</pre> <p> List elements are the UTF-8 encodings of the individual characters @@ -544,15 +609,15 @@ in the string. Invalid codepoints will result in encode/decode failure.</p> <marker id="DiameterIdentity"/> -<code> +<pre> DiameterIdentity() = OctetString() -</code> +</pre> <p> A value must have length at least 1.</p> <marker id="DiameterURI"/> -<code> +<pre> DiameterURI() = OctetString() | #diameter_URI{type = Type, fqdn = FQDN, @@ -567,19 +632,19 @@ where Port = integer() Transport = sctp | tcp Protocol = diameter | radius | 'tacacs+' -</code> +</pre> <p> On encode, fields port, transport and protocol default to 3868, sctp and diameter respectively. The grammar of an OctetString-valued DiameterURI() is as specified in -section 4.3 of RFC 3588. +section 4.3 of &the_rfc;. The record representation is used on decode.</p> <marker id="Enumerated"/> -<code> +<pre> Enumerated() = Integer32() -</code> +</pre> <p> On encode, values can be specified using the macros defined in a @@ -587,10 +652,10 @@ dictionary's hrl file.</p> <marker id="IPFilterRule"/> <marker id="QoSFilterRule"/> -<code> +<pre> IPFilterRule() = OctetString() QoSFilterRule() = OctetString() -</code> +</pre> <p> Values of these types are not currently parsed by diameter.</p> @@ -604,9 +669,7 @@ Values of these types are not currently parsed by diameter.</p> <title>SEE ALSO</title> <p> -<seealso marker="diameterc">diameterc(1)</seealso>, -<seealso marker="diameter">diameter(3)</seealso>, -<seealso marker="diameter_app">diameter_app(3)</seealso></p> +&man_compile;, &man_main;, &man_app;, &man_codec;, &man_make;</p> </section> diff --git a/lib/diameter/doc/src/diameter_examples.xml b/lib/diameter/doc/src/diameter_examples.xml index 966d1f1eee..1fd7755695 100644 --- a/lib/diameter/doc/src/diameter_examples.xml +++ b/lib/diameter/doc/src/diameter_examples.xml @@ -5,7 +5,7 @@ <header> <copyright> -<year>2011</year> +<year>2011</year><year>2012</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> @@ -37,7 +37,6 @@ under the License. <!-- ===================================================================== --> <p> -To be written. Example code can be found in the diameter application's <c>examples</c> subdirectory.</p> diff --git a/lib/diameter/doc/src/diameter_intro.xml b/lib/diameter/doc/src/diameter_intro.xml index ef08002a8b..fd578ccf45 100644 --- a/lib/diameter/doc/src/diameter_intro.xml +++ b/lib/diameter/doc/src/diameter_intro.xml @@ -1,10 +1,13 @@ <?xml version="1.0" encoding="latin1" ?> -<!DOCTYPE chapter SYSTEM "chapter.dtd"> +<!DOCTYPE chapter SYSTEM "chapter.dtd" [ + <!ENTITY % also SYSTEM "seealso.ent"> + %also; +]> <chapter> <header> <copyright> -<year>2011</year> +<year>2011</year><year>2012</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> @@ -35,7 +38,7 @@ under the License. <p> The diameter application is an implementation of the Diameter protocol -as defined by RFC 3588. +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 defined and input into diameter as configuration. @@ -44,11 +47,11 @@ agent. This chapter provides a short overview of the application.</p> <p> -A Diameter peer is implemented by configuring a <em>service</em> and +A Diameter node is implemented by configuring a <em>service</em> and one or more <em>transports</em> using the interface module <seealso marker="diameter">diameter</seealso>. The service configuration defines the Diameter applications to be -supported by the peer and, typically, the capabilities that it should +supported by the node and, typically, the capabilities that it should send to remote peers at capabilities exchange upon the establishment of transport connections. A transport is configured on a service and provides protocol-specific @@ -57,16 +60,17 @@ diameter and implemented by a transport module. The diameter application provides two transport modules: <seealso marker="diameter_tcp">diameter_tcp</seealso> and <seealso marker="diameter_sctp">diameter_sctp</seealso> for transport over TCP -(using <c>gen_tcp</c>) and SCTP (using <c>gen_sctp</c>) respectively. +(using <seealso marker="kernel:gen_tcp">gen_tcp</seealso>) and SCTP +(using <seealso marker="kernel:gen_sctp">gen_sctp</seealso>) respectively. Other transports can be provided by any module that implements diameter's <seealso marker="diameter_transport">transport interface</seealso>.</p> <p> -While a service typically implements a single Diameter peer (as +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 be used to -implement more than one Diameter peer.</p> +associated with capabilities AVP's so that a single service can be +used to implement more than one Diameter node.</p> <p> Each Diameter application defined on a service is configured with a @@ -76,19 +80,19 @@ diameter communicates the connectivity of remote peers, requests peer selection for outgoing requests, and communicates the reception of incoming Diameter request and answer messages. An application using diameter implements these application callback -modules to provide the functionality of the Diameter peer(s) it +modules to provide the functionality of the Diameter node(s) it implements.</p> <p> -Each Diameter application is also configured with one or more -dictionary modules +Each Diameter application is also configured with a +dictionary module that provide encode/decode functionality for outgoing/incoming -Diameter messages. -A module is generated from a <seealso -marker="diameter_dict">specification file</seealso> using the <seealso +Diameter messages belonging to the application. +A dictionary module is generated from a <seealso +marker="diameter_dict">dictionary file</seealso> using the <seealso marker="diameterc">diameterc</seealso> utility. -Dictionaries for the RFC 3588 Diameter Common Messages, Base -Accounting and Relay applications are provided by the diameter +Dictionaries for the &the_rfc; Diameter Common Messages, Base +Accounting and Relay applications are provided with the diameter application.</p> </chapter> diff --git a/lib/diameter/doc/src/diameter_make.xml b/lib/diameter/doc/src/diameter_make.xml new file mode 100644 index 0000000000..da6124310e --- /dev/null +++ b/lib/diameter/doc/src/diameter_make.xml @@ -0,0 +1,144 @@ +<?xml version="1.0" encoding="latin1" ?> +<!DOCTYPE erlref SYSTEM "erlref.dtd" [ + <!ENTITY filename + '<seealso marker="kernel:file#type-name">file:name()</seealso>'> + <!ENTITY dictionary + '<seealso marker="diameter_dict">dictionary file</seealso>'> + <!ENTITY % also SYSTEM "seealso.ent" > + <!ENTITY % here SYSTEM "seehere.ent" > + %also; + %here; +]> + +<erlref> +<header> +<copyright> +<year>2012</year> +<holder>Ericsson AB. All Rights Reserved.</holder> +</copyright> +<legalnotice> +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. + +</legalnotice> + +<title>diameter_make(3)</title> +<prepared>Anders Svensson</prepared> +<responsible></responsible> +<docno></docno> +<approved></approved> +<checked></checked> +<date></date> +<rev></rev> +<file>diameter_make.xml</file> +</header> + +<module>diameter_make</module> +<modulesummary>Diameter dictionary compilation.</modulesummary> + +<description> + +<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> + +<p> +The utility &man_compile; provides an alternate compilation +interface.</p> + +</description> + +<!-- ===================================================================== --> + +<funcs> + +<func> +<name>codec(Path::string(), [Opt]) -> ok | {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> + +<taglist> + +<tag><c>{include, Dir::string()}</c></tag> +<item> +<p> +Prepend the specified directory to the code path. +Use to point at beam files compiled from inherited dictionaries, +<c>&dict_inherits;</c> in a dictionary file creating a beam +dependency, not an erl/hrl dependency.</p> + +<p> +Multiple <c>include</c> options can be specified.</p> +</item> + +<tag><c>{outdir, Dir::string()}</c></tag> +<item> +<p> +Write generated source to the specified directory. +Defaults to the current working directory.</p> +</item> + +<tag><c>{name|prefix, string()}</c></tag> +<item> +<p> +Set <c>&dict_name;</c> or <c>&dict_prefix;</c> to the specified +string. +Overrides any setting in the file itself.</p> +</item> + +<tag><c>{inherits, Mod::string()}</c></tag> +<item> +<p> +Append &dict_inherits; of the specified module. +Specifying <c>"-"</c> has the effect of discarding clearing any +previous inherits, both in the dictionary file and on the options +list.</p> + +<p> +Multiple <c>inherits</c> options can be specified.</p> +</item> + +</taglist> + +</desc> +</func> + +</funcs> + +<!-- ===================================================================== --> + +<section> +<title>BUGS</title> + +<p> +All options are string-valued. +In particular, it is not currently possible to +an &dict_inherits; module as an atom() or a path as a &filename;</p> + +</section> + +<!-- ===================================================================== --> + +<section> +<title>SEE ALSO</title> + +<p> +&man_compile;, &man_dict;</p> + +</section> + +</erlref> diff --git a/lib/diameter/doc/src/diameter_sctp.xml b/lib/diameter/doc/src/diameter_sctp.xml index c1e839b8e1..5e3fd5eaf1 100644 --- a/lib/diameter/doc/src/diameter_sctp.xml +++ b/lib/diameter/doc/src/diameter_sctp.xml @@ -1,10 +1,21 @@ <?xml version="1.0" encoding="latin1" ?> -<!DOCTYPE erlref SYSTEM "erlref.dtd"> +<!DOCTYPE erlref SYSTEM "erlref.dtd" [ + <!ENTITY gen_sctp '<seealso marker="kernel:gen_sctp">gen_sctp(3)</seealso>'> + <!ENTITY gen_sctp_open1 + '<seealso marker="kernel:gen_sctp#open-1">gen_sctp:open/1</seealso>'> + <!ENTITY ip_address + '<seealso marker="kernel:inet#type-ip_address">inet:ip_address()</seealso>'> + <!ENTITY inet '<seealso marker="kernel:inet">inet(3)</seealso>'> + <!ENTITY % also SYSTEM "seealso.ent" > + <!ENTITY % here SYSTEM "seehere.ent" > + %also; + %here; +]> <erlref> <header> <copyright> -<year>2011</year> +<year>2011</year><year>2012</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -38,12 +49,11 @@ under the License. <description> <p> -This module implements diameter transport over SCTP using gen_sctp. +This module implements diameter transport over SCTP using &gen_sctp;. It can be specified as the value of a transport_module option to -<seealso -marker="diameter#add_transport">diameter:add_transport/2</seealso> +&mod_add_transport; and implements the behaviour documented in -<seealso marker="diameter_transport">diameter_transport(3)</seealso>.</p> +&man_transport;.</p> <marker id="start"/> </description> @@ -58,29 +68,28 @@ and implements the behaviour documented in <fsummary>Start a transport process.</fsummary> <type> <v>Type = connect | accept</v> -<v>Ref = reference()</v> +<v>Ref = &mod_transport_ref;</v> <v>Svc = #diameter_service{}</v> -<v>Opt = {raddr, ip_address()} | {rport, integer()} | term()</v> +<v>Opt = {raddr, &ip_address;} | {rport, integer()} | term()</v> <v>Pid = pid()</v> -<v>LAddr = ip_address()</v> +<v>LAddr = &ip_address;</v> <v>Reason = term()</v> </type> <desc> <p> -The start function required by <seealso -marker="diameter_transport#start">diameter_transport(3)</seealso>.</p> +The start function required by &man_transport;.</p> <p> The only diameter_sctp-specific argument is the options list. 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. +transport: the former is required while latter defaults to 3868 if +unspecified. More than one <c>raddr</c> option can be specified, in which case the connecting transport in question attempts each in sequence until an association is established. -Remaining options are any accepted by gen_sctp:open/1, with the exception +Remaining options are any accepted by &gen_sctp_open1;, with the exception of options <c>mode</c>, <c>binary</c>, <c>list</c>, <c>active</c> and <c>sctp_events</c>. Note that options <c>ip</c> and <c>port</c> specify the local address @@ -88,30 +97,40 @@ 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 Host-IP-Address -on the service are used. (In particular, one of these must be specified.) +If none are specified then the values of <c>Host-IP-Address</c> +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> +<warning> +<p> +An insufficiently large receive buffer may result in a peer having to +resend incoming messages: set the &inet; option <c>recbuf</c> to increase +the buffer size.</p> + +<p> +An insufficiently large send buffer may result in outgoing messages +being discarded: set the &inet; option <c>sndbuf</c> to increase +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 +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 <seealso -marker="diameter_app#handle_request">handle_request</seealso> or <seealso -marker="diameter_app#handle_answer">handle_answer</seealso> callback. -For an outbound message, either <c>undefined</c> (explicitly of -by specifying the outbound message as a <c>binary()</c>) or a tuple -should be set in the return value of <seealso -marker="diameter_app#handle_request">handle_request</seealso> +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 <seealso -marker="diameter_app#prepare_request">prepare_request</seealso>. -The value <c>undefined</c> uses a "next outbound stream" id and then -increments this modulo the total number outbound streams. That -is, successive values of <c>undefined</c> cycle through all outbound -streams.</p> +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. --> @@ -128,7 +147,7 @@ streams.</p> <title>SEE ALSO</title> <p> -<seealso marker="diameter_transport">diameter_transport(3)</seealso></p> +&man_main;, &man_transport;, &gen_sctp;, &inet;</p> </section> diff --git a/lib/diameter/doc/src/diameter_soc.xml b/lib/diameter/doc/src/diameter_soc.xml index 4f8581a904..16f6b9d5bb 100644 --- a/lib/diameter/doc/src/diameter_soc.xml +++ b/lib/diameter/doc/src/diameter_soc.xml @@ -1,11 +1,15 @@ <?xml version="1.0" encoding="latin1" ?> -<!DOCTYPE chapter SYSTEM "chapter.dtd"> +<!DOCTYPE chapter SYSTEM "chapter.dtd" [ + <!ENTITY % also SYSTEM "seealso.ent" > + %also; +]> <chapter> <header> <copyright> <year>2011</year> +<year>2012</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> @@ -41,34 +45,20 @@ Known points of questionable or non-compliance.</p> <!-- ===================================================================== --> <section> -<title>RFC 3588</title> +<title>&the_rfc;</title> <list> <item> <p> -The End-to-End Security framework (section 2.9) isn't implemented -since it is largely unspecified. -The document that was to describe it -(reference [AAACMS]) was abandoned in an uncompleted state several -years ago and the current draft RFC deprecates the framework, -including the P Flag in the AVP header.</p> -</item> - -<item> -<p> -There is no TLS support. -It's unclear (aka uninvestigated) how TLS would impact -diameter but IPsec can be used without it needing to know.</p> +There is no support for DTLS over SCTP.</p> </item> <item> <p> There is no explicit support for peer discovery (section 5.2). It can possibly be implemented on top of diameter as is but this is -probably something that diameter should do. -The current draft deprecates portions of the original RFC's mechanisms -however.</p> +probably something that diameter should do.</p> </item> <item> diff --git a/lib/diameter/doc/src/diameter_tcp.xml b/lib/diameter/doc/src/diameter_tcp.xml index a502e53972..e3b8c733b7 100644 --- a/lib/diameter/doc/src/diameter_tcp.xml +++ b/lib/diameter/doc/src/diameter_tcp.xml @@ -1,10 +1,32 @@ <?xml version="1.0" encoding="latin1" ?> -<!DOCTYPE erlref SYSTEM "erlref.dtd"> +<!DOCTYPE erlref SYSTEM "erlref.dtd" [ + <!ENTITY gen_tcp_connect3 + '<seealso marker="kernel:gen_tcp#connect-3">gen_tcp:connect/3</seealso>'> + <!ENTITY gen_tcp_listen2 + '<seealso marker="kernel:gen_tcp#listen-2">gen_tcp:listen/2</seealso>'> + <!ENTITY ip_address + '<seealso marker="kernel:inet#type-ip_address">inet:ip_address()</seealso>'> + <!ENTITY ssl_connect2 + '<seealso marker="ssl:ssl#connect-2">ssl:connect/2</seealso>'> + <!ENTITY ssl_connect3 + '<seealso marker="ssl:ssl#connect-3">ssl:connect/3</seealso>'> + <!ENTITY ssl_accept2 + '<seealso marker="ssl:ssl#ssl_accept-2">ssl:ssl_accept/2</seealso>'> + <!ENTITY ssl_listen2 + '<seealso marker="ssl:ssl#listen-2">ssl:listen/2</seealso>'> + <!ENTITY gen_tcp '<seealso marker="kernel:gen_tcp">gen_tcp(3)</seealso>'> + <!ENTITY inet '<seealso marker="kernel:inet">inet(3)</seealso>'> + <!ENTITY ssl '<seealso marker="ssl:ssl">ssl(3)</seealso>'> + <!ENTITY % also SYSTEM "seealso.ent" > + <!ENTITY % here SYSTEM "seehere.ent" > + %also; + %here; +]> <erlref> <header> <copyright> -<year>2011</year> +<year>2011</year><year>2012</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -38,12 +60,18 @@ under the License. <description> <p> -This module implements diameter transport over TCP using gen_tcp. -It can be specified as the value of a transport_module option to -<seealso -marker="diameter#add_transport">diameter:add_transport/2</seealso> +This module implements diameter transport over TCP using &gen_tcp;. +It can be specified as the value of a <c>transport_module</c> option to +&mod_add_transport; and implements the behaviour documented in -<seealso marker="diameter_transport">diameter_transport(3)</seealso>.</p> +&man_transport;. +TLS security is supported, both as an upgrade following +capabilities exchange as specified by &the_rfc; and +at connection establishment as in the current draft standard.</p> + +<p> +Note that the ssl application is required for TLS and must be started +before configuring TLS capability on diameter transports.</p> <marker id="start"/> </description> @@ -58,36 +86,66 @@ and implements the behaviour documented in <fsummary>Start a transport process.</fsummary> <type> <v>Type = connect | accept</v> -<v>Ref = reference()</v> +<v>Ref = &mod_transport_ref;</v> <v>Svc = #diameter_service{}</v> -<v>Opt = {raddr, ip_address()} | {rport, integer()} | term()</v> +<v>Opt = OwnOpt | SslOpt | TcpOpt</v> <v>Pid = pid()</v> -<v>LAddr = ip_address()</v> +<v>LAddr = &ip_address;</v> <v>Reason = term()</v> +<v>OwnOpt = {raddr, &ip_address;} + | {rport, integer()} + | {port, integer()}</v> +<v>SslOpt = {ssl_options, true | list()}</v> +<v>TcpOpt = term()</v> </type> <desc> <p> -The start function required by <seealso -marker="diameter_transport#start">diameter_transport(3)</seealso>.</p> +The start function required by &man_transport;.</p> <p> The only diameter_tcp-specific argument is the options list. Options <c>raddr</c> and <c>rport</c> specify the remote address -and port for a connecting transport and not valid for a listening +and port for a connecting transport and are not valid for a listening transport. -Remaining options are any accepted by gen_tcp:connect/3 for -a connecting transport, or gen_tcp:listen/2 for a listening transport, -with the exception of <c>binary</c>, <c>packet</c> and <c>active</c>. +Option <c>ssl_options</c> must be specified for a transport +that should support TLS: a value of <c>true</c> results in a +TLS handshake immediately upon connection establishment while +<c>list()</c> specifies options to be passed to &ssl_connect2; or +&ssl_accept2; +after capabilities exchange if TLS is negotiated. +Remaining options are any accepted by &ssl_connect3; or +&gen_tcp_connect3; for +a connecting transport, or &ssl_listen2; or &gen_tcp_listen2; for +a listening transport, depending on whether or not <c>{ssl_options, true}</c> +has been specified. +Options <c>binary</c>, +<c>packet</c> and <c>active</c> cannot be specified. Also, option <c>port</c> can be specified for a listening transport to specify the local listening port, the default being the standardized 3868 if unspecified. -Note that option <c>ip</c> specifies the local address.</p> +Note that the option <c>ip</c> specifies the local address.</p> + +<p> +An <c>ssl_options</c> list must be specified if and only if +the transport in question has set <c>Inband-Security-Id</c> to +1 (<c>TLS</c>), as +specified to either &mod_start_service; or +&mod_add_transport;, +so that the transport process will receive notification of +whether or not to commence with a TLS handshake following capabilities +exchange. +Failing to specify an options list on a TLS-capable transport +for which TLS is negotiated will cause TLS handshake to fail. +Failing to specify TLS capability when <c>ssl_options</c> has been +specified will cause the transport process to wait for a notification +that will not be forthcoming, which will eventually cause the RFC 3539 +watchdog to take down the connection.</p> <p> -If the service specifies more than one Host-IP-Address and -option <c>ip</c> is unspecified then then the -first of the service's addresses is used as the local address.</p> +If the <c>#diameter_service{}</c> record has more than one +<c>Host-IP-Address</c> and option <c>ip</c> is unspecified then the +first of the these addresses is used as the local address.</p> <p> The returned local address list has length one.</p> @@ -104,7 +162,7 @@ The returned local address list has length one.</p> <title>SEE ALSO</title> <p> -<seealso marker="diameter_transport">diameter_transport(3)</seealso></p> +&man_main;, &man_transport;, &gen_tcp;, &inet;, &ssl;</p> </section> diff --git a/lib/diameter/doc/src/diameter_transport.xml b/lib/diameter/doc/src/diameter_transport.xml index 37cc871e75..55b531155f 100644 --- a/lib/diameter/doc/src/diameter_transport.xml +++ b/lib/diameter/doc/src/diameter_transport.xml @@ -1,10 +1,18 @@ <?xml version="1.0" encoding="latin1" ?> -<!DOCTYPE erlref SYSTEM "erlref.dtd"> +<!DOCTYPE erlref SYSTEM "erlref.dtd" [ + <!ENTITY message '<seealso marker="#message">message()</seealso>'> + <!ENTITY ip_address + '<seealso marker="kernel:inet#type-ip_address">inet:ip_address()</seealso>'> + <!ENTITY % also SYSTEM "seealso.ent" > + <!ENTITY % here SYSTEM "seehere.ent" > + %also; + %here; +]> <erlref> <header> <copyright> -<year>2011</year> +<year>2011</year><year>2012</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -38,79 +46,116 @@ under the License. <description> <p> -A module specified as a <c>transport_module</c> to <seealso -marker="diameter#add_transport">diameter:add_transport/2</seealso> +A module specified as a <c>transport_module</c> to &mod_add_transport; must implement the interface documented here. The interface consists of a function with which diameter starts a transport process and a message interface with which the transport process communicates with the process that starts it (aka its parent).</p> -<marker id="start"/> </description> <!-- ===================================================================== --> +<section> +<title>DATA TYPES</title> + +<taglist> + +<marker id="message"/> + +<tag><c>message() = binary() | &codec_packet;</c></tag> +<item> +<p> +A Diameter message as passed over the transport interface.</p> + +<p> +For an inbound message from a transport process, a &codec_packet; must +contain the received message in its <c>bin</c> field. +In the case of an inbound request, any value set in the +<c>transport_data</c> field will passed back to the transport module +in the corresponding answer message, unless the sender supplies +another value.</p> + +<p> +For an outbound message to a transport process, a &codec_packet; has a +value other than <c>undefined</c> in its <c>transport_data</c> field +and has the binary() to send in its <c>bin</c> field.</p> +</item> + +</taglist> + +</section> + +<!-- ===================================================================== --> + <funcs> <func> -<name>Mod:start({Type, Ref}, Svc, Opts) - -> {ok, Pid} | {ok, Pid, LAddrs} | {error, Reason}</name> +<name>Mod:start({Type, Ref}, Svc, Config) + -> {ok, Pid} + | {ok, Pid, LAddrs} + | {error, Reason}</name> <fsummary>Start a transport process.</fsummary> <type> <v>Type = connect | accept</v> -<v>Ref = reference()</v> +<v>Ref = &mod_transport_ref;</v> <v>Svc = #diameter_service{}</v> -<v>Opts = term()</v> +<v>Config = term()</v> <v>Pid = pid()</v> -<v>LAddrs = [ip_address()]</v> +<v>LAddrs = [&ip_address;]</v> <v>Reason = term()</v> </type> <desc> <p> Start a transport process. -Called by diameter as a consequence of a call to <seealso -marker="diameter#add_transport">diameter:add_transport/2</seealso> in +Called by diameter as a consequence of a call to &mod_add_transport; in order to establish or accept a transport connection respectively. A transport process maintains a connection with a single remote peer.</p> <p> -The first argument indicates whether the transport process in question -is being started for a connecting (<c>connect</c>) or listening -(<c>accept</c>) transport. +<c>Type</c> indicates whether the transport process in question +is being started for a connecting (<c>Type=connect</c>) or listening +(<c>Type=accept</c>) transport. In the latter case, transport processes are started as required to -accept connections from multiple peers. -Ref is in each case the same value that was returned from the -call to <seealso -marker="diameter#add_transport">diameter:add_transport/2</seealso> +accept connections from multiple peers.</p> + +<p> +Ref is the value that was returned from the call to &mod_add_transport; that has lead to starting of a transport process.</p> <p> +<c>Svc</c> contains the capabilities passed to &mod_start_service; and +&mod_add_transport;, values passed to the latter overriding those +passed to the former.</p> + +<p> +<c>Config</c> is as passed in <c>transport_config</c> tuple in the +&mod_transport_opt; list passed to &mod_add_transport;.</p> + +<p> +The start function should use the <c>Host-IP-Address</c> list and/or +<c>Config</c> to select an appropriate list of local IP addresses, +and should return this list if different from the +<c>#diameter_service{}</c> addresses. +The returned list is used to populate <c>Host-IP-Address</c> AVPs in +outgoing capabilities exchange messages, the +<c>#diameter_service{}</c> addresses being used otherwise.</p> + +<p> A transport process must implement the message interface documented below. It should retain the pid of its parent, monitor the parent and terminate if it dies. It should not link to the parent. It should exit if its transport connection with its peer is lost.</p> -<p> -Transport processes for a given service are started sequentially.</p> - -<p> -The start function should use the 'Host-IP-Address' list on the service, -namely <c>Svc#diameter_service.host_ip_address</c>, and/or -<c>Opts</c> to select an appropriate list of local IP addresses, -and should return this list if different from the service addresses. -The returned list is used to populate 'Host-IP-Address' AVPs in outgoing -capabilities exchange messages, the service addresses being used -otherwise.</p> - -<marker id="MESSAGES"/> </desc> </func> </funcs> <!-- ===================================================================== --> +<marker id="MESSAGES"/> <section> <title>MESSAGES</title> @@ -120,33 +165,58 @@ All messages sent over the transport interface are of the form <c>{diameter, term()}</c>.</p> <p> -A transport process can expect the following messages from -diameter.</p> +A transport process can expect messages of the following types from +its parent.</p> <taglist> -<tag><c>{diameter, {send, Packet}}</c></tag> +<tag><c>{diameter, {send, &message;}}</c></tag> <item> <p> -An outbound Diameter message. -Packet can be either <c>binary()</c> (the message to be sent) -or a <c>#diameter_packet{}</c> whose <c>transport_data</c> field -containes a value other than undefined.</p> +An outbound Diameter message.</p> </item> <tag><c>{diameter, {close, Pid}}</c></tag> <item> <p> -A request to close the transport connection. -The transport process should terminate after closing the -connection. -Pid is the pid() of the parent process.</p> +A request to terminate the transport process after having received DPA +in response to DPR. +The transport process should exit. +<c>Pid</c> is the pid() of the parent process.</p> +</item> + +<tag><c>{diameter, {tls, Ref, Type, Bool}}</c></tag> +<item> +<p> +Indication of whether or not capabilities exchange has selected +inband security using TLS. +<c>Ref</c> is a reference() that must be included in the +<c>{diameter, {tls, Ref}}</c> reply message to the transport's +parent process (see below). +<c>Type</c> is either <c>connect</c> or <c>accept</c> depending on +whether the process has been started for a connecting or listening +transport respectively. +<c>Bool</c> is a boolean() indicating whether or not the transport +connection should be upgraded to TLS.</p> + +<p> +If TLS is requested (<c>Bool=true</c>) then a connecting process should +initiate a TLS handshake with the peer and an accepting process should +prepare to accept a handshake. +A successful handshake should be followed by a <c>{diameter, {tls, Ref}}</c> +message to the parent process. +A failed handshake should cause the process to exit.</p> + +<p> +This message is only sent to a transport process over whose +<c>Inband-Security-Id</c> configuration has indicated support for +TLS.</p> </item> </taglist> <p> -A transport process should send the following messages +A transport process should send messages of the following types to its parent.</p> <taglist> @@ -154,34 +224,35 @@ to its parent.</p> <tag><c>{diameter, {self(), connected}}</c></tag> <item> <p> -Inform the parent that the transport process with Type = accept has +Inform the parent that the transport process with <c>Type=accept</c> has established a connection with the peer. -Not sent if the transport process has Type = connect.</p> +Not sent if the transport process has <c>Type=connect</c>.</p> </item> <tag><c>{diameter, {self(), connected, Remote}}</c></tag> <item> <p> -Inform the parent that the transport process with Type = connect +Inform the parent that the transport process with <c>Type=connect</c> has established a connection with a peer. -Not sent if the transport process has Type = accept. -Remote is an arbitrary term that uniquely identifies the remote +Not sent if the transport process has <c>Type=accept</c>. +<c>Remote</c> is an arbitrary term that uniquely identifies the remote endpoint to which the transport has connected.</p> </item> -<tag><c>{diameter, {recv, Packet}}</c></tag> +<tag><c>{diameter, {recv, &message;}}</c></tag> +<item> +<p> +An inbound Diameter message.</p> +</item> + +<tag><c>{diameter, {tls, Ref}}</c></tag> <item> <p> -An inbound Diameter message. -Packet can be either <c>binary()</c> (the message to be sent) -or <c>#diameter_packet{}</c> -whose <c>packet</c> field contains a <c>binary()</c>. -Any value (other than undefined) set in -the <c>transport_data</c> field will be passed back with a -corresponding answer message in the case that the inbound message is a -request unless the sender sets another value. -How the <c>transport_data</c> is used/interpreted is up to the -transport module.</p> +Acknowledgment of a successful TLS handshake. +<c>Ref</c> is the reference() received in the +<c>{diameter, {tls, Ref, Type, Bool}}</c> message in response +to which the reply is sent. +A transport must exit if a handshake is not successful.</p> </item> </taglist> @@ -195,8 +266,7 @@ transport module.</p> <title>SEE ALSO</title> <p> -<seealso marker="diameter_tcp">diameter_tcp(3)</seealso>, -<seealso marker="diameter_sctp">diameter_sctp(3)</seealso></p> +&man_tcp;, &man_sctp;</p> </section> diff --git a/lib/diameter/doc/src/diameter_using.xml b/lib/diameter/doc/src/diameter_using.xml index 809b76bdf3..7d9c0cd492 100644 --- a/lib/diameter/doc/src/diameter_using.xml +++ b/lib/diameter/doc/src/diameter_using.xml @@ -5,7 +5,7 @@ <header> <copyright> -<year>2011</year> +<year>2011</year><year>2012</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> @@ -23,7 +23,7 @@ under the License. </legalnotice> -<title>Using the stack</title> +<title>Usage</title> <prepared></prepared> <responsible></responsible> <docno></docno> diff --git a/lib/diameter/doc/src/files.mk b/lib/diameter/doc/src/files.mk index 79d53abceb..00ced3d91e 100644 --- a/lib/diameter/doc/src/files.mk +++ b/lib/diameter/doc/src/files.mk @@ -2,7 +2,7 @@ # %CopyrightBegin% # -# Copyright Ericsson AB 2010-2011. All Rights Reserved. +# Copyright Ericsson AB 2010-2012. 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 @@ -26,6 +26,8 @@ XML_REF1_FILES = \ XML_REF3_FILES = \ diameter.xml \ diameter_app.xml \ + diameter_codec.xml \ + diameter_make.xml \ diameter_transport.xml \ diameter_tcp.xml \ diameter_sctp.xml diff --git a/lib/diameter/doc/src/notes.xml b/lib/diameter/doc/src/notes.xml index e2723f3e99..d241e2bd19 100644 --- a/lib/diameter/doc/src/notes.xml +++ b/lib/diameter/doc/src/notes.xml @@ -1,11 +1,17 @@ <?xml version="1.0" encoding="latin1" ?> -<!DOCTYPE chapter SYSTEM "chapter.dtd"> +<!DOCTYPE chapter SYSTEM "chapter.dtd" [ + <!ENTITY % also SYSTEM "seealso.ent" > + <!ENTITY % here SYSTEM "seehere.ent" > + %also; + %here; +]> <chapter> <header> <copyright> <year>2011</year> +<year>2012</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -36,6 +42,420 @@ first.</p> <!-- ===================================================================== --> +<section><title>Diameter 1.3.1</title> + + <section><title>Known Bugs and Problems</title> + <list> + <item> + <p> + Fix function clause resulting from use of an eval + callback.</p> + <p> + Own Id: OTP-10685</p> + </item> + </list> + </section> + +</section> + +<section><title>Diameter 1.3</title> + + <section><title>Fixed Bugs and Malfunctions</title> + <list> + <item> + <p> + Fix faulty handling of Origin-State-Id and faulty config + values.</p> + <p> + The former was expected in a list despite the + documentation requiring (correctly) an integer. A bare + value for a list-valued capability was not handled.</p> + <p> + Own Id: OTP-10440</p> + </item> + <item> + <p> + Fix timing of up/down events.</p> + <p> + Previously, a call to diameter:call/4 following a peer_up + callback might incorrectly return {error, no_connection}, + depending on timing. Both events now follow the + corresponding callbacks.</p> + <p> + Own Id: OTP-10459</p> + </item> + <item> + <p> + Make diameter:service_info/2 usable in peer_up, peer_down + and pick_peer callbacks.</p> + <p> + Except for in pick_peer when {call_mutates_state, false}, + it would previously hang indefinitely.</p> + <p> + Own Id: OTP-10460</p> + </item> + <item> + <p> + Verify that End-to-End and Hop-by-Hop Identifiers in an + incoming CEA/DPA match those sent in the corresponding + CER/DPR.</p> + <p> + The values were previously ignored. Answers whose + identifiers do not match are handled as unexpected.</p> + <p> + Own Id: OTP-10565</p> + </item> + <item> + <p> + Fix formatting problems in PDF documentation.</p> + <p> + In particular, text corresponding to links in HTML was + omitted in preformatted blocks. There are still issues + with indentation but this is not diameter-specific.</p> + <p> + Own Id: OTP-10583</p> + </item> + </list> + </section> + + + <section><title>Improvements and New Features</title> + <list> + <item> + <p> + Let prepare_request, prepare_retransmit and + handle_request callbacks return a function to be invoked + on outgoing messages after encode.</p> + <p> + This allows encoded messages to be logged for example.</p> + <p> + Own Id: OTP-10441</p> + </item> + <item> + <p> + Add service_opt() 'restrict_connections' to allow + multiple transport connections with the same peer.</p> + <p> + Own Id: OTP-10443</p> + </item> + <item> + <p> + Add service_opt() 'sequence' to allow the masking of a + constant onto the topmost bits of End-to-End and + Hop-by-Hop identifiers.</p> + <p> + This allows the same service on different nodes to use + distinct values in outgoing request messages.</p> + <p> + Own Id: OTP-10445</p> + </item> + <item> + <p> + Add diameter:service_info(PeerRef) to return the + transport_ref() and transport_opt() list of the + corresponding transport.</p> + <p> + This allows easy access to these from diameter_app + callbacks that only get peer_ref() as an argument.</p> + <p> + Own Id: OTP-10470</p> + </item> + <item> + <p> + Add reference pages diameter_codec(3) and + diameter_make(3).</p> + <p> + Own Id: OTP-10471</p> + </item> + <item> + <p> + Add events for service start and stop.</p> + <p> + Own Id: OTP-10492</p> + </item> + <item> + <p> + Add transport_opt() 'disconnect_cb' to make the sending + of DPR configurable.</p> + <p> + Whether or not DPR should be sent at application stop, + service stop or transport removal is determined by the + value returned by the callback, as is the + Disconnect-Cause and timeout if DPA is not received.</p> + <p> + Own Id: OTP-10493</p> + </item> + <item> + <p> + Add transport_opt() 'capx_timeout' for the timeout + associated with non-reception of CER/CEA.</p> + <p> + Own Id: OTP-10554</p> + </item> + <item> + <p> + Allow a handle_request callback to return a + #diameter_packet{}.</p> + <p> + This allows an answer to set transport_data and header + fields.</p> + <p> + Own Id: OTP-10566</p> + </item> + <item> + <p> + Update documentation for RFC 6733.</p> + <p> + RFC 3588 is now obsolete.</p> + <p> + Own Id: OTP-10568</p> + </item> + </list> + </section> + +</section> + +<section><title>Diameter 1.2</title> + + <section><title>Fixed Bugs and Malfunctions</title> + <list> + <item> + <p> + Fix broken Result-Code setting and Destination-Host/Realm + extraction.</p> + <p> + Result-Code was assumed to have arity 1 when setting this + value in an answer to a request containing AVP decode + errors. Destination-Host/Realm were only correctly + extracted from messages in the common application.</p> + <p> + Own Id: OTP-10202</p> + </item> + <item> + <p> + Handle insufficient capabilities configuration more + gracefully.</p> + <p> + A transport that does not have sufficient capabilities + configuration in order to encode CER/CEA will now emit an + error report noting the configuration error and exit + instead of failing. The error is not detected at + diameter:add_transport/2 since there is no requirement + that a service be configured before its transports.</p> + <p> + Own Id: OTP-10203</p> + </item> + <item> + <p> + Ensure a failing peer_up/down callback does not affect + transport connections to other peers.</p> + <p> + Such a failure would previously have taken down all of a + service's connections.</p> + <p> + Own Id: OTP-10215</p> + </item> + </list> + </section> + + + <section><title>Improvements and New Features</title> + <list> + <item> + <p> + Statistics related to Diameter messages can be retrieved + using diameter:service_info/2.</p> + <p> + Both Diameter and socket-level statistics are available, + for both incoming and outgoing messages.</p> + <p> + Own Id: OTP-9608</p> + </item> + <item> + <p> + Allow multiple transport_module/config to + diameter:add_transport/2.</p> + <p> + Multiple values are attempted in sequence until one + results in an established connection. This provides a way + for a connecting transport to specify configuration in + order of preference. (For example, SCTP before TCP.)</p> + <p> + Own Id: OTP-9885</p> + </item> + <item> + <p> + Add events for state transitions in the RFC 3539 watchdog + state machine.</p> + <p> + The watchdog state is also available through + diameter:service_info/2.</p> + <p> + Own Id: OTP-10212</p> + </item> + <item> + <p> + Add diameter:service_info(SvcName, connections).</p> + <p> + This provides an alternative to + diameter:service_info(SvcName, transport) that presents + information per established connection instead of per + transport reference.</p> + <p> + Own Id: OTP-10213</p> + </item> + <item> + <p> + Assorted documentation corrections/improvements.</p> + <p> + Own Id: OTP-10216</p> + </item> + </list> + </section> + +</section> + +<section><title>Diameter 1.1</title> + + <section><title>Fixed Bugs and Malfunctions</title> + <list> + <item> + <p> + Fix fault in sending of 'closed' events.</p> + <p> + The fault made it possible for the 'closed' event not to + be sent following a failed capabilities exchange.</p> + <p> + Own Id: OTP-9824</p> + </item> + <item> + <p> + Fix faulty diameterc -name/-prefix.</p> + <p> + A minor blunder when introducing the new dictionary + parser in diameter-1.0 broke these options.</p> + <p> + Own Id: OTP-9826</p> + </item> + </list> + </section> + +</section> + +<section><title>Diameter 1.0</title> + + <section><title>Fixed Bugs and Malfunctions</title> + <list> + <item> + <p> + Fix faulty cleanup after diameter:remove_transport/2.</p> + <p> + Removing a transport removed the configuration but did + not prevent the transport process from being restarted.</p> + <p> + Own Id: OTP-9756</p> + </item> + </list> + </section> + + + <section><title>Improvements and New Features</title> + <list> + <item> + <p> + Add support for TLS over TCP.</p> + <p> + RFC 3588 requires that a Diameter server support TLS. In + practice this seems to mean TLS over SCTP since there are + limitations with running over SCTP: see RFC 6083 (DTLS + over SCTP), which is a response to RFC 3436 (TLS over + SCTP). The current RFC 3588 draft acknowledges this by + equating TLS with TLS/TCP and DTLS/SCTP.</p> + <p> + TLS handshaking can take place either following a CER/CEA + that negotiates TLS using the Inband-Security-Id AVP (the + method documented in RFC 3588) or immediately following + connection establishment (the method added to the current + draft).</p> + <p> + Own Id: OTP-9605</p> + </item> + <item> + <p> + Improvements to the dictionary parser.</p> + <p> + The dictionary parser now emits useful error messages in + case of faults in the input file, also identifying the + line number at which the fault was detected. There are + semantic checks that were missing in the previous parser, + a fault in the interpretation of vendor id's in + combination with @inherits has been fixed and @end can be + used to terminate parsing explicitly instead of always + parsing to end of file.</p> + <p> + Own Id: OTP-9639</p> + </item> + <item> + <p> + Improve dictionary reusability.</p> + <p> + Reusing a dictionary just to get a different generated + module name or prefix previously required taking a copy + of the source, which may consist of several files if + inheritance is used, just to edit a couple of lines which + don't affect the semantics of the Diameter application + being defined. Options --name, --prefix and --inherits + have been added to diameterc to allow corresponding + values to be set at compile time.</p> + <p> + Own Id: OTP-9641</p> + </item> + <item> + <p> + Add capabilities_cb transport option.</p> + <p> + Its value is a function that's applied to the transport + reference and capabilities record after capabilities + exchange. If a callback returns anything but 'ok' then + the connection is closed. In the case of an incoming CER, + the callback can return a result code with which to + answer. Multiple callbacks can be specified and are + applied until either all return 'ok' or one doesn't.</p> + <p> + This provides a way to reject a peer connection.</p> + <p> + Own Id: OTP-9654</p> + </item> + <item> + <p> + Add @codecs to dictionary format.</p> + <p> + The semantics are similar to @custom_types but results in + codec functions of the form TypeName(encode|decode, + AvpName, Data) rather than AvpName(encode|decode, + TypeName, Data). That is, the role of the AVP name and + Diameter type name are reversed. This eliminates the need + for exporting one function for each AVP sharing a common + specialized encode/decode.</p> + <p> + Own Id: OTP-9708 Aux Id: OTP-9639 </p> + </item> + <item> + <p> + Add #diameter_callback{} for more flexible callback + configuration.</p> + <p> + The record allows individual functions to be configured + for each of the diameter_app(3) callbacks, as well as a + default callback.</p> + <p> + Own Id: OTP-9777</p> + </item> + </list> + </section> + +</section> + <section><title>Diameter 0.10</title> <section><title>Fixed Bugs and Malfunctions</title> @@ -181,8 +601,7 @@ Known issues or limitations:</p> Some agent-related functionality is not entirely complete. In particular, support for proxy agents, that advertise specific Diameter applications but otherwise relay messages in much the same -way as relay agents (for which a <seealso -marker="diameter_app#handle_request">handle_request/3</seealso> +way as relay agents (for which a handle_request callback can return a <c>relay</c> tuple), will be completed in an upcoming release. There may also be more explicit support for redirect agents, although @@ -214,8 +633,7 @@ could likely be expanded upon.</p> <item> <p> -The function <seealso -marker="diameter#service_info">diameter:service_info/2</seealso> +The function diameter:service_info/2 can be used to retrieve information about a started service (statistics, information about connected peers, etc) but this is not yet documented and both the input and output may change diff --git a/lib/diameter/doc/src/ref_man.xml b/lib/diameter/doc/src/ref_man.xml index 137ce79094..4b99fe716d 100644 --- a/lib/diameter/doc/src/ref_man.xml +++ b/lib/diameter/doc/src/ref_man.xml @@ -6,6 +6,7 @@ <header> <copyright> <year>2011</year> +<year>2012</year> <holder>Ericsson AB. All Rights Reserved.</holder> </copyright> <legalnotice> @@ -40,7 +41,9 @@ applications on top of the Diameter protocol. </p> <xi:include href="diameter.xml"/> <xi:include href="diameter_compile.xml"/> <xi:include href="diameter_app.xml"/> +<xi:include href="diameter_codec.xml"/> <xi:include href="diameter_dict.xml"/> +<xi:include href="diameter_make.xml"/> <xi:include href="diameter_transport.xml"/> <xi:include href="diameter_tcp.xml"/> <xi:include href="diameter_sctp.xml"/> diff --git a/lib/diameter/doc/src/seealso.ent b/lib/diameter/doc/src/seealso.ent new file mode 100644 index 0000000000..4647c42f85 --- /dev/null +++ b/lib/diameter/doc/src/seealso.ent @@ -0,0 +1,132 @@ +<?xml version="1.0" encoding="iso-8859-1" ?> + +<!-- + +%CopyrightBegin% + +Copyright Ericsson AB 2012. 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% + +--> + +<!-- + +Entities for cross references: less to type, easier to read and +less error prone. + +Additional intra-document entities are generated by seehere.sed. +That each definition is on a single (hideously long) line is +significant. + +--> + +<!ENTITY the_rfc 'RFC 6733'> + +<!-- diameter --> + +<!ENTITY mod_add_transport '<seealso marker="diameter#add_transport-2">diameter:add_transport/2</seealso>'> +<!ENTITY mod_call '<seealso marker="diameter#call-4">diameter:call/4</seealso>'> +<!ENTITY mod_origin_state_id '<seealso marker="diameter#origin_state_id-0">diameter:origin_state_id/0</seealso>'> +<!ENTITY mod_remove_transport '<seealso marker="diameter#remove_transport-2">diameter:remove_transport/2</seealso>'> +<!ENTITY mod_service_info '<seealso marker="diameter#service_info-2">diameter:service_info/2</seealso>'> +<!ENTITY mod_services '<seealso marker="diameter#services-0">diameter:services/0</seealso>'> +<!ENTITY mod_start_service '<seealso marker="diameter#start_service-2">diameter:start_service/2</seealso>'> +<!ENTITY mod_stop_service '<seealso marker="diameter#stop_service-1">diameter:stop_service/1</seealso>'> +<!ENTITY mod_subscribe '<seealso marker="diameter#subscribe-1">diameter:subscribe/1</seealso>'> + +<!ENTITY mod_application_alias '<seealso marker="diameter#application_alias">diameter:application_alias()</seealso>'> +<!ENTITY mod_application_module '<seealso marker="diameter#application_module">diameter:application_module()</seealso>'> +<!ENTITY mod_application_opt '<seealso marker="diameter#application_opt">diameter:application_opt()</seealso>'> +<!ENTITY mod_call_opt '<seealso marker="diameter#call_opt">diameter:call_opt()</seealso>'> +<!ENTITY mod_capability '<seealso marker="diameter#capability">diameter:capability()</seealso>'> +<!ENTITY mod_evaluable '<seealso marker="diameter#evaluable">diameter:evaluable()</seealso>'> +<!ENTITY mod_peer_filter '<seealso marker="diameter#peer_filter">diameter:peer_filter()</seealso>'> +<!ENTITY mod_service_event '<seealso marker="diameter#service_event">diameter:service_event()</seealso>'> +<!ENTITY mod_service_name '<seealso marker="diameter#service_name">diameter:service_name()</seealso>'> +<!ENTITY mod_service_opt '<seealso marker="diameter#service_opt">diameter:service_opt()</seealso>'> +<!ENTITY mod_transport_opt '<seealso marker="diameter#transport_opt">diameter:transport_opt()</seealso>'> +<!ENTITY mod_transport_ref '<seealso marker="diameter#transport_ref">diameter:transport_ref()</seealso>'> + +<!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 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 watchdog_timer '<seealso marker="#watchdog_timer">watchdog_timer</seealso>'> + +<!-- diameter_app --> + +<!ENTITY app_handle_answer '<seealso marker="diameter_app#Mod:handle_answer-4">handle_answer/4</seealso>'> +<!ENTITY app_handle_request '<seealso marker="diameter_app#Mod:handle_request-3">handle_request/3</seealso>'> +<!ENTITY app_handle_error '<seealso marker="diameter_app#Mod:handle_error-4">handle_error/4</seealso>'> +<!ENTITY app_peer_down '<seealso marker="diameter_app#Mod:peer_down-3">peer_up/3</seealso>'> +<!ENTITY app_peer_up '<seealso marker="diameter_app#Mod:peer_up-3">peer_up/3</seealso>'> +<!ENTITY app_pick_peer '<seealso marker="diameter_app#Mod:pick_peer-4">pick_peer/4</seealso>'> +<!ENTITY app_prepare_retransmit '<seealso marker="diameter_app#Mod:prepare_retransmit-3">prepare_retransmit/3</seealso>'> +<!ENTITY app_prepare_request '<seealso marker="diameter_app#Mod:prepare_request-3">prepare_request/3</seealso>'> + +<!ENTITY app_capabilities '<seealso marker="diameter_app#capabilities">diameter_app:capabilities()</seealso>'> +<!ENTITY app_peer '<seealso marker="diameter_app#peer">diameter_app:peer()</seealso>'> +<!ENTITY app_peer_ref '<seealso marker="diameter_app#peer_ref">diameter_app:peer_ref()</seealso>'> +<!ENTITY app_state '<seealso marker="diameter_app#state">diameter_app:state()</seealso>'> + +<!-- diameter_codec --> + +<!ENTITY codec_encode '<seealso marker="diameter_codec#encode-2">diameter_codec:encode/2</seealso>'> +<!ENTITY codec_decode '<seealso marker="diameter_codec#decode-2">diameter_codec:decode/2</seealso>'> + +<!ENTITY codec_avp '<seealso marker="diameter_codec#avp">diameter_codec:avp()</seealso>'> +<!ENTITY codec_header '<seealso marker="diameter_codec#header">diameter_codec:header()</seealso>'> +<!ENTITY codec_dictionary '<seealso marker="diameter_codec#dictionary">diameter_codec:dictionary()</seealso>'> +<!ENTITY codec_message '<seealso marker="diameter_codec#message">diameter_codec:message()</seealso>'> +<!ENTITY codec_packet '<seealso marker="diameter_codec#packet">diameter_codec:packet()</seealso>'> + +<!-- diameter_dict --> + +<!ENTITY dict_data_types '<seealso marker="diameter_dict#DATA_TYPES">diameter_dict(4)</seealso>'> + +<!ENTITY dict_Address '<seealso marker="diameter_dict#DATA_TYPES">Address()</seealso>'> +<!ENTITY dict_DiameterIdentity '<seealso marker="diameter_dict#DATA_TYPES">DiameterIdentity()</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>'> +<!ENTITY dict_UTF8String '<seealso marker="diameter_dict#DATA_TYPES">UTF8String()</seealso>'> +<!ENTITY dict_Unsigned32 '<seealso marker="diameter_dict#DATA_TYPES">Unsigned32()</seealso>'> + +<!ENTITY dict_name '<seealso marker="diameter_dict#name">@name</seealso>'> +<!ENTITY dict_prefix '<seealso marker="diameter_dict#prefix">@prefix</seealso>'> +<!ENTITY dict_inherits '<seealso marker="diameter_dict#inherits">@inherits</seealso>'> + +<!-- diameter_make --> + +<!ENTITY make_codec '<seealso marker="diameter_make#codec-2">diameter_make:codec/2</seealso>'> + +<!-- diameter_transport --> + +<!ENTITY transport_start + '<seealso marker="diameter_transport#Mod:start-3">start/3</seealso>'> + +<!-- reference pages --> + +<!ENTITY man_compile '<seealso marker="diameterc">diameterc(1)</seealso>'> +<!ENTITY man_main '<seealso marker="diameter">diameter(3)</seealso>'> +<!ENTITY man_app '<seealso marker="diameter_app">diameter_app(3)</seealso>'> +<!ENTITY man_codec '<seealso marker="diameter_codec">diameter_codec(3)</seealso>'> +<!ENTITY man_dict '<seealso marker="diameter_dict">diameter_dict(4)</seealso>'> +<!ENTITY man_make '<seealso marker="diameter_make">diameter_make(3)</seealso>'> +<!ENTITY man_transport '<seealso marker="diameter_transport">diameter_transport(3)</seealso>'> +<!ENTITY man_sctp '<seealso marker="diameter_sctp">diameter_sctp(3)</seealso>'> +<!ENTITY man_tcp '<seealso marker="diameter_tcp">diameter_tcp(3)</seealso>'> diff --git a/lib/diameter/src/subdirs.mk b/lib/diameter/doc/src/seehere.sed index 3e12d935bc..c62a783d40 100644 --- a/lib/diameter/src/subdirs.mk +++ b/lib/diameter/doc/src/seehere.sed @@ -1,8 +1,7 @@ -#-*-makefile-*- ; force emacs to enter makefile-mode - +# # %CopyrightBegin% # -# Copyright Ericsson AB 2010-2011. All Rights Reserved. +# Copyright Ericsson AB 2012. 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,5 +16,20 @@ # # %CopyrightEnd% -SUB_DIRS = compiler app transport -SUB_DIRECTORIES = $(SUB_DIRS)
\ No newline at end of file +# +# Map entities for inter-document references to ones for +# intra-document references like this: +# +# <!ENTITY aaa_xxx '<seealso marker="bbb#yyy">ccc:zzz</seealso>'> +# +# ===> +# +# <!ENTITY xxx '<seealso marker="#yyy">zzz</seealso>'> +# + +/<!ENTITY/!d +/#/!d +/"#/d +s@ [^_]*_@ @ +s@"[^#]*#@"#@ +s@>[^:]*:@>@ diff --git a/lib/diameter/doc/standard/draft-ietf-dime-capablities-update-07.txt b/lib/diameter/doc/standard/draft-ietf-dime-capablities-update-07.txt deleted file mode 100644 index bb7ec2d08c..0000000000 --- a/lib/diameter/doc/standard/draft-ietf-dime-capablities-update-07.txt +++ /dev/null @@ -1,392 +0,0 @@ -
-
-
-Network Working Group K. Jiao
-Internet-Draft Huawei
-Intended status: Standards Track G. Zorn
-Expires: April 27, 2011 Network Zen
- October 24, 2010
-
-
- The Diameter Capabilities Update Application
- draft-ietf-dime-capablities-update-07
-
-Abstract
-
- This document defines a new Diameter application and associated
- command codes. The Capabilities Update application is intended to
- allow the dynamic update of certain Diameter peer capabilities while
- the peer-to-peer connection is in the open state.
-
-Status of this Memo
-
- This Internet-Draft is submitted in full conformance with the
- provisions of BCP 78 and BCP 79.
-
- Internet-Drafts are working documents of the Internet Engineering
- Task Force (IETF). Note that other groups may also distribute
- working documents as Internet-Drafts. The list of current Internet-
- Drafts is at http://datatracker.ietf.org/drafts/current/.
-
- Internet-Drafts are draft documents valid for a maximum of six months
- and may be updated, replaced, or obsoleted by other documents at any
- time. It is inappropriate to use Internet-Drafts as reference
- material or to cite them other than as "work in progress."
-
- This Internet-Draft will expire on April 27, 2011.
-
-Copyright Notice
-
- Copyright (c) 2010 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.
-
-
-
-Jiao & Zorn Expires April 27, 2011 [Page 1]
-
-Internet-Draft Diameter Capabilities Update October 2010
-
-
-Table of Contents
-
- 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . 3
- 2. Specification of Requirements . . . . . . . . . . . . . . . . . 3
- 3. Diameter Protocol Considerations . . . . . . . . . . . . . . . 3
- 4. Capabilities Update . . . . . . . . . . . . . . . . . . . . . . 3
- 4.1. Command-Code Values . . . . . . . . . . . . . . . . . . . . 4
- 4.1.1. Capabilities-Update-Request . . . . . . . . . . . . . . 5
- 4.1.2. Capabilities-Update-Answer . . . . . . . . . . . . . . 5
- 5. Security Considerations . . . . . . . . . . . . . . . . . . . . 6
- 6. IANA Considerations . . . . . . . . . . . . . . . . . . . . . . 6
- 6.1. Application Identifier . . . . . . . . . . . . . . . . . . 6
- 6.2. Command Codes . . . . . . . . . . . . . . . . . . . . . . . 6
- 7. Contributors . . . . . . . . . . . . . . . . . . . . . . . . . 6
- 8. Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . 6
- 9. References . . . . . . . . . . . . . . . . . . . . . . . . . . 6
- 9.1. Normative References . . . . . . . . . . . . . . . . . . . 6
- 9.2. Informative References . . . . . . . . . . . . . . . . . . 7
- Authors' Addresses . . . . . . . . . . . . . . . . . . . . . . . . 7
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Jiao & Zorn Expires April 27, 2011 [Page 2]
-
-Internet-Draft Diameter Capabilities Update October 2010
-
-
-1. Introduction
-
- Capabilities exchange is an important component of the Diameter Base
- Protocol [I-D.ietf-dime-rfc3588bis], allowing peers to exchange
- identities and Diameter capabilities (protocol version number,
- supported Diameter applications, security mechanisms, etc.). As
- defined in RFC 3588, however, the capabilities exchange process takes
- place only once, at the inception of a transport connection between a
- given pair of peers. Therefore, if a peer's capabilities change (due
- to software update, for example), the existing connection(s) must be
- torn down (along with all of the associated user sessions) and
- restarted before the modified capabilities can be advertised.
-
- This document defines a new Diameter application intended to allow
- the dynamic update of a subset of Diameter peer capabilities over an
- existing connection. Because the Capabilities Update application
- specified herein operates over an existing transport connection,
- modification of certain capabilities is prohibited. Specifically,
- modifying the security mechanism in use is not allowed; if the
- security method used between a pair of peers is changed the affected
- connection MUST be restarted.
-
-
-2. Specification of Requirements
-
- 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 RFC 2119 [RFC2119].
-
-
-3. Diameter Protocol Considerations
-
- This section details the relationship of the Diameter Capabilities
- Update application to the Diameter Base Protocol.
-
- This document specifies Diameter Application-ID <TBD1>. Diameter
- nodes conforming to this specification MUST advertise support by
- including the value <TBD1> in the Auth-Application-Id of the
- Capabilities-Exchange-Request (CER) and Capabilities-Exchange-Answer
- (CEA) commands [I-D.ietf-dime-rfc3588bis].
-
-
-4. Capabilities Update
-
- When the capabilities of a Diameter node conforming to this
- specification change, it MUST notify all of the nodes with which it
- has an open transport connection and which have also advertised
- support for the Capabilities Update application using the
-
-
-
-Jiao & Zorn Expires April 27, 2011 [Page 3]
-
-Internet-Draft Diameter Capabilities Update October 2010
-
-
- Capabilities-Update-Request (CUR) message (Section 4.1.1). This
- message allows the update of a peer's capabilities (supported
- Diameter applications, etc.).
-
- A Diameter node only issues a given command to those peers that have
- advertised support for the Diameter application that defines the
- command; a Diameter node must cache the supported applications in
- order to ensure that unrecognized commands and/or Attribute-Value
- Pairs (AVPs) are not unnecessarily sent to a peer.
-
- The receiver of the CUR MUST determine common applications by
- computing the intersection of its own set of supported Application Id
- against all of the application identifier AVPs (Auth-Application-Id,
- Acct-Application-Id and Vendor-Specific- Application-Id) present in
- the CUR. The value of the Vendor-Id AVP in the Vendor-Specific-
- Application-Id MUST NOT be used during computation.
-
- If the receiver of a CUR does not have any applications in common
- with the sender then it MUST return a Capabilities-Update-Answer
- (CUA) (Section 4.1.2) with the Result-Code AVP set to
- DIAMETER_NO_COMMON_APPLICATION [I-D.ietf-dime-rfc3588bis], and SHOULD
- disconnect the transport layer connection; however, if active
- sessions are using the connection, peers MAY delay disconnection
- until the sessions can be redirected or gracefully terminated. Note
- that receiving a CUA from a peer advertising itself as a Relay (see
- [I-D.ietf-dime-rfc3588bis], Section 2.4) MUST be interpreted as
- having common applications with the peer.
-
- As for CER/CEA messages, the CUR and CUA messages MUST NOT be
- proxied, redirected or relayed.
-
- Even though the CUR/CUA messages cannot be proxied, it is still
- possible for an upstream agent to receive a message for which there
- are no peers available to handle the application that corresponds to
- the Command-Code. This could happen if, for example, the peers are
- too busy or down. In such instances, the 'E' bit MUST be set in the
- answer message with the Result-Code AVP set to
- DIAMETER_UNABLE_TO_DELIVER to inform the downstream peer to take
- action (e.g., re-routing requests to an alternate peer).
-
-4.1. Command-Code Values
-
- This section defines Command-Code [I-D.ietf-dime-rfc3588bis] values
- that MUST be supported by all Diameter implementations conforming to
- this specification. The following Command Codes are defined (using
- modified ABNF [I-D.ietf-dime-rfc3588bis]) in this document:
- Capabilities-Update-Request (CUR, Section 4.1.1) and Capabilities-
- Update-Answer (CUA, Section 4.1.2).
-
-
-
-Jiao & Zorn Expires April 27, 2011 [Page 4]
-
-Internet-Draft Diameter Capabilities Update October 2010
-
-
-4.1.1. Capabilities-Update-Request
-
- The Capabilities-Update-Request (CUR), indicated by the Command-Code
- set to <CUCC> and the Command Flags' 'R' bit set, is sent to update
- local capabilities. Upon detection of a transport failure, this
- message MUST NOT be sent to an alternate peer.
-
- When Diameter is run over the Stream Control Transmission Protocol
- [RFC4960], which allows connections to span multiple interfaces and
- multiple IP addresses, the Capabilities-Update-Request message MUST
- contain one Host-IP-Address AVP for each potential IP address that
- may be locally used when transmitting Diameter messages.
-
- Message Format
-
- <CUR> ::= < Diameter Header: <CUCC>, REQ >
- { Origin-Host }
- { Origin-Realm }
- 1* { Host-IP-Address }
- { Vendor-Id }
- { Product-Name }
- [ Origin-State-Id ]
- * [ Supported-Vendor-Id ]
- * [ Auth-Application-Id ]
- * [ Acct-Application-Id ]
- * [ Vendor-Specific-Application-Id ]
- [ Firmware-Revision ]
- * [ AVP ]
-
-4.1.2. Capabilities-Update-Answer
-
- The Capabilities-Update-Answer, indicated by the Command-Code set to
- <CUCC> and the Command Flags' 'R' bit cleared, is sent in response to
- a CUR message.
-
- Message Format
-
- <CUA> ::= < Diameter Header: <CUCC> >
- { Origin-Host }
- { Origin-Realm }
- { Result-Code }
- [ Error-Message ]
- * [ AVP ]
-
-
-
-
-
-
-
-
-Jiao & Zorn Expires April 27, 2011 [Page 5]
-
-Internet-Draft Diameter Capabilities Update October 2010
-
-
-5. Security Considerations
-
- The security considerations applicable to the Diameter Base Protocol
- [I-D.ietf-dime-rfc3588bis] are also applicable to this document.
-
-
-6. IANA Considerations
-
- This section explains the criteria to be used by the IANA for
- assignment of numbers within namespaces used within this document.
-
-6.1. Application Identifier
-
- This specification assigns the value <TBD1> from the Application
- Identifiers namespace [I-D.ietf-dime-rfc3588bis]. See Section 3 for
- the assignment of the namespace in this specification.
-
-6.2. Command Codes
-
- This specification assigns the value <CUCC> from the Command Codes
- namespace [I-D.ietf-dime-rfc3588bis]. See Section 4.1 for the
- assignment of the namespace in this specification.
-
-
-7. Contributors
-
- This document is based upon work done by Tina Tsou.
-
-
-8. Acknowledgements
-
- Thanks to Sebastien Decugis, Niklas Neumann, Subash Comerica, Lionel
- Morand, Dan Romascanu, Dan Harkins and Ravi for helpful review and
- discussion.
-
-
-9. References
-
-9.1. Normative References
-
- [I-D.ietf-dime-rfc3588bis]
- Fajardo, V., Arkko, J., Loughney, J., and G. Zorn,
- "Diameter Base Protocol", draft-ietf-dime-rfc3588bis-25
- (work in progress), September 2010.
-
- [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate
- Requirement Levels", BCP 14, RFC 2119, March 1997.
-
-
-
-
-Jiao & Zorn Expires April 27, 2011 [Page 6]
-
-Internet-Draft Diameter Capabilities Update October 2010
-
-
-9.2. Informative References
-
- [RFC4960] Stewart, R., "Stream Control Transmission Protocol",
- RFC 4960, September 2007.
-
-
-Authors' Addresses
-
- Jiao Kang
- Huawei Technologies
- Section B1, Huawei Industrial Base
- Bantian, Longgang District
- Shenzhen 518129
- P.R. China
-
- Phone: +86 755 2878-6690
- Email: [email protected]
-
-
- Glen Zorn
- Network Zen
- 227/358 Thanon Sanphawut
- Bang Na, Bangkok 10260
- Thailand
-
- Phone: +66 (0) 87-040-4617
- Email: [email protected]
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Jiao & Zorn Expires April 27, 2011 [Page 7]
-
diff --git a/lib/diameter/doc/standard/draft-ietf-dime-rfc3588bis-26.txt b/lib/diameter/doc/standard/rfc6733.txt index 87b9562f93..2f5a477347 100644 --- a/lib/diameter/doc/standard/draft-ietf-dime-rfc3588bis-26.txt +++ b/lib/diameter/doc/standard/rfc6733.txt @@ -1,62 +1,72 @@ -DIME V. Fajardo, Ed. -Internet-Draft Telcordia Technologies -Obsoletes: 3588 (if approved) J. Arkko -Intended status: Standards Track Ericsson Research -Expires: July 24, 2011 J. Loughney + + + +Internet Engineering Task Force (IETF) V. Fajardo, Ed. +Request for Comments: 6733 Telcordia Technologies +Obsoletes: 3588, 5719 J. Arkko +Category: Standards Track Ericsson Research +ISSN: 2070-1721 J. Loughney Nokia Research Center - G. Zorn + G. Zorn, Ed. Network Zen - January 20, 2011 + October 2012 Diameter Base Protocol - draft-ietf-dime-rfc3588bis-26.txt Abstract The Diameter base protocol is intended to provide an Authentication, - Authorization and Accounting (AAA) framework for applications such as - network access or IP mobility in both local and roaming situations. - This document specifies the message format, transport, error - reporting, accounting and security services used by all Diameter - applications. The Diameter base protocol as defined in this document - must be supported by all Diameter implementations. + Authorization, and Accounting (AAA) framework for applications such + as network access or IP mobility in both local and roaming + situations. This document specifies the message format, transport, + error reporting, accounting, and security services used by all + Diameter applications. The Diameter base protocol as defined in this + document obsoletes RFC 3588 and RFC 5719, and it must be supported by + all new Diameter implementations. -Status of this Memo +Status of This Memo - This Internet-Draft is submitted in full conformance with the - provisions of BCP 78 and BCP 79. + This is an Internet Standards Track document. - Internet-Drafts are working documents of the Internet Engineering - Task Force (IETF). Note that other groups may also distribute - working documents as Internet-Drafts. The list of current Internet- - Drafts is at http://datatracker.ietf.org/drafts/current/. + 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/rfc6733. - Internet-Drafts are draft documents valid for a maximum of six months - and may be updated, replaced, or obsoleted by other documents at any - time. It is inappropriate to use Internet-Drafts as reference - material or to cite them other than as "work in progress." - This Internet-Draft will expire on July 24, 2011. -Copyright Notice - Copyright (c) 2011 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 -Fajardo, et al. Expires July 24, 2011 [Page 1] + + + + + + +Fajardo, et al. Standards Track [Page 1] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 +Copyright Notice + + Copyright (c) 2012 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 @@ -65,256 +75,303 @@ Internet-Draft Diameter Base Protocol January 2011 the Trust Legal Provisions and are provided without warranty as described in the Simplified BSD License. + This document may contain material from IETF Documents or IETF + Contributions published or made publicly available before November + 10, 2008. The person(s) controlling the copyright in some of this + material may not have granted the IETF Trust the right to allow + modifications of such material outside the IETF Standards Process. + Without obtaining an adequate license from the person(s) controlling + the copyright in such materials, this document may not be modified + outside the IETF Standards Process, and derivative works of it may + not be created outside the IETF Standards Process, except to format + it for publication as an RFC or to translate it into languages other + than English. Table of Contents - 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . 6 - 1.1. Diameter Protocol . . . . . . . . . . . . . . . . . . . . 8 - 1.1.1. Description of the Document Set . . . . . . . . . . . 9 - 1.1.2. Conventions Used in This Document . . . . . . . . . . 10 - 1.1.3. Changes from RFC3588 . . . . . . . . . . . . . . . . 10 - 1.2. Terminology . . . . . . . . . . . . . . . . . . . . . . . 12 - 1.3. Approach to Extensibility . . . . . . . . . . . . . . . . 17 - 1.3.1. Defining New AVP Values . . . . . . . . . . . . . . . 18 - 1.3.2. Creating New AVPs . . . . . . . . . . . . . . . . . . 18 - 1.3.3. Creating New Commands . . . . . . . . . . . . . . . . 18 - 1.3.4. Creating New Diameter Applications . . . . . . . . . 19 - 2. Protocol Overview . . . . . . . . . . . . . . . . . . . . . . 21 - 2.1. Transport . . . . . . . . . . . . . . . . . . . . . . . . 22 - 2.1.1. SCTP Guidelines . . . . . . . . . . . . . . . . . . . 23 - 2.2. Securing Diameter Messages . . . . . . . . . . . . . . . 24 - 2.3. Diameter Application Compliance . . . . . . . . . . . . . 24 - 2.4. Application Identifiers . . . . . . . . . . . . . . . . . 24 - 2.5. Connections vs. Sessions . . . . . . . . . . . . . . . . 25 - 2.6. Peer Table . . . . . . . . . . . . . . . . . . . . . . . 26 - 2.7. Routing Table . . . . . . . . . . . . . . . . . . . . . . 27 - 2.8. Role of Diameter Agents . . . . . . . . . . . . . . . . . 28 - 2.8.1. Relay Agents . . . . . . . . . . . . . . . . . . . . 29 - 2.8.2. Proxy Agents . . . . . . . . . . . . . . . . . . . . 30 - 2.8.3. Redirect Agents . . . . . . . . . . . . . . . . . . . 31 - 2.8.4. Translation Agents . . . . . . . . . . . . . . . . . 32 - 2.9. Diameter Path Authorization . . . . . . . . . . . . . . . 33 - 3. Diameter Header . . . . . . . . . . . . . . . . . . . . . . . 35 - 3.1. Command Codes . . . . . . . . . . . . . . . . . . . . . . 38 - 3.2. Command Code ABNF specification . . . . . . . . . . . . . 38 - 3.3. Diameter Command Naming Conventions . . . . . . . . . . . 41 - 4. Diameter AVPs . . . . . . . . . . . . . . . . . . . . . . . . 42 - 4.1. AVP Header . . . . . . . . . . . . . . . . . . . . . . . 42 - 4.1.1. Optional Header Elements . . . . . . . . . . . . . . 43 - 4.2. Basic AVP Data Formats . . . . . . . . . . . . . . . . . 44 - 4.3. Derived AVP Data Formats . . . . . . . . . . . . . . . . 45 - 4.3.1. Common Derived AVPs . . . . . . . . . . . . . . . . . 45 - 4.4. Grouped AVP Values . . . . . . . . . . . . . . . . . . . 52 - - - -Fajardo, et al. Expires July 24, 2011 [Page 2] - -Internet-Draft Diameter Base Protocol January 2011 - - - 4.4.1. Example AVP with a Grouped Data type . . . . . . . . 53 - 4.5. Diameter Base Protocol AVPs . . . . . . . . . . . . . . . 56 - 5. Diameter Peers . . . . . . . . . . . . . . . . . . . . . . . 59 - 5.1. Peer Connections . . . . . . . . . . . . . . . . . . . . 59 - 5.2. Diameter Peer Discovery . . . . . . . . . . . . . . . . . 60 - 5.3. Capabilities Exchange . . . . . . . . . . . . . . . . . . 61 - 5.3.1. Capabilities-Exchange-Request . . . . . . . . . . . . 63 - 5.3.2. Capabilities-Exchange-Answer . . . . . . . . . . . . 63 - 5.3.3. Vendor-Id AVP . . . . . . . . . . . . . . . . . . . . 64 - 5.3.4. Firmware-Revision AVP . . . . . . . . . . . . . . . . 64 - 5.3.5. Host-IP-Address AVP . . . . . . . . . . . . . . . . . 64 - 5.3.6. Supported-Vendor-Id AVP . . . . . . . . . . . . . . . 65 - 5.3.7. Product-Name AVP . . . . . . . . . . . . . . . . . . 65 - 5.4. Disconnecting Peer connections . . . . . . . . . . . . . 65 - 5.4.1. Disconnect-Peer-Request . . . . . . . . . . . . . . . 66 - 5.4.2. Disconnect-Peer-Answer . . . . . . . . . . . . . . . 66 - 5.4.3. Disconnect-Cause AVP . . . . . . . . . . . . . . . . 66 - 5.5. Transport Failure Detection . . . . . . . . . . . . . . . 67 - 5.5.1. Device-Watchdog-Request . . . . . . . . . . . . . . . 67 - 5.5.2. Device-Watchdog-Answer . . . . . . . . . . . . . . . 67 - 5.5.3. Transport Failure Algorithm . . . . . . . . . . . . . 68 - 5.5.4. Failover and Failback Procedures . . . . . . . . . . 68 - 5.6. Peer State Machine . . . . . . . . . . . . . . . . . . . 69 - 5.6.1. Incoming connections . . . . . . . . . . . . . . . . 71 - 5.6.2. Events . . . . . . . . . . . . . . . . . . . . . . . 72 - 5.6.3. Actions . . . . . . . . . . . . . . . . . . . . . . . 73 - 5.6.4. The Election Process . . . . . . . . . . . . . . . . 75 - 6. Diameter message processing . . . . . . . . . . . . . . . . . 76 - 6.1. Diameter Request Routing Overview . . . . . . . . . . . . 76 - 6.1.1. Originating a Request . . . . . . . . . . . . . . . . 77 - 6.1.2. Sending a Request . . . . . . . . . . . . . . . . . . 77 - 6.1.3. Receiving Requests . . . . . . . . . . . . . . . . . 78 - 6.1.4. Processing Local Requests . . . . . . . . . . . . . . 78 - 6.1.5. Request Forwarding . . . . . . . . . . . . . . . . . 78 - 6.1.6. Request Routing . . . . . . . . . . . . . . . . . . . 78 - 6.1.7. Predictive Loop Avoidance . . . . . . . . . . . . . . 79 - 6.1.8. Redirecting Requests . . . . . . . . . . . . . . . . 79 - 6.1.9. Relaying and Proxying Requests . . . . . . . . . . . 80 - 6.2. Diameter Answer Processing . . . . . . . . . . . . . . . 82 - 6.2.1. Processing received Answers . . . . . . . . . . . . . 82 - 6.2.2. Relaying and Proxying Answers . . . . . . . . . . . . 82 - 6.3. Origin-Host AVP . . . . . . . . . . . . . . . . . . . . . 83 - 6.4. Origin-Realm AVP . . . . . . . . . . . . . . . . . . . . 83 - 6.5. Destination-Host AVP . . . . . . . . . . . . . . . . . . 83 - 6.6. Destination-Realm AVP . . . . . . . . . . . . . . . . . . 84 - 6.7. Routing AVPs . . . . . . . . . . . . . . . . . . . . . . 84 - 6.7.1. Route-Record AVP . . . . . . . . . . . . . . . . . . 84 - 6.7.2. Proxy-Info AVP . . . . . . . . . . . . . . . . . . . 84 - - - -Fajardo, et al. Expires July 24, 2011 [Page 3] - -Internet-Draft Diameter Base Protocol January 2011 - - - 6.7.3. Proxy-Host AVP . . . . . . . . . . . . . . . . . . . 85 - 6.7.4. Proxy-State AVP . . . . . . . . . . . . . . . . . . . 85 - 6.8. Auth-Application-Id AVP . . . . . . . . . . . . . . . . . 85 - 6.9. Acct-Application-Id AVP . . . . . . . . . . . . . . . . . 85 - 6.10. Inband-Security-Id AVP . . . . . . . . . . . . . . . . . 85 - 6.11. Vendor-Specific-Application-Id AVP . . . . . . . . . . . 86 - 6.12. Redirect-Host AVP . . . . . . . . . . . . . . . . . . . . 87 - 6.13. Redirect-Host-Usage AVP . . . . . . . . . . . . . . . . . 87 - 6.14. Redirect-Max-Cache-Time AVP . . . . . . . . . . . . . . . 88 - 7. Error Handling . . . . . . . . . . . . . . . . . . . . . . . 90 - 7.1. Result-Code AVP . . . . . . . . . . . . . . . . . . . . . 92 - 7.1.1. Informational . . . . . . . . . . . . . . . . . . . . 92 - 7.1.2. Success . . . . . . . . . . . . . . . . . . . . . . . 93 - 7.1.3. Protocol Errors . . . . . . . . . . . . . . . . . . . 93 - 7.1.4. Transient Failures . . . . . . . . . . . . . . . . . 94 - 7.1.5. Permanent Failures . . . . . . . . . . . . . . . . . 95 - 7.2. Error Bit . . . . . . . . . . . . . . . . . . . . . . . . 98 - 7.3. Error-Message AVP . . . . . . . . . . . . . . . . . . . . 99 - 7.4. Error-Reporting-Host AVP . . . . . . . . . . . . . . . . 99 - 7.5. Failed-AVP AVP . . . . . . . . . . . . . . . . . . . . . 99 - 7.6. Experimental-Result AVP . . . . . . . . . . . . . . . . . 100 - 7.7. Experimental-Result-Code AVP . . . . . . . . . . . . . . 100 - 8. Diameter User Sessions . . . . . . . . . . . . . . . . . . . 101 - 8.1. Authorization Session State Machine . . . . . . . . . . . 102 - 8.2. Accounting Session State Machine . . . . . . . . . . . . 107 - 8.3. Server-Initiated Re-Auth . . . . . . . . . . . . . . . . 112 - 8.3.1. Re-Auth-Request . . . . . . . . . . . . . . . . . . . 112 - 8.3.2. Re-Auth-Answer . . . . . . . . . . . . . . . . . . . 113 - 8.4. Session Termination . . . . . . . . . . . . . . . . . . . 114 - 8.4.1. Session-Termination-Request . . . . . . . . . . . . . 115 - 8.4.2. Session-Termination-Answer . . . . . . . . . . . . . 115 - 8.5. Aborting a Session . . . . . . . . . . . . . . . . . . . 116 - 8.5.1. Abort-Session-Request . . . . . . . . . . . . . . . . 116 - 8.5.2. Abort-Session-Answer . . . . . . . . . . . . . . . . 117 - 8.6. Inferring Session Termination from Origin-State-Id . . . 118 - 8.7. Auth-Request-Type AVP . . . . . . . . . . . . . . . . . . 118 - 8.8. Session-Id AVP . . . . . . . . . . . . . . . . . . . . . 119 - 8.9. Authorization-Lifetime AVP . . . . . . . . . . . . . . . 120 - 8.10. Auth-Grace-Period AVP . . . . . . . . . . . . . . . . . . 121 - 8.11. Auth-Session-State AVP . . . . . . . . . . . . . . . . . 121 - 8.12. Re-Auth-Request-Type AVP . . . . . . . . . . . . . . . . 121 - 8.13. Session-Timeout AVP . . . . . . . . . . . . . . . . . . . 122 - 8.14. User-Name AVP . . . . . . . . . . . . . . . . . . . . . . 122 - 8.15. Termination-Cause AVP . . . . . . . . . . . . . . . . . . 122 - 8.16. Origin-State-Id AVP . . . . . . . . . . . . . . . . . . . 124 - 8.17. Session-Binding AVP . . . . . . . . . . . . . . . . . . . 124 - 8.18. Session-Server-Failover AVP . . . . . . . . . . . . . . . 125 - 8.19. Multi-Round-Time-Out AVP . . . . . . . . . . . . . . . . 126 - - - -Fajardo, et al. Expires July 24, 2011 [Page 4] - -Internet-Draft Diameter Base Protocol January 2011 - - - 8.20. Class AVP . . . . . . . . . . . . . . . . . . . . . . . . 126 - 8.21. Event-Timestamp AVP . . . . . . . . . . . . . . . . . . . 126 - 9. Accounting . . . . . . . . . . . . . . . . . . . . . . . . . 127 - 9.1. Server Directed Model . . . . . . . . . . . . . . . . . . 127 - 9.2. Protocol Messages . . . . . . . . . . . . . . . . . . . . 128 - 9.3. Accounting Application Extension and Requirements . . . . 128 - 9.4. Fault Resilience . . . . . . . . . . . . . . . . . . . . 129 - 9.5. Accounting Records . . . . . . . . . . . . . . . . . . . 129 - 9.6. Correlation of Accounting Records . . . . . . . . . . . . 130 - 9.7. Accounting Command-Codes . . . . . . . . . . . . . . . . 131 - 9.7.1. Accounting-Request . . . . . . . . . . . . . . . . . 131 - 9.7.2. Accounting-Answer . . . . . . . . . . . . . . . . . . 132 - 9.8. Accounting AVPs . . . . . . . . . . . . . . . . . . . . . 133 - 9.8.1. Accounting-Record-Type AVP . . . . . . . . . . . . . 133 - 9.8.2. Acct-Interim-Interval AVP . . . . . . . . . . . . . . 134 - 9.8.3. Accounting-Record-Number AVP . . . . . . . . . . . . 135 - 9.8.4. Acct-Session-Id AVP . . . . . . . . . . . . . . . . . 135 - 9.8.5. Acct-Multi-Session-Id AVP . . . . . . . . . . . . . . 135 - 9.8.6. Accounting-Sub-Session-Id AVP . . . . . . . . . . . . 135 - 9.8.7. Accounting-Realtime-Required AVP . . . . . . . . . . 136 - 10. AVP Occurrence Table . . . . . . . . . . . . . . . . . . . . 137 - 10.1. Base Protocol Command AVP Table . . . . . . . . . . . . . 137 - 10.2. Accounting AVP Table . . . . . . . . . . . . . . . . . . 138 - 11. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 140 - 11.1. Changes to AVP Header Allocation . . . . . . . . . . . . 140 - 11.2. Diameter Header . . . . . . . . . . . . . . . . . . . . . 140 - 11.3. AVP Values . . . . . . . . . . . . . . . . . . . . . . . 140 - 11.3.1. Experimental-Result-Code AVP . . . . . . . . . . . . 140 - 11.4. Diameter TCP, SCTP, TLS/TCP and DTLS/SCTP Port Numbers . 141 - 11.5. S-NAPTR Parameters . . . . . . . . . . . . . . . . . . . 141 - 12. Diameter protocol related configurable parameters . . . . . . 142 - 13. Security Considerations . . . . . . . . . . . . . . . . . . . 143 - 13.1. TLS/TCP and DTLS/SCTP Usage . . . . . . . . . . . . . . . 143 - 13.2. Peer-to-Peer Considerations . . . . . . . . . . . . . . . 144 - 14. References . . . . . . . . . . . . . . . . . . . . . . . . . 145 - 14.1. Normative References . . . . . . . . . . . . . . . . . . 145 - 14.2. Informational References . . . . . . . . . . . . . . . . 147 - Appendix A. Acknowledgements . . . . . . . . . . . . . . . . . . 149 - A.1. RFC3588bis . . . . . . . . . . . . . . . . . . . . . . . 149 - A.2. RFC3588 . . . . . . . . . . . . . . . . . . . . . . . . . 150 - Appendix B. S-NAPTR Example . . . . . . . . . . . . . . . . . . 151 - Appendix C. Duplicate Detection . . . . . . . . . . . . . . . . 152 - Appendix D. Internationalized Domain Names . . . . . . . . . . . 154 - Authors' Addresses . . . . . . . . . . . . . . . . . . . . . . . 155 - - - - - - - -Fajardo, et al. Expires July 24, 2011 [Page 5] - -Internet-Draft Diameter Base Protocol January 2011 + 1. Introduction ....................................................7 + 1.1. Diameter Protocol ..........................................9 + 1.1.1. Description of the Document Set ....................10 + 1.1.2. Conventions Used in This Document ..................11 + 1.1.3. Changes from RFC 3588 ..............................11 + 1.2. Terminology ...............................................12 + 1.3. Approach to Extensibility .................................17 + 1.3.1. Defining New AVP Values ............................18 + 1.3.2. Creating New AVPs ..................................18 + 1.3.3. Creating New Commands ..............................18 + 1.3.4. Creating New Diameter Applications .................19 + 2. Protocol Overview ..............................................20 + 2.1. Transport .................................................22 + 2.1.1. SCTP Guidelines ....................................23 + 2.2. Securing Diameter Messages ................................24 + 2.3. Diameter Application Compliance ...........................24 + 2.4. Application Identifiers ...................................24 + 2.5. Connections vs. Sessions ..................................25 + 2.6. Peer Table ................................................26 + + + +Fajardo, et al. Standards Track [Page 2] + +RFC 6733 Diameter Base Protocol October 2012 + + + 2.7. Routing Table .............................................27 + 2.8. Role of Diameter Agents ...................................28 + 2.8.1. Relay Agents .......................................30 + 2.8.2. Proxy Agents .......................................31 + 2.8.3. Redirect Agents ....................................31 + 2.8.4. Translation Agents .................................32 + 2.9. Diameter Path Authorization ...............................33 + 3. Diameter Header ................................................34 + 3.1. Command Codes .............................................37 + 3.2. Command Code Format Specification .........................38 + 3.3. Diameter Command Naming Conventions .......................40 + 4. Diameter AVPs ..................................................40 + 4.1. AVP Header ................................................41 + 4.1.1. Optional Header Elements ...........................42 + 4.2. Basic AVP Data Formats ....................................43 + 4.3. Derived AVP Data Formats ..................................44 + 4.3.1. Common Derived AVP Data Formats ....................44 + 4.4. Grouped AVP Values ........................................51 + 4.4.1. Example AVP with a Grouped Data Type ...............52 + 4.5. Diameter Base Protocol AVPs ...............................55 + 5. Diameter Peers .................................................58 + 5.1. Peer Connections ..........................................58 + 5.2. Diameter Peer Discovery ...................................59 + 5.3. Capabilities Exchange .....................................60 + 5.3.1. Capabilities-Exchange-Request ......................62 + 5.3.2. Capabilities-Exchange-Answer .......................63 + 5.3.3. Vendor-Id AVP ......................................63 + 5.3.4. Firmware-Revision AVP ..............................64 + 5.3.5. Host-IP-Address AVP ................................64 + 5.3.6. Supported-Vendor-Id AVP ............................64 + 5.3.7. Product-Name AVP ...................................64 + 5.4. Disconnecting Peer Connections ............................64 + 5.4.1. Disconnect-Peer-Request ............................65 + 5.4.2. Disconnect-Peer-Answer .............................65 + 5.4.3. Disconnect-Cause AVP ...............................66 + 5.5. Transport Failure Detection ...............................66 + 5.5.1. Device-Watchdog-Request ............................67 + 5.5.2. Device-Watchdog-Answer .............................67 + 5.5.3. Transport Failure Algorithm ........................67 + 5.5.4. Failover and Failback Procedures ...................67 + 5.6. Peer State Machine ........................................68 + 5.6.1. Incoming Connections ...............................71 + 5.6.2. Events .............................................71 + 5.6.3. Actions ............................................72 + 5.6.4. The Election Process ...............................74 + + + + + + +Fajardo, et al. Standards Track [Page 3] + +RFC 6733 Diameter Base Protocol October 2012 + + + 6. Diameter Message Processing ....................................74 + 6.1. Diameter Request Routing Overview .........................74 + 6.1.1. Originating a Request ..............................75 + 6.1.2. Sending a Request ..................................76 + 6.1.3. Receiving Requests .................................76 + 6.1.4. Processing Local Requests ..........................76 + 6.1.5. Request Forwarding .................................77 + 6.1.6. Request Routing ....................................77 + 6.1.7. Predictive Loop Avoidance ..........................77 + 6.1.8. Redirecting Requests ...............................78 + 6.1.9. Relaying and Proxying Requests .....................79 + 6.2. Diameter Answer Processing ................................80 + 6.2.1. Processing Received Answers ........................81 + 6.2.2. Relaying and Proxying Answers ......................81 + 6.3. Origin-Host AVP ...........................................81 + 6.4. Origin-Realm AVP ..........................................82 + 6.5. Destination-Host AVP ......................................82 + 6.6. Destination-Realm AVP .....................................82 + 6.7. Routing AVPs ..............................................83 + 6.7.1. Route-Record AVP ...................................83 + 6.7.2. Proxy-Info AVP .....................................83 + 6.7.3. Proxy-Host AVP .....................................83 + 6.7.4. Proxy-State AVP ....................................83 + 6.8. Auth-Application-Id AVP ...................................83 + 6.9. Acct-Application-Id AVP ...................................84 + 6.10. Inband-Security-Id AVP ...................................84 + 6.11. Vendor-Specific-Application-Id AVP .......................84 + 6.12. Redirect-Host AVP ........................................85 + 6.13. Redirect-Host-Usage AVP ..................................85 + 6.14. Redirect-Max-Cache-Time AVP ..............................87 + 7. Error Handling .................................................87 + 7.1. Result-Code AVP ...........................................89 + 7.1.1. Informational ......................................90 + 7.1.2. Success ............................................90 + 7.1.3. Protocol Errors ....................................90 + 7.1.4. Transient Failures .................................92 + 7.1.5. Permanent Failures .................................92 + 7.2. Error Bit .................................................95 + 7.3. Error-Message AVP .........................................96 + 7.4. Error-Reporting-Host AVP ..................................96 + 7.5. Failed-AVP AVP ............................................96 + 7.6. Experimental-Result AVP ...................................97 + 7.7. Experimental-Result-Code AVP ..............................97 + 8. Diameter User Sessions .........................................98 + 8.1. Authorization Session State Machine .......................99 + 8.2. Accounting Session State Machine .........................104 + + + + + +Fajardo, et al. Standards Track [Page 4] + +RFC 6733 Diameter Base Protocol October 2012 + + + 8.3. Server-Initiated Re-Auth .................................110 + 8.3.1. Re-Auth-Request ...................................110 + 8.3.2. Re-Auth-Answer ....................................110 + 8.4. Session Termination ......................................111 + 8.4.1. Session-Termination-Request .......................112 + 8.4.2. Session-Termination-Answer ........................113 + 8.5. Aborting a Session .......................................113 + 8.5.1. Abort-Session-Request .............................114 + 8.5.2. Abort-Session-Answer ..............................114 + 8.6. Inferring Session Termination from Origin-State-Id .......115 + 8.7. Auth-Request-Type AVP ....................................116 + 8.8. Session-Id AVP ...........................................116 + 8.9. Authorization-Lifetime AVP ...............................117 + 8.10. Auth-Grace-Period AVP ...................................118 + 8.11. Auth-Session-State AVP ..................................118 + 8.12. Re-Auth-Request-Type AVP ................................118 + 8.13. Session-Timeout AVP .....................................119 + 8.14. User-Name AVP ...........................................119 + 8.15. Termination-Cause AVP ...................................120 + 8.16. Origin-State-Id AVP .....................................120 + 8.17. Session-Binding AVP .....................................120 + 8.18. Session-Server-Failover AVP .............................121 + 8.19. Multi-Round-Time-Out AVP ................................122 + 8.20. Class AVP ...............................................122 + 8.21. Event-Timestamp AVP .....................................122 + 9. Accounting ....................................................123 + 9.1. Server Directed Model ....................................123 + 9.2. Protocol Messages ........................................124 + 9.3. Accounting Application Extension and Requirements ........124 + 9.4. Fault Resilience .........................................125 + 9.5. Accounting Records .......................................125 + 9.6. Correlation of Accounting Records ........................126 + 9.7. Accounting Command Codes .................................127 + 9.7.1. Accounting-Request ................................127 + 9.7.2. Accounting-Answer .................................128 + 9.8. Accounting AVPs ..........................................129 + 9.8.1. Accounting-Record-Type AVP ........................129 + 9.8.2. Acct-Interim-Interval AVP .........................130 + 9.8.3. Accounting-Record-Number AVP ......................131 + 9.8.4. Acct-Session-Id AVP ...............................131 + 9.8.5. Acct-Multi-Session-Id AVP .........................131 + 9.8.6. Accounting-Sub-Session-Id AVP .....................131 + 9.8.7. Accounting-Realtime-Required AVP ..................132 + 10. AVP Occurrence Tables ........................................132 + 10.1. Base Protocol Command AVP Table .........................133 + 10.2. Accounting AVP Table ....................................134 + + + + + +Fajardo, et al. Standards Track [Page 5] + +RFC 6733 Diameter Base Protocol October 2012 + + + 11. IANA Considerations ..........................................135 + 11.1. AVP Header ..............................................135 + 11.1.1. AVP Codes ........................................136 + 11.1.2. AVP Flags ........................................136 + 11.2. Diameter Header .........................................136 + 11.2.1. Command Codes ....................................136 + 11.2.2. Command Flags ....................................137 + 11.3. AVP Values ..............................................137 + 11.3.1. Experimental-Result-Code AVP .....................137 + 11.3.2. Result-Code AVP Values ...........................137 + 11.3.3. Accounting-Record-Type AVP Values ................137 + 11.3.4. Termination-Cause AVP Values .....................137 + 11.3.5. Redirect-Host-Usage AVP Values ...................137 + 11.3.6. Session-Server-Failover AVP Values ...............137 + 11.3.7. Session-Binding AVP Values .......................137 + 11.3.8. Disconnect-Cause AVP Values ......................138 + 11.3.9. Auth-Request-Type AVP Values .....................138 + 11.3.10. Auth-Session-State AVP Values ...................138 + 11.3.11. Re-Auth-Request-Type AVP Values .................138 + 11.3.12. Accounting-Realtime-Required AVP Values .........138 + 11.3.13. Inband-Security-Id AVP (code 299) ...............138 + 11.4. _diameters Service Name and Port Number Registration ....138 + 11.5. SCTP Payload Protocol Identifiers .......................139 + 11.6. S-NAPTR Parameters ......................................139 + 12. Diameter Protocol-Related Configurable Parameters ............139 + 13. Security Considerations ......................................140 + 13.1. TLS/TCP and DTLS/SCTP Usage .............................140 + 13.2. Peer-to-Peer Considerations .............................141 + 13.3. AVP Considerations ......................................141 + 14. References ...................................................142 + 14.1. Normative References ....................................142 + 14.2. Informative References ..................................144 + Appendix A. Acknowledgements .....................................147 + A.1. This Document .............................................147 + A.2. RFC 3588 ..................................................148 + Appendix B. S-NAPTR Example ......................................148 + Appendix C. Duplicate Detection ..................................149 + Appendix D. Internationalized Domain Names .......................151 + + + + + + + + + + + + + +Fajardo, et al. Standards Track [Page 6] + +RFC 6733 Diameter Base Protocol October 2012 1. Introduction - Authentication, Authorization and Accounting (AAA) protocols such as + Authentication, Authorization, and Accounting (AAA) protocols such as TACACS [RFC1492] and RADIUS [RFC2865] were initially deployed to provide dial-up PPP [RFC1661] and terminal server access. Over time, AAA support was needed on many new access technologies, the scale and complexity of AAA networks grew, and AAA was also used on new - applications (such as voice over IP). This lead to new demands on - AAA protocols. + applications (such as voice over IP). This led to new demands on AAA + protocols. Network access requirements for AAA protocols are summarized in - [RFC2989]. These include: - + Aboba, et al. [RFC2989]. These include: Failover - [RFC2865] does not define failover mechanisms, and as a result, + [RFC2865] does not define failover mechanisms and, as a result, failover behavior differs between implementations. In order to provide well-defined failover behavior, Diameter supports - application-layer acknowledgements, and defines failover - algorithms and the associated state machine. This is described in - Section 5.5 and [RFC3539]. + application-layer acknowledgements and defines failover algorithms + and the associated state machine. Transmission-level security - [RFC2865] defines an application-layer authentication and - integrity scheme that is required only for use with Response + RADIUS [RFC2865] defines an application-layer authentication and + integrity scheme that is required only for use with response packets. While [RFC2869] defines an additional authentication and integrity mechanism, use is only required during Extensible - Authentication Protocol (EAP) sessions. While attribute-hiding is - supported, [RFC2865] does not provide support for per-packet - confidentiality. In accounting, [RFC2866] assumes that replay - protection is provided by the backend billing server, rather than - within the protocol itself. + Authentication Protocol (EAP) [RFC3748] sessions. While attribute + hiding is supported, [RFC2865] does not provide support for per- + packet confidentiality. In accounting, [RFC2866] assumes that + replay protection is provided by the backend billing server rather + than within the protocol itself. While [RFC3162] defines the use of IPsec with RADIUS, support for IPsec is not required. In order to provide universal support for @@ -322,50 +379,48 @@ Internet-Draft Diameter Base Protocol January 2011 domain AAA deployments, Diameter provides support for TLS/TCP and DTLS/SCTP. Security is discussed in Section 13. - Reliable transport - RADIUS runs over UDP, and does not define retransmission behavior; as a result, reliability varies between implementations. As described in [RFC2975], this is a major issue in accounting, where + packet loss may translate directly into revenue loss. In order to -Fajardo, et al. Expires July 24, 2011 [Page 6] - -Internet-Draft Diameter Base Protocol January 2011 - packet loss may translate directly into revenue loss. In order to - provide well defined transport behavior, Diameter runs over - reliable transport mechanisms (TCP, SCTP) as defined in [RFC3539]. +Fajardo, et al. Standards Track [Page 7] + +RFC 6733 Diameter Base Protocol October 2012 - Agent support - [RFC2865] does not provide for explicit support for agents, - including Proxies, Redirects and Relays. Since the expected - behavior is not defined, it varies between implementations. - Diameter defines agent behavior explicitly; this is described in - Section 2.8. + provide well-defined transport behavior, Diameter runs over + reliable transport mechanisms (TCP, Stream Control Transmission + Protocol (SCTP)) as defined in [RFC3539]. + + Agent support + RADIUS does not provide for explicit support for agents, including + proxies, redirects, and relays. Since the expected behavior is + not defined, it varies between implementations. Diameter defines + agent behavior explicitly; this is described in Section 2.8. Server-initiated messages - While RADIUS server-initiated messages are defined in [RFC5176], + While server-initiated messages are defined in RADIUS [RFC5176], support is optional. This makes it difficult to implement features such as unsolicited disconnect or re-authentication/ re-authorization on demand across a heterogeneous deployment. To - tackle this issue, support for server-initiated messages is + address this issue, support for server-initiated messages is mandatory in Diameter. - Transition support While Diameter does not share a common protocol data unit (PDU) with RADIUS, considerable effort has been expended in enabling - backward compatibility with RADIUS, so that the two protocols may + backward compatibility with RADIUS so that the two protocols may be deployed in the same network. Initially, it is expected that Diameter will be deployed within new network devices, as well as within gateways enabling communication between legacy RADIUS @@ -373,9 +428,8 @@ Internet-Draft Diameter Base Protocol January 2011 support to be added to legacy networks, by addition of a gateway or server speaking both RADIUS and Diameter. - In addition to addressing the above requirements, Diameter also - provides support for the following: - + In addition to addressing the above requirements, Diameter also + provides support for the following: Capability negotiation @@ -383,19 +437,19 @@ Internet-Draft Diameter Base Protocol January 2011 a mandatory/non-mandatory flag for attributes. Since RADIUS clients and servers are not aware of each other's capabilities, they may not be able to successfully negotiate a mutually - acceptable service, or in some cases, even be aware of what + acceptable service or, in some cases, even be aware of what service has been implemented. Diameter includes support for error + handling (Section 7), capability negotiation (Section 5.3), and + mandatory/non-mandatory Attribute-Value Pairs (AVPs) + (Section 4.1). -Fajardo, et al. Expires July 24, 2011 [Page 7] - -Internet-Draft Diameter Base Protocol January 2011 - handling (Section 7), capability negotiation (Section 5.3), and - mandatory/non-mandatory Attribute-Value Pairs (AVPs) (Section - 4.1). +Fajardo, et al. Standards Track [Page 8] + +RFC 6733 Diameter Base Protocol October 2012 Peer discovery and configuration @@ -403,7 +457,7 @@ Internet-Draft Diameter Base Protocol January 2011 RADIUS implementations typically require that the name or address of servers or clients be manually configured, along with the corresponding shared secrets. This results in a large - administrative burden, and creates the temptation to reuse the + administrative burden and creates the temptation to reuse the RADIUS shared secret, which can result in major security vulnerabilities if the Request Authenticator is not globally and temporally unique as required in [RFC2865]. Through DNS, Diameter @@ -411,7 +465,6 @@ Internet-Draft Diameter Base Protocol January 2011 of dynamic session keys is enabled via transmission-level security. - Over time, the capabilities of Network Access Server (NAS) devices have increased substantially. As a result, while Diameter is a considerably more sophisticated protocol than RADIUS, it remains @@ -427,42 +480,41 @@ Internet-Draft Diameter Base Protocol January 2011 o Error notification - o Extensibility, through addition of new applications, commands and - AVPs (required in [RFC2989]). + o Extensibility, required in [RFC2989], through addition of new + applications, commands, and AVPs - o Basic services necessary for applications, such as handling of + o Basic services necessary for applications, such as the handling of user sessions or accounting All data delivered by the protocol is in the form of AVPs. Some of these AVP values are used by the Diameter protocol itself, while others deliver data associated with particular applications that employ Diameter. AVPs may be arbitrarily added to Diameter messages, - the only restriction being that the Augmented Backus-Naur Form (ABNF, - [RFC5234]) Command Code syntax specification (Section 3.2) is - satisfied. AVPs are used by the base Diameter protocol to support - the following required features: + the only restriction being that the Command Code Format (CCF) + specification (Section 3.2) be satisfied. AVPs are used by the base + Diameter protocol to support the following required features: + o Transporting of user authentication information, for the purposes + of enabling the Diameter server to authenticate the user + o Transporting of service-specific authorization information, + between client and servers, allowing the peers to decide whether a + user's access request should be granted -Fajardo, et al. Expires July 24, 2011 [Page 8] - -Internet-Draft Diameter Base Protocol January 2011 - o Transporting of user authentication information, for the purposes - of enabling the Diameter server to authenticate the user. +Fajardo, et al. Standards Track [Page 9] + +RFC 6733 Diameter Base Protocol October 2012 - o Transporting of service-specific authorization information, - between client and servers, allowing the peers to decide whether a - user's access request should be granted. o Exchanging resource usage information, which may be used for accounting purposes, capacity planning, etc. - o Routing, relaying, proxying and redirecting of Diameter messages - through a server hierarchy. + o Routing, relaying, proxying, and redirecting of Diameter messages + through a server hierarchy - The Diameter base protocol satisfies the minimum requirements for an + The Diameter base protocol satisfies the minimum requirements for a AAA protocol, as specified by [RFC2989]. The base protocol may be used by itself for accounting purposes only, or it may be used with a Diameter application, such as Mobile IPv4 [RFC4004], or network @@ -473,16 +525,16 @@ Internet-Draft Diameter Base Protocol January 2011 many applications might provide functionality not provided by Diameter. Therefore, it is imperative that the designers of new applications understand their requirements before using Diameter. - See Section 2.4 for more information on Diameter applications. + See Section 1.3.4 for more information on Diameter applications. Any node can initiate a request. In that sense, Diameter is a peer- - to-peer protocol. In this document, a Diameter Client is a device at + to-peer protocol. In this document, a Diameter client is a device at the edge of the network that performs access control, such as a Network Access Server (NAS) or a Foreign Agent (FA). A Diameter client generates Diameter messages to request authentication, authorization, and accounting services for the user. A Diameter agent is a node that does not provide local user authentication or - authorization services; agents include proxies, redirects and relay + authorization services; agents include proxies, redirects, and relay agents. A Diameter server performs authentication and/or authorization of the user. A Diameter node may act as an agent for certain requests while acting as a server for others. @@ -494,33 +546,33 @@ Internet-Draft Diameter Base Protocol January 2011 The Diameter specification consists of an updated version of the base protocol specification (this document) and the Transport Profile - [RFC3539]. This document obsoletes RFC 3588. A summary of the base - protocol updates included in this document can be found in - Section 1.1.3. - - - -Fajardo, et al. Expires July 24, 2011 [Page 9] - -Internet-Draft Diameter Base Protocol January 2011 - + [RFC3539]. This document obsoletes both RFC 3588 and RFC 5719. A + summary of the base protocol updates included in this document can be + found in Section 1.1.3. This document defines the base protocol specification for AAA, which includes support for accounting. There are also a myriad of applications documents describing applications that use this base - specification for Authentication, Authorization and Accounting. + specification for Authentication, Authorization, and Accounting. These application documents specify how to use the Diameter protocol within the context of their application. + + +Fajardo, et al. Standards Track [Page 10] + +RFC 6733 Diameter Base Protocol October 2012 + + The Transport Profile document [RFC3539] discusses transport layer issues that arise with AAA protocols and recommendations on how to overcome these issues. This document also defines the Diameter failover algorithm and state machine. - Clarifications on the Routing of Diameter Request based on Username - and the Realm [RFC5729] defines specific behavior on how to route - request based on the content of the User-Name AVP (Attribute Value - Pair). + "Clarifications on the Routing of Diameter Request Based on the + Username and the Realm" [RFC5729] defines specific behavior on how to + route requests based on the content of the User-Name AVP (Attribute + Value Pair). 1.1.2. Conventions Used in This Document @@ -528,100 +580,100 @@ Internet-Draft Diameter Base Protocol January 2011 "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC2119]. -1.1.3. Changes from RFC3588 +1.1.3. Changes from RFC 3588 This document obsoletes RFC 3588 but is fully backward compatible with that document. The changes introduced in this document focus on - fixing issues that have surfaced during implementation of [RFC3588]. - An overview of some the major changes are given below. - - o Deprecated the use of Inband-Security AVP for negotiating - transport layer security. It has been generally considered that - bootstrapping of TLS via Inband-Security AVP creates certain - security risk because it does not completely protect the - information carried in the CER (Capabilities Exchange Request)/CEA - (Capabilities Exchange Answer). This version of Diameter adopted - a common approach of defining a well-known secured port that peers - should use when communicating via TLS/TCP and DTLS/SCTP. This new - approach augments the existing Inband-Security negotiation but - does not completely replace it. The old method is kept for - backwards compatibility reasons. + fixing issues that have surfaced during the implementation of + Diameter (RFC 3588). An overview of some the major changes are given + below. + + o Deprecated the use of the Inband-Security AVP for negotiating + Transport Layer Security (TLS) [RFC5246]. It has been generally + considered that bootstrapping of TLS via Inband-Security AVP + creates certain security risks because it does not completely + protect the information carried in the CER/CEA (Capabilities- + Exchange-Request/Capabilities-Exchange-Answer). This version of + Diameter adopts the common approach of defining a well-known + secured port that peers should use when communicating via TLS/TCP + and DTLS/SCTP. This new approach augments the existing in-band + security negotiation, but it does not completely replace it. The + old method is kept for backward compatibility reasons. o Deprecated the exchange of CER/CEA messages in the open state. - This feature was implied in the peer state machine table of - [RFC3588] but it was not clearly defined anywhere else in that + This feature was implied in the peer state machine table of RFC + 3588, but it was not clearly defined anywhere else in that document. As work on this document progressed, it became clear - that the multiplicity of meaning and use of Application Id AVPs in + that the multiplicity of meaning and use of Application-Id AVPs in the CER/CEA messages (and the messages themselves) is seen as an + abuse of the Diameter extensibility rules and thus required + simplification. Capabilities exchange in the open state has been + re-introduced in a separate specification [RFC6737], which clearly + defines new commands for this feature. -Fajardo, et al. Expires July 24, 2011 [Page 10] - -Internet-Draft Diameter Base Protocol January 2011 - abuse of the Diameter extensibility rules and thus required - simplification. It is assumed that the capabilities exchange in - the open state will be re-introduced in a separate specification - which clearly defines new commands for this feature. +Fajardo, et al. Standards Track [Page 11] + +RFC 6733 Diameter Base Protocol October 2012 + - o Simplified Security Requirements. The use of a secured transport + o Simplified security requirements. The use of a secured transport for exchanging Diameter messages remains mandatory. However, TLS/ - TCP and DTLS/SCTP has become the primary method of securing - Diameter and IPsec is a secondary alternative. See Section 13 for - details. The support for the End-to-End security framework - (E2ESequence AVP and 'P'-bit in the AVP header) has also been + TCP and DTLS/SCTP have become the primary methods of securing + Diameter with IPsec as a secondary alternative. See Section 13 + for details. The support for the End-to-End security framework + (E2E-Sequence AVP and 'P'-bit in the AVP header) has also been deprecated. - o Diameter Extensibility Changes. This includes fixes to the + o Changed Diameter extensibility. This includes fixes to the Diameter extensibility description (Section 1.3 and others) to better aid Diameter application designers; in addition, the new specification relaxes the policy with respect to the allocation of - command codes for vendor-specific uses. - - o Application Id Usage. Clarify the proper use of Application Id - information which can be found in multiple places within a - Diameter message. This includes correlating Application Ids found - in the message headers and AVPs. These changes also clearly - specify the proper Application Id value to use for specific base - protocol messages (ASR/ASA, STR/STA) as well as clarifying the - content and use of Vendor-Specific-Application-Id. - - o Routing Fixes. This document more clearly specifies what - information (AVPs and Application Id) can be used for making + Command Codes for vendor-specific uses. + + o Clarified Application Id usage. Clarify the proper use of + Application Id information, which can be found in multiple places + within a Diameter message. This includes correlating Application + Ids found in the message headers and AVPs. These changes also + clearly specify the proper Application Id value to use for + specific base protocol messages (ASR/ASA, STR/STA) as well as + clarify the content and use of Vendor-Specific-Application-Id. + + o Clarified routing fixes. This document more clearly specifies + what information (AVPs and Application Ids) can be used for making general routing decisions. A rule for the prioritization of redirect routing criteria when multiple route entries are found - via redirects has also been added (See Section 6.13 for details). + via redirects has also been added (see Section 6.13). - o Simplification of Diameter Peer Discovery. The Diameter discovery + o Simplified Diameter peer discovery. The Diameter discovery process now supports only widely used discovery schemes; the rest have been deprecated (see Section 5.2 for details). - There are many other many miscellaneous fixes that have been - introduced in this document that may not be considered significant - but they are important nonetheless. Examples are removal of obsolete - types, fixes to command ABNFs, fixes to the state machine, - clarification of the election process, message validation, fixes to - Failed-AVP and Result-Code AVP values, etc. A comprehensive list of - changes is not shown here for practical reasons. - - - + There are many other miscellaneous fixes that have been introduced in + this document that may not be considered significant, but they have + value nonetheless. Examples are removal of obsolete types, fixes to + the state machine, clarification of the election process, message + validation, fixes to Failed-AVP and Result-Code AVP values, etc. All + of the errata filed against RFC 3588 prior to the publication of this + document have been addressed. A comprehensive list of changes is not + shown here for practical reasons. +1.2. Terminology + AAA + Authentication, Authorization, and Accounting. -Fajardo, et al. Expires July 24, 2011 [Page 11] - -Internet-Draft Diameter Base Protocol January 2011 -1.2. Terminology - AAA - Authentication, Authorization and Accounting. +Fajardo, et al. Standards Track [Page 12] + +RFC 6733 Diameter Base Protocol October 2012 ABNF @@ -631,14 +683,12 @@ Internet-Draft Diameter Base Protocol January 2011 is used to define message exchanges in a bi-directional communications protocol. - Accounting The act of collecting information on resource usage for the - purpose of capacity planning, auditing, billing or cost + purpose of capacity planning, auditing, billing, or cost allocation. - Accounting Record An accounting record represents a summary of the resource @@ -647,114 +697,102 @@ Internet-Draft Diameter Base Protocol January 2011 accounting events or accounting events from several devices serving the same user. - Authentication The act of verifying the identity of an entity (subject). - Authorization The act of determining whether a requesting entity (subject) will be allowed access to a resource (object). - - AVP + Attribute-Value Pair (AVP) The Diameter protocol consists of a header followed by one or more Attribute-Value-Pairs (AVPs). An AVP includes a header and is used to encapsulate protocol-specific data (e.g., routing - information) as well as authentication, authorization or + information) as well as authentication, authorization, or + accounting information. + Command Code Format (CCF) + A modified form of ABNF used to define Diameter commands (see + Section 3.2). -Fajardo, et al. Expires July 24, 2011 [Page 12] - -Internet-Draft Diameter Base Protocol January 2011 + Diameter Agent + A Diameter Agent is a Diameter node that provides relay, proxy, + redirect, or translation services. - accounting information. - Diameter Agent - A Diameter Agent is a Diameter Node that provides either relay, - proxy, redirect or translation services. +Fajardo, et al. Standards Track [Page 13] + +RFC 6733 Diameter Base Protocol October 2012 Diameter Client - A Diameter Client is a Diameter Node that supports Diameter client - applications as well as the base protocol. Diameter Clients are + A Diameter client is a Diameter node that supports Diameter client + applications as well as the base protocol. Diameter clients are often implemented in devices situated at the edge of a network and provide access control services for that network. Typical - examples of Diameter Clients include the Network Access Server + examples of Diameter clients include the Network Access Server (NAS) and the Mobile IP Foreign Agent (FA). - Diameter Node - A Diameter Node is a host process that implements the Diameter - protocol, and acts either as a Client, Agent or Server. - + A Diameter node is a host process that implements the Diameter + protocol and acts as either a client, an agent, or a server. Diameter Peer - If a Diameter Node shares a direct transport connection with - another Diameter Node, it is a Diameter Peer to that Diameter - Node. - + Two Diameter nodes sharing a direct TCP or SCTP transport + connection are called Diameter peers. Diameter Server - A Diameter Server is a Diameter Node that handles authentication, - authorization and accounting requests for a particular realm. By - its very nature, a Diameter Server must support Diameter server + A Diameter server is a Diameter node that handles authentication, + authorization, and accounting requests for a particular realm. By + its very nature, a Diameter server must support Diameter server applications in addition to the base protocol. - Downstream Downstream is used to identify the direction of a particular - Diameter message from the Home Server towards the Diameter Client. - - - - - - - -Fajardo, et al. Expires July 24, 2011 [Page 13] - -Internet-Draft Diameter Base Protocol January 2011 - + Diameter message from the home server towards the Diameter client. Home Realm A Home Realm is the administrative domain with which the user maintains an account relationship. - Home Server - A Diameter Server which serves the Home Realm. - + A Diameter server that serves the Home Realm. - Interim accounting + Interim Accounting An interim accounting message provides a snapshot of usage during - a user's session. It is typically implemented in order to provide - for partial accounting of a user's session in the case a device - reboot or other network problem prevents the delivery of a session - summary message or session record. + a user's session. Typically, it is implemented in order to + provide for partial accounting of a user's session in case a + device reboot or other network problem prevents the delivery of a + session summary message or session record. + + + + +Fajardo, et al. Standards Track [Page 14] + +RFC 6733 Diameter Base Protocol October 2012 Local Realm A local realm is the administrative domain providing services to a user. An administrative domain may act as a local realm for - certain users, while being a home realm for others. - + certain users while being a home realm for others. Multi-session @@ -764,60 +802,56 @@ Internet-Draft Diameter Base Protocol January 2011 leg of the bundle would be a session while the entire bundle would be a multi-session. - Network Access Identifier The Network Access Identifier, or NAI [RFC4282], is used in the Diameter protocol to extract a user's identity and realm. The identity is used to identify the user during authentication and/or - authorization, while the realm is used for message routing + authorization while the realm is used for message routing purposes. - - - - - - - -Fajardo, et al. Expires July 24, 2011 [Page 14] - -Internet-Draft Diameter Base Protocol January 2011 - - Proxy Agent or Proxy In addition to forwarding requests and responses, proxies make policy decisions relating to resource usage and provisioning. - This is typically accomplished by tracking the state of NAS - devices. While proxies typically do not respond to client - Requests prior to receiving a Response from the server, they may - originate Reject messages in cases where policies are violated. - As a result, proxies need to understand the semantics of the - messages passing through them, and may not support all Diameter + Typically, this is accomplished by tracking the state of NAS + devices. While proxies usually do not respond to client requests + prior to receiving a response from the server, they may originate + Reject messages in cases where policies are violated. As a + result, proxies need to understand the semantics of the messages + passing through them, and they may not support all Diameter applications. - Realm The string in the NAI that immediately follows the '@' character. - NAI realm names are required to be unique, and are piggybacked on + NAI realm names are required to be unique and are piggybacked on the administration of the DNS namespace. Diameter makes use of the realm, also loosely referred to as domain, to determine - whether messages can be satisfied locally, or whether they must be + whether messages can be satisfied locally or whether they must be routed or redirected. In RADIUS, realm names are not necessarily piggybacked on the DNS namespace but may be independent of it. - Real-time Accounting + + + + + + +Fajardo, et al. Standards Track [Page 15] + +RFC 6733 Diameter Base Protocol October 2012 + + + Real-Time Accounting Real-time accounting involves the processing of information on - resource usage within a defined time window. Time constraints are - typically imposed in order to limit financial risk. The Diameter - Credit Control Application [RFC4006] is an example of an + resource usage within a defined time window. Typically, time + constraints are imposed in order to limit financial risk. The + Diameter Credit-Control Application [RFC4006] is an example of an application that defines real-time accounting functionality. - Relay Agent or Relay Relays forward requests and responses based on routing-related @@ -827,20 +861,9 @@ Internet-Draft Diameter Base Protocol January 2011 the semantics of messages or non-routing AVPs, and are capable of handling any Diameter application or message type. Since relays make decisions based on information in routing AVPs and realm - forwarding tables they do not keep state on NAS resource usage or + forwarding tables, they do not keep state on NAS resource usage or sessions in progress. - - - - - - -Fajardo, et al. Expires July 24, 2011 [Page 15] - -Internet-Draft Diameter Base Protocol January 2011 - - Redirect Agent Rather than forwarding requests and responses between clients and @@ -850,11 +873,10 @@ Internet-Draft Diameter Base Protocol January 2011 client and server. Redirect agents do not originate messages and are capable of handling any message type, although they may be configured only to redirect messages of certain types, while - acting as relay or proxy agents for other types. As with proxy + acting as relay or proxy agents for other types. As with relay agents, redirect agents do not keep state with respect to sessions or NAS resources. - Session A session is a related progression of events devoted to a @@ -863,14 +885,19 @@ Internet-Draft Diameter Base Protocol January 2011 packets with the same Session-Id are considered to be part of the same session. - Stateful Agent A stateful agent is one that maintains session state information, by keeping track of all authorized active sessions. Each authorized session is bound to a particular service, and its state - is considered active either until it is notified otherwise, or by - expiration. + is considered active either until it is notified otherwise or + until expiration. + + + +Fajardo, et al. Standards Track [Page 16] + +RFC 6733 Diameter Base Protocol October 2012 Sub-session @@ -881,53 +908,33 @@ Internet-Draft Diameter Base Protocol January 2011 during the same session) or serially. These changes in sessions are tracked with the Accounting-Sub-Session-Id. - - Transaction state + Transaction State The Diameter protocol requires that agents maintain transaction state, which is used for failover purposes. Transaction state - implies that upon forwarding a request, the Hop-by-Hop identifier + implies that upon forwarding a request, the Hop-by-Hop Identifier is saved; the field is replaced with a locally unique identifier, which is restored to its original value when the corresponding - - - -Fajardo, et al. Expires July 24, 2011 [Page 16] - -Internet-Draft Diameter Base Protocol January 2011 - - answer is received. The request's state is released upon receipt of the answer. A stateless agent is one that only maintains transaction state. - Translation Agent - A translation agent is a stateful Diameter node that performs - protocol translation between Diameter and another AAA protocol, - such as RADIUS. - - - Transport Connection - - A transport connection is a TCP or SCTP connection existing - directly between two Diameter peers, otherwise known as a Peer-to- - Peer Connection. - + A translation agent (TLA in Figure 4) is a stateful Diameter node + that performs protocol translation between Diameter and another + AAA protocol, such as RADIUS. Upstream Upstream is used to identify the direction of a particular - Diameter message from the Diameter Client towards the Home Server. - + Diameter message from the Diameter client towards the home server. User The entity or device requesting or using some resource, in support of which a Diameter client has generated a request. - 1.3. Approach to Extensibility The Diameter protocol is designed to be extensible, using several @@ -941,107 +948,108 @@ Internet-Draft Diameter Base Protocol January 2011 o Creating new applications - From the point of view of extensibility Diameter authentication, - authorization and accounting applications are treated in the same - way. - -Fajardo, et al. Expires July 24, 2011 [Page 17] +Fajardo, et al. Standards Track [Page 17] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 - Note: Protocol designers should try to re-use existing functionality, + From the point of view of extensibility, Diameter authentication, + authorization, and accounting applications are treated in the same + way. + + Note: Protocol designers should try to reuse existing functionality, namely AVP values, AVPs, commands, and Diameter applications. Reuse simplifies standardization and implementation. To avoid potential - interoperability issues it is important to ensure that the semantics - of the re-used features are well understood. Given that Diameter can - also carry RADIUS attributes as Diameter AVPs, such re-use - considerations apply also to existing RADIUS attributes that may be + interoperability issues, it is important to ensure that the semantics + of the reused features are well understood. Given that Diameter can + also carry RADIUS attributes as Diameter AVPs, such reuse + considerations also apply to existing RADIUS attributes that may be useful in a Diameter application. -1.3.1. Defining New AVP Values +1.3.1. Defining New AVP Values In order to allocate a new AVP value for AVPs defined in the Diameter - Base protocol, the IETF needs to approve a new RFC that describes the + base protocol, the IETF needs to approve a new RFC that describes the AVP value. IANA considerations for these AVP values are discussed in - Section 11.4. + Section 11.3. The allocation of AVP values for other AVPs is guided by the IANA considerations of the document that defines those AVPs. Typically, - allocation of new values for an AVP defined in an IETF RFC should - require IETF Review [RFC5226], whereas values for vendor-specific - AVPs can be allocated by the vendor. + allocation of new values for an AVP defined in an RFC would require + IETF Review [RFC5226], whereas values for vendor-specific AVPs can be + allocated by the vendor. -1.3.2. Creating New AVPs +1.3.2. Creating New AVPs A new AVP being defined MUST use one of the data types listed in - Section 4.2 or Section 4.3. If an appropriate derived data type is - already defined, it SHOULD be used instead of a base data type to - encourage reusability and good design practice. + Sections 4.2 or 4.3. If an appropriate derived data type is already + defined, it SHOULD be used instead of a base data type to encourage + reusability and good design practice. In the event that a logical grouping of AVPs is necessary, and multiple "groups" are possible in a given command, it is recommended that a Grouped AVP be used (see Section 4.4). The creation of new AVPs can happen in various ways. The recommended - approach is to define a new general-purpose AVP in a standards track - RFC approved by the IETF. However, as described in Section 11.1.1 - there are also other mechanisms. + approach is to define a new general-purpose AVP in a Standards Track + RFC approved by the IETF. However, as described in Section 11.1.1, + there are other mechanisms. -1.3.3. Creating New Commands +1.3.3. Creating New Commands A new Command Code MUST be allocated when required AVPs (those - indicated as {AVP} in the ABNF definition) are added to, deleted from + indicated as {AVP} in the CCF definition) are added to, deleted from, or redefined in (for example, by changing a required AVP into an optional one) an existing command. - Furthermore, if the transport characteristics of a command are - changed (for example, with respect to the number of round trips - required) a new Command Code MUST be registered. - -Fajardo, et al. Expires July 24, 2011 [Page 18] +Fajardo, et al. Standards Track [Page 18] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 + + Furthermore, if the transport characteristics of a command are + changed (for example, with respect to the number of round trips + required), a new Command Code MUST be registered. - A change to the ABNF of a command, such as described above, MUST + A change to the CCF of a command, such as described above, MUST result in the definition of a new Command Code. This subsequently - leads to the need to define a new Diameter Application for any - application that will use that new Command. - - The IANA considerations for commands are discussed in Section 11.2.1. - -1.3.4. Creating New Diameter Applications - - Every Diameter application specification MUST have an IANA assigned - Application Id (see Section 2.4 and Section 11.3). The managed - Application Id space is flat and there is no relationship between - different Diameter applications with respect to their Application - Ids. As such, there is no versioning support provided by these - application Ids itself; every Diameter application is a standalone - application. If the application has a relationship with other - Diameter applications, such a relationship is not known to Diameter. - - Before describing the rules for creating new Diameter applications it - is important to discuss the semantics of the AVPs occurrences as - stated in the ABNF and the M-bit flag (Section 4.1) for an AVP. - There is no relationship imposed between the two; they are set + leads to the need to define a new Diameter application for any + application that will use that new command. + + The IANA considerations for Command Codes are discussed in + Section 3.1. + +1.3.4. Creating New Diameter Applications + + Every Diameter application specification MUST have an IANA-assigned + Application Id (see Section 2.4). The managed Application ID space + is flat, and there is no relationship between different Diameter + applications with respect to their Application Ids. As such, there + is no versioning support provided by these Application Ids + themselves; every Diameter application is a standalone application. + If the application has a relationship with other Diameter + applications, such a relationship is not known to Diameter. + + Before describing the rules for creating new Diameter applications, + it is important to discuss the semantics of the AVP occurrences as + stated in the CCF and the M-bit flag (Section 4.1) for an AVP. There + is no relationship imposed between the two; they are set independently. - o The ABNF indicates what AVPs are placed into a Diameter Command by - the sender of that Command. Often, since there are multiple modes - of protocol interactions many of the AVPs are indicated as + o The CCF indicates what AVPs are placed into a Diameter command by + the sender of that command. Often, since there are multiple modes + of protocol interactions, many of the AVPs are indicated as optional. o The M-bit allows the sender to indicate to the receiver whether or not understanding the semantics of an AVP and its content is mandatory. If the M-bit is set by the sender and the receiver - does not understand the AVP or the values carried within that AVP + does not understand the AVP or the values carried within that AVP, then a failure is generated (see Section 7). It is the decision of the protocol designer when to develop a new @@ -1050,77 +1058,48 @@ Internet-Draft Diameter Base Protocol January 2011 of the following criteria are met: - M-bit Setting - An AVP with the M-bit in the MUST column of the AVP flag table is - added to an existing Command/Application. - An AVP with the M-bit in the MAY column of the AVP flag table is - added to an existing Command/Application. -Fajardo, et al. Expires July 24, 2011 [Page 19] +Fajardo, et al. Standards Track [Page 19] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 + + M-bit Setting + + An AVP with the M-bit in the MUST column of the AVP flag table is + added to an existing Command/Application. An AVP with the M-bit + in the MAY column of the AVP flag table is added to an existing + Command/Application. Note: The M-bit setting for a given AVP is relevant to an - Application and each command within that application which - includes the AVP. That is, if an AVP appears in two commands for + Application and each command within that application that includes + the AVP. That is, if an AVP appears in two commands for application Foo and the M-bit settings are different in each command, then there should be two AVP flag tables describing when to set the M-bit. Commands - A new command is used within the existing application either - because an additional command is added, an existing command has + A new command is used within the existing application because + either an additional command is added, an existing command has been modified so that a new Command Code had to be registered, or a command has been deleted. - If the ABNF definition of a command allows it, an implementation may + AVP Flag bits + + If an existing application changes the meaning/semantics of its + AVP Flags or adds new flag bits, then a new Diameter application + MUST be created. + + If the CCF definition of a command allows it, an implementation may add arbitrary optional AVPs with the M-bit cleared (including vendor- specific AVPs) to that command without needing to define a new application. Please refer to Section 11.1.1 for details. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Fajardo, et al. Expires July 24, 2011 [Page 20] - -Internet-Draft Diameter Base Protocol January 2011 - - 2. Protocol Overview The base Diameter protocol concerns itself with establishing @@ -1137,9 +1116,17 @@ Internet-Draft Diameter Base Protocol January 2011 The initial request for authentication and/or authorization of a user would include the Session-Id AVP. The Session-Id is then used in all subsequent messages to identify the user's session (see Section 8 for - more information). The communicating party may accept the request, - or reject it by returning an answer message with the Result-Code AVP - set to indicate an error occurred. The specific behavior of the + + + +Fajardo, et al. Standards Track [Page 20] + +RFC 6733 Diameter Base Protocol October 2012 + + + more information). The communicating party may accept the request or + reject it by returning an answer message with the Result-Code AVP set + to indicate that an error occurred. The specific behavior of the Diameter server or client receiving a request depends on the Diameter application employed. @@ -1153,30 +1140,23 @@ Internet-Draft Diameter Base Protocol January 2011 applications. For authentication and authorization, it is always extended for a particular application. - Diameter Clients MUST support the base protocol, which includes + Diameter clients MUST support the base protocol, which includes accounting. In addition, they MUST fully support each Diameter application that is needed to implement the client's service, e.g., - NASREQ and/or Mobile IPv4. A Diameter Client MUST be referred to as - "Diameter X Client" where X is the application which it supports, and - not a "Diameter Client". + Network Access Server Requirements (NASREQ) [RFC2881] and/or Mobile + IPv4. A Diameter client MUST be referred to as "Diameter X Client" + where X is the application that it supports and not a "Diameter + Client". - Diameter Servers MUST support the base protocol, which includes + Diameter servers MUST support the base protocol, which includes accounting. In addition, they MUST fully support each Diameter application that is needed to implement the intended service, e.g., - NASREQ and/or Mobile IPv4. A Diameter Server MUST be referred to as - "Diameter X Server" where X is the application which it supports, and + NASREQ and/or Mobile IPv4. A Diameter server MUST be referred to as + "Diameter X Server" where X is the application that it supports, and not a "Diameter Server". - Diameter Relays and redirect agents are transparent to the Diameter - applications but they MUST support the Diameter base protocol, which - - - -Fajardo, et al. Expires July 24, 2011 [Page 21] - -Internet-Draft Diameter Base Protocol January 2011 - - + Diameter relays and redirect agents are transparent to the Diameter + applications, but they MUST support the Diameter base protocol, which includes accounting, and all Diameter applications. Diameter proxies MUST support the base protocol, which includes @@ -1186,55 +1166,75 @@ Internet-Draft Diameter Base Protocol January 2011 "Diameter X Proxy" where X is the application which it supports, and not a "Diameter Proxy". + + + + + + + + + +Fajardo, et al. Standards Track [Page 21] + +RFC 6733 Diameter Base Protocol October 2012 + + 2.1. Transport The Diameter Transport profile is defined in [RFC3539]. - The base Diameter protocol is run on port 3868 for both TCP [RFC793] - and SCTP [RFC4960]. For TLS [RFC5246] and DTLS [RFC4347], a Diameter - node that initiate a connection prior to any message exchanges MUST - run on port [TBD]. It is assumed that TLS is run on top of TCP when - it is used and DTLS is run on top of SCTP when it is used. + The base Diameter protocol is run on port 3868 for both TCP [RFC0793] + and SCTP [RFC4960]. For TLS [RFC5246] and Datagram Transport Layer + Security (DTLS) [RFC6347], a Diameter node that initiates a + connection prior to any message exchanges MUST run on port 5658. It + is assumed that TLS is run on top of TCP when it is used, and DTLS is + run on top of SCTP when it is used. If the Diameter peer does not support receiving TLS/TCP and DTLS/SCTP - connections on port [TBD], i.e. the peer complies only with - [RFC3588], then the initiator MAY revert to using TCP or SCTP and on - port 3868. Note that this scheme is kept for the purpose of - backwards compatibility only and that there are inherent security - vulnerabilities when the initial CER/CEA messages are sent un- - protected (see Section 5.6). + connections on port 5658 (i.e., the peer complies only with RFC + 3588), then the initiator MAY revert to using TCP or SCTP on port + 3868. Note that this scheme is kept only for the purpose of backward + compatibility and that there are inherent security vulnerabilities + when the initial CER/CEA messages are sent unprotected (see + Section 5.6). - Diameter clients MUST support either TCP or SCTP, while agents and - servers SHOULD support both. + Diameter clients MUST support either TCP or SCTP; agents and servers + SHOULD support both. A Diameter node MAY initiate connections from a source port other than the one that it declares it accepts incoming connections on, and - MUST be prepared to receive connections on port 3868 for TCP or SCTP - and port [TBD] for TLS/TCP and DTLS/SCTP connections. A given - Diameter instance of the peer state machine MUST NOT use more than - one transport connection to communicate with a given peer, unless - multiple instances exist on the peer in which case a separate - connection per process is allowed. + it MUST always be prepared to receive connections on port 3868 for + TCP or SCTP and port 5658 for TLS/TCP and DTLS/SCTP connections. + When DNS-based peer discovery (Section 5.2) is used, the port numbers + received from SRV records take precedence over the default ports + (3868 and 5658). + + A given Diameter instance of the peer state machine MUST NOT use more + than one transport connection to communicate with a given peer, + unless multiple instances exist on the peer, in which, case a + separate connection per process is allowed. When no transport connection exists with a peer, an attempt to - connect SHOULD be periodically made. This behavior is handled via + connect SHOULD be made periodically. This behavior is handled via the Tc timer (see Section 12 for details), whose recommended value is 30 seconds. There are certain exceptions to this rule, such as when a peer has terminated the transport connection stating that it does not wish to communicate. When connecting to a peer and either zero or more transports are - specified, TLS SHOULD be tried first, followed by DTLS, then by TCP + specified, TLS SHOULD be tried first, followed by DTLS, then by TCP, + and finally by SCTP. See Section 5.2 for more information on peer + discovery. -Fajardo, et al. Expires July 24, 2011 [Page 22] - -Internet-Draft Diameter Base Protocol January 2011 - and finally by SCTP. See Section 5.2 for more information on peer - discovery. +Fajardo, et al. Standards Track [Page 22] + +RFC 6733 Diameter Base Protocol October 2012 + Diameter implementations SHOULD be able to interpret ICMP protocol port unreachable messages as explicit indications that the server is @@ -1253,18 +1253,18 @@ Internet-Draft Diameter Base Protocol January 2011 Diameter messages SHOULD be mapped into SCTP streams in a way that avoids head-of-the-line (HOL) blocking. Among different ways of performing the mapping that fulfill this requirement it is - RECOMMENDED that a Diameter node sends every Diameter message - (request or response) over the stream zero with the unordered flag - set. However, Diameter nodes MAY select and implement other design - alternatives for avoiding HOL blocking such as using multiple streams - with the unordered flag cleared (as originally instructed in - RFC3588). On the receiving side, a Diameter entity MUST be ready to - receive Diameter messages over any stream and it is free to return - responses over a different stream. This way, both sides manage the - available streams in the sending direction, independently of the - streams chosen by the other side to send a particular Diameter - message. These messages can be out-of-order and belong to different - Diameter sessions. + RECOMMENDED that a Diameter node send every Diameter message (request + or response) over stream zero with the unordered flag set. However, + Diameter nodes MAY select and implement other design alternatives for + avoiding HOL blocking such as using multiple streams with the + unordered flag cleared (as originally instructed in RFC 3588). On + the receiving side, a Diameter entity MUST be ready to receive + Diameter messages over any stream, and it is free to return responses + over a different stream. This way, both sides manage the available + streams in the sending direction, independently of the streams chosen + by the other side to send a particular Diameter message. These + messages can be out-of-order and belong to different Diameter + sessions. Out-of-order delivery has special concerns during a connection establishment and termination. When a connection is established, the @@ -1275,30 +1275,37 @@ Internet-Draft Diameter Base Protocol January 2011 the connection. In order to avoid this race condition, the receiver side SHOULD NOT use out-of-order delivery methods until the first message has been received from the initiator, proving that it has - moved to I-Open state. To trigger such message, the receiver side - could send a DWR immediatly after sending CEA. Upon reception of the - corresponding DWA, the receiver side should start using out-of-order - delivery methods to counter the HOL blocking. + moved to I-Open state. To trigger such a message, the receiver side + could send a DWR immediately after sending a CEA. Upon reception of + the corresponding DWA, the receiver side should start using out-of- + order delivery methods to counter the HOL blocking. Another race condition may occur when DPR and DPA messages are used. + Both DPR and DPA are small in size; thus, they may be delivered to + the peer faster than application messages when an out-of-order + delivery mechanism is used. Therefore, it is possible that a DPR/DPA -Fajardo, et al. Expires July 24, 2011 [Page 23] +Fajardo, et al. Standards Track [Page 23] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 + + exchange completes while application messages are still in transit, + resulting in a loss of these messages. An implementation could + mitigate this race condition, for example, using timers, and wait for + a short period of time for pending application level messages to + arrive before proceeding to disconnect the transport connection. + Eventually, lost messages are handled by the retransmission mechanism + described in Section 5.5.4. - Both DPR and DPA are small in size, thus they may be delivered faster - to the peer than application messages when out-of-order delivery - mechanism is used. Therefore, it is possible that a DPR/DPA exchange - completes while application messages are still in transit, resulting - to a loss of these messages. An implementation could mitigate this - race condition, for example, using timers and wait for a short period - of time for pending application level messages to arrive before - proceeding to disconnect the transport connection. Eventually, lost - messages are handled by the retransmission mechanism described in - Section 5.5.4. + A Diameter agent SHOULD use dedicated payload protocol identifiers + (PPIDs) for clear text and encrypted SCTP DATA chunks instead of only + using the unspecified payload protocol identifier (value 0). For + this purpose, two PPID values are allocated: the PPID value 46 is for + Diameter messages in clear text SCTP DATA chunks, and the PPID value + 47 is for Diameter messages in protected DTLS/SCTP DATA chunks. 2.2. Securing Diameter Messages @@ -1307,7 +1314,7 @@ Internet-Draft Diameter Base Protocol January 2011 the use of TLS/TCP and DTLS/SCTP. If desired, alternative security mechanisms that are independent of Diameter, such as IPsec [RFC4301], can be deployed to secure connections between peers. The Diameter - protocol MUST NOT be used without any security mechanism. + protocol MUST NOT be used without one of TLS, DTLS, or IPsec. 2.3. Diameter Application Compliance @@ -1318,37 +1325,40 @@ Internet-Draft Diameter Base Protocol January 2011 Implementations MAY add arbitrary optional AVPs with the M-bit cleared (including vendor-specific AVPs) to a command defined in an - application, but only if the command's ABNF syntax specification + application, but only if the command's CCF syntax specification allows for it. Please refer to Section 11.1.1 for details. 2.4. Application Identifiers - Each Diameter application MUST have an IANA assigned Application Id - (see Section 11.3). The base protocol does not require an - Application Id since its support is mandatory. During the - capabilities exchange, Diameter nodes inform their peers of locally - supported applications. Furthermore, all Diameter messages contain - an Application Id, which is used in the message forwarding process. + Each Diameter application MUST have an IANA-assigned Application ID. + The base protocol does not require an Application Id since its + support is mandatory. During the capabilities exchange, Diameter + nodes inform their peers of locally supported applications. + Furthermore, all Diameter messages contain an Application Id, which + is used in the message forwarding process. - The following Application Id values are defined: - Diameter Common Messages 0 - Diameter Base Accounting 3 - Relay 0xffffffff - Relay and redirect agents MUST advertise the Relay Application -Fajardo, et al. Expires July 24, 2011 [Page 24] + +Fajardo, et al. Standards Track [Page 24] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 + + The following Application Id values are defined: + + Diameter common message 0 + Diameter base accounting 3 + Relay 0xffffffff - Identifier, while all other Diameter nodes MUST advertise locally - supported applications. The receiver of a Capabilities Exchange - message advertising Relay service MUST assume that the sender - supports all current and future applications. + Relay and redirect agents MUST advertise the Relay Application ID, + while all other Diameter nodes MUST advertise locally supported + applications. The receiver of a Capabilities Exchange message + advertising relay service MUST assume that the sender supports all + current and future applications. Diameter relay and proxy agents are responsible for finding an upstream server that supports the application of a particular @@ -1358,16 +1368,15 @@ Internet-Draft Diameter Base Protocol January 2011 2.5. Connections vs. Sessions This section attempts to provide the reader with an understanding of - the difference between connection and session, which are terms used - extensively throughout this document. + the difference between "connection" and "session", which are terms + used extensively throughout this document. - A connection refers to a transport level connection between two peers + A connection refers to a transport-level connection between two peers that is used to send and receive Diameter messages. A session is a - logical concept at the application layer existing between the + logical concept at the application layer that exists between the Diameter client and the Diameter server; it is identified via the Session-Id AVP. - +--------+ +-------+ +--------+ | Client | | Relay | | Server | +--------+ +-------+ +--------+ @@ -1377,100 +1386,93 @@ Internet-Draft Diameter Base Protocol January 2011 <-----------------------------> User session x - Figure 1: Diameter connections and sessions + Figure 1: Diameter Connections and Sessions In the example provided in Figure 1, peer connection A is established - between the Client and the Relay. Peer connection B is established - between the Relay and the Server. User session X spans from the - Client via the Relay to the Server. Each "user" of a service causes + between the client and the relay. Peer connection B is established + between the relay and the server. User session X spans from the + client via the relay to the server. Each "user" of a service causes an auth request to be sent, with a unique session identifier. Once accepted by the server, both the client and the server are aware of the session. - It is important to note that there is no relationship between a - connection and a session, and that Diameter messages for multiple - sessions are all multiplexed through a single connection. Also note - that Diameter messages pertaining to the session, both application - specific and those that are defined in this document such as ASR/ASA, - RAR/RAA and STR/STA MUST carry the Application Id of the application. -Fajardo, et al. Expires July 24, 2011 [Page 25] +Fajardo, et al. Standards Track [Page 25] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 - Diameter messages pertaining to peer connection establishment and - maintenance such as CER/CEA, DWR/DWA and DPR/DPA MUST carry an - Application Id of zero (0). + It is important to note that there is no relationship between a + connection and a session, and that Diameter messages for multiple + sessions are all multiplexed through a single connection. Also, note + that Diameter messages pertaining to the session, both application- + specific and those that are defined in this document such as ASR/ASA, + RAR/RAA, and STR/STA, MUST carry the Application Id of the + application. Diameter messages pertaining to peer connection + establishment and maintenance such as CER/CEA, DWR/DWA, and DPR/DPA + MUST carry an Application Id of zero (0). 2.6. Peer Table - The Diameter Peer Table is used in message forwarding, and referenced - by the Routing Table. A Peer Table entry contains the following - fields: + The Diameter peer table is used in message forwarding and is + referenced by the routing table. A peer table entry contains the + following fields: - Host identity + Host Identity - Following the conventions described for the DiameterIdentity - derived AVP data format in Section 4.3. This field contains the + Following the conventions described for the DiameterIdentity- + derived AVP data format in Section 4.3.1, this field contains the contents of the Origin-Host (Section 6.3) AVP found in the CER or CEA message. - StatusT - This is the state of the peer entry, and MUST match one of the + This is the state of the peer entry, and it MUST match one of the values listed in Section 5.6. - Static or Dynamic Specifies whether a peer entry was statically configured or dynamically discovered. - - Expiration time + Expiration Time Specifies the time at which dynamically discovered peer table - entries are to be either refreshed, or expired. - + entries are to be either refreshed or expired. If public key + certificates are used for Diameter security (e.g., with TLS), this + value MUST NOT be greater than the expiry times in the relevant + certificates. TLS/TCP and DTLS/SCTP Enabled Specifies whether TLS/TCP and DTLS/SCTP is to be used when communicating with the peer. - Additional security information, when needed (e.g., keys, - certificates) - - + certificates). - - -Fajardo, et al. Expires July 24, 2011 [Page 26] +Fajardo, et al. Standards Track [Page 26] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 2.7. Routing Table All Realm-Based routing lookups are performed against what is - commonly known as the Routing Table (see Section 12). A Routing - Table Entry contains the following fields: + commonly known as the routing table (see Section 12). Each routing + table entry contains the following fields: Realm Name - This is the field that is MUST be used as a primary key in the + This is the field that MUST be used as a primary key in the routing table lookups. Note that some implementations perform their lookups based on longest-match-from-the-right on the realm rather than requiring an exact match. - Application Identifier An application is identified by an Application Id. A route entry @@ -1478,21 +1480,19 @@ Internet-Draft Diameter Base Protocol January 2011 the message header. This field MUST be used as a secondary key field in routing table lookups. - Local Action The Local Action field is used to identify how a message should be treated. The following actions are supported: - - 1. LOCAL - Diameter messages that can be satisfied locally, and - do not need to be routed to another Diameter entity. + 1. LOCAL - Diameter messages that can be satisfied locally and do + not need to be routed to another Diameter entity. 2. RELAY - All Diameter messages that fall within this category - MUST be routed to a next hop Diameter entity that is indicated + MUST be routed to a next-hop Diameter entity that is indicated by the identifier described below. Routing is done without modifying any non-routing AVPs. See Section 6.1.9 for - relaying guidelines + relaying guidelines. 3. PROXY - All Diameter messages that fall within this category MUST be routed to a next Diameter entity that is indicated by @@ -1504,47 +1504,53 @@ Internet-Draft Diameter Base Protocol January 2011 4. REDIRECT - Diameter messages that fall within this category MUST have the identity of the home Diameter server(s) appended, and returned to the sender of the message. See - Section 6.1.8 for redirect guidelines. + Section 6.1.8 for redirection guidelines. + + + -Fajardo, et al. Expires July 24, 2011 [Page 27] +Fajardo, et al. Standards Track [Page 27] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 Server Identifier - One or more servers to which the message is to be routed. These - servers MUST also be present in the Peer table. When the Local - Action is set to RELAY or PROXY, this field contains the identity - of the server(s) the message MUST be routed to. When the Local + The identity of one or more servers to which the message is to be + routed. This identity MUST also be present in the Host Identity + field of the peer table (Section 2.6). When the Local Action is + set to RELAY or PROXY, this field contains the identity of the + server(s) to which the message MUST be routed. When the Local Action field is set to REDIRECT, this field contains the identity - of one or more servers the message MUST be redirected to. + of one or more servers to which the message MUST be redirected. Static or Dynamic Specifies whether a route entry was statically configured or dynamically discovered. - Expiration time + Expiration Time Specifies the time at which a dynamically discovered route table - entry expires. + entry expires. If public key certificates are used for Diameter + security (e.g., with TLS), this value MUST NOT be greater than the + expiry time in the relevant certificates. It is important to note that Diameter agents MUST support at least - one of the LOCAL, RELAY, PROXY or REDIRECT modes of operation. + one of the LOCAL, RELAY, PROXY, or REDIRECT modes of operation. Agents do not need to support all modes of operation in order to - conform with the protocol specification, but MUST follow the protocol - compliance guidelines in Section 2. Relay agents and proxies MUST - NOT reorder AVPs. + conform with the protocol specification, but they MUST follow the + protocol compliance guidelines in Section 2. Relay agents and + proxies MUST NOT reorder AVPs. The routing table MAY include a default entry that MUST be used for any requests not matching any of the other entries. The routing table MAY consist of only such an entry. When a request is routed, the target server MUST have advertised the - Application Id (see Section 2.4) for the given message, or have + Application Id (see Section 2.4) for the given message or have advertised itself as a relay or proxy agent. Otherwise, an error is returned with the Result-Code AVP set to DIAMETER_UNABLE_TO_DELIVER. @@ -1552,23 +1558,24 @@ Internet-Draft Diameter Base Protocol January 2011 In addition to clients and servers, the Diameter protocol introduces relay, proxy, redirect, and translation agents, each of which is - defined in Section 1.3. These Diameter agents are useful for several + defined in Section 1.2. Diameter agents are useful for several reasons: o They can distribute administration of systems to a configurable grouping, including the maintenance of security associations. - o They can be used for concentration of requests from an number of - co-located or distributed NAS equipment sets to a set of like user - groups. -Fajardo, et al. Expires July 24, 2011 [Page 28] +Fajardo, et al. Standards Track [Page 28] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 + o They can be used for concentration of requests from a number of + co-located or distributed NAS equipment sets to a set of like user + groups. + o They can do value-added processing to the requests or responses. o They can be used for load balancing. @@ -1578,7 +1585,7 @@ Internet-Draft Diameter Base Protocol January 2011 The Diameter protocol requires that agents maintain transaction state, which is used for failover purposes. Transaction state - implies that upon forwarding a request, its Hop-by-Hop identifier is + implies that upon forwarding a request, its Hop-by-Hop Identifier is saved; the field is replaced with a locally unique identifier, which is restored to its original value when the corresponding answer is received. The request's state is released upon receipt of the @@ -1593,7 +1600,7 @@ Internet-Draft Diameter Base Protocol January 2011 A stateful agent is one that maintains session state information by keeping track of all authorized active sessions. Each authorized session is bound to a particular service, and its state is considered - active either until the agent is notified otherwise, or the session + active until either the agent is notified otherwise or the session expires. Each authorized session has an expiration, which is communicated by Diameter servers via the Session-Timeout AVP. @@ -1604,40 +1611,43 @@ Internet-Draft Diameter Base Protocol January 2011 o Limiting resources authorized to a particular user - o Per user or transaction auditing + o Per-user or per-transaction auditing A Diameter agent MAY act in a stateful manner for some requests and be stateless for others. A Diameter implementation MAY act as one - type of agent for some requests, and as another type of agent for + type of agent for some requests and as another type of agent for others. -2.8.1. Relay Agents - Relay Agents are Diameter agents that accept requests and route - messages to other Diameter nodes based on information found in the - messages (e.g., Destination-Realm). This routing decision is - performed using a list of supported realms, and known peers. This is -Fajardo, et al. Expires July 24, 2011 [Page 29] + +Fajardo, et al. Standards Track [Page 29] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 + +2.8.1. Relay Agents - known as the Routing Table, as is defined further in Section 2.7. + Relay agents are Diameter agents that accept requests and route + messages to other Diameter nodes based on information found in the + messages (e.g., the value of the Destination-Realm AVP Section 6.6). + This routing decision is performed using a list of supported realms + and known peers. This is known as the routing table, as is defined + further in Section 2.7. Relays may, for example, be used to aggregate requests from multiple Network Access Servers (NASes) within a common geographical area - (POP). The use of Relays is advantageous since it eliminates the - need for NASes to be configured with the necessary security - information they would otherwise require to communicate with Diameter - servers in other realms. Likewise, this reduces the configuration - load on Diameter servers that would otherwise be necessary when NASes - are added, changed or deleted. + (Point of Presence, POP). The use of relays is advantageous since it + eliminates the need for NASes to be configured with the necessary + security information they would otherwise require to communicate with + Diameter servers in other realms. Likewise, this reduces the + configuration load on Diameter servers that would otherwise be + necessary when NASes are added, changed, or deleted. Relays modify Diameter messages by inserting and removing routing - information, but do not modify any other portion of a message. + information, but they do not modify any other portion of a message. Relays SHOULD NOT maintain session state but MUST maintain transaction state. @@ -1650,44 +1660,46 @@ Internet-Draft Diameter Base Protocol January 2011 Figure 2: Relaying of Diameter messages - The example provided in Figure 2 depicts a request issued from NAS, + The example provided in Figure 2 depicts a request issued from a NAS, which is an access device, for the user [email protected]. Prior to - issuing the request, NAS performs a Diameter route lookup, using + issuing the request, the NAS performs a Diameter route lookup, using "example.com" as the key, and determines that the message is to be - relayed to DRL, which is a Diameter Relay. DRL performs the same - route lookup as NAS, and relays the message to HMS, which is - example.com's Home Diameter Server. HMS identifies that the request - can be locally supported (via the realm), processes the + relayed to a DRL, which is a Diameter relay. The DRL performs the + same route lookup as the NAS, and relays the message to the HMS, + which is example.com's home server. The HMS identifies that the + request can be locally supported (via the realm), processes the authentication and/or authorization request, and replies with an - answer, which is routed back to NAS using saved transaction state. - - Since Relays do not perform any application level processing, they - provide relaying services for all Diameter applications, and - therefore MUST advertise the Relay Application Id. + answer, which is routed back to the NAS using saved transaction + state. -2.8.2. Proxy Agents + Since relays do not perform any application-level processing, they + provide relaying services for all Diameter applications; therefore, + they MUST advertise the Relay Application Id. - Similarly to relays, proxy agents route Diameter messages using the - Diameter Routing Table. However, they differ since they modify - messages to implement policy enforcement. This requires that proxies - maintain the state of their downstream peers (e.g., access devices) - to enforce resource usage, provide admission control, and - provisioning. -Fajardo, et al. Expires July 24, 2011 [Page 30] +Fajardo, et al. Standards Track [Page 30] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 + +2.8.2. Proxy Agents + + Similar to relays, proxy agents route Diameter messages using the + Diameter routing table. However, they differ since they modify + messages to implement policy enforcement. This requires that proxies + maintain the state of their downstream peers (e.g., access devices) + to enforce resource usage, provide admission control, and provide + provisioning. Proxies may, for example, be used in call control centers or access - ISPs that provide outsourced connections, they can monitor the number - and types of ports in use, and make allocation and admission - decisions according to their configuration. + ISPs that provide outsourced connections; they can monitor the number + and type of ports in use and make allocation and admission decisions + according to their configuration. Since enforcing policies requires an understanding of the service - being provided, Proxies MUST only advertise the Diameter applications + being provided, proxies MUST only advertise the Diameter applications they support. 2.8.3. Redirect Agents @@ -1709,18 +1721,12 @@ Internet-Draft Diameter Base Protocol January 2011 The example provided in Figure 3 depicts a request issued from the access device, NAS, for the user [email protected]. The message is forwarded by the NAS to its relay, DRL, which does not have a routing - entry in its Diameter Routing Table for example.com. DRL has a + entry in its Diameter routing table for example.com. The DRL has a default route configured to DRD, which is a redirect agent that - returns a redirect notification to DRL, as well as HMS' contact - information. Upon receipt of the redirect notification, DRL - establishes a transport connection with HMS, if one doesn't already - exist, and forwards the request to it. - - - - - - + returns a redirect notification to DRL, as well as the HMS' contact + information. Upon receipt of the redirect notification, the DRL + establishes a transport connection with the HMS, if one doesn't + already exist, and forwards the request to it. @@ -1729,12 +1735,9 @@ Internet-Draft Diameter Base Protocol January 2011 - - - -Fajardo, et al. Expires July 24, 2011 [Page 31] +Fajardo, et al. Standards Track [Page 31] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 +------+ @@ -1755,10 +1758,10 @@ Internet-Draft Diameter Base Protocol January 2011 Figure 3: Redirecting a Diameter Message - Since redirect agents do not perform any application level + Since redirect agents do not perform any application-level processing, they provide relaying services for all Diameter - applications, and therefore MUST advertise the Relay Application - Identifier. + applications; therefore, they MUST advertise the Relay Application + ID. 2.8.4. Translation Agents @@ -1773,7 +1776,7 @@ Internet-Draft Diameter Base Protocol January 2011 MUST maintain transaction state. Translation of messages can only occur if the agent recognizes the - application of a particular request, and therefore translation agents + application of a particular request; therefore, translation agents MUST only advertise their locally supported applications. +------+ ---------> +------+ ---------> +------+ @@ -1788,23 +1791,24 @@ Internet-Draft Diameter Base Protocol January 2011 -Fajardo, et al. Expires July 24, 2011 [Page 32] +Fajardo, et al. Standards Track [Page 32] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 2.9. Diameter Path Authorization - As noted in Section 2.2, Diameter provides transmission level + As noted in Section 2.2, Diameter provides transmission-level security for each connection using TLS/TCP and DTLS/SCTP. Therefore, - each connection can be authenticated, replay and integrity protected. + each connection can be authenticated and can be replay and integrity + protected. - In addition to authenticating each connection, each connection as - well as the entire session MUST also be authorized. Before - initiating a connection, a Diameter Peer MUST check that its peers - are authorized to act in their roles. For example, a Diameter peer - may be authentic, but that does not mean that it is authorized to act - as a Diameter Server advertising a set of Diameter applications. + In addition to authenticating each connection, the entire session + MUST also be authorized. Before initiating a connection, a Diameter + peer MUST check that its peers are authorized to act in their roles. + For example, a Diameter peer may be authentic, but that does not mean + that it is authorized to act as a Diameter server advertising a set + of Diameter applications. Prior to bringing up a connection, authorization checks are performed at each connection along the path. Diameter capabilities negotiation @@ -1815,7 +1819,7 @@ Internet-Draft Diameter Base Protocol January 2011 As noted in Section 6.1.9, a relay or proxy agent MUST append a Route-Record AVP to all requests forwarded. The AVP contains the - identity of the peer the request was received from. + identity of the peer from which the request was received. The home Diameter server, prior to authorizing a session, MUST check the Route-Record AVPs to make sure that the route traversed by the @@ -1823,7 +1827,7 @@ Internet-Draft Diameter Base Protocol January 2011 realm may not wish to honor requests that have been routed through an untrusted realm. By authorizing a request, the home Diameter server is implicitly indicating its willingness to engage in the business - transaction as specified by the contractual relationship between the + transaction as specified by any contractual relationship between the server and the previous hop. A DIAMETER_AUTHORIZATION_REJECTED error message (see Section 7.1.5) is sent if the route traversed by the request is unacceptable. @@ -1839,72 +1843,24 @@ Internet-Draft Diameter Base Protocol January 2011 willingness to take on financial risk relative to the session. A local realm may wish to limit this exposure, for example, by establishing credit limits for intermediate realms and refusing to - accept responses which would violate those limits. By issuing an - accounting request corresponding to the authorization response, the + accept responses that would violate those limits. By issuing an -Fajardo, et al. Expires July 24, 2011 [Page 33] +Fajardo, et al. Standards Track [Page 33] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 + accounting request corresponding to the authorization response, the local realm implicitly indicates its agreement to provide the service indicated in the authorization response. If the service cannot be provided by the local realm, then a DIAMETER_UNABLE_TO_COMPLY error message MUST be sent within the accounting request; a Diameter client receiving an authorization response for a service that it cannot - perform MUST NOT substitute an alternate service, and then send + perform MUST NOT substitute an alternate service and then send accounting requests for the alternate service instead. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Fajardo, et al. Expires July 24, 2011 [Page 34] - -Internet-Draft Diameter Base Protocol January 2011 - - 3. Diameter Header A summary of the Diameter header format is shown below. The fields @@ -1915,7 +1871,7 @@ Internet-Draft Diameter Base Protocol January 2011 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Version | Message Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | command flags | Command-Code | + | Command Flags | Command Code | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Application-ID | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -1935,13 +1891,23 @@ Internet-Draft Diameter Base Protocol January 2011 The Message Length field is three octets and indicates the length of the Diameter message including the header fields and the padded - AVPs. Thus the message length field is always a multiple of 4. + AVPs. Thus, the Message Length field is always a multiple of 4. Command Flags The Command Flags field is eight bits. The following bits are assigned: + + + + + +Fajardo, et al. Standards Track [Page 34] + +RFC 6733 Diameter Base Protocol October 2012 + + 0 1 2 3 4 5 6 7 +-+-+-+-+-+-+-+-+ |R P E T r r r r| @@ -1952,127 +1918,113 @@ Internet-Draft Diameter Base Protocol January 2011 If set, the message is a request. If cleared, the message is an answer. - - - - -Fajardo, et al. Expires July 24, 2011 [Page 35] - -Internet-Draft Diameter Base Protocol January 2011 - - P(roxiable) - If set, the message MAY be proxied, relayed or redirected. If + If set, the message MAY be proxied, relayed, or redirected. If cleared, the message MUST be locally processed. - E(rror) If set, the message contains a protocol error, and the message - will not conform to the ABNF described for this command. + will not conform to the CCF described for this command. Messages with the 'E' bit set are commonly referred to as error - messages. This bit MUST NOT be set in request messages. See - Section 7.2. + messages. This bit MUST NOT be set in request messages (see + Section 7.2). - - T(Potentially re-transmitted message) + T(Potentially retransmitted message) This flag is set after a link failover procedure, to aid the removal of duplicate requests. It is set when resending requests not yet acknowledged, as an indication of a possible duplicate due to a link failure. This bit MUST be cleared when - sending a request for the first time, otherwise the sender MUST - set this flag. Diameter agents only need to be concerned about - the number of requests they send based on a single received - request; retransmissions by other entities need not be tracked. - Diameter agents that receive a request with the T flag set, - MUST keep the T flag set in the forwarded request. This flag - MUST NOT be set if an error answer message (e.g., a protocol - error) has been received for the earlier message. It can be - set only in cases where no answer has been received from the - server for a request and the request is sent again. This flag - MUST NOT be set in answer messages. - + sending a request for the first time; otherwise, the sender + MUST set this flag. Diameter agents only need to be concerned + about the number of requests they send based on a single + received request; retransmissions by other entities need not be + tracked. Diameter agents that receive a request with the T + flag set, MUST keep the T flag set in the forwarded request. + This flag MUST NOT be set if an error answer message (e.g., a + protocol error) has been received for the earlier message. It + can be set only in cases where no answer has been received from + the server for a request, and the request has been sent again. + This flag MUST NOT be set in answer messages. r(eserved) - These flag bits are reserved for future use, and MUST be set to - zero, and ignored by the receiver. + These flag bits are reserved for future use; they MUST be set + to zero and ignored by the receiver. - Command-Code - The Command-Code field is three octets, and is used in order to - communicate the command associated with the message. The 24-bit - address space is managed by IANA (see Section 11.2.1). - Command-Code values 16,777,214 and 16,777,215 (hexadecimal values - FFFFFE -FFFFFF) are reserved for experimental use (See Section - 11.3). -Fajardo, et al. Expires July 24, 2011 [Page 36] +Fajardo, et al. Standards Track [Page 35] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 + + + Command Code + The Command Code field is three octets and is used in order to + communicate the command associated with the message. The 24-bit + address space is managed by IANA (see Section 3.1). Command Code + values 16,777,214 and 16,777,215 (hexadecimal values FFFFFE- + FFFFFF) are reserved for experimental use (see Section 11.2). - Application-ID + Application-ID - Application-ID is four octets and is used to identify to which - application the message is applicable for. The application can be - an authentication application, an accounting application or a - vendor specific application. See Section 11.3 for the possible - values that the application-id may use. + Application-ID is four octets and is used to identify for which + application the message is applicable. The application can be an + authentication application, an accounting application, or a + vendor-specific application. - The value of the application-id field in the header MUST be the - same as any relevant application-id AVPs contained in the message. + The value of the Application-ID field in the header MUST be the + same as any relevant Application-Id AVPs contained in the message. Hop-by-Hop Identifier The Hop-by-Hop Identifier is an unsigned 32-bit integer field (in - network byte order) and aids in matching requests and replies. - The sender MUST ensure that the Hop-by-Hop identifier in a request - is unique on a given connection at any given time, and MAY attempt - to ensure that the number is unique across reboots. The sender of - an Answer message MUST ensure that the Hop-by-Hop Identifier field - contains the same value that was found in the corresponding - request. The Hop-by-Hop identifier is normally a monotonically - increasing number, whose start value was randomly generated. An - answer message that is received with an unknown Hop-by-Hop - Identifier MUST be discarded. - + network byte order) that aids in matching requests and replies. + The sender MUST ensure that the Hop-by-Hop Identifier in a request + is unique on a given connection at any given time, and it MAY + attempt to ensure that the number is unique across reboots. The + sender of an answer message MUST ensure that the Hop-by-Hop + Identifier field contains the same value that was found in the + corresponding request. The Hop-by-Hop Identifier is normally a + monotonically increasing number, whose start value was randomly + generated. An answer message that is received with an unknown + Hop-by-Hop Identifier MUST be discarded. End-to-End Identifier The End-to-End Identifier is an unsigned 32-bit integer field (in - network byte order) and is used to detect duplicate messages. - Upon reboot implementations MAY set the high order 12 bits to + network byte order) that is used to detect duplicate messages. + Upon reboot, implementations MAY set the high order 12 bits to contain the low order 12 bits of current time, and the low order 20 bits to a random value. Senders of request messages MUST insert a unique identifier on each message. The identifier MUST remain locally unique for a period of at least 4 minutes, even - across reboots. The originator of an Answer message MUST ensure + across reboots. The originator of an answer message MUST ensure that the End-to-End Identifier field contains the same value that was found in the corresponding request. The End-to-End Identifier MUST NOT be modified by Diameter agents of any kind. The - combination of the Origin-Host (see Section 6.3) and this field is + combination of the Origin-Host AVP (Section 6.3) and this field is used to detect duplicates. Duplicate requests SHOULD cause the - same answer to be transmitted (modulo the hop-by-hop Identifier - field and any routing AVPs that may be present), and MUST NOT - affect any state that was set when the original request was - processed. Duplicate answer messages that are to be locally - consumed (see Section 6.2) SHOULD be silently discarded. - - + same answer to be transmitted (modulo the Hop-by-Hop Identifier -Fajardo, et al. Expires July 24, 2011 [Page 37] +Fajardo, et al. Standards Track [Page 36] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 + field and any routing AVPs that may be present), and they MUST NOT + affect any state that was set when the original request was + processed. Duplicate answer messages that are to be locally + consumed (see Section 6.2) SHOULD be silently discarded. + AVPs AVPs are a method of encapsulating information relevant to the @@ -2080,17 +2032,17 @@ Internet-Draft Diameter Base Protocol January 2011 3.1. Command Codes - Each command Request/Answer pair is assigned a command code, and the + Each command Request/Answer pair is assigned a Command Code, and the sub-type (i.e., request or answer) is identified via the 'R' bit in the Command Flags field of the Diameter header. - - Every Diameter message MUST contain a command code in its header's - Command-Code field, which is used to determine the action that is to + Every Diameter message MUST contain a Command Code in its header's + Command Code field, which is used to determine the action that is to be taken for a particular message. The following Command Codes are defined in the Diameter base protocol: - Command-Name Abbrev. Code Reference + Section + Command Name Abbrev. Code Reference -------------------------------------------------------- Abort-Session-Request ASR 274 8.5.1 Abort-Session-Answer ASA 274 8.5.2 @@ -2111,140 +2063,142 @@ Internet-Draft Diameter Base Protocol January 2011 Session-Termination- STA 275 8.4.2 Answer -3.2. Command Code ABNF specification - Every Command Code defined MUST include a corresponding ABNF - specification, which is used to define the AVPs that MUST or MAY be - present when sending the message. The following format is used in - the definition: - command-def = <command-name> "::=" diameter-message - command-name = diameter-name -Fajardo, et al. Expires July 24, 2011 [Page 38] - -Internet-Draft Diameter Base Protocol January 2011 - diameter-name = ALPHA *(ALPHA / DIGIT / "-") +Fajardo, et al. Standards Track [Page 37] + +RFC 6733 Diameter Base Protocol October 2012 - diameter-message = header [ *fixed] [ *required] [ *optional] - header = "<" "Diameter Header:" command-id - [r-bit] [p-bit] [e-bit] [application-id] ">" +3.2. Command Code Format Specification - application-id = 1*DIGIT + Every Command Code defined MUST include a corresponding Command Code + Format (CCF) specification, which is used to define the AVPs that + MUST or MAY be present when sending the message. The following ABNF + specifies the CCF used in the definition: - command-id = 1*DIGIT - ; The Command Code assigned to the command + command-def = "<" command-name ">" "::=" diameter-message - r-bit = ", REQ" - ; If present, the 'R' bit in the Command - ; Flags is set, indicating that the message - ; is a request, as opposed to an answer. + command-name = diameter-name - p-bit = ", PXY" - ; If present, the 'P' bit in the Command - ; Flags is set, indicating that the message - ; is proxiable. + diameter-name = ALPHA *(ALPHA / DIGIT / "-") - e-bit = ", ERR" - ; If present, the 'E' bit in the Command - ; Flags is set, indicating that the answer - ; message contains a Result-Code AVP in - ; the "protocol error" class. + diameter-message = header *fixed *required *optional - fixed = [qual] "<" avp-spec ">" - ; Defines the fixed position of an AVP + header = "<Diameter-Header:" command-id + [r-bit] [p-bit] [e-bit] [application-id]">" - required = [qual] "{" avp-spec "}" - ; The AVP MUST be present and can appear - ; anywhere in the message. + application-id = 1*DIGIT + command-id = 1*DIGIT + ; The Command Code assigned to the command. - optional = [qual] "[" avp-name "]" - ; The avp-name in the 'optional' rule cannot - ; evaluate to any AVP Name which is included - ; in a fixed or required rule. The AVP can - ; appear anywhere in the message. - ; - ; NOTE: "[" and "]" have a slightly different - ; meaning than in ABNF (RFC 5234]). These braces - ; cannot be used to express optional fixed rules - ; (such as an optional ICV at the end). To do this, - ; the convention is '0*1fixed'. + r-bit = ", REQ" + ; If present, the 'R' bit in the Command + ; Flags is set, indicating that the message + ; is a request as opposed to an answer. + p-bit = ", PXY" + ; If present, the 'P' bit in the Command + ; Flags is set, indicating that the message + ; is proxiable. + e-bit = ", ERR" + ; If present, the 'E' bit in the Command + ; Flags is set, indicating that the answer + ; message contains a Result-Code AVP in + ; the "protocol error" class. + fixed = [qual] "<" avp-spec ">" + ; Defines the fixed position of an AVP. -Fajardo, et al. Expires July 24, 2011 [Page 39] - -Internet-Draft Diameter Base Protocol January 2011 + required = [qual] "{" avp-spec "}" + ; The AVP MUST be present and can appear + ; anywhere in the message. - qual = [min] "*" [max] - ; See ABNF conventions, RFC 5234 Section 4. - ; The absence of any qualifiers depends on - ; whether it precedes a fixed, required, or - ; optional rule. If a fixed or required rule has - ; no qualifier, then exactly one such AVP MUST - ; be present. If an optional rule has no - ; qualifier, then 0 or 1 such AVP may be - ; present. If an optional rule has a qualifier, - ; then the value of min MUST be 0 if present. - min = 1*DIGIT - ; The minimum number of times the element may - ; be present. If absent, the default value is zero - ; for fixed and optional rules and one for required - ; rules. The value MUST be at least one for for - ; required rules. - max = 1*DIGIT - ; The maximum number of times the element may - ; be present. If absent, the default value is - ; infinity. A value of zero implies the AVP MUST - ; NOT be present. - avp-spec = diameter-name - ; The avp-spec has to be an AVP Name, defined - ; in the base or extended Diameter - ; specifications. - - avp-name = avp-spec / "AVP" - ; The string "AVP" stands for *any* arbitrary AVP - ; Name, not otherwise listed in that command code - ; definition. Addition this AVP is recommended for - ; all command ABNFs to allow for extensibility. +Fajardo, et al. Standards Track [Page 38] + +RFC 6733 Diameter Base Protocol October 2012 - The following is a definition of a fictitious command code: + optional = [qual] "[" avp-name "]" + ; The avp-name in the 'optional' rule cannot + ; evaluate to any AVP Name that is included + ; in a fixed or required rule. The AVP can + ; appear anywhere in the message. + ; + ; NOTE: "[" and "]" have a slightly different + ; meaning than in ABNF. These braces + ; cannot be used to express optional fixed rules + ; (such as an optional ICV at the end). To do + ; this, the convention is '0*1fixed'. - Example-Request ::= < Diameter Header: 9999999, REQ, PXY > - { User-Name } - * { Origin-Host } - * [ AVP ] + qual = [min] "*" [max] + ; See ABNF conventions, RFC 5234, Section 4. + ; The absence of any qualifier depends on + ; whether it precedes a fixed, required, or + ; optional rule. If a fixed or required rule has + ; no qualifier, then exactly one such AVP MUST + ; be present. If an optional rule has no + ; qualifier, then 0 or 1 such AVP may be + ; present. If an optional rule has a qualifier, + ; then the value of min MUST be 0 if present. + min = 1*DIGIT + ; The minimum number of times the element may + ; be present. If absent, the default value is 0 + ; for fixed and optional rules and 1 for + ; required rules. The value MUST be at least 1 + ; for required rules. + max = 1*DIGIT + ; The maximum number of times the element may + ; be present. If absent, the default value is + ; infinity. A value of 0 implies the AVP MUST + ; NOT be present. + avp-spec = diameter-name + ; The avp-spec has to be an AVP Name, defined + ; in the base or extended Diameter + ; specifications. + avp-name = avp-spec / "AVP" + ; The string "AVP" stands for *any* arbitrary AVP + ; Name, not otherwise listed in that Command Code + ; definition. The inclusion of this string + ; is recommended for all CCFs to allow for + ; extensibility. -Fajardo, et al. Expires July 24, 2011 [Page 40] +Fajardo, et al. Standards Track [Page 39] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 + + + The following is a definition of a fictitious Command Code: + Example-Request ::= < Diameter Header: 9999999, REQ, PXY > + { User-Name } + 1* { Origin-Host } + * [ AVP ] 3.3. Diameter Command Naming Conventions Diameter command names typically includes one or more English words - followed by the verb Request or Answer. Each English word is + followed by the verb "Request" or "Answer". Each English word is delimited by a hyphen. A three-letter acronym for both the request and answer is also normally provided. @@ -2253,10 +2207,10 @@ Internet-Draft Diameter Base Protocol January 2011 the acronyms are STR and STA, respectively. Both the request and the answer for a given command share the same - command code. The request is identified by the R(equest) bit in the + Command Code. The request is identified by the R(equest) bit in the Diameter header set to one (1), to ask that a particular action be performed, such as authorizing a user or terminating a session. Once - the receiver has completed the request it issues the corresponding + the receiver has completed the request, it issues the corresponding answer, which includes a result code that communicates one of the following: @@ -2274,38 +2228,25 @@ Internet-Draft Diameter Base Protocol January 2011 Additional information, encoded within AVPs, may also be included in answer messages. +4. Diameter AVPs + Diameter AVPs carry specific authentication, accounting, + authorization, and routing information as well as configuration + details for the request and reply. - - - - - - - - - - - -Fajardo, et al. Expires July 24, 2011 [Page 41] +Fajardo, et al. Standards Track [Page 40] -Internet-Draft Diameter Base Protocol January 2011 - - -4. Diameter AVPs +RFC 6733 Diameter Base Protocol October 2012 - Diameter AVPs carry specific authentication, accounting, - authorization and routing information as well as configuration - details for the request and reply. Each AVP of type OctetString MUST be padded to align on a 32-bit boundary, while other AVP types align naturally. A number of zero- - valued bytes are added to the end of the AVP Data field till a word + valued bytes are added to the end of the AVP Data field until a word boundary is reached. The length of the padding is not reflected in the AVP Length field. @@ -2330,92 +2271,96 @@ Internet-Draft Diameter Base Protocol January 2011 The AVP Code, combined with the Vendor-Id field, identifies the attribute uniquely. AVP numbers 1 through 255 are reserved for - re-use of RADIUS attributes, without setting the Vendor-Id field. + reuse of RADIUS attributes, without setting the Vendor-Id field. AVP numbers 256 and above are used for Diameter, which are - allocated by IANA (see Section 11.1). - + allocated by IANA (see Section 11.1.1). AVP Flags The AVP Flags field informs the receiver how each attribute must - be handled. The 'r' (reserved) bits are unused and SHOULD be set - to 0. Note that subsequent Diameter applications MAY define - additional bits within the AVP Header, and an unrecognized bit - SHOULD be considered an error. The 'P' bit has been reserved for - future usage of end-to-end security. At the time of writing there - are no end-to-end security mechanisms specified therefore the 'P' - bit SHOULD be set to 0. + be handled. New Diameter applications SHOULD NOT define + additional AVP Flag bits. However, note that new Diameter + applications MAY define additional bits within the AVP header, and + an unrecognized bit SHOULD be considered an error. The sender of + the AVP MUST set 'R' (reserved) bits to 0 and the receiver SHOULD + ignore all 'R' (reserved) bits. The 'P' bit has been reserved for + future usage of end-to-end security. At the time of writing, + there are no end-to-end security mechanisms specified; therefore, + the 'P' bit SHOULD be set to 0. + + The 'M' bit, known as the Mandatory bit, indicates whether the + receiver of the AVP MUST parse and understand the semantics of the + AVP including its content. The receiving entity MUST return an + appropriate error message if it receives an AVP that has the M-bit -Fajardo, et al. Expires July 24, 2011 [Page 42] +Fajardo, et al. Standards Track [Page 41] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 - The 'M' Bit, known as the Mandatory bit, indicates whether the - receiver of the AVP MUST parse and understand the semantic of the - AVP including its content. The receiving entity MUST return an - appropriate error message if it receives an AVP that has the M-bit set but does not understand it. An exception applies when the AVP is embedded within a Grouped AVP. See Section 4.4 for details. - Diameter Relay and redirect agents MUST NOT reject messages with + Diameter relay and redirect agents MUST NOT reject messages with unrecognized AVPs. The 'M' bit MUST be set according to the rules defined in the - application specification which introduces or re-uses this AVP. - Within a given application, the M-bit setting for an AVP is either - defined for all command types or for each command type. + application specification that introduces or reuses this AVP. + Within a given application, the M-bit setting for an AVP is + defined either for all command types or for each command type. - AVPs with the 'M' bit cleared are informational only and a - receiver that receives a message with such an AVP that is not - supported, or whose value is not supported, MAY simply ignore the - AVP. + AVPs with the 'M' bit cleared are informational only; a receiver + that receives a message with such an AVP that is not supported, or + whose value is not supported, MAY simply ignore the AVP. The 'V' bit, known as the Vendor-Specific bit, indicates whether the optional Vendor-ID field is present in the AVP header. When - set the AVP Code belongs to the specific vendor code address + set, the AVP Code belongs to the specific vendor code address space. AVP Length The AVP Length field is three octets, and indicates the number of - octets in this AVP including the AVP Code, AVP Length, AVP Flags, - Vendor-ID field (if present) and the AVP data. If a message is - received with an invalid attribute length, the message MUST be - rejected. + octets in this AVP including the AVP Code field, AVP Length field, + AVP Flags field, Vendor-ID field (if present), and the AVP Data + field. If a message is received with an invalid attribute length, + the message MUST be rejected. 4.1.1. Optional Header Elements - The AVP Header contains one optional field. This field is only + The AVP header contains one optional field. This field is only present if the respective bit-flag is enabled. - Vendor-ID The Vendor-ID field is present if the 'V' bit is set in the AVP Flags field. The optional four-octet Vendor-ID field contains the - IANA assigned "SMI Network Management Private Enterprise Codes" - [RFC3232] value, encoded in network byte order. Any vendor or - standardization organization that are also treated like vendors in - the IANA managed "SMI Network Management Private Enterprise Codes" - space wishing to implement a vendor-specific Diameter AVP MUST use - their own Vendor-ID along with their privately managed AVP address + IANA-assigned "SMI Network Management Private Enterprise Codes" + [ENTERPRISE] value, encoded in network byte order. Any vendors or + standardization organizations that are also treated like vendors + in the IANA-managed "SMI Network Management Private Enterprise + Codes" space wishing to implement a vendor-specific Diameter AVP + MUST use their own Vendor-ID along with their privately managed + AVP address space, guaranteeing that they will not collide with + any other vendor's vendor-specific AVP(s) or with future IETF + AVPs. -Fajardo, et al. Expires July 24, 2011 [Page 43] - -Internet-Draft Diameter Base Protocol January 2011 - space, guaranteeing that they will not collide with any other - vendor's vendor-specific AVP(s), nor with future IETF AVPs. - A vendor ID value of zero (0) corresponds to the IETF adopted AVP - values, as managed by the IANA. Since the absence of the vendor - ID field implies that the AVP in question is not vendor specific, - implementations MUST NOT use the zero (0) vendor ID. +Fajardo, et al. Standards Track [Page 42] + +RFC 6733 Diameter Base Protocol October 2012 + + + A Vendor-ID value of zero (0) corresponds to the IETF-adopted AVP + values, as managed by IANA. Since the absence of the Vendor-ID + field implies that the AVP in question is not vendor specific, + implementations MUST NOT use the value of zero (0) for the + Vendor-ID field. 4.2. Basic AVP Data Formats @@ -2426,49 +2371,45 @@ Internet-Draft Diameter Base Protocol January 2011 type derived from the base data types. In the event that a new Basic AVP Data Format is needed, a new version of this RFC MUST be created. - OctetString The data contains arbitrary data of variable length. Unless otherwise noted, the AVP Length field MUST be set to at least 8 - (12 if the 'V' bit is enabled). AVP Values of this type that are - not a multiple of four-octets in length is followed by the - necessary padding so that the next AVP (if any) will start on a - 32-bit boundary. - + (12 if the 'V' bit is enabled). AVP values of this type that are + not a multiple of 4 octets in length are followed by the necessary + padding so that the next AVP (if any) will start on a 32-bit + boundary. Integer32 - 32 bit signed value, in network byte order. The AVP Length field + 32-bit signed value, in network byte order. The AVP Length field MUST be set to 12 (16 if the 'V' bit is enabled). - Integer64 - 64 bit signed value, in network byte order. The AVP Length field + 64-bit signed value, in network byte order. The AVP Length field MUST be set to 16 (20 if the 'V' bit is enabled). - Unsigned32 - 32 bit unsigned value, in network byte order. The AVP Length + 32-bit unsigned value, in network byte order. The AVP Length field MUST be set to 12 (16 if the 'V' bit is enabled). + Unsigned64 + 64-bit unsigned value, in network byte order. The AVP Length + field MUST be set to 16 (20 if the 'V' bit is enabled). -Fajardo, et al. Expires July 24, 2011 [Page 44] - -Internet-Draft Diameter Base Protocol January 2011 - Unsigned64 - 64 bit unsigned value, in network byte order. The AVP Length - field MUST be set to 16 (20 if the 'V' bit is enabled). +Fajardo, et al. Standards Track [Page 43] + +RFC 6733 Diameter Base Protocol October 2012 Float32 @@ -2478,7 +2419,6 @@ Internet-Draft Diameter Base Protocol January 2011 network byte order. The AVP Length field MUST be set to 12 (16 if the 'V' bit is enabled). - Float64 This represents floating point values of double precision as @@ -2486,73 +2426,69 @@ Internet-Draft Diameter Base Protocol January 2011 network byte order. The AVP Length field MUST be set to 16 (20 if the 'V' bit is enabled). - Grouped - The Data field is specified as a sequence of AVPs. Each of these - AVPs follows - in the order in which they are specified - - including their headers and padding. The AVP Length field is set - to 8 (12 if the 'V' bit is enabled) plus the total length of all - included AVPs, including their headers and padding. Thus the AVP - length field of an AVP of type Grouped is always a multiple of 4. - + The Data field is specified as a sequence of AVPs. These AVPs are + concatenated -- including their headers and padding -- in the + order in which they are specified and the result encapsulated in + the Data field. The AVP Length field is set to 8 (12 if the 'V' + bit is enabled) plus the total length of all included AVPs, + including their headers and padding. Thus, the AVP Length field + of an AVP of type Grouped is always a multiple of 4. 4.3. Derived AVP Data Formats In addition to using the Basic AVP Data Formats, applications may define data formats derived from the Basic AVP Data Formats. An application that defines new Derived AVP Data Formats MUST include - them in a section entitled "Derived AVP Data Formats", using the same + them in a section titled "Derived AVP Data Formats", using the same format as the definitions below. Each new definition MUST be either defined or listed with a reference to the RFC that defines the format. -4.3.1. Common Derived AVPs +4.3.1. Common Derived AVP Data Formats The following are commonly used Derived AVP Data Formats. + Address + The Address format is derived from the OctetString Basic AVP + Format. It is a discriminated union representing, for example, a + 32-bit (IPv4) [RFC0791] or 128-bit (IPv6) [RFC4291] address, most + significant octet first. The first two octets of the Address AVP + represent the AddressType, which contains an Address Family, + defined in [IANAADFAM]. The AddressType is used to discriminate + the content and format of the remaining octets. -Fajardo, et al. Expires July 24, 2011 [Page 45] +Fajardo, et al. Standards Track [Page 44] -Internet-Draft Diameter Base Protocol January 2011 - - - Address - - The Address format is derived from the OctetString AVP Base - Format. It is a discriminated union, representing, for example a - 32-bit (IPv4) [RFC791] or 128-bit (IPv6) [RFC4291] address, most - significant octet first. The first two octets of the Address AVP - represents the AddressType, which contains an Address Family - defined in [IANAADFAM]. The AddressType is used to discriminate - the content and format of the remaining octets. +RFC 6733 Diameter Base Protocol October 2012 Time - The Time format is derived from the OctetString AVP Base Format. + The Time format is derived from the OctetString Basic AVP Format. The string MUST contain four octets, in the same format as the first four bytes are in the NTP timestamp format. The NTP - Timestamp format is defined in Chapter 3 of [RFC5905]. + timestamp format is defined in Section 3 of [RFC5905]. This represents the number of seconds since 0h on 1 January 1900 with respect to the Coordinated Universal Time (UTC). - On 6h 28m 16s UTC, 7 February 2036 the time value will overflow. - SNTP [RFC5905] describes a procedure to extend the time to 2104. - This procedure MUST be supported by all Diameter nodes. - + On 6h 28m 16s UTC, 7 February 2036, the time value will overflow. + Simple Network Time Protocol (SNTP) [RFC5905] describes a + procedure to extend the time to 2104. This procedure MUST be + supported by all Diameter nodes. UTF8String - The UTF8String format is derived from the OctetString AVP Base - Format. This is a human readable string represented using the + The UTF8String format is derived from the OctetString Basic AVP + Format. This is a human-readable string represented using the ISO/IEC IS 10646-1 character set, encoded as an OctetString using - the UTF-8 [RFC3629] transformation format described in RFC 3629. + the UTF-8 transformation format [RFC3629]. Since additional code points are added by amendments to the 10646 standard from time to time, implementations MUST be prepared to @@ -2570,78 +2506,79 @@ Internet-Draft Diameter Base Protocol January 2011 or software, an alternative means of entry and display, such as hexadecimal, MAY be provided. - - -Fajardo, et al. Expires July 24, 2011 [Page 46] - -Internet-Draft Diameter Base Protocol January 2011 - - For information encoded in 7-bit US-ASCII, the UTF-8 charset is identical to the US-ASCII charset. UTF-8 may require multiple bytes to represent a single character / - code point; thus the length of an UTF8String in octets may be + code point; thus, the length of a UTF8String in octets may be different from the number of characters encoded. Note that the AVP Length field of an UTF8String is measured in - octets, not characters. + octets not characters. + + + + +Fajardo, et al. Standards Track [Page 45] + +RFC 6733 Diameter Base Protocol October 2012 + DiameterIdentity - The DiameterIdentity format is derived from the OctetString AVP - Base Format. + The DiameterIdentity format is derived from the OctetString Basic + AVP Format. DiameterIdentity = FQDN/Realm - - DiameterIdentity value is used to uniquely identify either: + The DiameterIdentity value is used to uniquely identify either: * A Diameter node for purposes of duplicate connection and routing loop detection. - * A Realm to determine whether messages can be satisfied locally, + * A Realm to determine whether messages can be satisfied locally or whether they must be routed or redirected. + When a DiameterIdentity value is used to identify a Diameter node, + the contents of the string MUST be the Fully Qualified Domain Name + (FQDN) of the Diameter node. If multiple Diameter nodes run on + the same host, each Diameter node MUST be assigned a unique + DiameterIdentity. If a Diameter node can be identified by several + FQDNs, a single FQDN should be picked at startup and used as the + only DiameterIdentity for that node, whatever the connection on + which it is sent. In this document, note that DiameterIdentity is + in ASCII form in order to be compatible with existing DNS + infrastructure. See Appendix D for interactions between the + Diameter protocol and Internationalized Domain Names (IDNs). - When a DiameterIdentity is used to identify a Diameter node the - contents of the string MUST be the FQDN of the Diameter node. If - multiple Diameter nodes run on the same host, each Diameter node - MUST be assigned a unique DiameterIdentity. If a Diameter node - can be identified by several FQDNs, a single FQDN should be picked - at startup, and used as the only DiameterIdentity for that node, - whatever the connection it is sent on. Note that in this - document, DiameterIdentity is in ASCII form in order to be - compatible with existing DNS infrastructure. See Appendix D for - interactions between the Diameter protocol and Internationalized - Domain Name (IDNs). + DiameterURI + The DiameterURI MUST follow the Uniform Resource Identifiers (RFC + 3986) syntax [RFC3986] rules specified below: - DiameterURI + "aaa://" FQDN [ port ] [ transport ] [ protocol ] - The DiameterURI MUST follow the Uniform Resource Identifiers (URI) - syntax [RFC3986] rules specified below: + ; No transport security + "aaas://" FQDN [ port ] [ transport ] [ protocol ] + ; Transport security used + FQDN = < Fully Qualified Domain Name > -Fajardo, et al. Expires July 24, 2011 [Page 47] - -Internet-Draft Diameter Base Protocol January 2011 - "aaa://" FQDN [ port ] [ transport ] [ protocol ] - ; No transport security - "aaas://" FQDN [ port ] [ transport ] [ protocol ] - ; Transport security used - FQDN = Fully Qualified Host Name +Fajardo, et al. Standards Track [Page 46] + +RFC 6733 Diameter Base Protocol October 2012 + port = ":" 1*DIGIT @@ -2649,8 +2586,9 @@ Internet-Draft Diameter Base Protocol January 2011 ; incoming connections. ; If absent, the default Diameter port ; (3868) is assumed if no transport - ; security is used and port (TBD) when - ; transport security (TLS/TCP and DTLS/SCTP) is used. + ; security is used and port 5658 when + ; transport security (TLS/TCP and DTLS/SCTP) + ; is used. transport = ";transport=" transport-protocol @@ -2660,46 +2598,47 @@ Internet-Draft Diameter Base Protocol January 2011 ; UDP MUST NOT be used when the aaa-protocol ; field is set to diameter. - transport-protocol = ( "tcp" / "sctp" / "udp" ) + transport-protocol = ( "tcp" / "sctp" / "udp" ) - protocol = ";protocol=" aaa-protocol + protocol = ";protocol=" aaa-protocol ; If absent, the default AAA protocol ; is Diameter. - aaa-protocol = ( "diameter" / "radius" / "tacacs+" ) + aaa-protocol = ( "diameter" / "radius" / "tacacs+" ) - The following are examples of valid Diameter host identities: + The following are examples of valid Diameter host identities: - aaa://host.example.com;transport=tcp - aaa://host.example.com:6666;transport=tcp - aaa://host.example.com;protocol=diameter - aaa://host.example.com:6666;protocol=diameter - aaa://host.example.com:6666;transport=tcp;protocol=diameter - aaa://host.example.com:1813;transport=udp;protocol=radius + aaa://host.example.com;transport=tcp + aaa://host.example.com:6666;transport=tcp + aaa://host.example.com;protocol=diameter + aaa://host.example.com:6666;protocol=diameter + aaa://host.example.com:6666;transport=tcp;protocol=diameter + aaa://host.example.com:1813;transport=udp;protocol=radius + Enumerated + The Enumerated format is derived from the Integer32 Basic AVP + Format. The definition contains a list of valid values and their + interpretation and is described in the Diameter application + introducing the AVP. -Fajardo, et al. Expires July 24, 2011 [Page 48] - -Internet-Draft Diameter Base Protocol January 2011 - Enumerated - Enumerated is derived from the Integer32 AVP Base Format. The - definition contains a list of valid values and their - interpretation and is described in the Diameter application - introducing the AVP. + +Fajardo, et al. Standards Track [Page 47] + +RFC 6733 Diameter Base Protocol October 2012 IPFilterRule - The IPFilterRule format is derived from the OctetString AVP Base + The IPFilterRule format is derived from the OctetString Basic AVP Format and uses the ASCII charset. The rule syntax is a modified subset of ipfw(8) from FreeBSD. Packets may be filtered based on the following information that is associated with it: @@ -2713,13 +2652,13 @@ Internet-Draft Diameter Base Protocol January 2011 IP options ICMP types - Rules for the appropriate direction are evaluated in order, with - the first matched rule terminating the evaluation. Each packet is - evaluated once. If no rule matches, the packet is dropped if the - last rule evaluated was a permit, and passed if the last rule was - a deny. + Rules for the appropriate direction are evaluated in order, with the + first matched rule terminating the evaluation. Each packet is + evaluated once. If no rule matches, the packet is dropped if the + last rule evaluated was a permit, and passed if the last rule was a + deny. - IPFilterRule filters MUST follow the format: + IPFilterRule filters MUST follow the format: action dir proto from src to dst [options] @@ -2737,22 +2676,28 @@ Internet-Draft Diameter Base Protocol January 2011 The <address/mask> may be specified as: ipno An IPv4 or IPv6 number in dotted- quad or canonical IPv6 form. Only + this exact IP number will match the + rule. + + + + + + -Fajardo, et al. Expires July 24, 2011 [Page 49] +Fajardo, et al. Standards Track [Page 48] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 - this exact IP number will match the - rule. ipno/bits An IP number as above with a mask width of the form 192.0.2.10/24. In this case, all IP numbers from 192.0.2.0 to 192.0.2.255 will match. The bit width MUST be valid for the - IP version and the IP number MUST + IP version, and the IP number MUST NOT have bits set beyond the mask. For a match to occur, the same IP version must be present in the @@ -2765,7 +2710,7 @@ Internet-Draft Diameter Base Protocol January 2011 is the address or set of addresses assigned to the terminal. For IPv4, a typical first rule is often "deny - in ip! assigned" + in ip! assigned". The sense of the match can be inverted by preceding an address with the not modifier (!), @@ -2773,7 +2718,7 @@ Internet-Draft Diameter Base Protocol January 2011 instead. This does not affect the selection of port numbers. - With the TCP, UDP and SCTP protocols, optional + With the TCP, UDP, and SCTP protocols, optional ports may be specified as: {port/port-port}[,ports[,...]] @@ -2796,33 +2741,35 @@ Internet-Draft Diameter Base Protocol January 2011 -Fajardo, et al. Expires July 24, 2011 [Page 50] + + +Fajardo, et al. Standards Track [Page 49] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 - ipoptions spec - Match if the IP header contains the comma - separated list of options specified in spec. The + ipoptions spec + Match if the IP header contains the comma-separated + list of options specified in spec. The supported IP options are: ssrr (strict source route), lsrr (loose source - route), rr (record packet route) and ts + route), rr (record packet route), and ts (timestamp). The absence of a particular option may be denoted with a '!'. tcpoptions spec - Match if the TCP header contains the comma - separated list of options specified in spec. The + Match if the TCP header contains the comma-separated + list of options specified in spec. The supported TCP options are: mss (maximum segment size), window (tcp window advertisement), sack (selective ack), ts (rfc1323 - timestamp) and cc (rfc1644 t/tcp connection + timestamp), and cc (rfc1644 t/tcp connection count). The absence of a particular option may be denoted with a '!'. - established + established TCP packets only. Match packets that have the RST or ACK bits set. @@ -2832,10 +2779,10 @@ Internet-Draft Diameter Base Protocol January 2011 tcpflags spec TCP packets only. Match if the TCP header - contains the comma separated list of flags + contains the comma-separated list of flags specified in spec. The supported TCP flags are: - fin, syn, rst, psh, ack and urg. The absence of a + fin, syn, rst, psh, ack, and urg. The absence of a particular flag may be denoted with a '!'. A rule that contains a tcpflags specification can never match a fragmented packet that has a non-zero @@ -2852,9 +2799,9 @@ Internet-Draft Diameter Base Protocol January 2011 -Fajardo, et al. Expires July 24, 2011 [Page 51] +Fajardo, et al. Standards Track [Page 50] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 echo reply (0), destination unreachable (3), @@ -2863,21 +2810,20 @@ Internet-Draft Diameter Base Protocol January 2011 solicitation (10), time-to-live exceeded (11), IP header bad (12), timestamp request (13), timestamp reply (14), information request (15), - information reply (16), address mask request (17) + information reply (16), address mask request (17), and address mask reply (18). - There is one kind of packet that the access device MUST always - discard, that is an IP fragment with a fragment offset of one. - This is a valid packet, but it only has one use, to try to - circumvent firewalls. - - An access device that is unable to interpret or apply a deny rule - MUST terminate the session. An access device that is unable to - interpret or apply a permit rule MAY apply a more restrictive - rule. An access device MAY apply deny rules of its own before the - supplied rules, for example to protect the access device owner's - infrastructure. + There is one kind of packet that the access device MUST always + discard, that is an IP fragment with a fragment offset of one. This + is a valid packet, but it only has one use, to try to circumvent + firewalls. + An access device that is unable to interpret or apply a deny rule + MUST terminate the session. An access device that is unable to + interpret or apply a permit rule MAY apply a more restrictive rule. + An access device MAY apply deny rules of its own before the supplied + rules, for example to protect the access device owner's + infrastructure. 4.4. Grouped AVP Values @@ -2885,75 +2831,76 @@ Internet-Draft Diameter Base Protocol January 2011 implies that the Data field is actually a sequence of AVPs. It is possible to include an AVP with a Grouped type within a Grouped type, that is, to nest them. AVPs within an AVP of type Grouped have the - same padding requirements as non-Grouped AVPs, as defined in Section - 4. + same padding requirements as non-Grouped AVPs, as defined in + Section 4.4. The AVP Code numbering space of all AVPs included in a Grouped AVP is - the same as for non-grouped AVPs. Receivers of a Grouped AVP that + the same as for non-Grouped AVPs. 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 + bit set is further encapsulated within other sub-groups, i.e., other Grouped AVPs embedded within the Grouped AVP. - Every Grouped AVP defined MUST include a corresponding grammar, using - ABNF [RFC5234] (with modifications), as defined below. - + Every Grouped AVP definition MUST include a corresponding grammar, + using ABNF [RFC5234] (with modifications), as defined below. + grouped-avp-def = "<" name ">" "::=" avp + name-fmt = ALPHA *(ALPHA / DIGIT / "-") -Fajardo, et al. Expires July 24, 2011 [Page 52] +Fajardo, et al. Standards Track [Page 51] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 - grouped-avp-def = <name> "::=" avp - - name-fmt = ALPHA *(ALPHA / DIGIT / "-") - name = name-fmt ; The name has to be the name of an AVP, ; defined in the base or extended Diameter ; specifications. - avp = header [ *fixed] [ *required] [ *optional] + avp = header *fixed *required *optional header = "<" "AVP-Header:" avpcode [vendor] ">" avpcode = 1*DIGIT - ; The AVP Code assigned to the Grouped AVP + ; The AVP Code assigned to the Grouped AVP. vendor = 1*DIGIT ; The Vendor-ID assigned to the Grouped AVP. ; If absent, the default value of zero is ; used. -4.4.1. Example AVP with a Grouped Data type +4.4.1. Example AVP with a Grouped Data Type The Example-AVP (AVP Code 999999) is of type Grouped and is used to clarify how Grouped AVP values work. The Grouped Data field has the - following ABNF grammar: - - - - - - - - + following CCF grammar: + Example-AVP ::= < AVP Header: 999999 > + { Origin-Host } + 1*{ Session-Id } + *[ AVP ] + An Example-AVP with Grouped Data follows. + The Origin-Host AVP (Section 6.3) is required. In this case: + Origin-Host = "example.com". + One or more Session-Ids must follow. Here there are two: + Session-Id = + "grump.example.com:33041;23432;893;0AF3B81" + Session-Id = + "grump.example.com:33054;23561;2358;0AF3B82" @@ -2964,31 +2911,11 @@ Internet-Draft Diameter Base Protocol January 2011 -Fajardo, et al. Expires July 24, 2011 [Page 53] +Fajardo, et al. Standards Track [Page 52] -Internet-Draft Diameter Base Protocol January 2011 - - - Example-AVP ::= < AVP Header: 999999 > - { Origin-Host } - 1*{ Session-Id } - *[ AVP ] - - An Example-AVP with Grouped Data follows. - - The Origin-Host AVP is required (Section 6.3). In this case: - - Origin-Host = "example.com". +RFC 6733 Diameter Base Protocol October 2012 - One or more Session-Ids must follow. Here there are two: - - Session-Id = - "grump.example.com:33041;23432;893;0AF3B81" - - Session-Id = - "grump.example.com:33054;23561;2358;0AF3B82" - optional AVPs included are Recovery-Policy = <binary> @@ -3007,25 +2934,42 @@ Internet-Draft Diameter Base Protocol January 2011 41d018d56fe938f3cbf089aac12a912a2f0d1923a9390e5f789cb2e5067 d3427475e49968f841 - The data for the optional AVPs is represented in hex since the format - of these AVPs is neither known at the time of definition of the - Example-AVP group, nor (likely) at the time when the example instance - of this AVP is interpreted - except by Diameter implementations which - support the same set of AVPs. The encoding example illustrates how - padding is used and how length fields are calculated. Also note that - AVPs may be present in the Grouped AVP value which the receiver - cannot interpret (here, the Recover-Policy and Futuristic-Acct-Record - AVPs). The length of the Example-AVP is the sum of all the length of - the member AVPs including their padding plus the Example-AVP header + The data for the optional AVPs is represented in hexadecimal form + since the format of these AVPs is not known at the time of definition + of the Example-AVP group nor (likely) at the time when the example + instance of this AVP is interpreted -- except by Diameter + implementations that support the same set of AVPs. The encoding + example illustrates how padding is used and how length fields are + calculated. Also, note that AVPs may be present in the Grouped AVP + value that the receiver cannot interpret (here, the Recover-Policy + and Futuristic-Acct-Record AVPs). The length of the Example-AVP is + the sum of all the length of the member AVPs, including their + padding, plus the Example-AVP header size. + + + + + + + + + + + + + + + + -Fajardo, et al. Expires July 24, 2011 [Page 54] - -Internet-Draft Diameter Base Protocol January 2011 - size. + +Fajardo, et al. Standards Track [Page 53] + +RFC 6733 Diameter Base Protocol October 2012 This AVP would be encoded as follows: @@ -3076,15 +3020,18 @@ Internet-Draft Diameter Base Protocol January 2011 -Fajardo, et al. Expires July 24, 2011 [Page 55] + + + +Fajardo, et al. Standards Track [Page 54] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 4.5. Diameter Base Protocol AVPs The following table describes the Diameter AVPs defined in the base - protocol, their AVP Code values, types, possible flag values. + protocol, their AVP Code values, types, and possible flag values. Due to space constraints, the short form DiamIdent is used to represent DiameterIdentity. @@ -3132,9 +3079,9 @@ Internet-Draft Diameter Base Protocol January 2011 -Fajardo, et al. Expires July 24, 2011 [Page 56] +Fajardo, et al. Standards Track [Page 55] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 +----------+ @@ -3154,7 +3101,7 @@ Internet-Draft Diameter Base Protocol January 2011 Record-Number | | | Accounting- 480 9.8.1 Enumerated | M | V | Record-Type | | | - Accounting- 44 9.8.4 OctetString| M | V | + Acct- 44 9.8.4 OctetString| M | V | Session-Id | | | Accounting- 287 9.8.6 Unsigned64 | M | V | Sub-Session-Id | | | @@ -3188,9 +3135,9 @@ Internet-Draft Diameter Base Protocol January 2011 -Fajardo, et al. Expires July 24, 2011 [Page 57] +Fajardo, et al. Standards Track [Page 56] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 +----------+ @@ -3244,9 +3191,9 @@ Internet-Draft Diameter Base Protocol January 2011 -Fajardo, et al. Expires July 24, 2011 [Page 58] +Fajardo, et al. Standards Track [Page 57] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 5. Diameter Peers @@ -3258,25 +3205,25 @@ Internet-Draft Diameter Base Protocol January 2011 Connections between diameter peers are established using their valid DiameterIdentity. A Diameter node initiating a connection to a peer - MUST know the peers DiameterIdentity. Methods for discovering a + MUST know the peer's DiameterIdentity. Methods for discovering a Diameter peer can be found in Section 5.2. - Although a Diameter node may have many possible peers that it is able - to communicate with, it may not be economical to have an established - connection to all of them. At a minimum, a Diameter node SHOULD have - an established connection with two peers per realm, known as the - primary and secondary peers. Of course, a node MAY have additional - connections, if it is deemed necessary. Typically, all messages for - a realm are sent to the primary peer, but in the event that failover - procedures are invoked, any pending requests are sent to the - secondary peer. However, implementations are free to load balance - requests between a set of peers. - - Note that a given peer MAY act as a primary for a given realm, while + Although a Diameter node may have many possible peers with which it + is able to communicate, it may not be economical to have an + established connection to all of them. At a minimum, a Diameter node + SHOULD have an established connection with two peers per realm, known + as the primary and secondary peers. Of course, a node MAY have + additional connections, if it is deemed necessary. Typically, all + messages for a realm are sent to the primary peer but, in the event + that failover procedures are invoked, any pending requests are sent + to the secondary peer. However, implementations are free to load + balance requests between a set of peers. + + Note that a given peer MAY act as a primary for a given realm while acting as a secondary for another realm. When a peer is deemed suspect, which could occur for various reasons, - including not receiving a DWA within an allotted timeframe, no new + including not receiving a DWA within an allotted time frame, no new requests should be forwarded to the peer, but failover procedures are invoked. When an active peer is moved to this mode, additional connections SHOULD be established to ensure that the necessary number @@ -3284,15 +3231,14 @@ Internet-Draft Diameter Base Protocol January 2011 There are two ways that a peer is removed from the suspect peer list: - 1. The peer is no longer reachable, causing the transport connection - to be shutdown. The peer is moved to the closed state. + to be shut down. The peer is moved to the closed state. - 2. Three watchdog messages are exchanged with accepted round trip + 2. Three watchdog messages are exchanged with accepted round-trip times, and the connection to the peer is considered stabilized. In the event the peer being removed is either the primary or - secondary, an alternate peer SHOULD replace the deleted peer, and + secondary, an alternate peer SHOULD replace the deleted peer and assume the role of either primary or secondary. @@ -3300,99 +3246,106 @@ Internet-Draft Diameter Base Protocol January 2011 -Fajardo, et al. Expires July 24, 2011 [Page 59] + +Fajardo, et al. Standards Track [Page 58] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 5.2. Diameter Peer Discovery - Allowing for dynamic Diameter agent discovery will make it possible - for simpler and more robust deployment of Diameter services. In - order to promote interoperable implementations of Diameter peer - discovery, the following mechanisms are described. These are based - on existing IETF standards. The first option (manual configuration) - MUST be supported by all Diameter nodes, while the latter option - (DNS) MAY be supported. + Allowing for dynamic Diameter agent discovery makes possible simpler + and more robust deployment of Diameter services. In order to promote + interoperable implementations of Diameter peer discovery, the + following mechanisms (manual configuration and DNS) are described. + These are based on existing IETF standards. Both mechanisms MUST be + supported by all Diameter implementations; either MAY be used. There are two cases where Diameter peer discovery may be performed. The first is when a Diameter client needs to discover a first-hop Diameter agent. The second case is when a Diameter agent needs to - discover another agent - for further handling of a Diameter - operation. In both cases, the following 'search order' is - recommended: - + discover another agent for further handling of a Diameter operation. + In both cases, the following 'search order' is recommended: - 1. The Diameter implementation consults its list of static + 1. The Diameter implementation consults its list of statically (manually) configured Diameter agent locations. These will be used if they exist and respond. - 2. The Diameter implementation performs a NAPTR query for a server - in a particular realm. The Diameter implementation has to know - in advance which realm to look for a Diameter agent. This could - be deduced, for example, from the 'realm' in a NAI that a - Diameter implementation needed to perform a Diameter operation - on. + in a particular realm. The Diameter implementation has to know, + in advance, in which realm to look for a Diameter agent. This + could be deduced, for example, from the 'realm' in an NAI on + which a Diameter implementation needed to perform a Diameter + operation. The NAPTR usage in Diameter follows the S-NAPTR DDDS application [RFC3958] in which the SERVICE field includes tags for the desired application and supported application protocol. The application service tag for a Diameter application is 'aaa' and the supported application protocol tags are 'diameter.tcp', - 'diameter.sctp', 'diameter.dtls' or 'diameter.tls.tcp'. + 'diameter.sctp', 'diameter.dtls', or 'diameter.tls.tcp' + [RFC6408]. The client can follow the resolution process defined by the - S-NAPTR DDDS [RFC3958] application to find a matching SRV, A or + S-NAPTR DDDS [RFC3958] application to find a matching SRV, A, or AAAA record of a suitable peer. The domain suffixes in the NAPTR replacement field SHOULD match the domain of the original query. An example can be found in Appendix B. 3. If no NAPTR records are found, the requester directly queries for - SRV records '_diameter._sctp'.realm, '_diameter._dtls'.realm, - '_diameter._tcp'.realm and '_diameter._tls'.realm depending on - the requesters network protocol capabilities. If SRV records are - found then the requester can perform address record query (A RR's + one of the following SRV records: for Diameter over TCP, use + "_diameter._tcp.realm"; for Diameter over TLS, use + "_diameters._tcp.realm"; for Diameter over SCTP, use + "_diameter._sctp.realm"; for Diameter over DTLS, use + "_diameters._sctp.realm". If SRV records are found, then the + requester can perform address record query (A RR's and/or AAAA + -Fajardo, et al. Expires July 24, 2011 [Page 60] +Fajardo, et al. Standards Track [Page 59] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 - and/or AAAA RR's) for the target hostname specified in the SRV - records. If no SRV records are found, the requester gives up. + RR's) for the target hostname specified in the SRV records + following the rules given in [RFC2782]. If no SRV records are + found, the requester gives up. If the server is using a site certificate, the domain name in the NAPTR query and the domain name in the replacement field MUST both be valid based on the site certificate handed out by the server in the - TLS/TCP and DTLS/SCTP or IKE exchange. Similarly, the domain name in - the SRV query and the domain name in the target in the SRV record - MUST both be valid based on the same site certificate. Otherwise, an - attacker could modify the DNS records to contain replacement values - in a different domain, and the client could not validate that this - was the desired behavior, or the result of an attack. - - Also, the Diameter Peer MUST check to make sure that the discovered + TLS/TCP and DTLS/SCTP or Internet Key Exchange Protocol (IKE) + exchange. Similarly, the domain name in the SRV query and the domain + name in the target in the SRV record MUST both be valid based on the + same site certificate. Otherwise, an attacker could modify the DNS + records to contain replacement values in a different domain, and the + client could not validate whether this was the desired behavior or + the result of an attack. + + Also, the Diameter peer MUST check to make sure that the discovered peers are authorized to act in its role. Authentication via IKE or TLS/TCP and DTLS/SCTP, or validation of DNS RRs via DNSSEC is not sufficient to conclude this. For example, a web server may have obtained a valid TLS/TCP and DTLS/SCTP certificate, and secured RRs may be included in the DNS, but this does not imply that it is - authorized to act as a Diameter Server. - - Authorization can be achieved for example, by configuration of a - Diameter Server CA. Alternatively this can be achieved by definition - of OIDs within TLS/TCP and DTLS/SCTP or IKE certificates so as to - signify Diameter Server authorization. - - A dynamically discovered peer causes an entry in the Peer Table (see + authorized to act as a Diameter server. + + Authorization can be achieved, for example, by the configuration of a + Diameter server Certification Authority (CA). The server CA issues a + certificate to the Diameter server, which includes an Object + Identifier (OID) to indicate the subject is a Diameter server in the + Extended Key Usage extension [RFC5280]. This certificate is then + used during TLS/TCP, DTLS/SCTP, or IKE security negotiation. + However, note that, at the time of writing, no Diameter server + Certification Authorities exist. + + A dynamically discovered peer causes an entry in the peer table (see Section 2.6) to be created. Note that entries created via DNS MUST - expire (or be refreshed) within the DNS TTL. If a peer is discovered - outside of the local realm, a routing table entry (see Section 2.7) - for the peer's realm is created. The routing table entry's - expiration MUST match the peer's expiration value. + expire (or be refreshed) within the DNS Time to Live (TTL). If a + peer is discovered outside of the local realm, a routing table entry + (see Section 2.7) for the peer's realm is created. The routing table + entry's expiration MUST match the peer's expiration value. 5.3. Capabilities Exchange @@ -3400,35 +3353,36 @@ Internet-Draft Diameter Base Protocol January 2011 exchange the Capabilities Exchange messages, as specified in the peer state machine (see Section 5.6). This message allows the discovery of a peer's identity and its capabilities (protocol version number, - supported Diameter applications, security mechanisms, etc.) + the identifiers of supported Diameter applications, security + mechanisms, etc.). - The receiver only issues commands to its peers that have advertised - support for the Diameter application that defines the command. A - Diameter node MUST cache the supported applications in order to - ensure that unrecognized commands and/or AVPs are not unnecessarily - sent to a peer. - - A receiver of a Capabilities-Exchange-Req (CER) message that does not -Fajardo, et al. Expires July 24, 2011 [Page 61] +Fajardo, et al. Standards Track [Page 60] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 - have any applications in common with the sender MUST return a + The receiver only issues commands to its peers that have advertised + support for the Diameter application that defines the command. A + Diameter node MUST cache the supported Application Ids in order to + ensure that unrecognized commands and/or AVPs are not unnecessarily + sent to a peer. + + A receiver of a Capabilities-Exchange-Request (CER) message that does + not have any applications in common with the sender MUST return a Capabilities-Exchange-Answer (CEA) with the Result-Code AVP set to - DIAMETER_NO_COMMON_APPLICATION, and SHOULD disconnect the transport + DIAMETER_NO_COMMON_APPLICATION and SHOULD disconnect the transport layer connection. Note that receiving a CER or CEA from a peer - advertising itself as a Relay (see Section 2.4) MUST be interpreted + advertising itself as a relay (see Section 2.4) MUST be interpreted as having common applications with the peer. The receiver of the Capabilities-Exchange-Request (CER) MUST determine common applications by computing the intersection of its - own set of supported Application Id against all of the application - identifier AVPs (Auth-Application-Id, Acct-Application-Id and Vendor- - Specific-Application-Id) present in the CER. The value of the + own set of supported Application Ids against all of the + Application-Id AVPs (Auth-Application-Id, Acct-Application-Id, and + Vendor-Specific-Application-Id) present in the CER. The value of the Vendor-Id AVP in the Vendor-Specific-Application-Id MUST NOT be used during computation. The sender of the Capabilities-Exchange-Answer (CEA) SHOULD include all of its supported applications as a hint to @@ -3438,12 +3392,13 @@ Internet-Draft Diameter Base Protocol January 2011 and DTLS/SCTP connection prior to the CER/CEA exchange. This protects the capabilities information of both peers. To support older Diameter implementations that do not fully conform to this - document, the transport security MAY still be negotiated via Inband- - Security AVP. In this case, the receiver of a Capabilities-Exchange- - Req (CER) message that does not have any security mechanisms in - common with the sender MUST return a Capabilities-Exchange-Answer - (CEA) with the Result-Code AVP set to DIAMETER_NO_COMMON_SECURITY, - and SHOULD disconnect the transport layer connection. + document, the transport security MAY still be negotiated via an + Inband-Security AVP. In this case, the receiver of a Capabilities- + Exchange-Request (CER) message that does not have any security + mechanisms in common with the sender MUST return a Capabilities- + Exchange-Answer (CEA) with the Result-Code AVP set to + DIAMETER_NO_COMMON_SECURITY and SHOULD disconnect the transport layer + connection. CERs received from unknown peers MAY be silently discarded, or a CEA MAY be issued with the Result-Code AVP set to DIAMETER_UNKNOWN_PEER. @@ -3455,34 +3410,34 @@ Internet-Draft Diameter Base Protocol January 2011 failure, all the pending transactions destined to the unknown peer can be discarded. - The CER and CEA messages MUST NOT be proxied, redirected or relayed. + The CER and CEA messages MUST NOT be proxied, redirected, or relayed. - Since the CER/CEA messages cannot be proxied, it is still possible - that an upstream agent receives a message for which it has no - available peers to handle the application that corresponds to the - Command-Code. In such instances, the 'E' bit is set in the answer - message (see Section 7.) with the Result-Code AVP set to - DIAMETER_UNABLE_TO_DELIVER to inform the downstream to take action - (e.g., re-routing request to an alternate peer). - -Fajardo, et al. Expires July 24, 2011 [Page 62] +Fajardo, et al. Standards Track [Page 61] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 + Since the CER/CEA messages cannot be proxied, it is still possible + that an upstream agent will receive a message for which it has no + available peers to handle the application that corresponds to the + Command Code. In such instances, the 'E' bit is set in the answer + message (Section 7) with the Result-Code AVP set to + DIAMETER_UNABLE_TO_DELIVER to inform the downstream agent to take + action (e.g., re-routing request to an alternate peer). + With the exception of the Capabilities-Exchange-Request message, a message of type Request that includes the Auth-Application-Id or Acct-Application-Id AVPs, or a message with an application-specific - command code, MAY only be forwarded to a host that has explicitly + Command Code MAY only be forwarded to a host that has explicitly advertised support for the application (or has advertised the Relay Application Id). 5.3.1. Capabilities-Exchange-Request - The Capabilities-Exchange-Request (CER), indicated by the Command- + The Capabilities-Exchange-Request (CER), indicated by the Command Code set to 257 and the Command Flags' 'R' bit set, is sent to exchange local capabilities. Upon detection of a transport failure, this message MUST NOT be sent to an alternate peer. @@ -3490,7 +3445,7 @@ Internet-Draft Diameter Base Protocol January 2011 When Diameter is run over SCTP [RFC4960] or DTLS/SCTP [RFC6083], which allow for connections to span multiple interfaces and multiple IP addresses, the Capabilities-Exchange-Request message MUST contain - one Host-IP- Address AVP for each potential IP address that MAY be + one Host-IP-Address AVP for each potential IP address that MAY be locally used when transmitting Diameter messages. Message Format @@ -3510,9 +3465,20 @@ Internet-Draft Diameter Base Protocol January 2011 [ Firmware-Revision ] * [ AVP ] + + + + + + +Fajardo, et al. Standards Track [Page 62] + +RFC 6733 Diameter Base Protocol October 2012 + + 5.3.2. Capabilities-Exchange-Answer - The Capabilities-Exchange-Answer (CEA), indicated by the Command-Code + The Capabilities-Exchange-Answer (CEA), indicated by the Command Code set to 257 and the Command Flags' 'R' bit cleared, is sent in response to a CER message. @@ -3522,13 +3488,6 @@ Internet-Draft Diameter Base Protocol January 2011 one Host-IP-Address AVP for each potential IP address that MAY be locally used when transmitting Diameter messages. - - -Fajardo, et al. Expires July 24, 2011 [Page 63] - -Internet-Draft Diameter Base Protocol January 2011 - - Message Format <CEA> ::= < Diameter Header: 257 > @@ -3552,22 +3511,34 @@ Internet-Draft Diameter Base Protocol January 2011 5.3.3. Vendor-Id AVP The Vendor-Id AVP (AVP Code 266) is of type Unsigned32 and contains - the IANA "SMI Network Management Private Enterprise Codes" [RFC3232] - value assigned to the vendor of the Diameter device. It is + the IANA "SMI Network Management Private Enterprise Codes" + [ENTERPRISE] value assigned to the Diameter Software vendor. It is envisioned that the combination of the Vendor-Id, Product-Name - (Section 5.3.7) and the Firmware-Revision (Section 5.3.4) AVPs may + (Section 5.3.7), and Firmware-Revision (Section 5.3.4) AVPs may provide useful debugging information. - A Vendor-Id value of zero in the CER or CEA messages is reserved and + A Vendor-Id value of zero in the CER or CEA message is reserved and indicates that this field is ignored. + + + + + + + +Fajardo, et al. Standards Track [Page 63] + +RFC 6733 Diameter Base Protocol October 2012 + + 5.3.4. Firmware-Revision AVP The Firmware-Revision AVP (AVP Code 267) is of type Unsigned32 and is used to inform a Diameter peer of the firmware revision of the issuing device. - For devices that do not have a firmware revision (general purpose + For devices that do not have a firmware revision (general-purpose computers running Diameter software modules, for instance), the revision of the Diameter software module may be reported instead. @@ -3577,77 +3548,70 @@ Internet-Draft Diameter Base Protocol January 2011 to inform a Diameter peer of the sender's IP address. All source addresses that a Diameter node expects to use with SCTP [RFC4960] or DTLS/SCTP [RFC6083] MUST be advertised in the CER and CEA messages by - - - -Fajardo, et al. Expires July 24, 2011 [Page 64] - -Internet-Draft Diameter Base Protocol January 2011 - - including a Host-IP-Address AVP for each address. 5.3.6. Supported-Vendor-Id AVP The Supported-Vendor-Id AVP (AVP Code 265) is of type Unsigned32 and contains the IANA "SMI Network Management Private Enterprise Codes" - [RFC3232] value assigned to a vendor other than the device vendor but - including the application vendor. This is used in the CER and CEA - messages in order to inform the peer that the sender supports (a - subset of) the vendor-specific AVPs defined by the vendor identified + [ENTERPRISE] value assigned to a vendor other than the device vendor + but including the application vendor. This is used in the CER and + CEA messages in order to inform the peer that the sender supports (a + subset of) the Vendor-Specific AVPs defined by the vendor identified in this AVP. The value of this AVP MUST NOT be set to zero. Multiple instances of this AVP containing the same value SHOULD NOT be sent. 5.3.7. Product-Name AVP - The Product-Name AVP (AVP Code 269) is of type UTF8String, and - contains the vendor assigned name for the product. The Product-Name + The Product-Name AVP (AVP Code 269) is of type UTF8String and + contains the vendor-assigned name for the product. The Product-Name AVP SHOULD remain constant across firmware revisions for the same product. -5.4. Disconnecting Peer connections +5.4. Disconnecting Peer Connections When a Diameter node disconnects one of its transport connections, - its peer cannot know the reason for the disconnect, and will most - likely assume that a connectivity problem occurred, or that the peer + its peer cannot know the reason for the disconnect and will most + likely assume that a connectivity problem occurred or that the peer has rebooted. In these cases, the peer may periodically attempt to reconnect, as stated in Section 2.1. In the event that the - disconnect was a result of either a shortage of internal resources, - or simply that the node in question has no intentions of forwarding - any Diameter messages to the peer in the foreseeable future, a - periodic connection request would not be welcomed. The - Disconnection-Reason AVP contains the reason the Diameter node issued - the Disconnect-Peer-Request message. + disconnect was a result of either a shortage of internal resources or + simply that the node in question has no intentions of forwarding any + Diameter messages to the peer in the foreseeable future, a periodic - The Disconnect-Peer-Request message is used by a Diameter node to - inform its peer of its intent to disconnect the transport layer, and - that the peer shouldn't reconnect unless it has a valid reason to do - so (e.g., message to be forwarded). Upon receipt of the message, the - Disconnect-Peer-Answer is returned, which SHOULD contain an error if - messages have recently been forwarded, and are likely in flight, - which would otherwise cause a race condition. - The receiver of the Disconnect-Peer-Answer initiates the transport - disconnect. The sender of the Disconnect-Peer-Answer should be able - to detect the transport closure and cleanup the connection. +Fajardo, et al. Standards Track [Page 64] + +RFC 6733 Diameter Base Protocol October 2012 + connection request would not be welcomed. The Disconnection-Reason + AVP contains the reason the Diameter node issued the Disconnect-Peer- + Request message. -Fajardo, et al. Expires July 24, 2011 [Page 65] - -Internet-Draft Diameter Base Protocol January 2011 + The Disconnect-Peer-Request message is used by a Diameter node to + inform its peer of its intent to disconnect the transport layer and + that the peer shouldn't reconnect unless it has a valid reason to do + so (e.g., message to be forwarded). Upon receipt of the message, the + Disconnect-Peer-Answer message is returned, which SHOULD contain an + error if messages have recently been forwarded, and are likely in + flight, which would otherwise cause a race condition. + The receiver of the Disconnect-Peer-Answer message initiates the + transport disconnect. The sender of the Disconnect-Peer-Answer + message should be able to detect the transport closure and clean up + the connection. 5.4.1. Disconnect-Peer-Request - The Disconnect-Peer-Request (DPR), indicated by the Command-Code set + The Disconnect-Peer-Request (DPR), indicated by the Command Code set to 282 and the Command Flags' 'R' bit set, is sent to a peer to - inform its intentions to shutdown the transport connection. Upon - detection of a transport failure, this message MUST NOT be sent to an - alternate peer. + inform it of its intentions to shut down the transport connection. + Upon detection of a transport failure, this message MUST NOT be sent + to an alternate peer. Message Format @@ -3659,28 +3623,14 @@ Internet-Draft Diameter Base Protocol January 2011 5.4.2. Disconnect-Peer-Answer - The Disconnect-Peer-Answer (DPA), indicated by the Command-Code set + The Disconnect-Peer-Answer (DPA), indicated by the Command Code set to 282 and the Command Flags' 'R' bit cleared, is sent as a response to the Disconnect-Peer-Request message. Upon receipt of this - message, the transport connection is shutdown. + message, the transport connection is shut down. - Message Format - <DPA> ::= < Diameter Header: 282 > - { Result-Code } - { Origin-Host } - { Origin-Realm } - [ Error-Message ] - [ Failed-AVP ] - * [ AVP ] -5.4.3. Disconnect-Cause AVP - The Disconnect-Cause AVP (AVP Code 273) is of type Enumerated. A - Diameter node MUST include this AVP in the Disconnect-Peer-Request - message to inform the peer of the reason for its intention to - shutdown the transport connection. The following values are - supported: @@ -3689,29 +3639,44 @@ Internet-Draft Diameter Base Protocol January 2011 +Fajardo, et al. Standards Track [Page 65] + +RFC 6733 Diameter Base Protocol October 2012 + Message Format + + <DPA> ::= < Diameter Header: 282 > + { Result-Code } + { Origin-Host } + { Origin-Realm } + [ Error-Message ] + [ Failed-AVP ] + * [ AVP ] -Fajardo, et al. Expires July 24, 2011 [Page 66] - -Internet-Draft Diameter Base Protocol January 2011 +5.4.3. Disconnect-Cause AVP + + The Disconnect-Cause AVP (AVP Code 273) is of type Enumerated. A + Diameter node MUST include this AVP in the Disconnect-Peer-Request + message to inform the peer of the reason for its intention to shut + down the transport connection. The following values are supported: - REBOOTING 0 - A scheduled reboot is imminent. Receiver of DPR with above result - code MAY attempt reconnection. + REBOOTING 0 + A scheduled reboot is imminent. A receiver of a DPR with + above result code MAY attempt reconnection. - BUSY 1 - The peer's internal resources are constrained, and it has - determined that the transport connection needs to be closed. - Receiver of DPR with above result code SHOULD NOT attempt - reconnection. + BUSY 1 + The peer's internal resources are constrained, and it has + determined that the transport connection needs to be closed. + A receiver of a DPR with above result code SHOULD NOT attempt + reconnection. - DO_NOT_WANT_TO_TALK_TO_YOU 2 - The peer has determined that it does not see a need for the - transport connection to exist, since it does not expect any - messages to be exchanged in the near future. Receiver of DPR - with above result code SHOULD NOT attempt reconnection. + DO_NOT_WANT_TO_TALK_TO_YOU 2 + The peer has determined that it does not see a need for the + transport connection to exist, since it does not expect any + messages to be exchanged in the near future. A receiver of a + DPR with above result code SHOULD NOT attempt reconnection. 5.5. Transport Failure Detection @@ -3723,9 +3688,21 @@ Internet-Draft Diameter Base Protocol January 2011 Watchdog-Answer messages, defined in this section, are used to pro- actively detect transport failures. + + + + + + + +Fajardo, et al. Standards Track [Page 66] + +RFC 6733 Diameter Base Protocol October 2012 + + 5.5.1. Device-Watchdog-Request - The Device-Watchdog-Request (DWR), indicated by the Command-Code set + The Device-Watchdog-Request (DWR), indicated by the Command Code set to 280 and the Command Flags' 'R' bit set, is sent to a peer when no traffic has been exchanged between two peers (see Section 5.5.3). Upon detection of a transport failure, this message MUST NOT be sent @@ -3741,18 +3718,10 @@ Internet-Draft Diameter Base Protocol January 2011 5.5.2. Device-Watchdog-Answer - The Device-Watchdog-Answer (DWA), indicated by the Command-Code set + The Device-Watchdog-Answer (DWA), indicated by the Command Code set to 280 and the Command Flags' 'R' bit cleared, is sent as a response to the Device-Watchdog-Request message. - - - -Fajardo, et al. Expires July 24, 2011 [Page 67] - -Internet-Draft Diameter Base Protocol January 2011 - - Message Format <DWA> ::= < Diameter Header: 280 > @@ -3767,7 +3736,7 @@ Internet-Draft Diameter Base Protocol January 2011 5.5.3. Transport Failure Algorithm The transport failure algorithm is defined in [RFC3539]. All - Diameter implementations MUST support the algorithm defined in the + Diameter implementations MUST support the algorithm defined in that specification in order to be compliant to the Diameter base protocol. 5.5.4. Failover and Failback Procedures @@ -3775,7 +3744,17 @@ Internet-Draft Diameter Base Protocol January 2011 In the event that a transport failure is detected with a peer, it is necessary for all pending request messages to be forwarded to an alternate agent, if possible. This is commonly referred to as - failover. + "failover". + + + + + + +Fajardo, et al. Standards Track [Page 67] + +RFC 6733 Diameter Base Protocol October 2012 + In order for a Diameter node to perform failover procedures, it is necessary for the node to maintain a pending message queue for a @@ -3783,16 +3762,16 @@ Internet-Draft Diameter Base Protocol January 2011 request is removed from the queue. The Hop-by-Hop Identifier field is used to match the answer with the queued request. - When a transport failure is detected, if possible all messages in the - queue are sent to an alternate agent with the T flag set. On booting - a Diameter client or agent, the T flag is also set on any records - still remaining to be transmitted in non-volatile storage. An - example of a case where it is not possible to forward the message to - an alternate server is when the message has a fixed destination, and - the unavailable peer is the message's final destination (see - Destination-Host AVP). Such an error requires that the agent return - an answer message with the 'E' bit set and the Result-Code AVP set to - DIAMETER_UNABLE_TO_DELIVER. + When a transport failure is detected, if possible, all messages in + the queue are sent to an alternate agent with the T flag set. On + booting a Diameter client or agent, the T flag is also set on any + remaining records in non-volatile storage that are still waiting to + be transmitted. An example of a case where it is not possible to + forward the message to an alternate server is when the message has a + fixed destination, and the unavailable peer is the message's final + destination (see Destination-Host AVP). Such an error requires that + the agent return an answer message with the 'E' bit set and the + Result-Code AVP set to DIAMETER_UNABLE_TO_DELIVER. It is important to note that multiple identical requests or answers MAY be received as a result of a failover. The End-to-End Identifier @@ -3801,17 +3780,9 @@ Internet-Draft Diameter Base Protocol January 2011 As described in Section 2.1, a connection request should be periodically attempted with the failed peer in order to re-establish - - - -Fajardo, et al. Expires July 24, 2011 [Page 68] - -Internet-Draft Diameter Base Protocol January 2011 - - the transport connection. Once a connection has been successfully established, messages can once again be forwarded to the peer. This - is commonly referred to as failback. + is commonly referred to as "failback". 5.6. Peer State Machine @@ -3824,16 +3795,24 @@ Internet-Draft Diameter Base Protocol January 2011 This state machine is closely coupled with the state machine described in [RFC3539], which is used to open, close, failover, - probe, and reopen transport connections. Note in particular that + probe, and reopen transport connections. In particular, note that [RFC3539] requires the use of watchdog messages to probe connections. For Diameter, DWR and DWA messages are to be used. - I- is used to represent the initiator (connecting) connection, while - the R- is used to represent the responder (listening) connection. - The lack of a prefix indicates that the event or action is the same - regardless of the connection on which the event occurred. + The I- prefix is used to represent the initiator (connecting) + connection, while the R- prefix is used to represent the responder + (listening) connection. The lack of a prefix indicates that the + event or action is the same regardless of the connection on which the + event occurred. + + + +Fajardo, et al. Standards Track [Page 68] + +RFC 6733 Diameter Base Protocol October 2012 + - The stable states that a state machine may be in are Closed, I-Open + The stable states that a state machine may be in are Closed, I-Open, and R-Open; all other states are intermediate. Note that I-Open and R-Open are equivalent except for whether the initiator or responder transport connection is used for communication. @@ -3848,23 +3827,15 @@ Internet-Draft Diameter Base Protocol January 2011 the results of an election on one peer are guaranteed to be the inverse of the results on the other. - For TLS/TCP and DTLS/SCTP usage, TLS/TCP and DTLS/SCTP handshake + For TLS/TCP and DTLS/SCTP usage, a TLS/TCP and DTLS/SCTP handshake SHOULD begin when both ends are in the closed state prior to any Diameter message exchanges. The TLS/TCP and DTLS/SCTP connection SHOULD be established before sending any CER or CEA message to secure and protect the capabilities information of both peers. The TLS/TCP and DTLS/SCTP connection SHOULD be disconnected when the state machine moves to the closed state. When connecting to responders - that do not conform to this document (i.e. older Diameter + that do not conform to this document (i.e., older Diameter implementations that are not prepared to received TLS/TCP and DTLS/ - - - -Fajardo, et al. Expires July 24, 2011 [Page 69] - -Internet-Draft Diameter Base Protocol January 2011 - - SCTP connections in the closed state), the initial TLS/TCP and DTLS/ SCTP connection attempt will fail. The initiator MAY then attempt to connect via TCP or SCTP and initiate the TLS/TCP and DTLS/SCTP @@ -3878,6 +3849,25 @@ Internet-Draft Diameter Base Protocol January 2011 Any implementation that produces equivalent results is considered compliant. + + + + + + + + + + + + + + +Fajardo, et al. Standards Track [Page 69] + +RFC 6733 Diameter Base Protocol October 2012 + + state event action next state ----------------------------------------------------------------- Closed Start I-Snd-Conn-Req Wait-Conn-Ack @@ -3914,13 +3904,6 @@ Internet-Draft Diameter Base Protocol January 2011 R-Conn-CER R-Reject Wait-Returns Timeout Error Closed - - -Fajardo, et al. Expires July 24, 2011 [Page 70] - -Internet-Draft Diameter Base Protocol January 2011 - - R-Open Send-Message R-Snd-Message R-Open R-Rcv-Message Process R-Open R-Rcv-DWR Process-DWR, R-Open @@ -3928,10 +3911,19 @@ Internet-Draft Diameter Base Protocol January 2011 R-Rcv-DWA Process-DWA R-Open R-Conn-CER R-Reject R-Open Stop R-Snd-DPR Closing - R-Rcv-DPR R-Snd-DPA, Closed - R-Disc + R-Rcv-DPR R-Snd-DPA Closing R-Peer-Disc R-Disc Closed + + + + + +Fajardo, et al. Standards Track [Page 70] + +RFC 6733 Diameter Base Protocol October 2012 + + I-Open Send-Message I-Snd-Message I-Open I-Rcv-Message Process I-Open I-Rcv-DWR Process-DWR, I-Open @@ -3939,8 +3931,7 @@ Internet-Draft Diameter Base Protocol January 2011 I-Rcv-DWA Process-DWA I-Open R-Conn-CER R-Reject I-Open Stop I-Snd-DPR Closing - I-Rcv-DPR I-Snd-DPA, Closed - I-Disc + I-Rcv-DPR I-Snd-DPA Closing I-Peer-Disc I-Disc Closed Closing I-Rcv-DPA I-Disc Closed @@ -3949,88 +3940,44 @@ Internet-Draft Diameter Base Protocol January 2011 I-Peer-Disc I-Disc Closed R-Peer-Disc R-Disc Closed -5.6.1. Incoming connections +5.6.1. Incoming Connections When a connection request is received from a Diameter peer, it is not, in the general case, possible to know the identity of that peer until a CER is received from it. This is because host and port - determine the identity of a Diameter peer; and the source port of an - incoming connection is arbitrary. Upon receipt of CER, the identity - of the connecting peer can be uniquely determined from Origin-Host. + determine the identity of a Diameter peer; the source port of an + incoming connection is arbitrary. Upon receipt of a CER, the + identity of the connecting peer can be uniquely determined from the + Origin-Host. For this reason, a Diameter peer must employ logic separate from the state machine to receive connection requests, accept them, and await - CER. Once CER arrives on a new connection, the Origin-Host that - identifies the peer is used to locate the state machine associated - with that peer, and the new connection and CER are passed to the - state machine as an R-Conn-CER event. + the CER. Once the CER arrives on a new connection, the Origin-Host + that identifies the peer is used to locate the state machine + associated with that peer, and the new connection and CER are passed + to the state machine as an R-Conn-CER event. The logic that handles incoming connections SHOULD close and discard - the connection if any message other than CER arrives, or if an + the connection if any message other than a CER arrives or if an implementation-defined timeout occurs prior to receipt of CER. - - - -Fajardo, et al. Expires July 24, 2011 [Page 71] - -Internet-Draft Diameter Base Protocol January 2011 - - Because handling of incoming connections up to and including receipt - of CER requires logic, separate from that of any individual state + of a CER requires logic, separate from that of any individual state machine associated with a particular peer, it is described separately in this section rather than in the state machine above. 5.6.2. Events Transitions and actions in the automaton are caused by events. In - this section, we will ignore the -I and -R prefix, since the actual - event would be identical, but would occur on one of two possible + this section, we will ignore the I- and R- prefixes, since the actual + event would be identical, but it would occur on one of two possible connections. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Fajardo, et al. Expires July 24, 2011 [Page 72] +Fajardo, et al. Standards Track [Page 71] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 Start The Diameter application has signaled that a @@ -4053,7 +4000,8 @@ Internet-Draft Diameter Base Protocol January 2011 Rcv-CEA A CEA message from the peer was received. - Rcv-Non-CEA A message other than CEA from the peer was received. + Rcv-Non-CEA A message, other than a CEA, from the peer was + received. Peer-Disc A disconnection indication from the peer was received. @@ -4066,7 +4014,7 @@ Internet-Draft Diameter Base Protocol January 2011 Send-Message A message is to be sent. - Rcv-Message A message other than CER, CEA, DPR, DPA, DWR or DWA + Rcv-Message A message other than CER, CEA, DPR, DPA, DWR, or DWA was received. Stop The Diameter application has signaled that a @@ -4077,16 +4025,15 @@ Internet-Draft Diameter Base Protocol January 2011 Actions in the automaton are caused by events and typically indicate the transmission of packets and/or an action to be taken on the - connection. In this section we will ignore the I- and R-prefix, - since the actual action would be identical, but would occur on one of - two possible connections. - + connection. In this section, we will ignore the I- and R- prefixes, + since the actual action would be identical, but it would occur on one + of two possible connections. -Fajardo, et al. Expires July 24, 2011 [Page 73] +Fajardo, et al. Standards Track [Page 72] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 Snd-Conn-Req A transport connection is initiated with the peer. @@ -4098,11 +4045,12 @@ Internet-Draft Diameter Base Protocol January 2011 is disconnected. Process-CER The CER associated with the R-Conn-CER is processed. + Snd-CER A CER message is sent to the peer. Snd-CEA A CEA message is sent to the peer. - Cleanup If necessary, the connection is shutdown, and any + Cleanup If necessary, the connection is shut down, and any local resources are freed. Error The transport layer connection is disconnected, @@ -4139,10 +4087,9 @@ Internet-Draft Diameter Base Protocol January 2011 - -Fajardo, et al. Expires July 24, 2011 [Page 74] +Fajardo, et al. Standards Track [Page 73] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 5.6.4. The Election Process @@ -4150,134 +4097,97 @@ Internet-Draft Diameter Base Protocol January 2011 The election is performed on the responder. The responder compares the Origin-Host received in the CER with its own Origin-Host as two streams of octets. If the local Origin-Host lexicographically - succeeds the received Origin-Host a Win-Election event is issued - locally. Diameter identities are in ASCII form therefore the lexical - comparison is consistent with DNS case insensitivity where octets - that fall in the ASCII range 'a' through 'z' MUST compare equally to - their upper-case counterparts between 'A' and 'Z'. See Appendix D - for interactions between the Diameter protocol and Internationalized - Domain Name (IDNs). + succeeds the received Origin-Host, a Win-Election event is issued + locally. Diameter identities are in ASCII form; therefore, the + lexical comparison is consistent with DNS case insensitivity, where + octets that fall in the ASCII range 'a' through 'z' MUST compare + equally to their uppercase counterparts between 'A' and 'Z'. See + Appendix D for interactions between the Diameter protocol and + Internationalized Domain Name (IDNs). The winner of the election MUST close the connection it initiated. Historically, maintaining the responder side of a connection was more efficient than maintaining the initiator side. However, current practices makes this distinction irrelevant. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Fajardo, et al. Expires July 24, 2011 [Page 75] - -Internet-Draft Diameter Base Protocol January 2011 - - -6. Diameter message processing +6. Diameter Message Processing This section describes how Diameter requests and answers are created and processed. 6.1. Diameter Request Routing Overview - A request is sent towards its final destination using a combination - of the Destination-Realm and Destination-Host AVPs, in one of these - three combinations: + A request is sent towards its final destination using one of the + following three combinations of the Destination-Realm and + Destination-Host AVPs: - o a request that is not able to be proxied (such as CER) MUST NOT + o A request that is not able to be proxied (such as a CER) MUST NOT contain either Destination-Realm or Destination-Host AVPs. - o a request that needs to be sent to a home server serving a + o A request that needs to be sent to a home server serving a specific realm, but not to a specific server (such as the first - request of a series of round-trips), MUST contain a Destination- - Realm AVP, but MUST NOT contain a Destination-Host AVP. For + request of a series of round trips), MUST contain a Destination- + Realm AVP but MUST NOT contain a Destination-Host AVP. For Diameter clients, the value of the Destination-Realm AVP MAY be extracted from the User-Name AVP, or other methods. - o otherwise, a request that needs to be sent to a specific home - server among those serving a given realm, MUST contain both the + o Otherwise, a request that needs to be sent to a specific home + server among those serving a given realm MUST contain both the Destination-Realm and Destination-Host AVPs. The Destination-Host AVP is used as described above when the destination of the request is fixed, which includes: - o Authentication requests that span multiple round trips + o Authentication requests that span multiple round trips. + + + + +Fajardo, et al. Standards Track [Page 74] + +RFC 6733 Diameter Base Protocol October 2012 + o A Diameter message that uses a security mechanism that makes use of a pre-established session key shared between the source and the final destination of the message. - o Server initiated messages that MUST be received by a specific + o Server-initiated messages that MUST be received by a specific Diameter client (e.g., access device), such as the Abort-Session- Request message, which is used to request that a particular user's session be terminated. - Note that an agent can forward a request to a host described in the - Destination-Host AVP only if the host in question is included in its - peer table (see Section 2.7). Otherwise, the request is routed based - on the Destination-Realm only (see Sections 6.1.6). + Note that an agent can only forward a request to a host described in + the Destination-Host AVP if the host in question is included in its + peer table (see Section 2.6). Otherwise, the request is routed based + on the Destination-Realm only (see Section 6.1.6). When a message is received, the message is processed in the following order: - - - - -Fajardo, et al. Expires July 24, 2011 [Page 76] - -Internet-Draft Diameter Base Protocol January 2011 - - o If the message is destined for the local host, the procedures listed in Section 6.1.4 are followed. o If the message is intended for a Diameter peer with whom the local host is able to directly communicate, the procedures listed in - Section 6.1.5 are followed. This is known as Request Forwarding. + Section 6.1.5 are followed. This is known as "Request + Forwarding". - o The procedures listed in Section 6.1.6 are followed, which is - known as Request Routing. + o The procedure listed in Section 6.1.6 is followed, which is known + as "Request Routing". - o If none of the above is successful, an answer is returned with the - Result-Code set to DIAMETER_UNABLE_TO_DELIVER, with the E-bit set. + o If none of the above are successful, an answer is returned with + the Result-Code set to DIAMETER_UNABLE_TO_DELIVER, with the 'E' + bit set. For routing of Diameter messages to work within an administrative domain, all Diameter nodes within the realm MUST be peers. - Note the processing rules contained in this section are intended to - be used as general guidelines to Diameter developers. Certain - implementations MAY use different methods than the ones described - here, and still comply with the protocol specification. See Section - 7 for more detail on error handling. + The overview contained in this section (6.1) is intended to provide + general guidelines to Diameter developers. Implementations are free + to use different methods than the ones described here as long as they + conform to the requirements specified in Sections 6.1.1 through + 6.1.9. See Section 7 for more details on error handling. 6.1.1. Originating a Request @@ -4285,33 +4195,35 @@ Internet-Draft Diameter Base Protocol January 2011 described in the application definition for that specific request, the following procedures MUST be followed: - o the Command-Code is set to the appropriate value - o the 'R' bit is set - o the End-to-End Identifier is set to a locally unique value - o the Origin-Host and Origin-Realm AVPs MUST be set to the - appropriate values, used to identify the source of the message - o the Destination-Host and Destination-Realm AVPs MUST be set to the - appropriate values as described in Section 6.1. +Fajardo, et al. Standards Track [Page 75] + +RFC 6733 Diameter Base Protocol October 2012 -6.1.2. Sending a Request - When sending a request, originated either locally, or as the result - of a forwarding or routing operation, the following procedures SHOULD - be followed: + o the Command Code is set to the appropriate value; - o The Hop-by-Hop Identifier SHOULD be set to a locally unique value. + o the 'R' bit is set; + o the End-to-End Identifier is set to a locally unique value; + o the Origin-Host and Origin-Realm AVPs MUST be set to the + appropriate values, used to identify the source of the message; + and + o the Destination-Host and Destination-Realm AVPs MUST be set to the + appropriate values, as described in Section 6.1. -Fajardo, et al. Expires July 24, 2011 [Page 77] - -Internet-Draft Diameter Base Protocol January 2011 +6.1.2. Sending a Request + When sending a request, originated either locally or as the result of + a forwarding or routing operation, the following procedures SHOULD be + followed: + + o The Hop-by-Hop Identifier SHOULD be set to a locally unique value. o The message SHOULD be saved in the list of pending requests. @@ -4328,25 +4240,34 @@ Internet-Draft Diameter Base Protocol January 2011 6.1.4. Processing Local Requests A request is known to be for local consumption when one of the - following conditions occur: + following conditions occurs: - o The Destination-Host AVP contains the local host's identity, + o The Destination-Host AVP contains the local host's identity; o The Destination-Host AVP is not present, the Destination-Realm AVP contains a realm the server is configured to process locally, and - the Diameter application is locally supported, or + the Diameter application is locally supported; or o Both the Destination-Host and the Destination-Realm are not present. + + + + +Fajardo, et al. Standards Track [Page 76] + +RFC 6733 Diameter Base Protocol October 2012 + + When a request is locally processed, the rules in Section 6.2 should be used to generate the corresponding answer. 6.1.5. Request Forwarding - Request forwarding is done using the Diameter Peer Table. The - Diameter peer table contains all of the peers that the local node is - able to directly communicate with. + Request forwarding is done using the Diameter peer table. The + Diameter peer table contains all of the peers with which the local + node is able to directly communicate. When a request is received, and the host encoded in the Destination- Host AVP is one that is present in the peer table, the message SHOULD @@ -4354,29 +4275,21 @@ Internet-Draft Diameter Base Protocol January 2011 6.1.6. Request Routing - Diameter request message routing is done via realms and application - identifiers. A Diameter message that may be forwarded by Diameter - agents (proxies, redirect or relay agents) MUST include the target + Diameter request message routing is done via realms and Application + Ids. A Diameter message that may be forwarded by Diameter agents + (proxies, redirect agents, or relay agents) MUST include the target realm in the Destination-Realm AVP. Request routing SHOULD rely on the Destination-Realm AVP and the Application Id present in the request message header to aid in the routing decision. The realm MAY be retrieved from the User-Name AVP, which is in the form of a - - - -Fajardo, et al. Expires July 24, 2011 [Page 78] - -Internet-Draft Diameter Base Protocol January 2011 - - Network Access Identifier (NAI). The realm portion of the NAI is inserted in the Destination-Realm AVP. Diameter agents MAY have a list of locally supported realms and - applications, and MAY have a list of externally supported realms and - applications. When a request is received that includes a realm + applications, and they MAY have a list of externally supported realms + and applications. When a request is received that includes a realm and/or application that is not locally supported, the message is - routed to the peer configured in the Routing Table (see Section 2.7). + routed to the peer configured in the routing table (see Section 2.7). Realm names and Application Ids are the minimum supported routing criteria, additional information may be needed to support redirect @@ -4385,13 +4298,23 @@ Internet-Draft Diameter Base Protocol January 2011 6.1.7. Predictive Loop Avoidance Before forwarding or routing a request, Diameter agents, in addition - to processing done in Section 6.1.3, SHOULD check for the presence of - candidate route's peer identity in any of the Route-Record AVPs. In - an event of the agent detecting the presence of a candidate route's - peer identity in a Route-Record AVP, the agent MUST ignore such route - for the Diameter request message and attempt alternate routes if any. - In case all the candidate routes are eliminated by the above - criteria, the agent SHOULD return DIAMETER_UNABLE_TO_DELIVER message. + to performing the processing described in Section 6.1.3, SHOULD check + for the presence of a candidate route's peer identity in any of the + Route-Record AVPs. In the event of the agent detecting the presence + of a candidate route's peer identity in a Route-Record AVP, the agent + MUST ignore such a route for the Diameter request message and attempt + alternate routes if any exist. In case all the candidate routes are + eliminated by the above criteria, the agent SHOULD return a + DIAMETER_UNABLE_TO_DELIVER message. + + + + + +Fajardo, et al. Standards Track [Page 77] + +RFC 6733 Diameter Base Protocol October 2012 + 6.1.8. Redirecting Requests @@ -4399,7 +4322,7 @@ Internet-Draft Diameter Base Protocol January 2011 to REDIRECT, it MUST reply with an answer message with the 'E' bit set, while maintaining the Hop-by-Hop Identifier in the header, and include the Result-Code AVP to DIAMETER_REDIRECT_INDICATION. Each of - the servers associated with the routing entry are added in separate + the servers associated with the routing entry are added in a separate Redirect-Host AVP. +------------------+ @@ -4417,21 +4340,13 @@ Internet-Draft Diameter Base Protocol January 2011 | Agent |<-------------| Server | +-------------+ 4. Answer +-------------+ - - - -Fajardo, et al. Expires July 24, 2011 [Page 79] - -Internet-Draft Diameter Base Protocol January 2011 - - Figure 5: Diameter Redirect Agent - The receiver of the answer message with the 'E' bit set, and the - Result-Code AVP set to DIAMETER_REDIRECT_INDICATION uses the hop-by- - hop field in the Diameter header to identify the request in the - pending message queue (see Section 5.3) that is to be redirected. If - no transport connection exists with the new agent, one is created, + The receiver of an answer message with the 'E' bit set and the + Result-Code AVP set to DIAMETER_REDIRECT_INDICATION uses the Hop-by- + Hop Identifier in the Diameter header to identify the request in the + pending message queue (see Section 5.5.4) that is to be redirected. + If no transport connection exists with the new peer, one is created, and the request is sent directly to it. Multiple Redirect-Host AVPs are allowed. The receiver of the answer @@ -4440,17 +4355,26 @@ Internet-Draft Diameter Base Protocol January 2011 When the Redirect-Host-Usage AVP included in the answer message has a non-zero value, a route entry for the redirect indications is created - and cached by the receiver. The redirect usage for such route entry - is set by the value of Redirect-Host-Usage AVP and the lifetime of - the cached route entry is set by Redirect-Max-Cache-Time AVP value. + and cached by the receiver. The redirect usage for such a route + entry is set by the value of Redirect-Host-Usage AVP and the lifetime + of the cached route entry is set by Redirect-Max-Cache-Time AVP + value. It is possible that multiple redirect indications can create multiple cached route entries differing only in their redirect usage and the peer to forward messages to. As an example, two(2) route entries that are created by two(2) redirect indications results in two(2) + + + +Fajardo, et al. Standards Track [Page 78] + +RFC 6733 Diameter Base Protocol October 2012 + + cached routes for the same realm and Application Id. However, one - has a redirect usage of ALL_SESSION where matching request will be - forwarded to one peer and the other has a redirect usage of ALL_REALM + has a redirect usage of ALL_SESSION, where matching requests will be + forwarded to one peer; the other has a redirect usage of ALL_REALM, where request are forwarded to another peer. Therefore, an incoming request that matches the realm and Application Id of both routes will need additional resolution. In such a case, a routing precedence @@ -4460,32 +4384,24 @@ Internet-Draft Diameter Base Protocol January 2011 6.1.9. Relaying and Proxying Requests A relay or proxy agent MUST append a Route-Record AVP to all requests - forwarded. The AVP contains the identity of the peer the request was - received from. + forwarded. The AVP contains the identity of the peer from which the + request was received. - The Hop-by-Hop identifier in the request is saved, and replaced with - a locally unique value. The source of the request is also saved, - which includes the IP address, port and protocol. + The Hop-by-Hop Identifier in the request is saved and replaced with a + locally unique value. The source of the request is also saved, which + includes the IP address, port, and protocol. A relay or proxy agent MAY include the Proxy-Info AVP in requests if it requires access to any local state information when the corresponding response is received. The Proxy-Info AVP has security - implications as state information is distribute to other entities. - As such, it is RECOMMMENDED to protect the content of the Proxy-Info - AVP with cryptographic mechanisms, for example by using a keyed - - - -Fajardo, et al. Expires July 24, 2011 [Page 80] - -Internet-Draft Diameter Base Protocol January 2011 - - - message digest. Such a mechanism, however, requires the management - of keys, although only locally at the Diameter server. Still, a full - description of the management of the keys used to protect the Proxy- - Info AVP is beyond the scope of this document. Below is a list of - commonly recommended: + implications as state information is distributed to other entities. + As such, it is RECOMMENDED that the content of the Proxy-Info AVP be + protected with cryptographic mechanisms, for example, by using a + keyed message digest such as HMAC-SHA1 [RFC2104]. Such a mechanism, + however, requires the management of keys, although only locally at + the Diameter server. Still, a full description of the management of + the keys used to protect the Proxy-Info AVP is beyond the scope of + this document. Below is a list of common recommendations: o The keys should be generated securely following the randomness recommendations in [RFC4086]. @@ -4494,32 +4410,39 @@ Internet-Draft Diameter Base Protocol January 2011 least 128 bits in strength. o The keys should not be used for any other purpose than generating - and verifying tickets. + and verifying instances of the Proxy-Info AVP. o The keys should be changed regularly. - o The keys should be changed if the ticket format or cryptographic + o The keys should be changed if the AVP format or cryptographic protection algorithms change. The message is then forwarded to the next hop, as identified in the - Routing Table. + routing table. + + + + +Fajardo, et al. Standards Track [Page 79] + +RFC 6733 Diameter Base Protocol October 2012 + Figure 6 provides an example of message routing using the procedures listed in these sections. - (Origin-Host=nas.example.net) (Origin-Host=nas.example.net) - (Origin-Realm=example.net) (Origin-Realm=example.net) - (Destination-Realm=example.com) (Destination- - Realm=example.com) + (Origin-Host=nas.example.net) (Origin-Host=nas.example.net) + (Origin-Realm=example.net) (Origin-Realm=example.net) + (Destination-Realm=example.com) (Destination-Realm=example.com) (Route-Record=nas.example.net) - +------+ ------> +------+ ------> +------+ - | | (Request) | | (Request) | | - | NAS +-------------------+ DRL +-------------------+ HMS | - | | | | | | - +------+ <------ +------+ <------ +------+ - example.net (Answer) example.net (Answer) example.com - (Origin-Host=hms.example.com) (Origin-Host=hms.example.com) - (Origin-Realm=example.com) (Origin-Realm=example.com) + +------+ ------> +------+ ------> +------+ + | | (Request) | | (Request) | | + | NAS +-------------------+ DRL +-------------------+ HMS | + | | | | | | + +------+ <------ +------+ <------ +------+ + example.net (Answer) example.net (Answer) example.com + (Origin-Host=hms.example.com) (Origin-Host=hms.example.com) + (Origin-Realm=example.com) (Origin-Realm=example.com) Figure 6: Routing of Diameter messages @@ -4527,15 +4450,7 @@ Internet-Draft Diameter Base Protocol January 2011 incoming messages. At a minimum, validation of the message header and relevant routing AVPs has to be done when relaying messages. Proxy agents may optionally perform more in-depth message validation - for applications it is interested in. - - - - -Fajardo, et al. Expires July 24, 2011 [Page 81] - -Internet-Draft Diameter Base Protocol January 2011 - + for applications in which it is interested. 6.2. Diameter Answer Processing @@ -4544,7 +4459,7 @@ Internet-Draft Diameter Base Protocol January 2011 additional procedures that MAY be discussed in the Diameter application defining the command: - o The same Hop-by-Hop identifier in the request is used in the + o The same Hop-by-Hop Identifier in the request is used in the answer. o The local host's identity is encoded in the Origin-Host AVP. @@ -4561,15 +4476,23 @@ Internet-Draft Diameter Base Protocol January 2011 o Any Proxy-Info AVPs in the request MUST be added to the answer message, in the same order they were present in the request. + + + +Fajardo, et al. Standards Track [Page 80] + +RFC 6733 Diameter Base Protocol October 2012 + + o The 'P' bit is set to the same value as the one in the request. o The same End-to-End identifier in the request is used in the answer. - Note that the error messages (see Section 7.3) are also subjected to + Note that the error messages (see Section 7) are also subjected to the above processing rules. -6.2.1. Processing received Answers +6.2.1. Processing Received Answers A Diameter client or proxy MUST match the Hop-by-Hop Identifier in an answer received against the list of pending requests. The @@ -4579,31 +4502,23 @@ Internet-Draft Diameter Base Protocol January 2011 6.2.2. Relaying and Proxying Answers - If the answer is for a request which was proxied or relayed, the - agent MUST restore the original value of the Diameter header's Hop- - by-Hop Identifier field. + If the answer is for a request that was proxied or relayed, the agent + MUST restore the original value of the Diameter header's Hop-by-Hop + Identifier field. If the last Proxy-Info AVP in the message is targeted to the local Diameter server, the AVP MUST be removed before the answer is - - - -Fajardo, et al. Expires July 24, 2011 [Page 82] - -Internet-Draft Diameter Base Protocol January 2011 - - forwarded. If a relay or proxy agent receives an answer with a Result-Code AVP indicating a failure, it MUST NOT modify the contents of the AVP. - Any additional local errors detected SHOULD be logged, but not + Any additional local errors detected SHOULD be logged but not reflected in the Result-Code AVP. If the agent receives an answer message with a Result-Code AVP indicating success, and it wishes to modify the AVP to indicate an error, it MUST modify the Result-Code AVP to contain the appropriate error in the message destined towards - the access device as well as include the Error-Reporting-Host AVP and - it MUST issue an STR on behalf of the access device towards the + the access device as well as include the Error-Reporting-Host AVP; it + MUST also issue an STR on behalf of the access device towards the Diameter server. The agent MUST then send the answer to the host that it received the @@ -4612,10 +4527,19 @@ Internet-Draft Diameter Base Protocol January 2011 6.3. Origin-Host AVP The Origin-Host AVP (AVP Code 264) is of type DiameterIdentity, and - MUST be present in all Diameter messages. This AVP identifies the + it MUST be present in all Diameter messages. This AVP identifies the endpoint that originated the Diameter message. Relay agents MUST NOT modify this AVP. + + + + +Fajardo, et al. Standards Track [Page 81] + +RFC 6733 Diameter Base Protocol October 2012 + + The value of the Origin-Host AVP is guaranteed to be unique within a single host. @@ -4638,17 +4562,9 @@ Internet-Draft Diameter Base Protocol January 2011 The Destination-Host AVP (AVP Code 293) is of type DiameterIdentity. This AVP MUST be present in all unsolicited agent initiated messages, - MAY be present in request messages, and MUST NOT be present in Answer + MAY be present in request messages, and MUST NOT be present in answer messages. - - - -Fajardo, et al. Expires July 24, 2011 [Page 83] - -Internet-Draft Diameter Base Protocol January 2011 - - The absence of the Destination-Host AVP will cause a message to be sent to any Diameter server supporting the application within the realm specified in Destination-Realm AVP. @@ -4658,20 +4574,28 @@ Internet-Draft Diameter Base Protocol January 2011 6.6. Destination-Realm AVP - The Destination-Realm AVP (AVP Code 283) is of type DiameterIdentity, - and contains the realm the message is to be routed to. The - Destination-Realm AVP MUST NOT be present in Answer messages. - Diameter Clients insert the realm portion of the User-Name AVP. + The Destination-Realm AVP (AVP Code 283) is of type DiameterIdentity + and contains the realm to which the message is to be routed. The + Destination-Realm AVP MUST NOT be present in answer messages. + Diameter clients insert the realm portion of the User-Name AVP. Diameter servers initiating a request message use the value of the Origin-Realm AVP from a previous message received from the intended target host (unless it is known a priori). When present, the Destination-Realm AVP is used to perform message routing decisions. - An ABNF for a request message that includes the Destination-Realm AVP + The CCF for a request message that includes the Destination-Realm AVP SHOULD list the Destination-Realm AVP as a required AVP (an AVP - indicated as {AVP}) otherwise the message is inherently a non- + indicated as {AVP}); otherwise, the message is inherently a non- routable message. + + + +Fajardo, et al. Standards Track [Page 82] + +RFC 6733 Diameter Base Protocol October 2012 + + This AVP SHOULD be placed as close to the Diameter header as possible. @@ -4692,19 +4616,11 @@ Internet-Draft Diameter Base Protocol January 2011 The Proxy-Info AVP (AVP Code 284) is of type Grouped. This AVP contains the identity and local state information of the Diameter node that creates and adds it to a message. The Grouped Data field - has the following ABNF grammar: + has the following CCF grammar: Proxy-Info ::= < AVP Header: 284 > { Proxy-Host } { Proxy-State } - - - -Fajardo, et al. Expires July 24, 2011 [Page 84] - -Internet-Draft Diameter Base Protocol January 2011 - - * [ AVP ] 6.7.3. Proxy-Host AVP @@ -4728,10 +4644,18 @@ Internet-Draft Diameter Base Protocol January 2011 Application-Id AVP MUST match the Application Id present in the Diameter message header. + + + +Fajardo, et al. Standards Track [Page 83] + +RFC 6733 Diameter Base Protocol October 2012 + + 6.9. Acct-Application-Id AVP The Acct-Application-Id AVP (AVP Code 259) is of type Unsigned32 and - is used in order to advertise support of the Accounting portion of an + is used in order to advertise support of the accounting portion of an application (see Section 2.4). If present in a message other than CER and CEA, the value of the Acct-Application-Id AVP MUST match the Application Id present in the Diameter message header. @@ -4740,10 +4664,10 @@ Internet-Draft Diameter Base Protocol January 2011 The Inband-Security-Id AVP (AVP Code 299) is of type Unsigned32 and is used in order to advertise support of the security portion of the - application. The use of this AVP in CER and CEA messages is no - longer recommended. Instead, discovery of a Diameter entities - security capabilities can be done either through static configuration - or via Diameter Peer Discovery described in Section 5.2. + application. The use of this AVP in CER and CEA messages is NOT + RECOMMENDED. Instead, discovery of a Diameter entity's security + capabilities can be done either through static configuration or via + Diameter Peer Discovery as described in Section 5.2. The following values are supported: @@ -4753,36 +4677,37 @@ Internet-Draft Diameter Base Protocol January 2011 This peer does not support TLS/TCP and DTLS/SCTP. This is the default value, if the AVP is omitted. - - - -Fajardo, et al. Expires July 24, 2011 [Page 85] - -Internet-Draft Diameter Base Protocol January 2011 - - TLS 1 - This node supports TLS/TCP and DTLS/SCTP security, as defined by - [RFC5246]. + This node supports TLS/TCP [RFC5246] and DTLS/SCTP [RFC6083] + security. 6.11. Vendor-Specific-Application-Id AVP The Vendor-Specific-Application-Id AVP (AVP Code 260) is of type Grouped and is used to advertise support of a vendor-specific - Diameter Application. Exactly one instance of either Auth- + Diameter application. Exactly one instance of either Auth- Application-Id or Acct-Application-Id AVP MUST be present. The Application Id carried by either Auth-Application-Id or Acct- - Application-Id AVP MUST comply with vendor specific Application Id - assignment described in Sec 11.3. It MUST also match the Application - Id present in the Diameter header except when used in a CER or CEA - message. + Application-Id AVP MUST comply with vendor-specific Application Id + assignment described in Section 11.3. It MUST also match the + Application Id present in the Diameter header except when used in a + CER or CEA message. The Vendor-Id AVP is an informational AVP pertaining to the vendor who may have authorship of the vendor-specific Diameter application. It MUST NOT be used as a means of defining a completely separate vendor-specific Application Id space. + + + + +Fajardo, et al. Standards Track [Page 84] + +RFC 6733 Diameter Base Protocol October 2012 + + The Vendor-Specific-Application-Id AVP SHOULD be placed as close to the Diameter header as possible. @@ -4795,9 +4720,9 @@ Internet-Draft Diameter Base Protocol January 2011 A Vendor-Specific-Application-Id AVP MUST contain exactly one of either Auth-Application-Id or Acct-Application-Id. If a Vendor- - Specific-Application-Id is received without any of these two AVPs, + Specific-Application-Id is received without one of these two AVPs, then the recipient SHOULD issue an answer with a Result-Code set to - DIAMETER_MISSING_AVP. The answer SHOULD also include a Failed-AVP + DIAMETER_MISSING_AVP. The answer SHOULD also include a Failed-AVP, which MUST contain an example of an Auth-Application-Id AVP and an Acct-Application-Id AVP. @@ -4805,22 +4730,13 @@ Internet-Draft Diameter Base Protocol January 2011 Auth-Application-Id and Acct-Application-Id, then the recipient MUST issue an answer with Result-Code set to DIAMETER_AVP_OCCURS_TOO_MANY_TIMES. The answer MUST also include a - Failed-AVP which MUST contain the received Auth-Application-Id AVP + Failed-AVP, which MUST contain the received Auth-Application-Id AVP and Acct-Application-Id AVP. - - - - -Fajardo, et al. Expires July 24, 2011 [Page 86] - -Internet-Draft Diameter Base Protocol January 2011 - - 6.12. Redirect-Host AVP The Redirect-Host AVP (AVP Code 292) is of type DiameterURI. One or - more of instances of this AVP MUST be present if the answer message's + more instances of this AVP MUST be present if the answer message's 'E' bit is set and the Result-Code AVP is set to DIAMETER_REDIRECT_INDICATION. @@ -4836,63 +4752,55 @@ Internet-Draft Diameter Base Protocol January 2011 This AVP MAY be present in answer messages whose 'E' bit is set and the Result-Code AVP is set to DIAMETER_REDIRECT_INDICATION. - When present, this AVP provides a hints about how the routing entry + When present, this AVP provides hints about how the routing entry resulting from the Redirect-Host is to be used. The following values are supported: + + +Fajardo, et al. Standards Track [Page 85] + +RFC 6733 Diameter Base Protocol October 2012 + + DONT_CACHE 0 The host specified in the Redirect-Host AVP SHOULD NOT be cached. This is the default value. - ALL_SESSION 1 All messages within the same session, as defined by the same value of the Session-ID AVP SHOULD be sent to the host specified in the Redirect-Host AVP. - ALL_REALM 2 All messages destined for the realm requested SHOULD be sent to the host specified in the Redirect-Host AVP. - REALM_AND_APPLICATION 3 All messages for the application requested to the realm specified SHOULD be sent to the host specified in the Redirect-Host AVP. - - - -Fajardo, et al. Expires July 24, 2011 [Page 87] - -Internet-Draft Diameter Base Protocol January 2011 - - ALL_APPLICATION 4 All messages for the application requested SHOULD be sent to the host specified in the Redirect-Host AVP. - ALL_HOST 5 All messages that would be sent to the host that generated the Redirect-Host SHOULD be sent to the host specified in the - Redirect- Host AVP. - + Redirect-Host AVP. ALL_USER 6 All messages for the user requested SHOULD be sent to the host specified in the Redirect-Host AVP. - - When multiple cached routes are created by redirect indications and they differ only in redirect usage and peers to forward requests to (see Section 6.1.8), a precedence rule MUST be applied to the @@ -4902,6 +4810,16 @@ Internet-Draft Diameter Base Protocol January 2011 other as they appear. The order is as follows: + + + + + +Fajardo, et al. Standards Track [Page 86] + +RFC 6733 Diameter Base Protocol October 2012 + + 1. ALL_SESSION 2. ALL_USER @@ -4917,58 +4835,31 @@ Internet-Draft Diameter Base Protocol January 2011 6.14. Redirect-Max-Cache-Time AVP The Redirect-Max-Cache-Time AVP (AVP Code 262) is of type Unsigned32. - This AVP MUST be present in answer messages whose 'E' bit is set, the - Result-Code AVP is set to DIAMETER_REDIRECT_INDICATION and the - Redirect-Host-Usage AVP set to a non-zero value. - - - - -Fajardo, et al. Expires July 24, 2011 [Page 88] - -Internet-Draft Diameter Base Protocol January 2011 - + This AVP MUST be present in answer messages whose 'E' bit is set, + whose Result-Code AVP is set to DIAMETER_REDIRECT_INDICATION, and + whose Redirect-Host-Usage AVP set to a non-zero value. This AVP contains the maximum number of seconds the peer and route table entries, created as a result of the Redirect-Host, SHOULD be cached. Note that once a host is no longer reachable, any associated - cache, peer and routing table entries MUST be deleted. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + cache, peer, and routing table entries MUST be deleted. +7. Error Handling + There are two different types of errors in Diameter; protocol errors + and application errors. A protocol error is one that occurs at the + base protocol level and MAY require per-hop attention (e.g., a + message routing error). Application errors, on the other hand, + generally occur due to a problem with a function specified in a + Diameter application (e.g., user authentication, missing AVP). + Result-Code AVP values that are used to report protocol errors MUST + only be present in answer messages whose 'E' bit is set. When a + request message is received that causes a protocol error, an answer + message is returned with the 'E' bit set, and the Result-Code AVP is + set to the appropriate protocol error value. As the answer is sent + back towards the originator of the request, each proxy or relay agent + MAY take action on the message. @@ -4980,27 +4871,10 @@ Internet-Draft Diameter Base Protocol January 2011 -Fajardo, et al. Expires July 24, 2011 [Page 89] +Fajardo, et al. Standards Track [Page 87] -Internet-Draft Diameter Base Protocol January 2011 - - -7. Error Handling +RFC 6733 Diameter Base Protocol October 2012 - There are two different types of errors in Diameter; protocol and - application errors. A protocol error is one that occurs at the base - protocol level, and MAY require per hop attention (e.g., message - routing error). Application errors, on the other hand, generally - occur due to a problem with a function specified in a Diameter - application (e.g., user authentication, missing AVP). - - Result-Code AVP values that are used to report protocol errors MUST - only be present in answer messages whose 'E' bit is set. When a - request message is received that causes a protocol error, an answer - message is returned with the 'E' bit set, and the Result-Code AVP is - set to the appropriate protocol error value. As the answer is sent - back towards the originator of the request, each proxy or relay agent - MAY take action on the message. 1. Request +---------+ Link Broken +-------------------------->|Diameter |----///----+ @@ -5014,7 +4888,7 @@ Internet-Draft Diameter Base Protocol January 2011 | Relay 3 |-----------+ +---------+ - Figure 7: Example of Protocol Error causing answer message + Figure 7: Example of Protocol Error Causing Answer Message Figure 7 provides an example of a message forwarded upstream by a Diameter relay. When the message is received by Relay 2, and it @@ -5032,40 +4906,40 @@ Internet-Draft Diameter Base Protocol January 2011 +---------+ 4. Answer +---------+ 3. Answer +---------+ (Missing AVP) (Missing AVP) - Figure 8: Example of Application Error Answer message - - - -Fajardo, et al. Expires July 24, 2011 [Page 90] - -Internet-Draft Diameter Base Protocol January 2011 - + Figure 8: Example of Application Error Answer Message Figure 8 provides an example of a Diameter message that caused an application error. When application errors occur, the Diameter - entity reporting the error clears the 'R' bit in the Command Flags, + entity reporting the error clears the 'R' bit in the Command Flags and adds the Result-Code AVP with the proper value. Application - errors do not require any proxy or relay agent involvement, and - therefore the message would be forwarded back to the originator of + errors do not require any proxy or relay agent involvement; + therefore, the message would be forwarded back to the originator of the request. In the case where the answer message itself contains errors, any related session SHOULD be terminated by sending an STR or ASR message. The Termination-Cause AVP in the STR MAY be filled with the appropriate value to indicate the cause of the error. An application - MAY also send an application-specific request instead of STR or ASR - to signal the error in the case where no state is maintained or to - allow for some form of error recovery with the corresponding Diameter - entity. + MAY also send an application-specific request instead of an STR or + ASR message to signal the error in the case where no state is + maintained or to allow for some form of error recovery with the + corresponding Diameter entity. + + + +Fajardo, et al. Standards Track [Page 88] + +RFC 6733 Diameter Base Protocol October 2012 + There are certain Result-Code AVP application errors that require additional AVPs to be present in the answer. In these cases, the Diameter node that sets the Result-Code AVP to indicate the error - MUST add the AVPs. Examples are: + MUST add the AVPs. Examples are as follows: o A request with an unrecognized AVP is received with the 'M' bit - (Mandatory bit) set, causes an answer to be sent with the Result- - Code AVP set to DIAMETER_AVP_UNSUPPORTED, and the Failed-AVP AVP + (Mandatory bit) set causes an answer to be sent with the Result- + Code AVP set to DIAMETER_AVP_UNSUPPORTED and the Failed-AVP AVP containing the offending AVP. o A request with an AVP that is received with an unrecognized value @@ -5073,46 +4947,46 @@ Internet-Draft Diameter Base Protocol January 2011 DIAMETER_INVALID_AVP_VALUE, with the Failed-AVP AVP containing the AVP causing the error. - o A received command which is missing AVP(s) that are defined as - required in the commands ABNF; examples are AVPs indicated as + o A received command that is missing AVPs that are defined as + required in the commands CCF; examples are AVPs indicated as {AVP}. The receiver issues an answer with the Result-Code set to - DIAMETER_MISSING_AVP, and creates an AVP with the AVP Code and + DIAMETER_MISSING_AVP and creates an AVP with the AVP Code and other fields set as expected in the missing AVP. The created AVP - is then added to the Failed- AVP AVP. + is then added to the Failed-AVP AVP. The Result-Code AVP describes the error that the Diameter node encountered in its processing. In case there are multiple errors, the Diameter node MUST report only the first error it encountered - (detected possibly in some implementation dependent order). The + (detected possibly in some implementation-dependent order). The specific errors that can be described by this AVP are described in the following section. +7.1. Result-Code AVP + The Result-Code AVP (AVP Code 268) is of type Unsigned32 and + indicates whether a particular request was completed successfully or + an error occurred. All Diameter answer messages in IETF-defined + Diameter application specifications MUST include one Result-Code AVP. + A non-successful Result-Code AVP (one containing a non-2xxx value + other than DIAMETER_REDIRECT_INDICATION) MUST include the Error- + Reporting-Host AVP if the host setting the Result-Code AVP is + different from the identity encoded in the Origin-Host AVP. + The Result-Code data field contains an IANA-managed 32-bit address + space representing errors (see Section 11.3.2). Diameter provides + the following classes of errors, all identified by the thousands + digit in the decimal notation: -Fajardo, et al. Expires July 24, 2011 [Page 91] - -Internet-Draft Diameter Base Protocol January 2011 -7.1. Result-Code AVP - The Result-Code AVP (AVP Code 268) is of type Unsigned32 and - indicates whether a particular request was completed successfully or - whether an error occurred. All Diameter answer messages in IETF - defined Diameter application specification MUST include one Result- - Code AVP. A non-successful Result-Code AVP (one containing a non - 2xxx value other than DIAMETER_REDIRECT_INDICATION) MUST include the - Error-Reporting-Host AVP if the host setting the Result-Code AVP is - different from the identity encoded in the Origin-Host AVP. +Fajardo, et al. Standards Track [Page 89] + +RFC 6733 Diameter Base Protocol October 2012 - The Result-Code data field contains an IANA-managed 32-bit address - space representing errors (see Section 11.4). Diameter provides the - following classes of errors, all identified by the thousands digit in - the decimal notation: o 1xxx (Informational) @@ -5124,7 +4998,7 @@ Internet-Draft Diameter Base Protocol January 2011 o 5xxx (Permanent Failure) - A non-recognized class (one whose first digit is not defined in this + An unrecognized class (one whose first digit is not defined in this section) MUST be handled as a permanent failure. 7.1.1. Informational @@ -5133,7 +5007,6 @@ Internet-Draft Diameter Base Protocol January 2011 requester that a request could not be satisfied, and additional action is required on its part before access is granted. - DIAMETER_MULTI_ROUND_AUTH 1001 This informational error is returned by a Diameter server to @@ -5141,24 +5014,11 @@ Internet-Draft Diameter Base Protocol January 2011 used requires multiple round trips, and a subsequent request needs to be issued in order for access to be granted. - - - - - - - -Fajardo, et al. Expires July 24, 2011 [Page 92] - -Internet-Draft Diameter Base Protocol January 2011 - - 7.1.2. Success Errors that fall within the Success category are used to inform a peer that a request has been successfully completed. - DIAMETER_SUCCESS 2001 The request was successfully completed. @@ -5174,27 +5034,33 @@ Internet-Draft Diameter Base Protocol January 2011 Errors that fall within the Protocol Error category SHOULD be treated on a per-hop basis, and Diameter proxies MAY attempt to correct the error, if it is possible. Note that these errors MUST only be used - in answer messages whose 'E' bit is set. This document omits some - error codes defined in [RFC3588]. To provide backward compatibility - with [RFC3588] implementations these error code values are not re- - used and hence the error codes values enumerated below are non- - sequential. + in answer messages whose 'E' bit is set. + + +Fajardo, et al. Standards Track [Page 90] + +RFC 6733 Diameter Base Protocol October 2012 + + + DIAMETER_COMMAND_UNSUPPORTED 3001 + + This error code is used when a Diameter entity receives a message + with a Command Code that it does not support. + DIAMETER_UNABLE_TO_DELIVER 3002 - This error is given when Diameter can not deliver the message to + This error is given when Diameter cannot deliver the message to the destination, either because no host within the realm supporting the required application was available to process the - request, or because Destination-Host AVP was given without the + request or because the Destination-Host AVP was given without the associated Destination-Realm AVP. - DIAMETER_REALM_NOT_SERVED 3003 The intended realm of the request is not recognized. - DIAMETER_TOO_BUSY 3004 When returned, a Diameter node SHOULD attempt to send the message @@ -5202,13 +5068,6 @@ Internet-Draft Diameter Base Protocol January 2011 specific server is requested, and it cannot provide the requested service. - - -Fajardo, et al. Expires July 24, 2011 [Page 93] - -Internet-Draft Diameter Base Protocol January 2011 - - DIAMETER_LOOP_DETECTED 3005 An agent detected a loop while trying to get the message to the @@ -5216,121 +5075,110 @@ Internet-Draft Diameter Base Protocol January 2011 if one is available, but the peer reporting the error has identified a configuration problem. - DIAMETER_REDIRECT_INDICATION 3006 A redirect agent has determined that the request could not be - satisfied locally and the initiator of the request SHOULD direct + satisfied locally, and the initiator of the request SHOULD direct the request directly to the server, whose contact information has been added to the response. When set, the Redirect-Host AVP MUST be present. - DIAMETER_APPLICATION_UNSUPPORTED 3007 A request was sent for an application that is not supported. + DIAMETER_INVALID_HDR_BITS 3008 - DIAMETER_INVALID_BIT_IN_HEADER 3011 + A request was received whose bits in the Diameter header were set + either to an invalid combination or to a value that is + inconsistent with the Command Code's definition. - This error is returned when a reserved bit in the Diameter header - is set to one (1) or the bits in the Diameter header defined in - Section 3 are set incorrectly. - DIAMETER_INVALID_MESSAGE_LENGTH 3012 +Fajardo, et al. Standards Track [Page 91] + +RFC 6733 Diameter Base Protocol October 2012 - This error is returned when a request is received with an invalid - message length. + 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. + + DIAMETER_UNKNOWN_PEER 3010 + + A CER was received from an unknown peer. 7.1.4. Transient Failures Errors that fall within the transient failures category are used to inform a peer that the request could not be satisfied at the time it - was received, but MAY be able to satisfy the request in the future. + was received but MAY be able to satisfy the request in the future. Note that these errors MUST be used in answer messages whose 'E' bit is not set. - DIAMETER_AUTHENTICATION_REJECTED 4001 The authentication process for the user failed, most likely due to an invalid password used by the user. Further attempts MUST only - - - -Fajardo, et al. Expires July 24, 2011 [Page 94] - -Internet-Draft Diameter Base Protocol January 2011 - - be tried after prompting the user for a new password. - DIAMETER_OUT_OF_SPACE 4002 A Diameter node received the accounting request but was unable to commit it to stable storage due to a temporary lack of space. - ELECTION_LOST 4003 The peer has determined that it has lost the election process and has therefore disconnected the transport connection. - 7.1.5. Permanent Failures Errors that fall within the permanent failures category are used to - inform the peer that the request failed, and should not be attempted + inform the peer that the request failed and should not be attempted again. Note that these errors SHOULD be used in answer messages whose 'E' bit is not set. In error conditions where it is not - possible or efficient to compose application-specific answer grammar - then answer messages with E-bit set and complying to the grammar - described in 7.2 MAY also be used for permanent errors. + possible or efficient to compose application-specific answer grammar, + answer messages with the 'E' bit set and which comply to the grammar + described in Section 7.2 MAY also be used for permanent errors. - To provide backward compatibility with existing implementations that - follow [RFC3588], some of the error values that have previously been - used in this category by [RFC3588] will not be re-used. Therefore - the error values enumerated here may be non-sequential. - DIAMETER_AVP_UNSUPPORTED 5001 - The peer received a message that contained an AVP that is not - recognized or supported and was marked with the Mandatory bit. A - Diameter message with this error MUST contain one or more Failed- - AVP AVP containing the AVPs that caused the failure. - DIAMETER_UNKNOWN_SESSION_ID 5002 - The request contained an unknown Session-Id. +Fajardo, et al. Standards Track [Page 92] + +RFC 6733 Diameter Base Protocol October 2012 - DIAMETER_AUTHORIZATION_REJECTED 5003 - A request was received for which the user could not be authorized. - This error could occur if the service requested is not permitted + DIAMETER_AVP_UNSUPPORTED 5001 + The peer received a message that contained an AVP that is not + recognized or supported and was marked with the 'M' (Mandatory) + bit. A Diameter message with this error MUST contain one or more + Failed-AVP AVPs containing the AVPs that caused the failure. + DIAMETER_UNKNOWN_SESSION_ID 5002 -Fajardo, et al. Expires July 24, 2011 [Page 95] - -Internet-Draft Diameter Base Protocol January 2011 + The request contained an unknown Session-Id. + DIAMETER_AUTHORIZATION_REJECTED 5003 + A request was received for which the user could not be authorized. + This error could occur if the service requested is not permitted to the user. - DIAMETER_INVALID_AVP_VALUE 5004 The request contained an AVP with an invalid value in its data portion. A Diameter message indicating this error MUST include the offending AVPs within a Failed-AVP AVP. - DIAMETER_MISSING_AVP 5005 The request did not contain an AVP that is required by the Command @@ -5340,21 +5188,28 @@ Internet-Draft Diameter Base Protocol January 2011 Vendor-Id if applicable. The value field of the missing AVP should be of correct minimum length and contain zeroes. - DIAMETER_RESOURCES_EXCEEDED 5006 A request was received that cannot be authorized because the user has already expended allowed resources. An example of this error - condition is a user that is restricted to one dial-up PPP port, - attempts to establish a second PPP connection. - + condition is when a user that is restricted to one dial-up PPP + port attempts to establish a second PPP connection. DIAMETER_CONTRADICTING_AVPS 5007 The Home Diameter server has detected AVPs in the request that - contradicted each other, and is not willing to provide service to - the user. The Failed-AVP AVPs MUST be present which contains the - AVPs that contradicted each other. + contradicted each other, and it is not willing to provide service + to the user. The Failed-AVP AVP MUST be present, which contain + the AVPs that contradicted each other. + + + + + + +Fajardo, et al. Standards Track [Page 93] + +RFC 6733 Diameter Base Protocol October 2012 DIAMETER_AVP_NOT_ALLOWED 5008 @@ -5363,22 +5218,12 @@ Internet-Draft Diameter Base Protocol January 2011 Failed-AVP AVP MUST be included and contain a copy of the offending AVP. - DIAMETER_AVP_OCCURS_TOO_MANY_TIMES 5009 A message was received that included an AVP that appeared more often than permitted in the message definition. The Failed-AVP AVP MUST be included and contain a copy of the first instance of - - - -Fajardo, et al. Expires July 24, 2011 [Page 96] - -Internet-Draft Diameter Base Protocol January 2011 - - - the offending AVP that exceeded the maximum number of occurrences - + the offending AVP that exceeded the maximum number of occurrences. DIAMETER_NO_COMMON_APPLICATION 5010 @@ -5386,18 +5231,21 @@ Internet-Draft Diameter Base Protocol January 2011 whereby no applications are common between the CER sending peer and the CER receiving peer. - DIAMETER_UNSUPPORTED_VERSION 5011 This error is returned when a request was received, whose version number is unsupported. - DIAMETER_UNABLE_TO_COMPLY 5012 This error is returned when a request is rejected for unspecified reasons. + DIAMETER_INVALID_BIT_IN_HEADER 5013 + + This error is returned when a reserved bit in the Diameter header + is set to one (1) or the bits in the Diameter header are set + incorrectly. DIAMETER_INVALID_AVP_LENGTH 5014 @@ -5407,56 +5255,41 @@ Internet-Draft Diameter Base Protocol January 2011 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 + 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. - - - DIAMETER_NO_COMMON_SECURITY 5017 - - This error is returned when a CER message is received, and there - are no common security mechanisms supported between the peers. A - Capabilities-Exchange-Answer (CEA) MUST be returned with the - Result-Code AVP set to DIAMETER_NO_COMMON_SECURITY. - - -Fajardo, et al. Expires July 24, 2011 [Page 97] +Fajardo, et al. Standards Track [Page 94] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 - DIAMETER_UNKNOWN_PEER 5018 - - A CER was received from an unknown peer. - - - DIAMETER_COMMAND_UNSUPPORTED 5019 - - This error code is used when a Diameter entity receives a message - with a Command Code that it does not support. - + 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. - DIAMETER_INVALID_HDR_BITS 5020 + DIAMETER_INVALID_MESSAGE_LENGTH 5015 - A request was received whose bits in the Diameter header were - either set to an invalid combination, or to a value that is - inconsistent with the command code's definition. + This error is returned when a request is received with an invalid + message length. + DIAMETER_INVALID_AVP_BIT_COMBO 5016 - DIAMETER_INVALID_AVP_BITS 5021 + The request contained an AVP with which is not allowed to have the + given value in the AVP Flags field. A Diameter message indicating + this error MUST include the offending AVPs within a Failed-AVP + AVP. - 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. + DIAMETER_NO_COMMON_SECURITY 5017 + This error is returned when a CER message is received, and there + are no common security mechanisms supported between the peers. A + Capabilities-Exchange-Answer (CEA) message MUST be returned with + the Result-Code AVP set to DIAMETER_NO_COMMON_SECURITY. 7.2. Error Bit @@ -5465,12 +5298,12 @@ Internet-Draft Diameter Base Protocol January 2011 the 'E' bit MUST NOT be sent as a response to an answer message. Note that a message with the 'E' bit set is still subjected to the processing rules defined in Section 6.2. When set, the answer - message will not conform to the ABNF specification for the command, - and will instead conform to the following ABNF: + message will not conform to the CCF specification for the command; + instead, it and will conform to the following CCF: Message Format - <answer-message> ::= < Diameter Header: code, ERR [PXY] > + <answer-message> ::= < Diameter Header: code, ERR [, PXY] > 0*1< Session-Id > { Origin-Host } { Origin-Realm } @@ -5481,16 +5314,16 @@ Internet-Draft Diameter Base Protocol January 2011 [ Failed-AVP ] [ Experimental-Result ] * [ Proxy-Info ] + * [ AVP ] -Fajardo, et al. Expires July 24, 2011 [Page 98] + +Fajardo, et al. Standards Track [Page 95] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 - * [ AVP ] - Note that the code used in the header is the same than the one found in the request message, but with the 'R' bit cleared and the 'E' bit set. The 'P' bit in the header is set to the same value as the one @@ -5499,10 +5332,10 @@ Internet-Draft Diameter Base Protocol January 2011 7.3. Error-Message AVP The Error-Message AVP (AVP Code 281) is of type UTF8String. It MAY - accompany a Result-Code AVP as a human readable error message. The + accompany a Result-Code AVP as a human-readable error message. The Error-Message AVP is not intended to be useful in an environment where error messages are processed automatically. It SHOULD NOT be - expected that the content of this AVP is parsed by network entities. + expected that the content of this AVP be parsed by network entities. 7.4. Error-Reporting-Host AVP @@ -5511,8 +5344,8 @@ Internet-Draft Diameter Base Protocol January 2011 host that sent the Result-Code AVP to a value other than 2001 (Success), only if the host setting the Result-Code is different from the one encoded in the Origin-Host AVP. This AVP is intended to be - used for troubleshooting purposes, and MUST be set when the Result- - Code AVP indicates a failure. + used for troubleshooting purposes, and it MUST be set when the + Result-Code AVP indicates a failure. 7.5. Failed-AVP AVP @@ -5520,43 +5353,44 @@ Internet-Draft Diameter Base Protocol January 2011 debugging information in cases where a request is rejected or not fully processed due to erroneous information in a specific AVP. The value of the Result-Code AVP will provide information on the reason - for the Failed-AVP AVP. A Diameter message SHOULD contain only one - Failed-AVP that corresponds to the error indicated by the Result-Code - AVP. For practical purposes, this Failed-AVP would typically refer - to the first AVP processing error that a Diameter node encounters. + for the Failed-AVP AVP. A Diameter answer message SHOULD contain an + instance of the Failed-AVP AVP that corresponds to the error + indicated by the Result-Code AVP. For practical purposes, this + Failed-AVP would typically refer to the first AVP processing error + that a Diameter node encounters. The possible reasons for this AVP are the presence of an improperly constructed AVP, an unsupported or unrecognized AVP, an invalid AVP value, the omission of a required AVP, the presence of an explicitly - excluded AVP (see tables in Section 10), or the presence of two or - more occurrences of an AVP which is restricted to 0, 1, or 0-1 + excluded AVP (see tables in Section 10) or the presence of two or + more occurrences of an AVP that is restricted to 0, 1, or 0-1 occurrences. A Diameter message SHOULD contain one Failed-AVP AVP, containing the entire AVP that could not be processed successfully. If the failure reason is omission of a required AVP, an AVP with the missing AVP - code, the missing vendor id, and a zero filled payload of the minimum + code, the missing Vendor-Id, and a zero-filled payload of the minimum required length for the omitted AVP will be added. If the failure + reason is an invalid AVP length where the reported length is less -Fajardo, et al. Expires July 24, 2011 [Page 99] +Fajardo, et al. Standards Track [Page 96] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 - reason is an invalid AVP length where the reported length is less than the minimum AVP header length or greater than the reported - message length, a copy of the offending AVP header and a zero filled + message length, a copy of the offending AVP header and a zero-filled payload of the minimum required length SHOULD be added. - 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. + 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. AVP Format @@ -5577,7 +5411,7 @@ Internet-Draft Diameter Base Protocol January 2011 { Experimental-Result-Code } The Vendor-Id AVP (see Section 5.3.3) in this grouped AVP identifies - the vendor responsible for the assignment of the result code which + the vendor responsible for the assignment of the result code that follows. All Diameter answer messages defined in vendor-specific applications MUST include either one Result-Code AVP or one Experimental-Result AVP. @@ -5590,23 +5424,24 @@ Internet-Draft Diameter Base Protocol January 2011 It is recommended that vendor-specific result codes follow the same conventions given for the Result-Code AVP regarding the different - types of result codes and the handling of errors (for non 2xxx + types of result codes and the handling of errors (for non-2xxx values). -Fajardo, et al. Expires July 24, 2011 [Page 100] + +Fajardo, et al. Standards Track [Page 97] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 8. Diameter User Sessions In general, Diameter can provide two different types of services to applications. The first involves authentication and authorization, - and can optionally make use of accounting. The second only makes use - of accounting. + and it can optionally make use of accounting. The second only makes + use of accounting. When a service makes use of the authentication and/or authorization portion of an application, and a user requests access to the network, @@ -5614,27 +5449,28 @@ Internet-Draft Diameter Base Protocol January 2011 auth request is defined in a service-specific Diameter application (e.g., NASREQ). The request contains a Session-Id AVP, which is used in subsequent messages (e.g., subsequent authorization, accounting, - etc) relating to the user's session. The Session-Id AVP is a means + etc.) relating to the user's session. The Session-Id AVP is a means for the client and servers to correlate a Diameter message with a user session. - When a Diameter server authorizes a user to use network resources for - a finite amount of time, and it is willing to extend the - authorization via a future request, it MUST add the Authorization- - Lifetime AVP to the answer message. The Authorization-Lifetime AVP - defines the maximum number of seconds a user MAY make use of the - resources before another authorization request is expected by the - server. The Auth-Grace-Period AVP contains the number of seconds - following the expiration of the Authorization-Lifetime, after which - the server will release all state information related to the user's - session. Note that if payment for services is expected by the - serving realm from the user's home realm, the Authorization-Lifetime - AVP, combined with the Auth-Grace-Period AVP, implies the maximum - length of the session the home realm is willing to be fiscally - responsible for. Services provided past the expiration of the - Authorization-Lifetime and Auth-Grace-Period AVPs are the - responsibility of the access device. Of course, the actual cost of - services rendered is clearly outside the scope of the protocol. + When a Diameter server authorizes a user to implement network + resources for a finite amount of time, and it is willing to extend + the authorization via a future request, it MUST add the + Authorization- Lifetime AVP to the answer message. The + Authorization-Lifetime AVP defines the maximum number of seconds a + user MAY make use of the resources before another authorization + request is expected by the server. The Auth-Grace-Period AVP + contains the number of seconds following the expiration of the + Authorization-Lifetime, after which the server will release all state + information related to the user's session. Note that if payment for + services is expected by the serving realm from the user's home realm, + the Authorization-Lifetime AVP, combined with the Auth-Grace-Period + AVP, implies the maximum length of the session for which the home + realm is willing to be fiscally responsible. Services provided past + the expiration of the Authorization-Lifetime and Auth-Grace-Period + AVPs are the responsibility of the access device. Of course, the + actual cost of services rendered is clearly outside the scope of the + protocol. An access device that does not expect to send a re-authorization or a session termination request to the server MAY include the Auth- @@ -5648,32 +5484,33 @@ Internet-Draft Diameter Base Protocol January 2011 value NO_STATE_MAINTAINED MUST NOT be set in subsequent re- authorization requests and answers. - The base protocol does not include any authorization request -Fajardo, et al. Expires July 24, 2011 [Page 101] +Fajardo, et al. Standards Track [Page 98] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 + The base protocol does not include any authorization request messages, since these are largely application-specific and are defined in a Diameter application document. However, the base protocol does define a set of messages that are used to terminate user sessions. These are used to allow servers that maintain state information to free resources. - When a service only makes use of the Accounting portion of the + When a service only makes use of the accounting portion of the Diameter protocol, even in combination with an application, the Session-Id is still used to identify user sessions. However, the session termination messages are not used, since a session is signaled as being terminated by issuing an accounting stop message. Diameter may also be used for services that cannot be easily - categorized as authentication, authorization or accounting (e.g., - certain 3GPP IMS interfaces). In such cases, the finite state + categorized as authentication, authorization, or accounting (e.g., + certain Third Generation Partnership Project Internet Multimedia + System (3GPP IMS) interfaces). In such cases, the finite state machine defined in subsequent sections may not be applicable. - Therefore, the applications itself MAY need to define its own finite + Therefore, the application itself MAY need to define its own finite state machine. However, such application-specific state machines SHOULD follow the general state machine framework outlined in this document such as the use of Session-Id AVPs and the use of STR/STA, @@ -5681,12 +5518,12 @@ Internet-Draft Diameter Base Protocol January 2011 8.1. Authorization Session State Machine - This section contains a set of finite state machines, representing - the life cycle of Diameter sessions, and which MUST be observed by - all Diameter implementations that make use of the authentication - and/or authorization portion of a Diameter application. The term - Service-Specific below refers to a message defined in a Diameter - application (e.g., Mobile IPv4, NASREQ). + This section contains a set of finite state machines, which represent + the life cycle of Diameter sessions and which MUST be observed by all + Diameter implementations that make use of the authentication and/or + authorization portion of a Diameter application. The term "Service- + Specific" below refers to a message defined in a Diameter application + (e.g., Mobile IPv4, NASREQ). There are four different authorization session state machines supported in the Diameter base protocol. The first two describe a @@ -5700,26 +5537,25 @@ Internet-Draft Diameter Base Protocol January 2011 When a session is moved to the Idle state, any resources that were allocated for the particular session must be released. Any event not - listed in the state machines MUST be considered as an error - condition, and an answer, if applicable, MUST be returned to the - originator of the message. + listed in the state machines MUST be considered an error condition, + and an answer, if applicable, MUST be returned to the originator of + the message. - In the case that an application does not support re-auth, the state - -Fajardo, et al. Expires July 24, 2011 [Page 102] +Fajardo, et al. Standards Track [Page 99] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 - transitions related to server-initiated re-auth when both client and - server session maintains state (e.g., Send RAR, Pending, Receive RAA) - MAY be ignored. + In the case that an application does not support re-auth, the state + transitions related to server-initiated re-auth, when both client and + server sessions maintain state (e.g., Send RAR, Pending, Receive + RAA), MAY be ignored. - In the state table, the event 'Failure to send X' means that the + In the state table, the event "Failure to send X" means that the Diameter agent is unable to send command X to the desired - destination. This could be due to the peer being down, or due to the + destination. This could be due to the peer being down or due to the peer sending back a transient failure or temporary protocol error notification DIAMETER_TOO_BUSY or DIAMETER_LOOP_DETECTED in the Result-Code AVP of the corresponding Answer command. The event 'X @@ -5731,8 +5567,8 @@ Internet-Draft Diameter Base Protocol January 2011 CLIENT, STATEFUL State Event Action New State --------------------------------------------------------------- - Idle Client or Device Requests Send Pending - access service + Idle Client or device requests Send Pending + access service- specific auth req @@ -5748,39 +5584,38 @@ Internet-Draft Diameter Base Protocol January 2011 UNKNOWN_ SESSION_ID - Pending Successful Service-specific Grant Open + Pending Successful service-specific Grant Open authorization answer Access received with default Auth-Session-State value - Pending Successful Service-specific Sent STR Discon - authorization answer received + Pending Successful service-specific Sent STR Discon + authorization answer received, but service not provided Pending Error processing successful Sent STR Discon - Service-specific authorization + service-specific authorization answer - -Fajardo, et al. Expires July 24, 2011 [Page 103] +Fajardo, et al. Standards Track [Page 100] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 - Pending Failed Service-specific Cleanup Idle + Pending Failed service-specific Clean up Idle authorization answer received Open User or client device Send Open - requests access to service service + requests access to service service- specific auth req - Open Successful Service-specific Provide Open - authorization answer received Service + Open Successful service-specific Provide Open + authorization answer received service - Open Failed Service-specific Discon. Idle + Open Failed service-specific Discon. Idle authorization answer user/device received. @@ -5796,10 +5631,10 @@ Internet-Draft Diameter Base Protocol January 2011 Discon. user/device - Open Session-Timeout Expires on Send STR Discon - Access Device + Open Session-Timeout expires on Send STR Discon + access device - Open ASR Received, Send ASA Discon + Open ASR received, Send ASA Discon client will comply with with request to end the Result-Code = session = SUCCESS, @@ -5814,17 +5649,18 @@ Internet-Draft Diameter Base Protocol January 2011 Auth-Grace-Period expires on access device - Discon ASR Received Send ASA Discon + Discon ASR received Send ASA Discon + - Discon STA Received Discon. Idle -Fajardo, et al. Expires July 24, 2011 [Page 104] +Fajardo, et al. Standards Track [Page 101] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 + Discon STA received Discon. Idle user/device The following state machine is observed by a server when it is @@ -5835,31 +5671,34 @@ Internet-Draft Diameter Base Protocol January 2011 --------------------------------------------------------------- Idle Service-specific authorization Send Open request received, and successful - user is authorized serv. + user is authorized service- specific answer Idle Service-specific authorization Send Idle - request received, and failed serv. - user is not authorized specific + request received, and failed + user is not authorized service- + specific answer Open Service-specific authorization Send Open request received, and user successful - is authorized serv. specific + is authorized service- + specific answer Open Service-specific authorization Send Idle - request received, and user failed serv. - is not authorized specific + request received, and user failed + is not authorized service- + specific answer, - Cleanup + Clean up Open Home server wants to confirm Send RAR Pending authentication and/or authorization of the user - Pending Received RAA with a failed Cleanup Idle + Pending Received RAA with a failed Clean up Idle Result-Code Pending Received RAA with Result-Code Update Open @@ -5868,32 +5707,33 @@ Internet-Draft Diameter Base Protocol January 2011 Open Home server wants to Send ASR Discon terminate the service - Open Authorization-Lifetime (and Cleanup Idle - Auth-Grace-Period) expires - on home server. - Open Session-Timeout expires on Cleanup Idle -Fajardo, et al. Expires July 24, 2011 [Page 105] +Fajardo, et al. Standards Track [Page 102] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 + Open Authorization-Lifetime (and Clean up Idle + Auth-Grace-Period) expires + on home server + + Open Session-Timeout expires on Clean up Idle home server Discon Failure to send ASR Wait, Discon resend ASR - Discon ASR successfully sent and Cleanup Idle + Discon ASR successfully sent and Clean up Idle ASA Received with Result-Code - Not ASA Received None No Change. + Not ASA Received None No Change Discon Any STR Received Send STA, Idle - Cleanup. + Clean up The following state machine is observed by a client when state is not maintained on the server: @@ -5901,48 +5741,47 @@ Internet-Draft Diameter Base Protocol January 2011 CLIENT, STATELESS State Event Action New State --------------------------------------------------------------- - Idle Client or Device Requests Send Pending - access service + Idle Client or device requests Send Pending + access service- specific auth req - Pending Successful Service-specific Grant Open - authorization answer Access + Pending Successful service-specific Grant Open + authorization answer access received with Auth-Session- State set to NO_STATE_MAINTAINED - Pending Failed Service-specific Cleanup Idle + Pending Failed service-specific Clean up Idle authorization answer received - Open Session-Timeout Expires on Discon. Idle - Access Device user/device + Open Session-Timeout expires on Discon. Idle + access device user/device Open Service to user is terminated Discon. Idle user/device - The following state machine is observed by a server when it is not - maintaining state for the session: - - - -Fajardo, et al. Expires July 24, 2011 [Page 106] +Fajardo, et al. Standards Track [Page 103] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 + + The following state machine is observed by a server when it is not + maintaining state for the session: SERVER, STATELESS State Event Action New State --------------------------------------------------------------- - Idle Service-specific authorization Send serv. Idle - request received, and specific - successfully processed answer + Idle Service-specific authorization Send Idle + request received, and service- + successfully processed specific + answer 8.2. Accounting Session State Machine @@ -5960,8 +5799,8 @@ Internet-Draft Diameter Base Protocol January 2011 machine in this section described below. The default server side state machine requires the reception of - accounting records in any order and at any time, and does not place - any standards requirement on the processing of these records. + accounting records in any order and at any time, and it does not + place any standards requirement on the processing of these records. Implementations of Diameter may perform checking, ordering, correlation, fraud detection, and other tasks based on these records. AVPs may need to be inspected as a part of these tasks. The tasks @@ -5970,7 +5809,7 @@ Internet-Draft Diameter Base Protocol January 2011 or even policy dependent, they are not standardized by the Diameter specifications. Applications MAY define requirements on when to accept accounting records based on the used value of Accounting- - Realtime-Required AVP, credit limits checks, and so on. + Realtime-Required AVP, credit-limit checks, and so on. However, the Diameter base protocol defines one optional server side state machine that MAY be followed by applications that require @@ -5978,31 +5817,31 @@ Internet-Draft Diameter Base Protocol January 2011 that such tracking is incompatible with the ability to sustain long duration connectivity problems. Therefore, the use of this state machine is recommended only in applications where the value of the - Accounting-Realtime-Required AVP is DELIVER_AND_GRANT, and hence + Accounting-Realtime-Required AVP is DELIVER_AND_GRANT; hence, accounting connectivity problems are required to cause the serviced user to be disconnected. Otherwise, records produced by the client - may be lost by the server which no longer accepts them after the - connectivity is re-established. This state machine is the third - state machine in this section. The state machine is supervised by a - supervision session timer Ts, which the value should be reasonably -Fajardo, et al. Expires July 24, 2011 [Page 107] +Fajardo, et al. Standards Track [Page 104] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 - higher than the Acct_Interim_Interval value. Ts MAY be set to two - times the value of the Acct_Interim_Interval so as to avoid the - accounting session in the Diameter server to change to Idle state in - case of short transient network failure. + may be lost by the server, which no longer accepts them after the + connectivity is re-established. This state machine is the third + state machine in this section. The state machine is supervised by a + supervision session timer Ts, whose value should be reasonably higher + than the Acct_Interim_Interval value. Ts MAY be set to two times the + value of the Acct_Interim_Interval so as to avoid the accounting + session in the Diameter server to change to Idle state in case of + short transient network failure. Any event not listed in the state machines MUST be considered as an error condition, and a corresponding answer, if applicable, MUST be returned to the originator of the message. - In the state table, the event 'Failure to send' means that the + In the state table, the event "Failure to send" means that the Diameter client is unable to communicate with the desired destination. This could be due to the peer being down, or due to the peer sending back a transient failure or temporary protocol error @@ -6010,17 +5849,17 @@ Internet-Draft Diameter Base Protocol January 2011 DIAMETER_LOOP_DETECTED in the Result-Code AVP of the Accounting Answer command. - The event 'Failed answer' means that the Diameter client received a + The event "Failed answer" means that the Diameter client received a non-transient failure notification in the Accounting Answer command. - Note that the action 'Disconnect user/dev' MUST have an effect also - to the authorization session state table, e.g., cause the STR message + Note that the action "Disconnect user/dev" MUST also have an effect + on the authorization session state table, e.g., cause the STR message to be sent, if the given application has both authentication/ authorization and accounting portions. - The states PendingS, PendingI, PendingL, PendingE and PendingB stand + The states PendingS, PendingI, PendingL, PendingE, and PendingB stand for pending states to wait for an answer to an accounting request - related to a Start, Interim, Stop, Event or buffered record, + related to a Start, Interim, Stop, Event, or buffered record, respectively. CLIENT, ACCOUNTING @@ -6037,36 +5876,36 @@ Internet-Draft Diameter Base Protocol January 2011 Idle Records in storage Send PendingB record - PendingS Successful accounting Open - start answer received - - PendingS Failure to send and buffer Store Open -Fajardo, et al. Expires July 24, 2011 [Page 108] +Fajardo, et al. Standards Track [Page 105] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 - space available and realtime Start + PendingS Successful accounting Open + start answer received + + PendingS Failure to send and buffer Store Open + space available and real time Start not equal to DELIVER_AND_GRANT Record PendingS Failure to send and no buffer Open - space available and realtime + space available and real time equal to GRANT_AND_LOSE PendingS Failure to send and no Disconnect Idle buffer space available and user/dev - realtime not equal to + real time not equal to GRANT_AND_LOSE PendingS Failed accounting start answer Open - received and realtime equal + received and real time equal to GRANT_AND_LOSE PendingS Failed accounting start answer Disconnect Idle - received and realtime not user/dev + received and real time not user/dev equal to GRANT_AND_LOSE PendingS User service terminated Store PendingS @@ -6077,6 +5916,7 @@ Internet-Draft Diameter Base Protocol January 2011 accounting interim record + Open User service terminated Send PendingL accounting stop req. @@ -6087,34 +5927,35 @@ Internet-Draft Diameter Base Protocol January 2011 PendingI Failure to send and (buffer Store Open space available or old interim record can be overwritten) record - and realtime not equal to + and real time not equal to DELIVER_AND_GRANT - PendingI Failure to send and no buffer Open - space available and realtime - equal to GRANT_AND_LOSE - PendingI Failure to send and no Disconnect Idle - buffer space available and user/dev -Fajardo, et al. Expires July 24, 2011 [Page 109] +Fajardo, et al. Standards Track [Page 106] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 + + PendingI Failure to send and no buffer Open + space available and real time + equal to GRANT_AND_LOSE - realtime not equal to + PendingI Failure to send and no Disconnect Idle + buffer space available and user/dev + real time not equal to GRANT_AND_LOSE PendingI Failed accounting interim Open - answer received and realtime + answer received and real time equal to GRANT_AND_LOSE PendingI Failed accounting interim Disconnect Idle answer received and user/dev - realtime not equal to + real time not equal to GRANT_AND_LOSE PendingI User service terminated Store PendingI @@ -6148,6 +5989,13 @@ Internet-Draft Diameter Base Protocol January 2011 space available stop record + + +Fajardo, et al. Standards Track [Page 107] + +RFC 6733 Diameter Base Protocol October 2012 + + PendingL Failure to send and no buffer Idle space available @@ -6155,124 +6003,133 @@ Internet-Draft Diameter Base Protocol January 2011 received - -Fajardo, et al. Expires July 24, 2011 [Page 110] - -Internet-Draft Diameter Base Protocol January 2011 - - SERVER, STATELESS ACCOUNTING State Event Action New State --------------------------------------------------------------- Idle Accounting start request Send Idle - received, and successfully accounting + received and successfully accounting processed. start answer Idle Accounting event request Send Idle - received, and successfully accounting + received and successfully accounting processed. event answer - Idle Interim record received, Send Idle + Idle Interim record received Send Idle and successfully processed. accounting interim answer Idle Accounting stop request Send Idle - received, and successfully accounting + received and successfully accounting processed stop answer - Idle Accounting request received, Send Idle + Idle Accounting request received; Send Idle no space left to store accounting - records answer, + records answer; Result-Code = OUT_OF_ SPACE + + + + + + + + + + + + + + +Fajardo, et al. Standards Track [Page 108] + +RFC 6733 Diameter Base Protocol October 2012 + + SERVER, STATEFUL ACCOUNTING State Event Action New State --------------------------------------------------------------- Idle Accounting start request Send Open - received, and successfully accounting + received and successfully accounting processed. start - answer, + answer; Start Ts Idle Accounting event request Send Idle - received, and successfully accounting + received and successfully accounting processed. event answer - - Idle Accounting request received, Send Idle + Idle Accounting request received; Send Idle no space left to store accounting - records answer, - - - -Fajardo, et al. Expires July 24, 2011 [Page 111] - -Internet-Draft Diameter Base Protocol January 2011 - - + records answer; Result-Code = OUT_OF_ SPACE - Open Interim record received, Send Open + Open Interim record received Send Open and successfully processed. accounting interim - answer, + answer; Restart Ts Open Accounting stop request Send Idle - received, and successfully accounting - processed stop answer, + received and successfully accounting + processed stop answer; Stop Ts - Open Accounting request received, Send Idle + Open Accounting request received; Send Idle no space left to store accounting - records answer, + records answer; Result-Code = OUT_OF_ - SPACE, + SPACE; Stop Ts Open Session supervision timer Ts Stop Ts Idle expired + + + + + + + + +Fajardo, et al. Standards Track [Page 109] + +RFC 6733 Diameter Base Protocol October 2012 + + 8.3. Server-Initiated Re-Auth A Diameter server may initiate a re-authentication and/or re- authorization service for a particular session by issuing a Re-Auth- Request (RAR). - For example, for pre-paid services, the Diameter server that + For example, for prepaid services, the Diameter server that originally authorized a session may need some confirmation that the user is still using the services. - An access device that receives a RAR message with Session-Id equal to - a currently active session MUST initiate a re-auth towards the user, - if the service supports this particular feature. Each Diameter - application MUST state whether server-initiated re-auth is supported, - since some applications do not allow access devices to prompt the - user for re-auth. + An access device that receives an RAR message with the Session-Id + equal to a currently active session MUST initiate a re-auth towards + the user, if the service supports this particular feature. Each + Diameter application MUST state whether server-initiated re-auth is + supported, since some applications do not allow access devices to + prompt the user for re-auth. 8.3.1. Re-Auth-Request - The Re-Auth-Request (RAR), indicated by the Command-Code set to 258 + The Re-Auth-Request (RAR), indicated by the Command Code set to 258 and the message flags' 'R' bit set, may be sent by any server to the access device that is providing session service, to request that the - - - -Fajardo, et al. Expires July 24, 2011 [Page 112] - -Internet-Draft Diameter Base Protocol January 2011 - - user be re-authenticated and/or re-authorized. @@ -6294,15 +6151,22 @@ Internet-Draft Diameter Base Protocol January 2011 8.3.2. Re-Auth-Answer - The Re-Auth-Answer (RAA), indicated by the Command-Code set to 258 + The Re-Auth-Answer (RAA), indicated by the Command Code set to 258 and the message flags' 'R' bit clear, is sent in response to the RAR. - The Result-Code AVP MUST be present, and indicates the disposition of - the request. + The Result-Code AVP MUST be present, and it indicates the disposition + of the request. + + + + +Fajardo, et al. Standards Track [Page 110] + +RFC 6733 Diameter Base Protocol October 2012 + A successful RAA message MUST be followed by an application-specific authentication and/or authorization message. - Message Format <RAA> ::= < Diameter Header: 258, PXY > @@ -6321,14 +6185,6 @@ Internet-Draft Diameter Base Protocol January 2011 * [ Proxy-Info ] * [ AVP ] - - - -Fajardo, et al. Expires July 24, 2011 [Page 113] - -Internet-Draft Diameter Base Protocol January 2011 - - 8.4. Session Termination It is necessary for a Diameter server that authorized a session, for @@ -6356,6 +6212,14 @@ Internet-Draft Diameter Base Protocol January 2011 It is also possible that a session that was authorized is never actually started due to action of a proxy. For example, a proxy may + + + +Fajardo, et al. Standards Track [Page 111] + +RFC 6733 Diameter Base Protocol October 2012 + + modify an authorization answer, converting the result from success to failure, prior to forwarding the message to the access device. If the answer did not contain an Auth-Session-State AVP with the value @@ -6366,36 +6230,27 @@ Internet-Draft Diameter Base Protocol January 2011 A Diameter server that receives an STR message MUST clean up resources (e.g., session state) associated with the Session-Id - specified in the STR, and return a Session-Termination-Answer. + specified in the STR and return a Session-Termination-Answer. A Diameter server also MUST clean up resources when the Session- Timeout expires, or when the Authorization-Lifetime and the Auth- - Grace-Period AVPs expires without receipt of a re-authorization + Grace-Period AVPs expire without receipt of a re-authorization request, regardless of whether an STR for that session is received. The access device is not expected to provide service beyond the expiration of these timers; thus, expiration of either of these timers implies that the access device may have unexpectedly shut down. - - - -Fajardo, et al. Expires July 24, 2011 [Page 114] - -Internet-Draft Diameter Base Protocol January 2011 - - 8.4.1. Session-Termination-Request - The Session-Termination-Request (STR), indicated by the Command-Code + The Session-Termination-Request (STR), indicated by the Command Code set to 275 and the Command Flags' 'R' bit set, is sent by a Diameter - client or by a Diameter proxy to inform the Diameter Server that an + client or by a Diameter proxy to inform the Diameter server that an authenticated and/or authorized session is being terminated. + Message Format - Message Format - - <STR> ::= < Diameter Header: 275, REQ, PXY > + <STR> ::= < Diameter Header: 275, REQ, PXY > < Session-Id > { Origin-Host } { Origin-Realm } @@ -6410,40 +6265,33 @@ Internet-Draft Diameter Base Protocol January 2011 * [ Route-Record ] * [ AVP ] -8.4.2. Session-Termination-Answer - - The Session-Termination-Answer (STA), indicated by the Command-Code - set to 275 and the message flags' 'R' bit clear, is sent by the - Diameter Server to acknowledge the notification that the session has - been terminated. The Result-Code AVP MUST be present, and MAY - contain an indication that an error occurred while servicing the STR. - - Upon sending or receipt of the STA, the Diameter Server MUST release - all resources for the session indicated by the Session-Id AVP. Any - intermediate server in the Proxy-Chain MAY also release any - resources, if necessary. - - - - - +Fajardo, et al. Standards Track [Page 112] + +RFC 6733 Diameter Base Protocol October 2012 +8.4.2. Session-Termination-Answer -Fajardo, et al. Expires July 24, 2011 [Page 115] - -Internet-Draft Diameter Base Protocol January 2011 + The Session-Termination-Answer (STA), indicated by the Command Code + set to 275 and the message flags' 'R' bit clear, is sent by the + Diameter server to acknowledge the notification that the session has + been terminated. The Result-Code AVP MUST be present, and it MAY + contain an indication that an error occurred while servicing the STR. + Upon sending or receipt of the STA, the Diameter server MUST release + all resources for the session indicated by the Session-Id AVP. Any + intermediate server in the Proxy-Chain MAY also release any + resources, if necessary. - Message Format + Message Format - <STA> ::= < Diameter Header: 275, PXY > + <STA> ::= < Diameter Header: 275, PXY > < Session-Id > { Result-Code } { Origin-Host } @@ -6473,31 +6321,29 @@ Internet-Draft Diameter Base Protocol January 2011 An access device that receives an ASR with Session-ID equal to a currently active session MAY stop the session. Whether the access - device stops the session or not is implementation- and/or - configuration-dependent. For example, an access device may honor + device stops the session or not is implementation and/or + configuration dependent. For example, an access device may honor ASRs from certain agents only. In any case, the access device MUST + + + +Fajardo, et al. Standards Track [Page 113] + +RFC 6733 Diameter Base Protocol October 2012 + + respond with an Abort-Session-Answer, including a Result-Code AVP to indicate what action it took. 8.5.1. Abort-Session-Request - The Abort-Session-Request (ASR), indicated by the Command-Code set to + The Abort-Session-Request (ASR), indicated by the Command Code set to 274 and the message flags' 'R' bit set, may be sent by any Diameter server or any Diameter proxy to the access device that is providing session service, to request that the session identified by the Session-Id be stopped. - - - - - -Fajardo, et al. Expires July 24, 2011 [Page 116] - -Internet-Draft Diameter Base Protocol January 2011 - - - Message Format + Message Format <ASR> ::= < Diameter Header: 274, REQ, PXY > < Session-Id > @@ -6514,20 +6360,35 @@ Internet-Draft Diameter Base Protocol January 2011 8.5.2. Abort-Session-Answer - The Abort-Session-Answer (ASA), indicated by the Command-Code set to + The Abort-Session-Answer (ASA), indicated by the Command Code set to 274 and the message flags' 'R' bit clear, is sent in response to the - ASR. The Result-Code AVP MUST be present, and indicates the + ASR. The Result-Code AVP MUST be present and indicates the disposition of the request. If the session identified by Session-Id in the ASR was successfully - terminated, Result-Code is set to DIAMETER_SUCCESS. If the session - is not currently active, Result-Code is set to + terminated, the Result-Code is set to DIAMETER_SUCCESS. If the + session is not currently active, the Result-Code is set to DIAMETER_UNKNOWN_SESSION_ID. If the access device does not stop the - session for any other reason, Result-Code is set to + session for any other reason, the Result-Code is set to DIAMETER_UNABLE_TO_COMPLY. - Message Format + + + + + + + + + + +Fajardo, et al. Standards Track [Page 114] + +RFC 6733 Diameter Base Protocol October 2012 + + + Message Format <ASA> ::= < Diameter Header: 274, PXY > < Session-Id > @@ -6545,14 +6406,6 @@ Internet-Draft Diameter Base Protocol January 2011 * [ Proxy-Info ] * [ AVP ] - - - -Fajardo, et al. Expires July 24, 2011 [Page 117] - -Internet-Draft Diameter Base Protocol January 2011 - - 8.6. Inferring Session Termination from Origin-State-Id The Origin-State-Id is used to allow detection of terminated sessions @@ -6560,94 +6413,96 @@ Internet-Draft Diameter Base Protocol January 2011 shutdown of an access device. A Diameter client or access device increments the value of the - Origin-State-Id every time it is started or powered-up. The new + Origin-State-Id every time it is started or powered up. The new Origin-State-Id is then sent in the CER/CEA message immediately upon connection to the server. The Diameter server receiving the new Origin-State-Id can determine whether the sending Diameter client had - abruptly shutdown by comparing the old value of the Origin-State-Id + abruptly shut down by comparing the old value of the Origin-State-Id it has kept for that specific client is less than the new value and whether it has un-terminated sessions originating from that client. An access device can also include the Origin-State-Id in request - messages other than CER if there are relays or proxies in between the - access device and the server. In this case, however, the server + messages other than the CER if there are relays or proxies in between + the access device and the server. In this case, however, the server cannot discover that the access device has been restarted unless and - until it receives a new request from it. Therefore this mechanism is - more opportunistic across proxies and relays. + until it receives a new request from it. Therefore, this mechanism + is more opportunistic across proxies and relays. The Diameter server may assume that all sessions that were active prior to detection of a client restart have been terminated. The Diameter server MAY clean up all session state associated with such - lost sessions, and MAY also issues STRs for all such lost sessions + lost sessions, and it MAY also issue STRs for all such lost sessions that were authorized on upstream servers, to allow session state to be cleaned up globally. + + + + +Fajardo, et al. Standards Track [Page 115] + +RFC 6733 Diameter Base Protocol October 2012 + + 8.7. Auth-Request-Type AVP The Auth-Request-Type AVP (AVP Code 274) is of type Enumerated and is included in application-specific auth requests to inform the peers - whether a user is to be authenticated only, authorized only or both. + whether a user is to be authenticated only, authorized only, or both. Note any value other than both MAY cause RADIUS interoperability issues. The following values are defined: - AUTHENTICATE_ONLY 1 - The request being sent is for authentication only, and MUST - contain the relevant application specific authentication AVPs that + The request being sent is for authentication only, and it MUST + contain the relevant application-specific authentication AVPs that are needed by the Diameter server to authenticate the user. - - - - - - - -Fajardo, et al. Expires July 24, 2011 [Page 118] - -Internet-Draft Diameter Base Protocol January 2011 - - AUTHORIZE_ONLY 2 - The request being sent is for authorization only, and MUST contain - the application-specific authorization AVPs that are necessary to - identify the service being requested/offered. - + The request being sent is for authorization only, and it MUST + contain the application-specific authorization AVPs that are + necessary to identify the service being requested/offered. AUTHORIZE_AUTHENTICATE 3 The request contains a request for both authentication and authorization. The request MUST include both the relevant - application-specific authentication information, and authorization + application-specific authentication information and authorization information necessary to identify the service being requested/ offered. - 8.8. Session-Id AVP The Session-Id AVP (AVP Code 263) is of type UTF8String and is used to identify a specific session (see Section 8). All messages - pertaining to a specific session MUST include only one Session-Id AVP - and the same value MUST be used throughout the life of a session. - When present, the Session-Id SHOULD appear immediately following the - Diameter Header (see Section 3). + pertaining to a specific session MUST include only one Session-Id + AVP, and the same value MUST be used throughout the life of a + session. When present, the Session-Id SHOULD appear immediately + following the Diameter header (see Section 3). The Session-Id MUST be globally and eternally unique, as it is meant to uniquely identify a user session without reference to any other - information, and may be needed to correlate historical authentication - information with accounting information. The Session-Id includes a - mandatory portion and an implementation-defined portion; a - recommended format for the implementation-defined portion is outlined - below. + information, and it may be needed to correlate historical + authentication information with accounting information. The + Session-Id includes a mandatory portion and an implementation-defined + portion; a recommended format for the implementation-defined portion + is outlined below. The Session-Id MUST begin with the sender's identity encoded in the - DiameterIdentity type (see Section 4.4). The remainder of the - Session-Id is delimited by a ";" character, and MAY be any sequence - that the client can guarantee to be eternally unique; however, the - following format is recommended, (square brackets [] indicate an - optional element): + DiameterIdentity type (see Section 4.3.1). The remainder of the + Session-Id is delimited by a ";" character, and it MAY be any + + + +Fajardo, et al. Standards Track [Page 116] + +RFC 6733 Diameter Base Protocol October 2012 + + + sequence that the client can guarantee to be eternally unique; + however, the following format is recommended, (square brackets [] + indicate an optional element): <DiameterIdentity>;<high 32 bits>;<low 32 bits>[;<optional value>] @@ -6657,22 +6512,14 @@ Internet-Draft Diameter Base Protocol January 2011 processors. At startup, the high 32 bits of the 64-bit value MAY be initialized to the time in NTP format [RFC5905], and the low 32 bits MAY be initialized to zero. This will for practical purposes - - - -Fajardo, et al. Expires July 24, 2011 [Page 119] - -Internet-Draft Diameter Base Protocol January 2011 - - eliminate the possibility of overlapping Session-Ids after a reboot, assuming the reboot process takes longer than a second. Alternatively, an implementation MAY keep track of the increasing value in non-volatile memory. - <optional value> is implementation specific but may include a modem's - device Id, a layer 2 address, timestamp, etc. + <optional value> is implementation specific, but it may include a + modem's device Id, a Layer 2 address, timestamp, etc. Example, in which there is no optional value: @@ -6683,45 +6530,44 @@ Internet-Draft Diameter Base Protocol January 2011 accesspoint7.example.com;1876543210;523;[email protected] The Session-Id is created by the Diameter application initiating the - session, which in most cases is done by the client. Note that a - Session-Id MAY be used for both the authentication, authorization and - accounting commands of a given application. + session, which, in most cases, is done by the client. Note that a + Session-Id MAY be used for both the authentication, authorization, + and accounting commands of a given application. 8.9. Authorization-Lifetime AVP The Authorization-Lifetime AVP (AVP Code 291) is of type Unsigned32 and contains the maximum number of seconds of service to be provided to the user before the user is to be re-authenticated and/or re- - authorized. Care should be taken when the Authorization- Lifetime - value is determined, since a low, non-zero, value could create + authorized. Care should be taken when the Authorization-Lifetime + value is determined, since a low, non-zero value could create significant Diameter traffic, which could congest both the network and the agents. A value of zero (0) means that immediate re-auth is necessary by the access device. The absence of this AVP, or a value of all ones - (meaning all bits in the 32 bit field are set to one) means no re- + (meaning all bits in the 32-bit field are set to one) means no re- auth is expected. + + +Fajardo, et al. Standards Track [Page 117] + +RFC 6733 Diameter Base Protocol October 2012 + + If both this AVP and the Session-Timeout AVP are present in a message, the value of the latter MUST NOT be smaller than the Authorization-Lifetime AVP. An Authorization-Lifetime AVP MAY be present in re-authorization - messages, and contains the number of seconds the user is authorized - to receive service from the time the re-auth answer message is - received by the access device. + messages, and it contains the number of seconds the user is + authorized to receive service from the time the re-auth answer + message is received by the access device. This AVP MAY be provided by the client as a hint of the maximum lifetime that it is willing to accept. The server MUST return a - - - -Fajardo, et al. Expires July 24, 2011 [Page 120] - -Internet-Draft Diameter Base Protocol January 2011 - - - value that is equal to, or smaller, than the one provided by the + value that is equal to, or smaller than, the one provided by the client. 8.10. Auth-Grace-Period AVP @@ -6739,7 +6585,6 @@ Internet-Draft Diameter Base Protocol January 2011 the value in the server's answer message is binding. The following values are supported: - STATE_MAINTAINED 0 This value is used to specify that session state is being @@ -6747,46 +6592,42 @@ Internet-Draft Diameter Base Protocol January 2011 message when service to the user is terminated. This is the default value. - NO_STATE_MAINTAINED 1 This value is used to specify that no session termination messages will be sent by the access device upon expiration of the Authorization-Lifetime. - 8.12. Re-Auth-Request-Type AVP The Re-Auth-Request-Type AVP (AVP Code 285) is of type Enumerated and is included in application-specific auth answers to inform the client of the action expected upon expiration of the Authorization-Lifetime. - If the answer message contains an Authorization-Lifetime AVP with a - positive value, the Re-Auth-Request-Type AVP MUST be present in an - answer message. The following values are defined: - AUTHORIZE_ONLY 0 - An authorization only re-auth is expected upon expiration of the - Authorization-Lifetime. This is the default value if the AVP is +Fajardo, et al. Standards Track [Page 118] + +RFC 6733 Diameter Base Protocol October 2012 -Fajardo, et al. Expires July 24, 2011 [Page 121] - -Internet-Draft Diameter Base Protocol January 2011 + If the answer message contains an Authorization-Lifetime AVP with a + positive value, the Re-Auth-Request-Type AVP MUST be present in an + answer message. The following values are defined: + AUTHORIZE_ONLY 0 + An authorization only re-auth is expected upon expiration of the + Authorization-Lifetime. This is the default value if the AVP is not present in answer messages that include the Authorization- Lifetime. - AUTHORIZE_AUTHENTICATE 1 An authentication and authorization re-auth is expected upon expiration of the Authorization-Lifetime. - 8.13. Session-Timeout AVP The Session-Timeout AVP (AVP Code 27) [RFC2865] is of type Unsigned32 @@ -6799,10 +6640,10 @@ Internet-Draft Diameter Base Protocol January 2011 A session that terminates on an access device due to the expiration of the Session-Timeout MUST cause an STR to be issued, unless both the access device and the home server had previously agreed that no - session termination messages would be sent (see Section 8.11). + session termination messages would be sent (see Section 8). A Session-Timeout AVP MAY be present in a re-authorization answer - message, and contains the remaining number of seconds from the + message, and it contains the remaining number of seconds from the beginning of the re-auth. A value of zero, or the absence of this AVP, means that this session @@ -6810,7 +6651,7 @@ Internet-Draft Diameter Base Protocol January 2011 This AVP MAY be provided by the client as a hint of the maximum timeout that it is willing to accept. However, the server MAY return - a value that is equal to, or smaller, than the one provided by the + a value that is equal to, or smaller than, the one provided by the client. 8.14. User-Name AVP @@ -6819,83 +6660,29 @@ Internet-Draft Diameter Base Protocol January 2011 contains the User-Name, in a format consistent with the NAI specification [RFC4282]. -8.15. Termination-Cause AVP - - The Termination-Cause AVP (AVP Code 295) is of type Enumerated, and - is used to indicate the reason why a session was terminated on the - access device. The following values are defined: - -Fajardo, et al. Expires July 24, 2011 [Page 122] +Fajardo, et al. Standards Track [Page 119] -Internet-Draft Diameter Base Protocol January 2011 - - - DIAMETER_LOGOUT 1 - - The user initiated a disconnect - - - DIAMETER_SERVICE_NOT_PROVIDED 2 - - This value is used when the user disconnected prior to the receipt - of the authorization answer message. - - - DIAMETER_BAD_ANSWER 3 - - This value indicates that the authorization answer received by the - access device was not processed successfully. - - - DIAMETER_ADMINISTRATIVE 4 - - The user was not granted access, or was disconnected, due to - administrative reasons, such as the receipt of a Abort-Session- - Request message. - - - DIAMETER_LINK_BROKEN 5 - - The communication to the user was abruptly disconnected. - - - DIAMETER_AUTH_EXPIRED 6 - - The user's access was terminated since its authorized session time - has expired. - - - DIAMETER_USER_MOVED 7 - - The user is receiving services from another access device. - - - DIAMETER_SESSION_TIMEOUT 8 +RFC 6733 Diameter Base Protocol October 2012 - The user's session has timed out, and service has been terminated. +8.15. Termination-Cause AVP - - - - - - -Fajardo, et al. Expires July 24, 2011 [Page 123] - -Internet-Draft Diameter Base Protocol January 2011 - + The Termination-Cause AVP (AVP Code 295) is of type Enumerated, and + is used to indicate the reason why a session was terminated on the + access device. The currently assigned values for this AVP can be + found in the IANA registry for Termination-Cause AVP Values + [IANATCV]. 8.16. Origin-State-Id AVP The Origin-State-Id AVP (AVP Code 278), of type Unsigned32, is a monotonically increasing value that is advanced whenever a Diameter - entity restarts with loss of previous state, for example upon reboot. - Origin-State-Id MAY be included in any Diameter message, including - CER. + entity restarts with loss of previous state, for example, upon + reboot. Origin-State-Id MAY be included in any Diameter message, + including CER. A Diameter entity issuing this AVP MUST create a higher value for this AVP each time its state is reset. A Diameter entity MAY set @@ -6911,20 +6698,34 @@ Internet-Draft Diameter Base Protocol January 2011 message, it allows other Diameter entities to infer that sessions associated with a lower Origin-State-Id are no longer active. If an access device does not intend for such inferences to be made, it MUST - either not include Origin-State-Id in any message, or set its value - to 0. + either not include Origin-State-Id in any message or set its value to + 0. 8.17. Session-Binding AVP - The Session-Binding AVP (AVP Code 270) is of type Unsigned32, and MAY - be present in application-specific authorization answer messages. If - present, this AVP MAY inform the Diameter client that all future + The Session-Binding AVP (AVP Code 270) is of type Unsigned32, and it + MAY be present in application-specific authorization answer messages. + If present, this AVP MAY inform the Diameter client that all future application-specific re-auth and Session-Termination-Request messages for this session MUST be sent to the same authorization server. - This field is a bit mask, and the following bits have been defined: + + + + + + + + +Fajardo, et al. Standards Track [Page 120] + +RFC 6733 Diameter Base Protocol October 2012 + + + This field is a bit mask, and the following bits have been defined: + RE_AUTH 1 When set, future re-auth messages for this session MUST NOT @@ -6932,23 +6733,13 @@ Internet-Draft Diameter Base Protocol January 2011 value, the Destination-Host AVP MUST be present in all re-auth messages for this session. - STR 2 When set, the STR message for this session MUST NOT include the Destination-Host AVP. When cleared, the default value, the - - - -Fajardo, et al. Expires July 24, 2011 [Page 124] - -Internet-Draft Diameter Base Protocol January 2011 - - Destination-Host AVP MUST be present in the STR message for this session. - ACCOUNTING 4 When set, all accounting messages for this session MUST NOT @@ -6956,10 +6747,9 @@ Internet-Draft Diameter Base Protocol January 2011 value, the Destination-Host AVP, if known, MUST be present in all accounting messages for this session. - 8.18. Session-Server-Failover AVP - The Session-Server-Failover AVP (AVP Code 271) is of type Enumerated, + The Session-Server-Failover AVP (AVP Code 271) is of type Enumerated and MAY be present in application-specific authorization answer messages that either do not include the Session-Binding AVP or include the Session-Binding AVP with any of the bits set to a zero @@ -6970,11 +6760,24 @@ Internet-Draft Diameter Base Protocol January 2011 The following values are supported: - REFUSE_SERVICE 0 If either the re-auth or the STR message delivery fails, terminate - service with the user, and do not attempt any subsequent attempts. + service with the user and do not attempt any subsequent attempts. + + + + + + + + + + + +Fajardo, et al. Standards Track [Page 121] + +RFC 6733 Diameter Base Protocol October 2012 TRY_AGAIN 1 @@ -6982,34 +6785,23 @@ Internet-Draft Diameter Base Protocol January 2011 If either the re-auth or the STR message delivery fails, resend the failed message without the Destination-Host AVP present. - ALLOW_SERVICE 2 If re-auth message delivery fails, assume that re-authorization succeeded. If STR message delivery fails, terminate the session. - TRY_AGAIN_ALLOW_SERVICE 3 If either the re-auth or the STR message delivery fails, resend the failed message without the Destination-Host AVP present. If - - - -Fajardo, et al. Expires July 24, 2011 [Page 125] - -Internet-Draft Diameter Base Protocol January 2011 - - the second delivery fails for re-auth, assume re-authorization succeeded. If the second delivery fails for STR, terminate the session. - 8.19. Multi-Round-Time-Out AVP - The Multi-Round-Time-Out AVP (AVP Code 272) is of type Unsigned32, - and SHOULD be present in application-specific authorization answer + The Multi-Round-Time-Out AVP (AVP Code 272) is of type Unsigned32 and + SHOULD be present in application-specific authorization answer messages whose Result-Code AVP is set to DIAMETER_MULTI_ROUND_AUTH. This AVP contains the maximum number of seconds that the access device MUST provide the user in responding to an authentication @@ -7031,37 +6823,24 @@ Internet-Draft Diameter Base Protocol January 2011 8.21. Event-Timestamp AVP - The Event-Timestamp (AVP Code 55) is of type Time, and MAY be - included in an Accounting-Request and Accounting-Answer messages to - record the time that the reported event occurred, in seconds since - January 1, 1900 00:00 UTC. - - + The Event-Timestamp (AVP Code 55) is of type Time and MAY be included + in an Accounting-Request and Accounting-Answer messages to record the + time that the reported event occurred, in seconds since January 1, + 1900 00:00 UTC. - - - - - - - - - - - -Fajardo, et al. Expires July 24, 2011 [Page 126] +Fajardo, et al. Standards Track [Page 122] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 9. Accounting This accounting protocol is based on a server directed model with capabilities for real-time delivery of accounting information. - Several fault resilience methods [RFC2975] have been built in to the + Several fault resilience methods [RFC2975] have been built into the protocol in order minimize loss of accounting data in various fault situations and under different assumptions about the capabilities of the used devices. @@ -7075,15 +6854,16 @@ Internet-Draft Diameter Base Protocol January 2011 timeliness requirements. As discussed in [RFC2975], real-time transfer of accounting records - is a requirement, such as the need to perform credit limit checks and + is a requirement, such as the need to perform credit-limit checks and fraud detection. Note that batch accounting is not a requirement, and is therefore not supported by Diameter. Should batched accounting be required in the future, a new Diameter application will need to be created, or it could be handled using another protocol. - Note, however, that even if at the Diameter layer accounting requests - are processed one by one, transport protocols used under Diameter - typically batch several requests in the same packet under heavy - traffic conditions. This may be sufficient for many applications. + Note, however, that even if at the Diameter layer, accounting + requests are processed one by one; transport protocols used under + Diameter typically batch several requests in the same packet under + heavy traffic conditions. This may be sufficient for many + applications. The authorization server (chain) directs the selection of proper transfer strategy, based on its knowledge of the user and @@ -7097,7 +6877,7 @@ Internet-Draft Diameter Base Protocol January 2011 records from the Diameter client is delayed or unsuccessful. The Diameter accounting server MAY override the interim interval or - the realtime requirements by including the Acct-Interim-Interval or + the real-time requirements by including the Acct-Interim-Interval or Accounting-Realtime-Required AVP in the Accounting-Answer message. When one of these AVPs is present, the latest value received SHOULD be used in further accounting activities for the same session. @@ -7107,16 +6887,15 @@ Internet-Draft Diameter Base Protocol January 2011 - -Fajardo, et al. Expires July 24, 2011 [Page 127] +Fajardo, et al. Standards Track [Page 123] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 9.2. Protocol Messages A Diameter node that receives a successful authentication and/or - authorization messages from the Diameter server SHOULD collect + authorization message from the Diameter server SHOULD collect accounting information for the session. The Accounting-Request message is used to transmit the accounting information to the Diameter server, which MUST reply with the Accounting-Answer message @@ -7129,12 +6908,12 @@ Internet-Draft Diameter Base Protocol January 2011 9.3. Accounting Application Extension and Requirements - Each Diameter application (e.g., NASREQ, MobileIP), SHOULD define - their Service-Specific AVPs that MUST be present in the Accounting- - Request message in a section entitled "Accounting AVPs". The - application MUST assume that the AVPs described in this document will - be present in all Accounting messages, so only their respective - service-specific AVPs need to be defined in that section. + Each Diameter application (e.g., NASREQ, Mobile IP) SHOULD define its + service-specific AVPs that MUST be present in the Accounting-Request + message in a section titled "Accounting AVPs". The application MUST + assume that the AVPs described in this document will be present in + all Accounting messages, so only their respective service-specific + AVPs need to be defined in that section. Applications have the option of using one or both of the following accounting application extension models: @@ -7150,40 +6929,37 @@ Internet-Draft Diameter Base Protocol January 2011 advertise the Diameter base accounting Application Id during capabilities exchange. - Coupled Accounting Service - The accounting messages will carry the Application Id of the + The accounting message will carry the Application Id of the application that is using it. The application itself will process the received accounting records or forward them to an accounting server. There is no accounting application advertisement required - during capabilities exchange and the accounting messages will be - routed the same as any of the other application messages. - + during capabilities exchange, and the accounting messages will be + routed the same way as any of the other application messages. + In cases where an application does not define its own accounting + service, it is preferred that the split accounting model be used. -Fajardo, et al. Expires July 24, 2011 [Page 128] +Fajardo, et al. Standards Track [Page 124] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 - In cases where an application does not define its own accounting - service, it is preferred that the split accounting model be used. - 9.4. Fault Resilience - Diameter Base protocol mechanisms are used to overcome small message - loss and network faults of temporary nature. + Diameter base protocol mechanisms are used to overcome small message + loss and network faults of a temporary nature. Diameter peers acting as clients MUST implement the use of failover to guard against server failures and certain network failures. Diameter peers acting as agents or related off-line processing systems MUST detect duplicate accounting records caused by the - sending of same record to several servers and duplication of messages - in transit. This detection MUST be based on the inspection of the - Session-Id and Accounting-Record-Number AVP pairs. Appendix C + sending of the same record to several servers and duplication of + messages in transit. This detection MUST be based on the inspection + of the Session-Id and Accounting-Record-Number AVP pairs. Appendix C discusses duplicate detection needs and implementation issues. Diameter clients MAY have non-volatile memory for the safe storage of @@ -7191,23 +6967,23 @@ Internet-Draft Diameter Base Protocol January 2011 partitions, and server failures. If such memory is available, the client SHOULD store new accounting records there as soon as the records are created and until a positive acknowledgement of their - reception from the Diameter Server has been received. Upon a reboot, - the client MUST starting sending the records in the non-volatile - memory to the accounting server with appropriate modifications in + reception from the Diameter server has been received. Upon a reboot, + the client MUST start sending the records in the non-volatile memory + to the accounting server with the appropriate modifications in termination cause, session length, and other relevant information in the records. A further application of this protocol may include AVPs to control - how many accounting records may at most be stored in the Diameter - client without committing them to the non-volatile memory or + the maximum number of accounting records that may be stored in the + Diameter client without committing them to the non-volatile memory or transferring them to the Diameter server. The client SHOULD NOT remove the accounting data from any of its memory areas before the correct Accounting-Answer has been received. - The client MAY remove oldest, undelivered or yet unacknowledged - accounting data if it runs out of resources such as memory. It is an - implementation dependent matter for the client to accept new sessions - under this condition. + The client MAY remove the oldest, undelivered, or as yet + unacknowledged accounting data if it runs out of resources such as + memory. It is an implementation-dependent matter for the client to + accept new sessions under this condition. 9.5. Accounting Records @@ -7217,15 +6993,17 @@ Internet-Draft Diameter Base Protocol January 2011 Different types of accounting records are sent depending on the actual type of accounted service and the authorization server's + directions for interim accounting. If the accounted service is a + + -Fajardo, et al. Expires July 24, 2011 [Page 129] +Fajardo, et al. Standards Track [Page 125] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 - directions for interim accounting. If the accounted service is a one-time event, meaning that the start and stop of the event are simultaneous, then the Accounting-Record-Type AVP MUST be present and set to the value EVENT_RECORD. @@ -7251,11 +7029,11 @@ Internet-Draft Diameter Base Protocol January 2011 session. A particular value of Accounting-Sub-Session-Id MUST appear only in - one sequence of accounting records from a DIAMETER client, except for + one sequence of accounting records from a Diameter client, except for the purposes of retransmission. The one sequence that is sent MUST be either one record with Accounting-Record-Type AVP set to the value - EVENT_RECORD, or several records starting with one having the value - START_RECORD, followed by zero or more INTERIM_RECORD and a single + EVENT_RECORD or several records starting with one having the value + START_RECORD, followed by zero or more INTERIM_RECORDs and a single STOP_RECORD. A particular Diameter application specification MUST define the type of sequences that MUST be used. @@ -7265,20 +7043,21 @@ Internet-Draft Diameter Base Protocol January 2011 accounting records with a specific application session by using the Session-Id of the particular application session in the accounting messages. Accounting messages MAY also use a different Session-Id - from that of the application sessions in which case other session + from that of the application sessions, in which case, other session- related information is needed to perform correlation. In cases where an application requires multiple accounting sub- - session, an Accounting-Sub-Session-Id AVP is used to differentiate + sessions, an Accounting-Sub-Session-Id AVP is used to differentiate each sub-session. The Session-Id would remain constant for all sub- - sessions and is be used to correlate all the sub-sessions to a + sessions and is used to correlate all the sub-sessions to a particular application session. Note that receiving a STOP_RECORD -Fajardo, et al. Expires July 24, 2011 [Page 130] + +Fajardo, et al. Standards Track [Page 126] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 with no Accounting-Sub-Session-Id AVP when sub-sessions were @@ -7290,36 +7069,36 @@ Internet-Draft Diameter Base Protocol January 2011 record may span multiple different Diameter applications and sessions used by the same user at a given time. In such cases, the Acct- Multi-Session-Id AVP is used. The Acct-Multi-Session-Id AVP SHOULD - be signaled by the server to the access device (typically during + be signaled by the server to the access device (typically, during authorization) when it determines that a request belongs to an existing session. The access device MUST then include the Acct- Multi-Session-Id AVP in all subsequent accounting messages. The Acct-Multi-Session-Id AVP MAY include the value of the original - Session-Id. It's contents are implementation specific, but MUST be - globally unique across other Acct-Multi-Session-Id, and MUST NOT + Session-Id. Its contents are implementation specific, but the MUST + be globally unique across other Acct-Multi-Session-Ids and MUST NOT change during the life of a session. A Diameter application document MUST define the exact concept of a - session that is being accounted, and MAY define the concept of a + session that is being accounted, and it MAY define the concept of a multi-session. For instance, the NASREQ DIAMETER application treats - a single PPP connection to a Network Access Server as one session, - and a set of Multilink PPP sessions as one multi-session. + a single PPP connection to a Network Access Server as one session and + a set of Multilink PPP sessions as one multi-session. -9.7. Accounting Command-Codes +9.7. Accounting Command Codes - This section defines Command-Code values that MUST be supported by - all Diameter implementations that provide Accounting services. + This section defines Command Code values that MUST be supported by + all Diameter implementations that provide accounting services. 9.7.1. Accounting-Request - The Accounting-Request (ACR) command, indicated by the Command-Code + The Accounting-Request (ACR) command, indicated by the Command Code field set to 271 and the Command Flags' 'R' bit set, is sent by a Diameter node, acting as a client, in order to exchange accounting information with a peer. - The AVP listed below SHOULD include service-specific accounting AVPs, - as described in Section 9.3. + In addition to the AVPs listed below, Accounting-Request messages + SHOULD include service-specific accounting AVPs. @@ -7332,9 +7111,9 @@ Internet-Draft Diameter Base Protocol January 2011 -Fajardo, et al. Expires July 24, 2011 [Page 131] +Fajardo, et al. Standards Track [Page 127] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 Message Format @@ -7363,16 +7142,16 @@ Internet-Draft Diameter Base Protocol January 2011 9.7.2. Accounting-Answer - The Accounting-Answer (ACA) command, indicated by the Command-Code + The Accounting-Answer (ACA) command, indicated by the Command Code field set to 271 and the Command Flags' 'R' bit cleared, is used to acknowledge an Accounting-Request command. The Accounting-Answer command contains the same Session-Id as the corresponding request. - Only the target Diameter Server, known as the home Diameter Server, + Only the target Diameter server, known as the home Diameter server, SHOULD respond with the Accounting-Answer command. - The AVP listed below SHOULD include service-specific accounting AVPs, - as described in Section 9.3. + In addition to the AVPs listed below, Accounting-Answer messages + SHOULD include service-specific accounting AVPs. @@ -7388,9 +7167,9 @@ Internet-Draft Diameter Base Protocol January 2011 -Fajardo, et al. Expires July 24, 2011 [Page 132] +Fajardo, et al. Standards Track [Page 128] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 Message Format @@ -7429,13 +7208,12 @@ Internet-Draft Diameter Base Protocol January 2011 and contains the type of accounting record being sent. The following values are currently defined for the Accounting-Record-Type AVP: - EVENT_RECORD 1 An Accounting Event Record is used to indicate that a one-time event has occurred (meaning that the start and end of the event are simultaneous). This record contains all information relevant - to the service, and is the only record of the service. + to the service, and it is the only record of the service. @@ -7444,20 +7222,20 @@ Internet-Draft Diameter Base Protocol January 2011 -Fajardo, et al. Expires July 24, 2011 [Page 133] + +Fajardo, et al. Standards Track [Page 129] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 START_RECORD 2 - An Accounting Start, Interim, and Stop Records are used to - indicate that a service of a measurable length has been given. An - Accounting Start Record is used to initiate an accounting session, + Accounting Start, Interim, and Stop Records are used to indicate + that a service of a measurable length has been given. An + Accounting Start Record is used to initiate an accounting session and contains accounting information that is relevant to the initiation of the session. - INTERIM_RECORD 3 An Interim Accounting Record contains cumulative accounting @@ -7468,14 +7246,12 @@ Internet-Draft Diameter Base Protocol January 2011 applications. The selection of whether to use INTERIM_RECORD records is done by the Acct-Interim-Interval AVP. - STOP_RECORD 4 An Accounting Stop Record is sent to terminate an accounting session and contains cumulative accounting information relevant to the existing session. - 9.8.2. Acct-Interim-Interval AVP The Acct-Interim-Interval AVP (AVP Code 85) is of type Unsigned32 and @@ -7483,31 +7259,31 @@ Internet-Draft Diameter Base Protocol January 2011 client. The client uses information in this AVP to decide how and when to produce accounting records. With different values in this AVP, service sessions can result in one, two, or two+N accounting - records, based on the needs of the home-organization. The following + records, based on the needs of the home organization. The following accounting record production behavior is directed by the inclusion of this AVP: - 1. The omission of the Acct-Interim-Interval AVP or its inclusion with Value field set to 0 means that EVENT_RECORD, START_RECORD, and STOP_RECORD are produced, as appropriate for the service. - 2. The inclusion of the AVP with Value field set to a non-zero value means that INTERIM_RECORD records MUST be produced between the START_RECORD and STOP_RECORD records. The Value field of this AVP is the nominal interval between these records in seconds. + The Diameter node that originates the accounting information, + known as the client, MUST produce the first INTERIM_RECORD record + roughly at the time when this nominal interval has elapsed from + + -Fajardo, et al. Expires July 24, 2011 [Page 134] +Fajardo, et al. Standards Track [Page 130] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 - The Diameter node that originates the accounting information, - known as the client, MUST produce the first INTERIM_RECORD record - roughly at the time when this nominal interval has elapsed from the START_RECORD, the next one again as the interval has elapsed once more, and so on until the session ends and a STOP_RECORD record is produced. @@ -7522,10 +7298,10 @@ Internet-Draft Diameter Base Protocol January 2011 The Accounting-Record-Number AVP (AVP Code 485) is of type Unsigned32 and identifies this record within one session. As Session-Id AVPs are globally unique, the combination of Session-Id and Accounting- - Record-Number AVPs is also globally unique, and can be used in + Record-Number AVPs is also globally unique and can be used in matching accounting records with confirmations. An easy way to produce unique numbers is to set the value to 0 for records of type - EVENT_RECORD and START_RECORD, and set the value to 1 for the first + EVENT_RECORD and START_RECORD and set the value to 1 for the first INTERIM_RECORD, 2 for the second, and so on until the value for STOP_RECORD is one more than for the last INTERIM_RECORD. @@ -7539,10 +7315,10 @@ Internet-Draft Diameter Base Protocol January 2011 The Acct-Multi-Session-Id AVP (AVP Code 50) is of type UTF8String, following the format specified in Section 8.8. The Acct-Multi- - Session-Id AVP is used to link together multiple related accounting - sessions, where each session would have a unique Session-Id, but the - same Acct-Multi-Session-Id AVP. This AVP MAY be returned by the - Diameter server in an authorization answer, and MUST be used in all + Session-Id AVP is used to link multiple related accounting sessions, + where each session would have a unique Session-Id but the same Acct- + Multi-Session-Id AVP. This AVP MAY be returned by the Diameter + server in an authorization answer, and it MUST be used in all accounting messages for the given session. 9.8.6. Accounting-Sub-Session-Id AVP @@ -7553,18 +7329,17 @@ Internet-Draft Diameter Base Protocol January 2011 session, and the value of this AVP MUST be monotonically increased by one for all new sub-sessions. The absence of this AVP implies no sub-sessions are in use, with the exception of an Accounting-Request + whose Accounting-Record-Type is set to STOP_RECORD. A STOP_RECORD + message with no Accounting-Sub-Session-Id AVP present will signal the + termination of all sub-sessions for a given Session-Id. -Fajardo, et al. Expires July 24, 2011 [Page 135] +Fajardo, et al. Standards Track [Page 131] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 - whose Accounting-Record-Type is set to STOP_RECORD. A STOP_RECORD - message with no Accounting-Sub-Session-Id AVP present will signal the - termination of all sub-sessions for a given Session-Id. - 9.8.7. Accounting-Realtime-Required AVP The Accounting-Realtime-Required AVP (AVP Code 483) is of type @@ -7574,7 +7349,6 @@ Internet-Draft Diameter Base Protocol January 2011 if the sending of accounting records to the accounting server has been temporarily prevented due to, for instance, a network problem. - DELIVER_AND_GRANT 1 The AVP with Value field set to DELIVER_AND_GRANT means that the @@ -7584,7 +7358,6 @@ Internet-Draft Diameter Base Protocol January 2011 the accounting record stream to a backup server is not a reason to discontinue the service to the user. - GRANT_AND_STORE 2 The AVP with Value field set to GRANT_AND_STORE means that service @@ -7594,60 +7367,51 @@ Internet-Draft Diameter Base Protocol January 2011 This is the default behavior if the AVP isn't included in the reply from the authorization server. - GRANT_AND_LOSE 3 The AVP with Value field set to GRANT_AND_LOSE means that service SHOULD be granted even if the records cannot be delivered or stored. +10. AVP Occurrence Tables + The following tables present the AVPs defined in this document and + specify in which Diameter messages they MAY or MAY NOT be present. + AVPs that occur only inside a Grouped AVP are not shown in these + tables. + The tables use the following symbols: + 0 The AVP MUST NOT be present in the message. + 0+ Zero or more instances of the AVP MAY be present in the + message. - - -Fajardo, et al. Expires July 24, 2011 [Page 136] +Fajardo, et al. Standards Track [Page 132] -Internet-Draft Diameter Base Protocol January 2011 - - -10. AVP Occurrence Table - - The following tables presents the AVPs defined in this document, and - specifies in which Diameter messages they MAY be present or not. - AVPs that occur only inside a Grouped AVP are not shown in this - table. +RFC 6733 Diameter Base Protocol October 2012 - The table uses the following symbols: + 0-1 Zero or one instance of the AVP MAY be present in the message. + It is considered an error if there are more than one instance + of the AVP. - 0 The AVP MUST NOT be present in the message. + 1 One instance of the AVP MUST be present in the message. - 0+ Zero or more instances of the AVP MAY be present in the - message. - - 0-1 Zero or one instance of the AVP MAY be present in the message. - It is considered an error if there are more than one instance of - the AVP. - - 1 One instance of the AVP MUST be present in the message. - - 1+ At least one instance of the AVP MUST be present in the - message. + 1+ At least one instance of the AVP MUST be present in the + message. 10.1. Base Protocol Command AVP Table - The table in this section is limited to the non-accounting Command + The table in this section is limited to the non-Accounting Command Codes defined in this specification. +-----------------------------------------------+ - | Command-Code | + | Command Code | +---+---+---+---+---+---+---+---+---+---+---+---+ Attribute Name |CER|CEA|DPR|DPA|DWR|DWA|RAR|RAA|ASR|ASA|STR|STA| --------------------+---+---+---+---+---+---+---+---+---+---+---+---+ @@ -7665,22 +7429,29 @@ Internet-Draft Diameter Base Protocol January 2011 Class |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0+ |0+ | Destination-Host |0 |0 |0 |0 |0 |0 |1 |0 |1 |0 |0-1|0 | Destination-Realm |0 |0 |0 |0 |0 |0 |1 |0 |1 |0 |1 |0 | - - - -Fajardo, et al. Expires July 24, 2011 [Page 137] - -Internet-Draft Diameter Base Protocol January 2011 - - Disconnect-Cause |0 |0 |1 |0 |0 |0 |0 |0 |0 |0 |0 |0 | Error-Message |0 |0-1|0 |0-1|0 |0-1|0 |0-1|0 |0-1|0 |0-1| Error-Reporting-Host|0 |0 |0 |0 |0 |0 |0 |0-1|0 |0-1|0 |0-1| - Failed-AVP |0 |0+ |0 |0+ |0 |0+ |0 |0+ |0 |0+ |0 |0+ | + Failed-AVP |0 |0-1|0 |0-1|0 |0-1|0 |0-1|0 |0-1|0 |0-1| Firmware-Revision |0-1|0-1|0 |0 |0 |0 |0 |0 |0 |0 |0 |0 | Host-IP-Address |1+ |1+ |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 | Inband-Security-Id |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 | Multi-Round-Time-Out|0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 | + + + + + + + + + + +Fajardo, et al. Standards Track [Page 133] + +RFC 6733 Diameter Base Protocol October 2012 + + Origin-Host |1 |1 |1 |1 |1 |1 |1 |1 |1 |1 |1 |1 | Origin-Realm |1 |1 |1 |1 |1 |1 |1 |1 |1 |1 |1 |1 | Origin-State-Id |0-1|0-1|0 |0 |0-1|0-1|0-1|0-1|0-1|0-1|0-1|0-1| @@ -7724,9 +7495,17 @@ Internet-Draft Diameter Base Protocol January 2011 -Fajardo, et al. Expires July 24, 2011 [Page 138] + + + + + + + + +Fajardo, et al. Standards Track [Page 134] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 +-----------+ @@ -7749,6 +7528,7 @@ Internet-Draft Diameter Base Protocol January 2011 Destination-Realm | 1 | 0 | Error-Reporting-Host | 0 | 0+ | Event-Timestamp | 0-1 | 0-1 | + Failed-AVP | 0 | 0-1 | Origin-Host | 1 | 1 | Origin-Realm | 1 | 1 | Proxy-Info | 0+ | 0+ | @@ -7760,144 +7540,220 @@ Internet-Draft Diameter Base Protocol January 2011 Vendor-Specific-Application-Id| 0-1 | 0-1 | ------------------------------+-----+-----+ +11. IANA Considerations + This section provides guidance to the Internet Assigned Numbers + Authority (IANA) regarding registration of values related to the + Diameter protocol, in accordance with [RFC5226]. Existing IANA + registries and assignments put in place by RFC 3588 remain the same + unless explicitly updated or deprecated in this section. +11.1. AVP Header + As defined in Section 4, the AVP header contains three fields that + require IANA namespace management: the AVP Code, Vendor-ID, and Flags + fields. - - - - - - - - - - - -Fajardo, et al. Expires July 24, 2011 [Page 139] +Fajardo, et al. Standards Track [Page 135] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 -11. IANA Considerations +11.1.1. AVP Codes - This section provides guidance to the Internet Assigned Numbers - Authority (IANA) regarding registration of values related to the - Diameter protocol, in accordance with BCP 26 [RFC5226]. The policies - and procedures for the IANA put in place by [RFC3588] applies here. - The criteria used by the IANA for assignment of numbers within this - namespace remains the same unless otherwise stated in this section. - Existing assignments remains the same unless explicitly updated or - deprecated in this secion. + There are multiple namespaces. Vendors can have their own AVP Codes + namespace that will be identified by their Vendor-ID (also known as + Enterprise-Number), and they control the assignments of their vendor- + specific AVP Codes within their own namespace. The absence of a + Vendor-ID or a Vendor-ID value of zero (0) identifies the IETF AVP + Codes namespace, which is under IANA control. The AVP Codes and + sometimes possible values in an AVP are controlled and maintained by + IANA. AVP Code 0 is not used. AVP Codes 1-255 are managed + separately as RADIUS Attribute Types. Where a Vendor-Specific AVP is + implemented by more than one vendor, allocation of global AVPs should + be encouraged instead. + + AVPs may be allocated following Expert Review (by a Designated + Expert) with Specification Required [RFC5226]. A block allocation + (release of more than three AVPs at a time for a given purpose) + requires IETF Review [RFC5226]. -11.1. Changes to AVP Header Allocation +11.1.2. AVP Flags - For AVP Headers, the only change is the AVP code block allocations. - Block allocation (release of more than 3 at a time for a given - purpose) now only require IETF Review as opposed to an IETF - Consensus. + Section 4.1 describes the existing AVP Flags. The remaining bits can + only be assigned via a Standards Action [RFC5226]. 11.2. Diameter Header - For the Diameter Header, the command code namespace allocation has +11.2.1. Command Codes + + For the Diameter header, the Command Code namespace allocation has changed. The new allocation rules are as follows: - The command code values 256 - 8,388,607 (0x100 to 0x7fffff) are + The Command Code values 256 - 8,388,607 (0x100 to 0x7fffff) are for permanent, standard commands, allocated by IETF Review [RFC5226]. The values 8,388,608 - 16,777,213 (0x800000 - 0xfffffd) are - reserved for vendor-specific command codes, to be allocated on a + reserved for vendor-specific Command Codes, to be allocated on a First Come, First Served basis by IANA [RFC5226]. The request to IANA for a Vendor-Specific Command Code SHOULD include a reference - to a publicly available specification which documents the command + to a publicly available specification that documents the command in sufficient detail to aid in interoperability between independent implementations. If the specification cannot be made - publicly available, the request for a vendor-specific command code + publicly available, the request for a vendor-specific Command Code MUST include the contact information of persons and/or entities responsible for authoring and maintaining the command. + + + + + +Fajardo, et al. Standards Track [Page 136] + +RFC 6733 Diameter Base Protocol October 2012 + + + The values 16,777,214 and 16,777,215 (hexadecimal values 0xfffffe + - 0xffffff) are reserved for experimental commands. As these + codes are only for experimental and testing purposes, no guarantee + is made for interoperability between Diameter peers using + experimental commands. + +11.2.2. Command Flags + + Section 3 describes the existing Command Flags field. The remaining + bits can only be assigned via a Standards Action [RFC5226]. + 11.3. AVP Values For AVP values, the Experimental-Result-Code AVP value allocation has - been added. The new rule is as follows: + been added; see Section 11.3.1. The old AVP value allocation rule, + IETF Consensus, has been updated to IETF Review as per [RFC5226], and + affected AVPs are listed as reminders. 11.3.1. Experimental-Result-Code AVP Values for this AVP are purely local to the indicated vendor, and no IANA registry is maintained for them. +11.3.2. Result-Code AVP Values + New values are available for assignment via IETF Review [RFC5226]. +11.3.3. Accounting-Record-Type AVP Values -Fajardo, et al. Expires July 24, 2011 [Page 140] - -Internet-Draft Diameter Base Protocol January 2011 + New values are available for assignment via IETF Review [RFC5226]. + +11.3.4. Termination-Cause AVP Values + New values are available for assignment via IETF Review [RFC5226]. -11.4. Diameter TCP, SCTP, TLS/TCP and DTLS/SCTP Port Numbers +11.3.5. Redirect-Host-Usage AVP Values - Updated port number assignments are described in this section. The - IANA has assigned port number 3868 for TCP and SCTP. The port number - [TBD] has been assigned for TLS/TCP and DTLS/SCTP. + New values are available for assignment via IETF Review [RFC5226]. -11.5. S-NAPTR Parameters +11.3.6. Session-Server-Failover AVP Values - This document registers a new S-NAPTR Application Service Tag value - of "aaa". + New values are available for assignment via IETF Review [RFC5226]. - This document also registers the following S-NAPTR Application - Protocol Tags: +11.3.7. Session-Binding AVP Values - Tag | Protocol - -------------------|--------- - diameter.tcp | TCP - diameter.sctp | SCTP - diameter.tls.tcp | TLS/TCP - diameter.dtls.sctp | DTLS/SCTP + New values are available for assignment via IETF Review [RFC5226]. +Fajardo, et al. Standards Track [Page 137] + +RFC 6733 Diameter Base Protocol October 2012 + + +11.3.8. Disconnect-Cause AVP Values + New values are available for assignment via IETF Review [RFC5226]. +11.3.9. Auth-Request-Type AVP Values + New values are available for assignment via IETF Review [RFC5226]. +11.3.10. Auth-Session-State AVP Values + New values are available for assignment via IETF Review [RFC5226]. +11.3.11. Re-Auth-Request-Type AVP Values + New values are available for assignment via IETF Review [RFC5226]. +11.3.12. Accounting-Realtime-Required AVP Values + New values are available for assignment via IETF Review [RFC5226]. +11.3.13. Inband-Security-Id AVP (code 299) + The use of this AVP has been deprecated. +11.4. _diameters Service Name and Port Number Registration + IANA has registered the "_diameters" service name and assigned port + numbers for TLS/TCP and DTLS/SCTP according to the guidelines given + in [RFC6335]. + Service Name: _diameters + Transport Protocols: TCP, SCTP + Assignee: IESG <[email protected]> + Contact: IETF Chair <[email protected]> + Description: Diameter over TLS/TCP and DTLS/SCTP + Reference: RFC 6733 + Port Number: 5868, from the User Range -Fajardo, et al. Expires July 24, 2011 [Page 141] + + +Fajardo, et al. Standards Track [Page 138] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 + + +11.5. SCTP Payload Protocol Identifiers + + Two SCTP payload protocol identifiers have been registered in the + SCTP Payload Protocol Identifiers registry: + + + Value | SCTP Payload Protocol Identifier + -------|----------------------------------- + 46 | Diameter in a SCTP DATA chunk + 47 | Diameter in a DTLS/SCTP DATA chunk + +11.6. S-NAPTR Parameters -12. Diameter protocol related configurable parameters + The following tag has been registered in the S-NAPTR Application + Protocol Tags registry: + + Tag | Protocol + -------------------|--------- + diameter.dtls.sctp | DTLS/SCTP + +12. Diameter Protocol-Related Configurable Parameters This section contains the configurable parameters that are found throughout this document: @@ -7915,8 +7771,8 @@ Internet-Draft Diameter Base Protocol January 2011 A Diameter proxy server routes messages based on the realm portion of a Network Access Identifier (NAI). The server MUST have a table of Realm Names, and the address of the peer to which the - message must be forwarded to. The routing table MAY also include - a "default route", which is typically used for all messages that + message must be forwarded. The routing table MAY also include a + "default route", which is typically used for all messages that cannot be locally processed. Tc timer @@ -7927,30 +7783,9 @@ Internet-Draft Diameter Base Protocol January 2011 - - - - - - - - - - - - - - - - - - - - - -Fajardo, et al. Expires July 24, 2011 [Page 142] +Fajardo, et al. Standards Track [Page 139] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 13. Security Considerations @@ -7959,34 +7794,34 @@ Internet-Draft Diameter Base Protocol January 2011 [RFC5246] or DTLS/SCTP [RFC6083]. Additional security mechanisms such as IPsec [RFC4301] MAY also be deployed to secure connections between peers. However, all Diameter base protocol implementations - MUST support the use of TLS/TCP and DTLS/SCTP and the Diameter - protocol MUST NOT be used without any security mechanism. + MUST support the use of TLS/TCP and DTLS/SCTP, and the Diameter + protocol MUST NOT be used without one of TLS, DTLS, or IPsec. If a Diameter connection is to be protected via TLS/TCP and DTLS/SCTP or IPsec, then TLS/TCP and DTLS/SCTP or IPsec/IKE SHOULD begin prior to any Diameter message exchange. All security parameters for TLS/ TCP and DTLS/SCTP or IPsec are configured independent of the Diameter - protocol. All Diameter message will be sent through the TLS/TCP and + protocol. All Diameter messages will be sent through the TLS/TCP and DTLS/SCTP or IPsec connection after a successful setup. For TLS/TCP and DTLS/SCTP connections to be established in the open state, the CER/CEA exchange MUST include an Inband-Security-ID AVP with a value of TLS/TCP and DTLS/SCTP. The TLS/TCP and DTLS/SCTP - handshake will begin when both ends successfully reached the open + handshake will begin when both ends successfully reach the open state, after completion of the CER/CEA exchange. If the TLS/TCP and DTLS/SCTP handshake is successful, all further messages will be sent - via TLS/TCP and DTLS/SCTP. If the handshake fails, both ends move to - the closed state. See Sections 13.1 for more details. + via TLS/TCP and DTLS/SCTP. If the handshake fails, both ends MUST + move to the closed state. See Section 13.1 for more details. 13.1. TLS/TCP and DTLS/SCTP Usage Diameter nodes using TLS/TCP and DTLS/SCTP for security MUST mutually authenticate as part of TLS/TCP and DTLS/SCTP session establishment. In order to ensure mutual authentication, the Diameter node acting as - TLS/TCP and DTLS/SCTP server MUST request a certificate from the + the TLS/TCP and DTLS/SCTP server MUST request a certificate from the Diameter node acting as TLS/TCP and DTLS/SCTP client, and the - Diameter node acting as TLS/TCP and DTLS/SCTP client MUST be prepared - to supply a certificate on request. + Diameter node acting as the TLS/TCP and DTLS/SCTP client MUST be + prepared to supply a certificate on request. Diameter nodes MUST be able to negotiate the following TLS/TCP and DTLS/SCTP cipher suites: @@ -8000,16 +7835,24 @@ Internet-Draft Diameter Base Protocol January 2011 TLS_RSA_WITH_AES_128_CBC_SHA - Diameter nodes MAY negotiate other TLS/TCP and DTLS/SCTP cipher -Fajardo, et al. Expires July 24, 2011 [Page 143] + +Fajardo, et al. Standards Track [Page 140] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 + + Note that it is quite possible that support for the + TLS_RSA_WITH_AES_128_CBC_SHA cipher suite will be REQUIRED at some + future date. Diameter nodes MAY negotiate other TLS/TCP and DTLS/ + SCTP cipher suites. - suites. + If public key certificates are used for Diameter security (for + example, with TLS), the value of the expiration times in the routing + and peer tables MUST NOT be greater than the expiry time in the + relevant certificates. 13.2. Peer-to-Peer Considerations @@ -8027,67 +7870,105 @@ Internet-Draft Diameter Base Protocol January 2011 peers may not be known beforehand and therefore peer discovery may be required. +13.3. AVP Considerations + Diameter AVPs often contain security-sensitive data; for example, + user passwords and location data, network addresses and cryptographic + keys. The following AVPs defined in this document are considered to + be security-sensitive: + o Acct-Interim-Interval + o Accounting-Realtime-Required + o Acct-Multi-Session-Id + o Accounting-Record-Number + o Accounting-Record-Type + o Accounting-Session-Id + o Accounting-Sub-Session-Id + o Class +Fajardo, et al. Standards Track [Page 141] + +RFC 6733 Diameter Base Protocol October 2012 + o Session-Id + o Session-Binding + o Session-Server-Failover + o User-Name + Diameter messages containing these or any other AVPs considered to be + security-sensitive MUST only be sent protected via mutually + authenticated TLS or IPsec. In addition, those messages MUST NOT be + sent via intermediate nodes unless there is end-to-end security + between the originator and recipient or the originator has locally + trusted configuration that indicates that end-to-end security is not + needed. For example, end-to-end security may not be required in the + case where an intermediary node is known to be operated as part of + the same administrative domain as the endpoints so that an ability to + successfully compromise the intermediary would imply a high + probability of being able to compromise the endpoints as well. Note + that no end-to-end security mechanism is specified in this document. +14. References +14.1. Normative References + [FLOATPOINT] + Institute of Electrical and Electronics Engineers, "IEEE + Standard for Binary Floating-Point Arithmetic, ANSI/IEEE + Standard 754-1985", August 1985. + [IANAADFAM] + IANA, "Address Family Numbers", + <http://www.iana.org/assignments/address-family-numbers>. + [RFC0791] Postel, J., "Internet Protocol", STD 5, RFC 791, + September 1981. + [RFC0793] Postel, J., "Transmission Control Protocol", STD 7, + RFC 793, September 1981. + [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate + Requirement Levels", BCP 14, RFC 2119, March 1997. + [RFC3492] Costello, A., "Punycode: A Bootstring encoding of Unicode + for Internationalized Domain Names in Applications + (IDNA)", RFC 3492, March 2003. - - -Fajardo, et al. Expires July 24, 2011 [Page 144] +Fajardo, et al. Standards Track [Page 142] -Internet-Draft Diameter Base Protocol January 2011 - - -14. References - -14.1. Normative References - - [FLOATPOINT] - Institute of Electrical and Electronics Engineers, "IEEE - Standard for Binary Floating-Point Arithmetic, ANSI/IEEE - Standard 754-1985", August 1985. +RFC 6733 Diameter Base Protocol October 2012 - [IANAADFAM] - IANA,, "Address Family Numbers", - http://www.iana.org/assignments/address-family-numbers. - [RADTYPE] IANA,, "RADIUS Types", - http://www.iana.org/assignments/radius-types. + [RFC3539] Aboba, B. and J. Wood, "Authentication, Authorization and + Accounting (AAA) Transport Profile", RFC 3539, June 2003. - [RFC791] Postel, J., "Internet Protocol", RFC 791, September 1981. + [RFC3629] Yergeau, F., "UTF-8, a transformation format of ISO + 10646", STD 63, RFC 3629, November 2003. - [RFC793] Postel, J., "Transmission Control Protocol", RFC 793, - January 1981. + [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. - [RFC3539] Aboba, B. and J. Wood, "Authentication, Authorization and - Accounting (AAA) Transport Profile", RFC 3539, June 2003. + [RFC3986] Berners-Lee, T., Fielding, R., and L. Masinter, "Uniform + Resource Identifier (URI): Generic Syntax", STD 66, + RFC 3986, January 2005. [RFC4004] Calhoun, P., Johansson, T., Perkins, C., Hiller, T., and P. McCann, "Diameter Mobile IPv4 Application", RFC 4004, @@ -8101,51 +7982,44 @@ Internet-Draft Diameter Base Protocol January 2011 Loughney, "Diameter Credit-Control Application", RFC 4006, August 2005. - [RFC5234] Crocker, D. and P. Overell, "Augmented BNF for Syntax - Specifications: ABNF", STD 68, RFC 5234, January 2008. - - [RFC3588] Calhoun, P., Loughney, J., Guttman, E., Zorn, G., and J. - Arkko, "Diameter Base Protocol", RFC 3588, September 2003. + [RFC4086] Eastlake, D., Schiller, J., and S. Crocker, "Randomness + Requirements for Security", BCP 106, RFC 4086, June 2005. - [RFC5226] Narten, T. and H. Alvestrand, "Guidelines for Writing an - IANA Considerations Section in RFCs", BCP 26, RFC 5226, - May 2008. + [RFC4282] Aboba, B., Beadles, M., Arkko, J., and P. Eronen, "The + Network Access Identifier", RFC 4282, December 2005. [RFC4291] Hinden, R. and S. Deering, "IP Version 6 Addressing Architecture", RFC 4291, February 2006. + [RFC4960] Stewart, R., "Stream Control Transmission Protocol", + RFC 4960, September 2007. + [RFC5226] Narten, T. and H. Alvestrand, "Guidelines for Writing an + IANA Considerations Section in RFCs", BCP 26, RFC 5226, + May 2008. -Fajardo, et al. Expires July 24, 2011 [Page 145] - -Internet-Draft Diameter Base Protocol January 2011 - + [RFC5234] Crocker, D. and P. Overell, "Augmented BNF for Syntax + Specifications: ABNF", STD 68, RFC 5234, January 2008. - [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate - Requirement Levels", BCP 14, RFC 2119, March 1997. + [RFC5246] Dierks, T. and E. Rescorla, "The Transport Layer Security + (TLS) Protocol Version 1.2", RFC 5246, August 2008. - [RFC4282] Aboba, B., Beadles, M., Arkko, J., and P. Eronen, "The - Network Access Identifier", RFC 4282, December 2005. - [RFC4086] Eastlake, D., Schiller, J., and S. Crocker, "Randomness - Requirements for Security", BCP 106, RFC 4086, June 2005. - [RFC4960] Stewart, R., "Stream Control Transmission Protocol", - RFC 4960, September 2007. - [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. +Fajardo, et al. Standards Track [Page 143] + +RFC 6733 Diameter Base Protocol October 2012 - [RFC5246] Dierks, T. and E. Rescorla, "The Transport Layer Security - (TLS) Protocol Version 1.2", RFC 5246, August 2008. - [RFC3986] Berners-Lee, T., Fielding, R., and L. Masinter, "Uniform - Resource Identifier (URI): Generic Syntax", STD 66, - RFC 3986, January 2005. + [RFC5280] Cooper, D., Santesson, S., Farrell, S., Boeyen, S., + Housley, R., and W. Polk, "Internet X.509 Public Key + Infrastructure Certificate and Certificate Revocation List + (CRL) Profile", RFC 5280, May 2008. - [RFC3629] Yergeau, F., "UTF-8, a transformation format of ISO - 10646", STD 63, RFC 3629, November 2003. + [RFC5729] Korhonen, J., Jones, M., Morand, L., and T. Tsou, + "Clarifications on the Routing of Diameter Requests Based + on the Username and the Realm", RFC 5729, December 2009. [RFC5890] Klensin, J., "Internationalized Domain Names for Applications (IDNA): Definitions and Document Framework", @@ -8154,103 +8028,120 @@ Internet-Draft Diameter Base Protocol January 2011 [RFC5891] Klensin, J., "Internationalized Domain Names in Applications (IDNA): Protocol", RFC 5891, August 2010. - [RFC3492] Costello, A., "Punycode: A Bootstring encoding of Unicode - for Internationalized Domain Names in Applications - (IDNA)", RFC 3492, March 2003. - - [RFC5729] Korhonen, J., Jones, M., Morand, L., and T. Tsou, - "Clarifications on the Routing of Diameter Requests Based - on the Username and the Realm", RFC 5729, December 2009. - - [RFC4347] Rescorla, E. and N. Modadugu, "Datagram Transport Layer - Security", RFC 4347, April 2006. - [RFC6083] Tuexen, M., Seggelmann, R., and E. Rescorla, "Datagram Transport Layer Security (DTLS) for Stream Control Transmission Protocol (SCTP)", RFC 6083, January 2011. + [RFC6347] Rescorla, E. and N. Modadugu, "Datagram Transport Layer + Security Version 1.2", RFC 6347, January 2012. + [RFC6408] Jones, M., Korhonen, J., and L. Morand, "Diameter + Straightforward-Naming Authority Pointer (S-NAPTR) Usage", + RFC 6408, November 2011. +14.2. Informative References -Fajardo, et al. Expires July 24, 2011 [Page 146] - -Internet-Draft Diameter Base Protocol January 2011 + [ENTERPRISE] IANA, "SMI Network Management Private Enterprise + Codes", + <http://www.iana.org/assignments/enterprise-numbers>. + [IANATCV] IANA, "Termination-Cause AVP Values (code 295)", + <http://www.iana.org/assignments/aaa-parameters/ + aaa-parameters.xml#aaa-parameters-16>. -14.2. Informational References + [RFC1492] Finseth, C., "An Access Control Protocol, Sometimes + Called TACACS", RFC 1492, July 1993. - [RFC2989] Aboba, B., Calhoun, P., Glass, S., Hiller, T., McCann, P., - Shiino, H., Walsh, P., Zorn, G., Dommety, G., Perkins, C., - Patil, B., Mitton, D., Manning, S., Beadles, M., Chen, X., - Sivalingham, S., Hameed, A., Munson, M., Jacobs, S., Lim, - B., Hirschman, B., Hsu, R., Koo, H., Lipford, M., - Campbell, E., Xu, Y., Baba, S., and E. Jaques, "Criteria - for Evaluating AAA Protocols for Network Access", - RFC 2989, November 2000. + [RFC1661] Simpson, W., "The Point-to-Point Protocol (PPP)", + STD 51, RFC 1661, July 1994. - [RFC2975] Aboba, B., Arkko, J., and D. Harrington, "Introduction to - Accounting Management", RFC 2975, October 2000. + [RFC2104] Krawczyk, H., Bellare, M., and R. Canetti, "HMAC: + Keyed-Hashing for Message Authentication", RFC 2104, + February 1997. - [RFC3232] Reynolds, J., "Assigned Numbers: RFC 1700 is Replaced by - an On-line Database", RFC 3232, January 2002. - [RFC5176] Chiba, M., Dommety, G., Eklund, M., Mitton, D., and B. - Aboba, "Dynamic Authorization Extensions to Remote - Authentication Dial In User Service (RADIUS)", RFC 5176, - January 2008. - [RFC1661] Simpson, W., "The Point-to-Point Protocol (PPP)", STD 51, - RFC 1661, July 1994. - [RFC2866] Rigney, C., "RADIUS Accounting", RFC 2866, June 2000. - [RFC2869] Rigney, C., Willats, W., and P. Calhoun, "RADIUS - Extensions", RFC 2869, June 2000. +Fajardo, et al. Standards Track [Page 144] + +RFC 6733 Diameter Base Protocol October 2012 - [RFC2865] Rigney, C., Willens, S., Rubens, A., and W. Simpson, - "Remote Authentication Dial In User Service (RADIUS)", - RFC 2865, June 2000. - [RFC3162] Aboba, B., Zorn, G., and D. Mitton, "RADIUS and IPv6", - RFC 3162, August 2001. + [RFC2782] Gulbrandsen, A., Vixie, P., and L. Esibov, "A DNS RR + for specifying the location of services (DNS SRV)", + RFC 2782, February 2000. - [RFC4301] Kent, S. and K. Seo, "Security Architecture for the - Internet Protocol", RFC 4301, December 2005. + [RFC2865] Rigney, C., Willens, S., Rubens, A., and W. Simpson, + "Remote Authentication Dial In User Service (RADIUS)", + RFC 2865, June 2000. - [RFC5905] Mills, D., Martin, J., Burbank, J., and W. Kasch, "Network - Time Protocol Version 4: Protocol and Algorithms - Specification", RFC 5905, June 2010. + [RFC2866] Rigney, C., "RADIUS Accounting", RFC 2866, June 2000. - [RFC1492] Finseth, C., "An Access Control Protocol, Sometimes Called - TACACS", RFC 1492, July 1993. + [RFC2869] Rigney, C., Willats, W., and P. Calhoun, "RADIUS + Extensions", RFC 2869, June 2000. - [RFC4690] Klensin, J., Faltstrom, P., Karp, C., and IAB, "Review and + [RFC2881] Mitton, D. and M. Beadles, "Network Access Server + Requirements Next Generation (NASREQNG) NAS Model", + RFC 2881, July 2000. + [RFC2975] Aboba, B., Arkko, J., and D. Harrington, "Introduction + to Accounting Management", RFC 2975, October 2000. + [RFC2989] Aboba, B., Calhoun, P., Glass, S., Hiller, T., McCann, + P., Shiino, H., Walsh, P., Zorn, G., Dommety, G., + Perkins, C., Patil, B., Mitton, D., Manning, S., + Beadles, M., Chen, X., Sivalingham, S., Hameed, A., + Munson, M., Jacobs, S., Lim, B., Hirschman, B., Hsu, + R., Koo, H., Lipford, M., Campbell, E., Xu, Y., Baba, + S., and E. Jaques, "Criteria for Evaluating AAA + Protocols for Network Access", RFC 2989, November 2000. -Fajardo, et al. Expires July 24, 2011 [Page 147] - -Internet-Draft Diameter Base Protocol January 2011 + [RFC3162] Aboba, B., Zorn, G., and D. Mitton, "RADIUS and IPv6", + RFC 3162, August 2001. + [RFC3748] Aboba, B., Blunk, L., Vollbrecht, J., Carlson, J., and + H. Levkowetz, "Extensible Authentication Protocol + (EAP)", RFC 3748, June 2004. - Recommendations for Internationalized Domain Names - (IDNs)", RFC 4690, September 2006. + [RFC4301] Kent, S. and K. Seo, "Security Architecture for the + Internet Protocol", RFC 4301, December 2005. - [RFC5461] Gont, F., "TCP's Reaction to Soft Errors", RFC 5461, - February 2009. + [RFC4690] Klensin, J., Faltstrom, P., Karp, C., and IAB, "Review + and Recommendations for Internationalized Domain Names + (IDNs)", RFC 4690, September 2006. - [RFC5927] Gont, F., "ICMP Attacks against TCP", RFC 5927, July 2010. + [RFC5176] Chiba, M., Dommety, G., Eklund, M., Mitton, D., and B. + Aboba, "Dynamic Authorization Extensions to Remote + Authentication Dial In User Service (RADIUS)", + RFC 5176, January 2008. - [RFC3692] Narten, T., "Assigning Experimental and Testing Numbers - Considered Useful", BCP 82, RFC 3692, January 2004. +Fajardo, et al. Standards Track [Page 145] + +RFC 6733 Diameter Base Protocol October 2012 + + [RFC5461] Gont, F., "TCP's Reaction to Soft Errors", RFC 5461, + February 2009. + [RFC5905] Mills, D., Martin, J., Burbank, J., and W. Kasch, + "Network Time Protocol Version 4: Protocol and + Algorithms Specification", RFC 5905, June 2010. + [RFC5927] Gont, F., "ICMP Attacks against TCP", RFC 5927, + July 2010. + [RFC6335] Cotton, M., Eggert, L., Touch, J., Westerlund, M., and + S. Cheshire, "Internet Assigned Numbers Authority + (IANA) Procedures for the Management of the Service + Name and Transport Protocol Port Number Registry", + BCP 165, RFC 6335, August 2011. + [RFC6737] Kang, J. and G. Zorn, "The Diameter Capabilities Update + Application", RFC 6737, October 2012. @@ -8284,80 +8175,83 @@ Internet-Draft Diameter Base Protocol January 2011 -Fajardo, et al. Expires July 24, 2011 [Page 148] +Fajardo, et al. Standards Track [Page 146] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 Appendix A. Acknowledgements -A.1. RFC3588bis +A.1. This Document The authors would like to thank the following people that have provided proposals and contributions to this document: To Vishnu Ram and Satendra Gera for their contributions on - Capabilities Updates, Predictive Loop Avoidance as well as many other - technical proposals. To Tolga Asveren for his insights and + capabilities updates, predictive loop avoidance, as well as many + other technical proposals. To Tolga Asveren for his insights and contributions on almost all of the proposed solutions incorporated - into this document. To Timothy Smith for helping on the Capabilities - Updates and other topics. To Tony Zhang for providing fixes to loop - holes on composing Failed-AVPs as well as many other issues and + into this document. To Timothy Smith for helping on the capabilities + Update and other topics. To Tony Zhang for providing fixes to + loopholes on composing Failed-AVPs as well as many other issues and topics. To Jan Nordqvist for clearly stating the usage of - Application Ids. To Anders Kristensen for providing needed technical + Application Ids. To Anders Kristensen for providing needed technical opinions. To David Frascone for providing invaluable review of the document. To Mark Jones for providing clarifying text on vendor - command codes and other vendor specific indicators. + command codes and other vendor-specific indicators. To Victor + Pascual and Sebastien Decugis for new text and recommendations on + SCTP/DTLS. To Jouni Korhonen for taking over the editing task and + resolving last bits from versions 27 through 29. - Special thanks to the Diameter extensibility design team which helped - resolve the tricky question of mandatory AVPs and ABNF semantics. - The members of this team are as follows: + Special thanks to the Diameter extensibility design team, which + helped resolve the tricky question of mandatory AVPs and ABNF + semantics. The members of this team are as follows: Avi Lior, Jari Arkko, Glen Zorn, Lionel Morand, Mark Jones, Tolga - Asveren Jouni Korhonen, Glenn McGregor. + Asveren, Jouni Korhonen, and Glenn McGregor. Special thanks also to people who have provided invaluable comments and inputs especially in resolving controversial issues: - Glen Zorn, Yoshihiro Ohba, Marco Stura, and Pasi Eronen. + Glen Zorn, Yoshihiro Ohba, Marco Stura, Stephen Farrel, Pete Resnick, + Peter Saint-Andre, Robert Sparks, Krishna Prasad, Sean Turner, Barry + Leiba, and Pasi Eronen. Finally, we would like to thank the original authors of this document: - Pat Calhoun, John Loughney, Jari Arkko, Erik Guttman and Glen Zorn. + Pat Calhoun, John Loughney, Jari Arkko, Erik Guttman, and Glen Zorn. Their invaluable knowledge and experience has given us a robust and flexible AAA protocol that many people have seen great value in adopting. We greatly appreciate their support and stewardship for the continued improvements of Diameter as a protocol. We would also like to extend our gratitude to folks aside from the authors who have - assisted and contributed to the original version of this document. - Their efforts significantly contributed to the success of Diameter. - - - -Fajardo, et al. Expires July 24, 2011 [Page 149] +Fajardo, et al. Standards Track [Page 147] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 -A.2. RFC3588 + assisted and contributed to the original version of this document. + Their efforts significantly contributed to the success of Diameter. + +A.2. RFC 3588 The authors would like to thank Nenad Trifunovic, Tony Johansson and Pankaj Patel for their participation in the pre-IETF Document Reading - Party. Allison Mankin, Jonathan Wood and Bernard Aboba provided - invaluable assistance in working out transport issues, and similarly - with Steven Bellovin in the security area. + Party. Allison Mankin, Jonathan Wood, and Bernard Aboba provided + invaluable assistance in working out transport issues and this was + also the case with Steven Bellovin in the security area. Paul Funk and David Mitton were instrumental in getting the Peer State Machine correct, and our deep thanks go to them for their time. Text in this document was also provided by Paul Funk, Mark Eklund, - Mark Jones and Dave Spence. Jacques Caron provided many great + Mark Jones, and Dave Spence. Jacques Caron provided many great comments as a result of a thorough review of the spec. The authors would also like to acknowledge the following people for @@ -8367,96 +8261,57 @@ A.2. RFC3588 David Frascone, Daniel C. Fox, Lol Grant, Ignacio Goyret, Nancy Greene, Peter Heitman, Fredrik Johansson, Mark Jones, Martin Julien, Bob Kopacz, Paul Krumviede, Fergal Ladley, Ryan Moats, Victor Muslin, - Kenneth Peirce, John Schnizlein, Sumit Vakil, John R. Vollbrecht and + Kenneth Peirce, John Schnizlein, Sumit Vakil, John R. Vollbrecht, and Jeff Weisberg. Finally, Pat Calhoun would like to thank Sun Microsystems since most of the effort put into this document was done while he was in their employ. - - - - - - - - - - - - - - - - - - - - - - -Fajardo, et al. Expires July 24, 2011 [Page 150] - -Internet-Draft Diameter Base Protocol January 2011 - - Appendix B. S-NAPTR Example As an example, consider a client that wishes to resolve aaa: - example1.com. The client performs a NAPTR query for that domain, and - the following NAPTR records are returned: + ex1.example.com. The client performs a NAPTR query for that domain, + and the following NAPTR records are returned: ;; order pref flags service regexp replacement IN NAPTR 50 50 "s" "aaa:diameter.tls.tcp" "" - _diameter._tls.example1.com + _diameter._tls.ex1.example.com IN NAPTR 100 50 "s" "aaa:diameter.tcp" "" - _aaa._tcp.example1.com + _aaa._tcp.ex1.example.com IN NAPTR 150 50 "s" "aaa:diameter.sctp" "" - _diameter._sctp.example1.com + _diameter._sctp.ex1.example.com - This indicates that the server supports TLS, TCP and SCTP in that + This indicates that the server supports TLS, TCP, and SCTP in that order. If the client supports TLS, TLS will be used, targeted to a - host determined by an SRV lookup of _diameter._tls.example1.com. + + + +Fajardo, et al. Standards Track [Page 148] + +RFC 6733 Diameter Base Protocol October 2012 + + + host determined by an SRV lookup of _diameter._tls.ex1.example.com. That lookup would return: ;; Priority Weight Port Target - IN SRV 0 1 5060 server1.example1.com - IN SRV 0 2 5060 server2.example1.com + IN SRV 0 1 5060 server1.ex1.example.com + IN SRV 0 2 5060 server2.ex1.example.com As an alternative example, a client that wishes to resolve aaa: - example2.com. The client performs a NAPTR query for that domain, and - the following NAPTR records are returned: + ex2.example.com. The client performs a NAPTR query for that domain, + and the following NAPTR records are returned: ;; order pref flags service regexp replacement IN NAPTR 150 50 "a" "aaa:diameter.tls.tcp" "" - server1.example2.com + server1.ex2.example.com IN NAPTR 150 50 "a" "aaa:diameter.tls.tcp" "" - server2.example2.com + server2.ex2.example.com This indicates that the server supports TCP available at the returned host names. - - - - - - - - - - - - - - - -Fajardo, et al. Expires July 24, 2011 [Page 151] - -Internet-Draft Diameter Base Protocol January 2011 - - Appendix C. Duplicate Detection As described in Section 9.4, accounting record duplicate detection is @@ -8464,14 +8319,14 @@ Appendix C. Duplicate Detection reasons: o Failover to an alternate server. Where close to real-time - performance is required, failover thresholds need to be kept low - and this may lead to an increased likelihood of duplicates. - Failover can occur at the client or within Diameter agents. - - o Failure of a client or agent after sending of a record from non- - volatile memory, but prior to receipt of an application layer ACK - and deletion of the record. record to be sent. This will result - in retransmission of the record soon after the client or agent has + performance is required, failover thresholds need to be kept low. + This may lead to an increased likelihood of duplicates. Failover + can occur at the client or within Diameter agents. + + o Failure of a client or agent after sending a record from non- + volatile memory, but prior to receipt of an application-layer ACK + and deletion of the record to be sent. This will result in + retransmission of the record soon after the client or agent has rebooted. o Duplicates received from RADIUS gateways. Since the @@ -8481,48 +8336,48 @@ Appendix C. Duplicate Detection o Implementation problems and misconfiguration. - The T flag is used as an indication of an application layer + The T flag is used as an indication of an application-layer retransmission event, e.g., due to failover to an alternate server. It is defined only for request messages sent by Diameter clients or agents. For instance, after a reboot, a client may not know whether + + + +Fajardo, et al. Standards Track [Page 149] + +RFC 6733 Diameter Base Protocol October 2012 + + it has already tried to send the accounting records in its non- volatile memory before the reboot occurred. Diameter servers MAY use the T flag as an aid when processing requests and detecting duplicate messages. However, servers that do this MUST ensure that duplicates are found even when the first transmitted request arrives at the server after the retransmitted request. It can be used only in cases - where no answer has been received from the Server for a request and + where no answer has been received from the server for a request and the request is sent again, (e.g., due to a failover to an alternate peer, due to a recovered primary peer or due to a client re-sending a stored record from non-volatile memory such as after reboot of a client or agent). - In some cases the Diameter accounting server can delay the duplicate + In some cases, the Diameter accounting server can delay the duplicate detection and accounting record processing until a post-processing phase takes place. At that time records are likely to be sorted according to the included User-Name and duplicate elimination is easy - in this case. In other situations it may be necessary to perform + in this case. In other situations, it may be necessary to perform real-time duplicate detection, such as when credit limits are imposed or real-time fraud detection is desired. - - - -Fajardo, et al. Expires July 24, 2011 [Page 152] - -Internet-Draft Diameter Base Protocol January 2011 - - In general, only generation of duplicates due to failover or re- sending of records in non-volatile storage can be reliably detected - by Diameter clients or agents. In such cases the Diameter client or - agents can mark the message as possible duplicate by setting the T + by Diameter clients or agents. In such cases, the Diameter client or + agents can mark the message as a possible duplicate by setting the T flag. Since the Diameter server is responsible for duplicate - detection, it can choose to make use of the T flag or not, in order - to optimize duplicate detection. Since the T flag does not affect - interoperability, and may not be needed by some servers, generation - of the T flag is REQUIRED for Diameter clients and agents, but MAY be - implemented by Diameter servers. + detection, it can choose whether or not to make use of the T flag, in + order to optimize duplicate detection. Since the T flag does not + affect interoperability, and it may not be needed by some servers, + generation of the T flag is REQUIRED for Diameter clients and agents, + but it MAY be implemented by Diameter servers. As an example, it can be usually be assumed that duplicates appear within a time window of longest recorded network partition or device @@ -8535,40 +8390,39 @@ Internet-Draft Diameter Base Protocol January 2011 The following is an example of how the T flag may be used by the server to detect duplicate requests. - A Diameter server MAY check the T flag of the received message to determine if the record is a possible duplicate. If the T flag is set in the request message, the server searches for a duplicate within a configurable duplication time window backward and forward. This limits database searching to those records where - the T flag is set. In a well run network, network partitions and + the T flag is set. In a well-run network, network partitions and + + + +Fajardo, et al. Standards Track [Page 150] + +RFC 6733 Diameter Base Protocol October 2012 + + device faults will presumably be rare events, so this approach represents a substantial optimization of the duplicate detection process. During failover, it is possible for the original record - to be received after the T flag marked record, due to differences + to be received after the T-flag-marked record, due to differences in network delays experienced along the path by the original and duplicate transmissions. The likelihood of this occurring increases as the failover interval is decreased. In order to be - able to detect out of order duplicates, the Diameter server should - use backward and forward time windows when performing duplicate - checking for the T flag marked request. For example, in order to - allow time for the original record to exit the network and be - recorded by the accounting server, the Diameter server can delay - processing records with the T flag set until a time period - TIME_WAIT + RECORD_PROCESSING_TIME has elapsed after the closing - of the original transport connection. After this time period has - expired, then it may check the T flag marked records against the + able to detect duplicates that are out of order, the Diameter + server should use backward and forward time windows when + performing duplicate checking for the T-flag-marked request. For + example, in order to allow time for the original record to exit + the network and be recorded by the accounting server, the Diameter + server can delay processing records with the T flag set until a + time period TIME_WAIT + RECORD_PROCESSING_TIME has elapsed after + the closing of the original transport connection. After this time + period, it may check the T-flag-marked records against the database with relative assurance that the original records, if sent, have been received and recorded. - - - -Fajardo, et al. Expires July 24, 2011 [Page 153] - -Internet-Draft Diameter Base Protocol January 2011 - - Appendix D. Internationalized Domain Names To be compatible with the existing DNS infrastructure and simplify @@ -8579,14 +8433,7 @@ Appendix D. Internationalized Domain Names recommendations in [RFC4690] and [RFC5890]. Applications that provide support for IDNs outside of the Diameter protocol but interacting with it SHOULD use the representation and conversion - framework described in [RFC5890], [RFC5891] and [RFC3492]. - - - - - - - + framework described in [RFC5890], [RFC5891], and [RFC3492]. @@ -8608,21 +8455,9 @@ Appendix D. Internationalized Domain Names - - - - - - - - - - - - -Fajardo, et al. Expires July 24, 2011 [Page 154] +Fajardo, et al. Standards Track [Page 151] -Internet-Draft Diameter Base Protocol January 2011 +RFC 6733 Diameter Base Protocol October 2012 Authors' Addresses @@ -8634,7 +8469,7 @@ Authors' Addresses USA Phone: +1-908-421-1845 - Email: [email protected] + EMail: [email protected] Jari Arkko @@ -8643,7 +8478,7 @@ Authors' Addresses Finland Phone: +358 40 5079256 - Email: [email protected] + EMail: [email protected] John Loughney @@ -8653,17 +8488,17 @@ Authors' Addresses US Phone: +1-650-283-8068 - Email: [email protected] + EMail: [email protected] - Glenn Zorn + Glen Zorn (editor) Network Zen - 1310 East Thomas Street - Seattle, WA 98102 - US + 227/358 Thanon Sanphawut + Bang Na, Bangkok 10260 + Thailand - Phone: - Email: [email protected] + Phone: +66 (0) 87-0404617 + EMail: [email protected] @@ -8676,6 +8511,5 @@ Authors' Addresses -Fajardo, et al. Expires July 24, 2011 [Page 155] +Fajardo, et al. Standards Track [Page 152] - diff --git a/lib/diameter/doc/standard/rfc6737.txt b/lib/diameter/doc/standard/rfc6737.txt new file mode 100644 index 0000000000..50aa33e98f --- /dev/null +++ b/lib/diameter/doc/standard/rfc6737.txt @@ -0,0 +1,339 @@ + + + + + + +Internet Engineering Task Force (IETF) K. Jiao +Request for Comments: 6737 Huawei +Category: Standards Track G. Zorn +ISSN: 2070-1721 Network Zen + October 2012 + + + The Diameter Capabilities Update Application + +Abstract + + This document defines a new Diameter application and associated + Command Codes. The Capabilities Update application is intended to + allow the dynamic update of certain Diameter peer capabilities while + the peer-to-peer connection is in the open state. + +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/rfc6737. + +Copyright Notice + + Copyright (c) 2012 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. + + + + + + + +Jiao & Zorn Standards Track [Page 1] + +RFC 6737 Diameter Capabilities Update October 2012 + + +Table of Contents + + 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . 2 + 2. Specification of Requirements . . . . . . . . . . . . . . . . . 2 + 3. Diameter Protocol Considerations . . . . . . . . . . . . . . . 3 + 4. Capabilities Update . . . . . . . . . . . . . . . . . . . . . . 3 + 4.1. Command Code Values . . . . . . . . . . . . . . . . . . . . 4 + 4.1.1. Capabilities-Update-Request . . . . . . . . . . . . . . 4 + 4.1.2. Capabilities-Update-Answer . . . . . . . . . . . . . . 5 + 5. Security Considerations . . . . . . . . . . . . . . . . . . . . 5 + 6. IANA Considerations . . . . . . . . . . . . . . . . . . . . . . 5 + 6.1. Application Identifier . . . . . . . . . . . . . . . . . . 5 + 6.2. Command Codes . . . . . . . . . . . . . . . . . . . . . . . 5 + 7. Contributors . . . . . . . . . . . . . . . . . . . . . . . . . 5 + 8. Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . 5 + 9. References . . . . . . . . . . . . . . . . . . . . . . . . . . 6 + 9.1. Normative References . . . . . . . . . . . . . . . . . . . 6 + 9.2. Informative References . . . . . . . . . . . . . . . . . . 6 + +1. Introduction + + Capabilities exchange is an important component of the Diameter base + protocol [RFC6733], allowing peers to exchange identities and + Diameter capabilities (protocol version number, supported Diameter + applications, security mechanisms, etc.). As defined in RFC 3588, + however, the capabilities exchange process takes place only once, at + the inception of a transport connection between a given pair of + peers. Therefore, if a peer's capabilities change (due to a software + update, for example), the existing connection(s) must be torn down + (along with all of the associated user sessions) and restarted before + the modified capabilities can be advertised. + + This document defines a new Diameter application intended to allow + the dynamic update of a subset of Diameter peer capabilities over an + existing connection. Because the Capabilities Update application + specified herein operates over an existing transport connection, + modification of certain capabilities is prohibited. Specifically, + modifying the security mechanism in use is not allowed; if the + security method used between a pair of peers is changed, the affected + connection MUST be restarted. + +2. Specification of Requirements + + 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 RFC 2119 [RFC2119]. + + + + + +Jiao & Zorn Standards Track [Page 2] + +RFC 6737 Diameter Capabilities Update October 2012 + + +3. Diameter Protocol Considerations + + This section details the relationship of the Diameter Capabilities + Update application to the Diameter base protocol. + + This document specifies Diameter Application-Id 10. Diameter nodes + conforming to this specification MUST advertise support by including + the value 10 in the Auth-Application-Id of the Capabilities-Exchange- + Request (CER) and Capabilities-Exchange-Answer (CEA) commands + [RFC6733]. + +4. Capabilities Update + + When the capabilities of a Diameter node conforming to this + specification change, the node MUST notify all of the nodes with + which it has an open transport connection and which have also + advertised support for the Capabilities Update application using the + Capabilities-Update-Request (CUR) message (Section 4.1.1). This + message allows the update of a peer's capabilities (supported + Diameter applications, etc.). + + A Diameter node only issues a given command to those peers that have + advertised support for the Diameter application that defines the + command; a Diameter node must cache the supported applications in + order to ensure that unrecognized commands and/or Attribute-Value + Pairs (AVPs) are not unnecessarily sent to a peer. + + The receiver of the CUR MUST determine common applications by + computing the intersection of its own set of supported Application + Ids against all of the Application-Id AVPs (Auth-Application-Id, + Acct-Application-Id, and Vendor-Specific-Application-Id) present in + the CUR. The value of the Vendor-Id AVP in the Vendor-Specific- + Application-Id MUST NOT be used during computation. + + If the receiver of a CUR does not have any applications in common + with the sender, then it MUST return a Capabilities-Update-Answer + (CUA) (Section 4.1.2) with the Result-Code AVP set to + DIAMETER_NO_COMMON_APPLICATION [RFC6733], and it SHOULD disconnect + the transport-layer connection. However, if active sessions are + using the connection, peers MAY delay disconnection until the + sessions can be redirected or gracefully terminated. Note that + receiving a CUA from a peer advertising itself as a relay (see + [RFC6733], Section 2.4) MUST be interpreted as having common + applications with the peer. + + As for CER/CEA messages, the CUR and CUA messages MUST NOT be + proxied, redirected, or relayed. + + + + +Jiao & Zorn Standards Track [Page 3] + +RFC 6737 Diameter Capabilities Update October 2012 + + + Even though the CUR/CUA messages cannot be proxied, it is still + possible for an upstream agent to receive a message for which there + are no peers available to handle the application that corresponds to + the Command Code. This could happen if, for example, the peers are + too busy or down. In such instances, the 'E' bit MUST be set in the + answer message with the Result-Code AVP set to + DIAMETER_UNABLE_TO_DELIVER to inform the downstream peer to take + action (e.g., re-routing requests to an alternate peer). + +4.1. Command Code Values + + This section defines Command Code [RFC6733] values that MUST be + supported by all Diameter implementations conforming to this + specification. The following Command Codes are defined in this + document: Capabilities-Update-Request (CUR, Section 4.1.1), and + Capabilities-Update-Answer (CUA, Section 4.1.2). The Diameter + Command Code Format (CCF) ([RFC6733], Section 3.2) is used in the + definitions. + +4.1.1. Capabilities-Update-Request + + The Capabilities-Update-Request (CUR), indicated by the Command Code + set to 328 and the Command Flags' 'R' bit set, is sent to update + local capabilities. Upon detection of a transport failure, this + message MUST NOT be sent to an alternate peer. + + When Diameter is run over the Stream Control Transmission Protocol + (SCTP) [RFC4960], which allows connections to span multiple + interfaces and multiple IP addresses, the Capabilities-Update-Request + message MUST contain one Host-IP-Address AVP for each potential IP + address that may be locally used when transmitting Diameter messages. + + Message Format + + <CUR> ::= < Diameter Header: 328, REQ > + { Origin-Host } + { Origin-Realm } + 1* { Host-IP-Address } + { Vendor-Id } + { Product-Name } + [ Origin-State-Id ] + * [ Supported-Vendor-Id ] + * [ Auth-Application-Id ] + * [ Acct-Application-Id ] + * [ Vendor-Specific-Application-Id ] + [ Firmware-Revision ] + * [ AVP ] + + + + +Jiao & Zorn Standards Track [Page 4] + +RFC 6737 Diameter Capabilities Update October 2012 + + +4.1.2. Capabilities-Update-Answer + + The Capabilities-Update-Answer, indicated by the Command Code set to + 328 and the Command Flags' 'R' bit cleared, is sent in response to a + CUR message. + + Message Format + + <CUA> ::= < Diameter Header: 328 > + { Origin-Host } + { Origin-Realm } + { Result-Code } + [ Error-Message ] + * [ AVP ] + +5. Security Considerations + + The security considerations applicable to the Diameter base protocol + [RFC6733] are also applicable to this document. + +6. IANA Considerations + + This section explains the criteria to be used by the IANA for + assignment of numbers within namespaces used within this document. + +6.1. Application Identifier + + This specification assigns the value 10 (Diameter Capabilities + Update) from the Application Identifiers namespace [RFC6733]. See + Section 3 for the assignment of the namespace in this specification. + +6.2. Command Codes + + This specification assigns the value 328 (Capabilities-Update- + Request/Capabilities-Update-Answer (CUR/CUA)) from the Command Codes + namespace [RFC6733]. See Section 4.1 for the assignment of the + namespace in this specification. + +7. Contributors + + This document is based upon work done by Tina Tsou. + +8. Acknowledgements + + Thanks to Sebastien Decugis, Niklas Neumann, Subash Comerica, Lionel + Morand, Dan Romascanu, Dan Harkins, and Ravi for helpful review and + discussion. + + + + +Jiao & Zorn Standards Track [Page 5] + +RFC 6737 Diameter Capabilities Update October 2012 + + +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. + +9.2. Informative References + + [RFC4960] Stewart, R., "Stream Control Transmission Protocol", + RFC 4960, September 2007. + +Authors' Addresses + + Jiao Kang + Huawei Technologies + Section F1, Huawei Industrial Base + Bantian, Longgang District + Shenzhen 518129 + P.R. China + + EMail: [email protected] + + + Glen Zorn + Network Zen + 227/358 Thanon Sanphawut + Bang Na, Bangkok 10260 + Thailand + + Phone: +66 (0) 909-201060 + EMail: [email protected] + + + + + + + + + + + + + + + + +Jiao & Zorn Standards Track [Page 6] + diff --git a/lib/diameter/examples/GNUmakefile b/lib/diameter/examples/code/GNUmakefile index 4c3f87939b..98e36a99e3 100644 --- a/lib/diameter/examples/GNUmakefile +++ b/lib/diameter/examples/code/GNUmakefile @@ -1,19 +1,19 @@ -# +# # %CopyrightBegin% -# -# Copyright Ericsson AB 2010-2011. All Rights Reserved. -# +# +# Copyright Ericsson AB 2010-2012. 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% # diff --git a/lib/diameter/examples/client.erl b/lib/diameter/examples/code/client.erl index 36a77dd524..bfe71b0e56 100644 --- a/lib/diameter/examples/client.erl +++ b/lib/diameter/examples/code/client.erl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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,7 +38,7 @@ -module(client). -include_lib("diameter/include/diameter.hrl"). --include_lib("diameter/src/app/diameter_gen_base_rfc3588.hrl"). +-include_lib("diameter/include/diameter_gen_base_rfc3588.hrl"). -export([start/1, %% start a service connect/2, %% add a connecting transport @@ -112,7 +112,7 @@ cast(Name) -> {'Auth-Application-Id', 0}, {'Re-Auth-Request-Type', 1}], diameter:call(Name, ?APP_ALIAS, RAR, [detach]). - + cast() -> cast(?SVC_NAME). diff --git a/lib/diameter/examples/client_cb.erl b/lib/diameter/examples/code/client_cb.erl index 524a8f94a1..ee3dcb2fec 100644 --- a/lib/diameter/examples/client_cb.erl +++ b/lib/diameter/examples/code/client_cb.erl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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 @@ -module(client_cb). -include_lib("diameter/include/diameter.hrl"). --include_lib("diameter/src/app/diameter_gen_base_rfc3588.hrl"). +-include_lib("diameter/include/diameter_gen_base_rfc3588.hrl"). %% diameter callbacks -export([peer_up/3, diff --git a/lib/diameter/examples/peer.erl b/lib/diameter/examples/code/peer.erl index 89203e15c3..8fdeba57bf 100644 --- a/lib/diameter/examples/peer.erl +++ b/lib/diameter/examples/code/peer.erl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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,7 +25,7 @@ -module(peer). -include_lib("diameter/include/diameter.hrl"). --include_lib("diameter/src/app/diameter_gen_base_rfc3588.hrl"). +-include_lib("diameter/include/diameter_gen_base_rfc3588.hrl"). -export([start/2, listen/2, @@ -117,6 +117,11 @@ server(T) -> %% %% 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, [{ip, addr(LA)}, diff --git a/lib/diameter/examples/redirect.erl b/lib/diameter/examples/code/redirect.erl index b54701243f..d4d94ab23a 100644 --- a/lib/diameter/examples/redirect.erl +++ b/lib/diameter/examples/code/redirect.erl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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 @@ -module(redirect). -include_lib("diameter/include/diameter.hrl"). --include_lib("diameter/src/app/diameter_gen_base_rfc3588.hrl"). +-include_lib("diameter/include/diameter_gen_base_rfc3588.hrl"). -export([start/1, listen/2, diff --git a/lib/diameter/examples/redirect_cb.erl b/lib/diameter/examples/code/redirect_cb.erl index ea7ad38749..da31add70d 100644 --- a/lib/diameter/examples/redirect_cb.erl +++ b/lib/diameter/examples/code/redirect_cb.erl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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/relay.erl b/lib/diameter/examples/code/relay.erl index deecb1cfc0..d3438f83f3 100644 --- a/lib/diameter/examples/relay.erl +++ b/lib/diameter/examples/code/relay.erl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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,7 +32,7 @@ -module(relay). -include_lib("diameter/include/diameter.hrl"). --include_lib("diameter/src/app/diameter_gen_base_rfc3588.hrl"). +-include_lib("diameter/include/diameter_gen_base_rfc3588.hrl"). -export([start/1, listen/2, diff --git a/lib/diameter/examples/relay_cb.erl b/lib/diameter/examples/code/relay_cb.erl index 9ed6517d5c..9f9cd8d5ae 100644 --- a/lib/diameter/examples/relay_cb.erl +++ b/lib/diameter/examples/code/relay_cb.erl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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 @@ -module(relay_cb). -include_lib("diameter/include/diameter.hrl"). --include_lib("diameter/src/app/diameter_gen_base_rfc3588.hrl"). +-include_lib("diameter/include/diameter_gen_base_rfc3588.hrl"). %% diameter callbacks -export([peer_up/3, diff --git a/lib/diameter/examples/sctp.erl b/lib/diameter/examples/code/sctp.erl index 2e0e9d8b0b..08de023571 100644 --- a/lib/diameter/examples/sctp.erl +++ b/lib/diameter/examples/code/sctp.erl @@ -1,3 +1,21 @@ +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2010-2011. 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% +%% -module(sctp). diff --git a/lib/diameter/examples/server.erl b/lib/diameter/examples/code/server.erl index ebb408e501..3959461cec 100644 --- a/lib/diameter/examples/server.erl +++ b/lib/diameter/examples/code/server.erl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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,7 +35,7 @@ -module(server). -include_lib("diameter/include/diameter.hrl"). --include_lib("diameter/src/app/diameter_gen_base_rfc3588.hrl"). +-include_lib("diameter/include/diameter_gen_base_rfc3588.hrl"). -export([start/1, %% start a service listen/2, %% add a listening transport diff --git a/lib/diameter/examples/server_cb.erl b/lib/diameter/examples/code/server_cb.erl index 43b8e24b5c..0f6eb32ed6 100644 --- a/lib/diameter/examples/server_cb.erl +++ b/lib/diameter/examples/code/server_cb.erl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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/src/app/diameter_gen_base_rfc3588.hrl"). +-include_lib("diameter/include/diameter_gen_base_rfc3588.hrl"). %% diameter callbacks -export([peer_up/3, @@ -76,7 +76,7 @@ handle_request(#diameter_packet{msg = Req, errors = []}, _SvcName, {_, Caps}) %% ... or one that wasn't. 3xxx errors are answered by diameter itself %% but these are 5xxx errors for which we must contruct a reply. %% diameter will set Result-Code and Failed-AVP's. -handle_request(#diameter_packet{msg = Req} = Pkt, _SvcName, {_, Caps}) +handle_request(#diameter_packet{msg = Req}, _SvcName, {_, Caps}) when is_record(Req, diameter_base_RAR) -> #diameter_caps{origin_host = {OH,_}, origin_realm = {OR,_}} diff --git a/lib/diameter/examples/dict/rfc4004_mip.dia b/lib/diameter/examples/dict/rfc4004_mip.dia new file mode 100644 index 0000000000..575ad4394a --- /dev/null +++ b/lib/diameter/examples/dict/rfc4004_mip.dia @@ -0,0 +1,280 @@ +;; +;; %CopyrightBegin% +;; +;; Copyright Ericsson AB 2010-2011. 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% +;; + +;; +;; RFC 4004, Diameter Mobile IPv4 Application +;; +;; Edits: +;; +;; - MIP-nonce -> MIP-Nonce +;; - Session-ID -> Session-Id +;; - Omit MIP-HA-to-MN-SPI, MIP-MN-FA-SPI and MIP-MN-HA-SPI, none of +;; which are defined. +;; + +@id 2 + +@inherits rfc3588_base + +;; =========================================================================== + +@avp_types + + MIP-Reg-Request 320 OctetString M + MIP-Reg-Reply 321 OctetString M + MIP-MN-AAA-Auth 322 Grouped M + MIP-Mobile-Node-Address 333 Address M + MIP-Home-Agent-Address 334 Address M + MIP-Candidate-Home-Agent-Host 336 DiamIdent M + MIP-Feature-Vector 337 Unsigned32 M + MIP-Auth-Input-Data-Length 338 Unsigned32 M + MIP-Authenticator-Length 339 Unsigned32 M + MIP-Authenticator-Offset 340 Unsigned32 M + MIP-MN-AAA-SPI 341 Unsigned32 M + MIP-Filter-Rule 342 IPFilterRule M + MIP-FA-Challenge 344 OctetString M + MIP-Originating-Foreign-AAA 347 Grouped M + MIP-Home-Agent-Host 348 Grouped M + + MIP-FA-to-HA-SPI 318 Unsigned32 M + MIP-FA-to-MN-SPI 319 Unsigned32 M + MIP-HA-to-FA-SPI 323 Unsigned32 M + MIP-MN-to-FA-MSA 325 Grouped M + MIP-FA-to-MN-MSA 326 Grouped M + MIP-FA-to-HA-MSA 328 Grouped M + MIP-HA-to-FA-MSA 329 Grouped M + MIP-MN-to-HA-MSA 331 Grouped M + MIP-HA-to-MN-MSA 332 Grouped M + MIP-Nonce 335 OctetString M + MIP-Session-Key 343 OctetString M + MIP-Algorithm-Type 345 Enumerated M + MIP-Replay-Mode 346 Enumerated M + MIP-MSA-Lifetime 367 Unsigned32 M + +;; =========================================================================== + +@messages + + ;; 5.1. AA-Mobile-Node-Request + + AMR ::= < Diameter Header: 260, REQ, PXY > + + < Session-Id > + { Auth-Application-Id } + { User-Name } + { Destination-Realm } + { Origin-Host } + { Origin-Realm } + { MIP-Reg-Request } + { MIP-MN-AAA-Auth } + [ Acct-Multi-Session-Id ] + [ Destination-Host ] + [ Origin-State-Id ] + [ MIP-Mobile-Node-Address ] + [ MIP-Home-Agent-Address ] + [ MIP-Feature-Vector ] + [ MIP-Originating-Foreign-AAA ] + [ Authorization-Lifetime ] + [ Auth-Session-State ] + [ MIP-FA-Challenge ] + [ MIP-Candidate-Home-Agent-Host ] + [ MIP-Home-Agent-Host ] + [ MIP-HA-to-FA-SPI ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + ;; 5.2. AA-Mobile-Node-Answer + + AMA ::= < Diameter Header: 260, PXY > + + < Session-Id > + { Auth-Application-Id } + { Result-Code } + { Origin-Host } + { Origin-Realm } + [ Acct-Multi-Session-Id ] + [ User-Name ] + [ Authorization-Lifetime ] + [ Auth-Session-State ] + [ Error-Message ] + [ Error-Reporting-Host ] + [ Re-Auth-Request-Type ] + [ MIP-Feature-Vector ] + [ MIP-Reg-Reply ] + [ MIP-MN-to-FA-MSA ] + [ MIP-MN-to-HA-MSA ] + [ MIP-FA-to-MN-MSA ] + [ MIP-FA-to-HA-MSA ] + [ MIP-HA-to-MN-MSA ] + [ MIP-MSA-Lifetime ] + [ MIP-Home-Agent-Address ] + [ MIP-Mobile-Node-Address ] + * [ MIP-Filter-Rule ] + [ Origin-State-Id ] + * [ Proxy-Info ] + * [ AVP ] + + ;; 5.3. Home-Agent-MIP-Request + + HAR ::= < Diameter Header: 262, REQ, PXY > + + < Session-Id > + { Auth-Application-Id } + { Authorization-Lifetime } + { Auth-Session-State } + { MIP-Reg-Request } + { Origin-Host } + { Origin-Realm } + { User-Name } + { Destination-Realm } + { MIP-Feature-Vector } + [ Destination-Host ] + [ MIP-MN-to-HA-MSA ] + [ MIP-MN-to-FA-MSA ] + [ MIP-HA-to-MN-MSA ] + [ MIP-HA-to-FA-MSA ] + [ MIP-MSA-Lifetime ] + [ MIP-Originating-Foreign-AAA ] + [ MIP-Mobile-Node-Address ] + [ MIP-Home-Agent-Address ] + * [ MIP-Filter-Rule ] + [ Origin-State-Id ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + ;; 5.4. Home-Agent-MIP-Answer + + HAA ::= < Diameter Header: 262, PXY > + + < Session-Id > + { Auth-Application-Id } + { Result-Code } + { Origin-Host } + { Origin-Realm } + [ Acct-Multi-Session-Id ] + [ User-Name ] + [ Error-Reporting-Host ] + [ Error-Message ] + [ MIP-Reg-Reply ] + [ MIP-Home-Agent-Address ] + [ MIP-Mobile-Node-Address ] + [ MIP-FA-to-HA-SPI ] + [ MIP-FA-to-MN-SPI ] + [ Origin-State-Id ] + * [ Proxy-Info ] + * [ AVP ] + +;; =========================================================================== + +@grouped + + MIP-MN-AAA-Auth ::= < AVP Header: 322 > + + { MIP-MN-AAA-SPI } + { MIP-Auth-Input-Data-Length } + { MIP-Authenticator-Length } + { MIP-Authenticator-Offset } + * [ AVP ] + + + MIP-Originating-Foreign-AAA ::= < AVP Header: 347 > + + { Origin-Realm } + { Origin-Host } + * [ AVP ] + + MIP-Home-Agent-Host ::= < AVP Header: 348 > + + { Destination-Realm } + { Destination-Host } + * [ AVP ] + + MIP-FA-to-MN-MSA ::= < AVP Header: 326 > + + { MIP-FA-to-MN-SPI } + { MIP-Algorithm-Type } + { MIP-Session-Key } + * [ AVP ] + + MIP-FA-to-HA-MSA ::= < AVP Header: 328 > + + { MIP-FA-to-HA-SPI } + { MIP-Algorithm-Type } + { MIP-Session-Key } + * [ AVP ] + + MIP-HA-to-FA-MSA ::= < AVP Header: 329 > + + { MIP-HA-to-FA-SPI } + { MIP-Algorithm-Type } + { MIP-Session-Key } + * [ AVP ] + + MIP-HA-to-MN-MSA ::= < AVP Header: 332 > + + ; { MIP-HA-to-MN-SPI } + { MIP-Algorithm-Type } + { MIP-Replay-Mode } + { MIP-Session-Key } + * [ AVP ] + + MIP-MN-to-FA-MSA ::= < AVP Header: 325 > + + ; { MIP-MN-FA-SPI } + { MIP-Algorithm-Type } + { MIP-Nonce } + * [ AVP ] + + MIP-MN-to-HA-MSA ::= < AVP Header: 331 > + + ; { MIP-MN-HA-SPI } + { MIP-Algorithm-Type } + { MIP-Replay-Mode } + { MIP-Nonce } + * [ AVP ] + +;; =========================================================================== + +@enum MIP-Algorithm-Type + + HMAC-SHA-1 2 + +@enum MIP-Replay-Mode + + NONE 1 + TIMESTAMPS 2 + NONCES 3 + +;; =========================================================================== + +@define Result-Code + + ;; 6.1. Transient Failures + + MIP_REPLY_FAILURE 4005 + HA_NOT_AVAILABLE 4006 + BAD_KEY 4007 + MIP_FILTER_NOT_SUPPORTED 4008 + + ;; 6.2. Permanent Failures + + NO_FOREIGN_HA_SERVICE 5024 + END_TO_END_MIP_KEY_ENCRYPTION 5025 diff --git a/lib/diameter/examples/dict/rfc4005_nas.dia b/lib/diameter/examples/dict/rfc4005_nas.dia new file mode 100644 index 0000000000..a4b44e38bb --- /dev/null +++ b/lib/diameter/examples/dict/rfc4005_nas.dia @@ -0,0 +1,740 @@ +;; +;; %CopyrightBegin% +;; +;; Copyright Ericsson AB 2010-2011. 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% +;; + +;; +;; RFC 4005, Diameter Network Access Server Application +;; +;; Edits: +;; +;; - Acounting-Auth-Method -> Accounting-Auth-Method +;; - Connection-Info -> ConnectInfo +;; - Framed-Appletalk-Link -> Framed-AppleTalk-Link +;; - Framed-Appletalk-Network -> Framed-AppleTalk-Network +;; - Framed-Appletalk-Zone -> Framed-AppleTalk-Zone +;; - Qos-Filter-Rule -> QoS-Filter-Rule +;; - Redirect-Host-Usase -> Redirect-Host-Usage +;; - Redirected-Host -> Redirect-Host +;; - Redirected-Host-Usage -> Redirect-Host-Usage +;; - Redirected-Host-Cache-Time -> Redirect-Max-Cache-Time +;; - Redirected-Max-Cache-Time -> Redirect-Max-Cache-Time +;; + +@id 1 + +@inherits rfc3588_base + +;; =========================================================================== + +@avp_types + + ;; 4. NAS Session AVPs + + NAS-Port 5 Unsigned32 M + NAS-Port-Id 87 UTF8String M + NAS-Port-Type 61 Enumerated M + Called-Station-Id 30 UTF8String M + Calling-Station-Id 31 UTF8String M + Connect-Info 77 UTF8String M + Originating-Line-Info 94 OctetString - + Reply-Message 18 UTF8String M + + ;; 5. NAS Authentication AVPs + + User-Password 2 OctetString M + Password-Retry 75 Unsigned32 M + Prompt 76 Enumerated M + CHAP-Auth 402 Grouped M + CHAP-Algorithm 403 Enumerated M + CHAP-Ident 404 OctetString M + CHAP-Response 405 OctetString M + CHAP-Challenge 60 OctetString M + ARAP-Password 70 OctetString M + ARAP-Challenge-Response 84 OctetString M + ARAP-Security 73 Unsigned32 M + ARAP-Security-Data 74 OctetString M + + ;; 6. NAS Authorization AVPs + + Service-Type 6 Enumerated M + Callback-Number 19 UTF8String M + Callback-Id 20 UTF8String M + Idle-Timeout 28 Unsigned32 M + Port-Limit 62 Unsigned32 M + NAS-Filter-Rule 400 IPFilterRule M + Filter-Id 11 UTF8String M + Configuration-Token 78 OctetString M + QoS-Filter-Rule 407 QoSFilterRule - + Framed-Protocol 7 Enumerated M + Framed-Routing 10 Enumerated M + Framed-MTU 12 Unsigned32 M + Framed-Compression 13 Enumerated M + Framed-IP-Address 8 OctetString M + Framed-IP-Netmask 9 OctetString M + Framed-Route 22 UTF8String M + Framed-Pool 88 OctetString M + Framed-Interface-Id 96 Unsigned64 M + Framed-IPv6-Prefix 97 OctetString M + Framed-IPv6-Route 99 UTF8String M + Framed-IPv6-Pool 100 OctetString M + Framed-IPX-Network 23 UTF8String M + Framed-AppleTalk-Link 37 Unsigned32 M + Framed-AppleTalk-Network 38 Unsigned32 M + Framed-AppleTalk-Zone 39 OctetString M + ARAP-Features 71 OctetString M + ARAP-Zone-Access 72 Enumerated M + Login-IP-Host 14 OctetString M + Login-IPv6-Host 98 OctetString M + Login-Service 15 Enumerated M + Login-TCP-Port 16 Unsigned32 M + Login-LAT-Service 34 OctetString M + Login-LAT-Node 35 OctetString M + Login-LAT-Group 36 OctetString M + Login-LAT-Port 63 OctetString M + + ;; 7. NAS Tunneling + + Tunneling 401 Grouped M + Tunnel-Type 64 Enumerated M + Tunnel-Medium-Type 65 Enumerated M + Tunnel-Client-Endpoint 66 UTF8String M + Tunnel-Server-Endpoint 67 UTF8String M + Tunnel-Password 69 OctetString M + Tunnel-Private-Group-Id 81 OctetString M + Tunnel-Assignment-Id 82 OctetString M + Tunnel-Preference 83 Unsigned32 M + Tunnel-Client-Auth-Id 90 UTF8String M + Tunnel-Server-Auth-Id 91 UTF8String M + + ;; 8. NAS Accounting + + Accounting-Input-Octets 363 Unsigned64 M + Accounting-Output-Octets 364 Unsigned64 M + Accounting-Input-Packets 365 Unsigned64 M + Accounting-Output-Packets 366 Unsigned64 M + Acct-Session-Time 46 Unsigned32 M + Acct-Authentic 45 Enumerated M + Accounting-Auth-Method 406 Enumerated M + Acct-Delay-Time 41 Unsigned32 M + Acct-Link-Count 51 Unsigned32 M + Acct-Tunnel-Connection 68 OctetString M + Acct-Tunnel-Packets-Lost 86 Unsigned32 M + + ;; 9.3. AVPs Used Only for Compatibility + + NAS-Identifier 32 UTF8String M + NAS-IP-Address 4 OctetString M + NAS-IPv6-Address 95 OctetString M + State 24 OctetString M + ;;Termination-Cause 295 Enumerated M + Origin-AAA-Protocol 408 Enumerated M + +;; =========================================================================== + +@messages + + AAR ::= < Diameter Header: 265, REQ, PXY > + + < Session-Id > + { Auth-Application-Id } + { Origin-Host } + { Origin-Realm } + { Destination-Realm } + { Auth-Request-Type } + [ Destination-Host ] + [ NAS-Identifier ] + [ NAS-IP-Address ] + [ NAS-IPv6-Address ] + [ NAS-Port ] + [ NAS-Port-Id ] + [ NAS-Port-Type ] + [ Origin-AAA-Protocol ] + [ Origin-State-Id ] + [ Port-Limit ] + [ User-Name ] + [ User-Password ] + [ Service-Type ] + [ State ] + [ Authorization-Lifetime ] + [ Auth-Grace-Period ] + [ Auth-Session-State ] + [ Callback-Number ] + [ Called-Station-Id ] + [ Calling-Station-Id ] + [ Originating-Line-Info ] + [ Connect-Info ] + [ CHAP-Auth ] + [ CHAP-Challenge ] + * [ Framed-Compression ] + [ Framed-Interface-Id ] + [ Framed-IP-Address ] + * [ Framed-IPv6-Prefix ] + [ Framed-IP-Netmask ] + [ Framed-MTU ] + [ Framed-Protocol ] + [ ARAP-Password ] + [ ARAP-Security ] + * [ ARAP-Security-Data ] + * [ Login-IP-Host ] + * [ Login-IPv6-Host ] + [ Login-LAT-Group ] + [ Login-LAT-Node ] + [ Login-LAT-Port ] + [ Login-LAT-Service ] + * [ Tunneling ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + AAA ::= < Diameter Header: 265, PXY > + + < Session-Id > + { Auth-Application-Id } + { Auth-Request-Type } + { Result-Code } + { Origin-Host } + { Origin-Realm } + [ User-Name ] + [ Service-Type ] + * [ Class ] + * [ Configuration-Token ] + [ Acct-Interim-Interval ] + [ Error-Message ] + [ Error-Reporting-Host ] + * [ Failed-AVP ] + [ Idle-Timeout ] + [ Authorization-Lifetime ] + [ Auth-Grace-Period ] + [ Auth-Session-State ] + [ Re-Auth-Request-Type ] + [ Multi-Round-Time-Out ] + [ Session-Timeout ] + [ State ] + * [ Reply-Message ] + [ Origin-AAA-Protocol ] + [ Origin-State-Id ] + * [ Filter-Id ] + [ Password-Retry ] + [ Port-Limit ] + [ Prompt ] + [ ARAP-Challenge-Response ] + [ ARAP-Features ] + [ ARAP-Security ] + * [ ARAP-Security-Data ] + [ ARAP-Zone-Access ] + [ Callback-Id ] + [ Callback-Number ] + [ Framed-AppleTalk-Link ] + * [ Framed-AppleTalk-Network ] + [ Framed-AppleTalk-Zone ] + * [ Framed-Compression ] + [ Framed-Interface-Id ] + [ Framed-IP-Address ] + * [ Framed-IPv6-Prefix ] + [ Framed-IPv6-Pool ] + * [ Framed-IPv6-Route ] + [ Framed-IP-Netmask ] + * [ Framed-Route ] + [ Framed-Pool ] + [ Framed-IPX-Network ] + [ Framed-MTU ] + [ Framed-Protocol ] + [ Framed-Routing ] + * [ Login-IP-Host ] + * [ Login-IPv6-Host ] + [ Login-LAT-Group ] + [ Login-LAT-Node ] + [ Login-LAT-Port ] + [ Login-LAT-Service ] + [ Login-Service ] + [ Login-TCP-Port ] + * [ NAS-Filter-Rule ] + * [ QoS-Filter-Rule ] + * [ Tunneling ] + * [ Redirect-Host ] + [ Redirect-Host-Usage ] + [ Redirect-Max-Cache-Time ] + * [ Proxy-Info ] + * [ AVP ] + + RAR ::= < Diameter Header: 258, REQ, PXY > + + < Session-Id > + { Origin-Host } + { Origin-Realm } + { Destination-Realm } + { Destination-Host } + { Auth-Application-Id } + { Re-Auth-Request-Type } + [ User-Name ] + [ Origin-AAA-Protocol ] + [ Origin-State-Id ] + [ NAS-Identifier ] + [ NAS-IP-Address ] + [ NAS-IPv6-Address ] + [ NAS-Port ] + [ NAS-Port-Id ] + [ NAS-Port-Type ] + [ Service-Type ] + [ Framed-IP-Address ] + [ Framed-IPv6-Prefix ] + [ Framed-Interface-Id ] + [ Called-Station-Id ] + [ Calling-Station-Id ] + [ Originating-Line-Info ] + [ Acct-Session-Id ] + [ Acct-Multi-Session-Id ] + [ State ] + * [ Class ] + [ Reply-Message ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + RAA ::= < Diameter Header: 258, PXY > + + < Session-Id > + { Result-Code } + { Origin-Host } + { Origin-Realm } + [ User-Name ] + [ Origin-AAA-Protocol ] + [ Origin-State-Id ] + [ Error-Message ] + [ Error-Reporting-Host ] + * [ Failed-AVP ] + * [ Redirect-Host ] + [ Redirect-Host-Usage ] + [ Redirect-Max-Cache-Time ] + [ Service-Type ] + * [ Configuration-Token ] + [ Idle-Timeout ] + [ Authorization-Lifetime ] + [ Auth-Grace-Period ] + [ Re-Auth-Request-Type ] + [ State ] + * [ Class ] + * [ Reply-Message ] + [ Prompt ] + * [ Proxy-Info ] + * [ AVP ] + + STR ::= < Diameter Header: 275, REQ, PXY > + + < Session-Id > + { Origin-Host } + { Origin-Realm } + { Destination-Realm } + { Auth-Application-Id } + { Termination-Cause } + [ User-Name ] + [ Destination-Host ] + * [ Class ] + [ Origin-AAA-Protocol ] + [ Origin-State-Id ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + STA ::= < Diameter Header: 275, PXY > + + < Session-Id > + { Result-Code } + { Origin-Host } + { Origin-Realm } + [ User-Name ] + * [ Class ] + [ Error-Message ] + [ Error-Reporting-Host ] + * [ Failed-AVP ] + [ Origin-AAA-Protocol ] + [ Origin-State-Id ] + * [ Redirect-Host ] + [ Redirect-Host-Usage ] + [ Redirect-Max-Cache-Time ] + * [ Proxy-Info ] + * [ AVP ] + + ASR ::= < Diameter Header: 274, REQ, PXY > + + < Session-Id > + { Origin-Host } + { Origin-Realm } + { Destination-Realm } + { Destination-Host } + { Auth-Application-Id } + [ User-Name ] + [ Origin-AAA-Protocol ] + [ Origin-State-Id ] + [ NAS-Identifier ] + [ NAS-IP-Address ] + [ NAS-IPv6-Address ] + [ NAS-Port ] + [ NAS-Port-Id ] + [ NAS-Port-Type ] + [ Service-Type ] + [ Framed-IP-Address ] + [ Framed-IPv6-Prefix ] + [ Framed-Interface-Id ] + [ Called-Station-Id ] + [ Calling-Station-Id ] + [ Originating-Line-Info ] + [ Acct-Session-Id ] + [ Acct-Multi-Session-Id ] + [ State ] + * [ Class ] + * [ Reply-Message ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + ASA ::= < Diameter Header: 274, PXY > + + < Session-Id > + { Result-Code } + { Origin-Host } + { Origin-Realm } + [ User-Name ] + [ Origin-AAA-Protocol ] + [ Origin-State-Id ] + [ State] + [ Error-Message ] + [ Error-Reporting-Host ] + * [ Failed-AVP ] + * [ Redirect-Host ] + [ Redirect-Host-Usage ] + [ Redirect-Max-Cache-Time ] + * [ Proxy-Info ] + * [ AVP ] + + ACR ::= < Diameter Header: 271, REQ, PXY > + + < Session-Id > + { Origin-Host } + { Origin-Realm } + { Destination-Realm } + { Accounting-Record-Type } + { Accounting-Record-Number } + [ Acct-Application-Id ] + [ Vendor-Specific-Application-Id ] + [ User-Name ] + [ Accounting-Sub-Session-Id ] + [ Acct-Session-Id ] + [ Acct-Multi-Session-Id ] + [ Origin-AAA-Protocol ] + [ Origin-State-Id ] + [ Destination-Host ] + [ Event-Timestamp ] + [ Acct-Delay-Time ] + [ NAS-Identifier ] + [ NAS-IP-Address ] + [ NAS-IPv6-Address ] + [ NAS-Port ] + [ NAS-Port-Id ] + [ NAS-Port-Type ] + * [ Class ] + [ Service-Type ] + [ Termination-Cause ] + [ Accounting-Input-Octets ] + [ Accounting-Input-Packets ] + [ Accounting-Output-Octets ] + [ Accounting-Output-Packets ] + [ Acct-Authentic ] + [ Accounting-Auth-Method ] + [ Acct-Link-Count ] + [ Acct-Session-Time ] + [ Acct-Tunnel-Connection ] + [ Acct-Tunnel-Packets-Lost ] + [ Callback-Id ] + [ Callback-Number ] + [ Called-Station-Id ] + [ Calling-Station-Id ] + * [ Connect-Info ] + [ Originating-Line-Info ] + [ Authorization-Lifetime ] + [ Session-Timeout ] + [ Idle-Timeout ] + [ Port-Limit ] + [ Accounting-Realtime-Required ] + [ Acct-Interim-Interval ] + * [ Filter-Id ] + * [ NAS-Filter-Rule ] + * [ QoS-Filter-Rule ] + [ Framed-AppleTalk-Link ] + [ Framed-AppleTalk-Network ] + [ Framed-AppleTalk-Zone ] + [ Framed-Compression ] + [ Framed-Interface-Id ] + [ Framed-IP-Address ] + [ Framed-IP-Netmask ] + * [ Framed-IPv6-Prefix ] + [ Framed-IPv6-Pool ] + * [ Framed-IPv6-Route ] + [ Framed-IPX-Network ] + [ Framed-MTU ] + [ Framed-Pool ] + [ Framed-Protocol ] + * [ Framed-Route ] + [ Framed-Routing ] + * [ Login-IP-Host ] + * [ Login-IPv6-Host ] + [ Login-LAT-Group ] + [ Login-LAT-Node ] + [ Login-LAT-Port ] + [ Login-LAT-Service ] + [ Login-Service ] + [ Login-TCP-Port ] + * [ Tunneling ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + ACA ::= < Diameter Header: 271, PXY > + + < Session-Id > + { Result-Code } + { Origin-Host } + { Origin-Realm } + { Accounting-Record-Type } + { Accounting-Record-Number } + [ Acct-Application-Id ] + [ Vendor-Specific-Application-Id ] + [ User-Name ] + [ Accounting-Sub-Session-Id ] + [ Acct-Session-Id ] + [ Acct-Multi-Session-Id ] + [ Event-Timestamp ] + [ Error-Message ] + [ Error-Reporting-Host ] + * [ Failed-AVP ] + [ Origin-AAA-Protocol ] + [ Origin-State-Id ] + [ NAS-Identifier ] + [ NAS-IP-Address ] + [ NAS-IPv6-Address ] + [ NAS-Port ] + [ NAS-Port-Id ] + [ NAS-Port-Type ] + [ Service-Type ] + [ Termination-Cause ] + [ Accounting-Realtime-Required ] + [ Acct-Interim-Interval ] + * [ Class ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + +;; =========================================================================== + +@grouped + + CHAP-Auth ::= < AVP Header: 402 > + + { CHAP-Algorithm } + { CHAP-Ident } + [ CHAP-Response ] + * [ AVP ] + + Tunneling ::= < AVP Header: 401 > + + { Tunnel-Type } + { Tunnel-Medium-Type } + { Tunnel-Client-Endpoint } + { Tunnel-Server-Endpoint } + [ Tunnel-Preference ] + [ Tunnel-Client-Auth-Id ] + [ Tunnel-Server-Auth-Id ] + [ Tunnel-Assignment-Id ] + [ Tunnel-Password ] + [ Tunnel-Private-Group-Id ] + +;; =========================================================================== + +@enum NAS-Port-Type + + ASYNC 0 + SYNC 1 + ISDN_SYNC 2 + ISDN_ASYNC_V120 3 + ISDN_ASYNC_V110 4 + VIRTUAL 5 + PIAFS 6 + HDLC_CLEAR_CHANNEL 7 + X25 8 + X75 9 + G3FAX 10 + SDSL 11 + ADSL-CAP 12 + ADSL-DMT 13 + IDSL 14 + ETHERNET 15 + XDSL 16 + CABLE 17 + WIRELESS_OTHER 18 + 'WIRELESS_802.11' 19 + TOKEN-RING 20 + FDDI 21 + WIRELESS_CDMA2000 22 + WIRELESS_UMTS 23 + WIRELESS_1X-EV 24 + IAPP 25 + +@enum Prompt + + NO_ECHO 0 + ECHO 1 + +@enum CHAP-Algorithm + + WITH_MD5 5 + +@enum Service-Type + + LOGIN 1 + FRAMED 2 + CALLBACK_LOGIN 3 + CALLBACK_FRAMED 4 + OUTBOUND 5 + ADMINISTRATIVE 6 + NAS_PROMPT 7 + AUTHENTICATE_ONLY 8 + CALLBACK_NAS_PROMPT 9 + CALL_CHECK 10 + CALLBACK_ADMINISTRATIVE 11 + VOICE 12 + FAX 13 + MODEM_RELAY 14 + IAPP-REGISTER 15 + IAPP-AP-CHECK 16 + AUTHORIZE_ONLY 17 + +@enum Framed-Protocol + + PPP 1 + SLIP 2 + ARAP 3 + GANDALF 4 + XYLOGICS 5 + X75 6 + +@enum Framed-Routing + + NONE 0 + SEND 1 + LISTEN 2 + SEND_AND_LISTEN 3 + +@enum Framed-Compression + + NONE 0 + VJ 1 + IPX 2 + STAC-LZS 3 + +@enum ARAP-Zone-Access + + DEFAULT 1 + FILTER_INCLUSIVELY 2 + FILTER_EXCLUSIVELY 4 + +@enum Login-Service + + TELNET 0 + RLOGIN 1 + TCP_CLEAR 2 + PORTMASTER 3 + LAT 4 + X25-PAD 5 + X25-T3POS 6 + TCP_CLEAR_QUIET 8 + +@enum Tunnel-Type + + PPTP 1 + L2F 2 + L2TP 3 + ATMP 4 + VTP 5 + AH 6 + IP-IP 7 + MIN-IP-IP 8 + ESP 9 + GRE 10 + DVS 11 + IP-IN-IP 12 + VLAN 13 + +@enum Tunnel-Medium-Type + + IPV4 1 + IPV6 2 + NSAP 3 + HDLC 4 + BBN_1822 5 + '802' 6 + E163 7 + E164 8 + F69 9 + X121 10 + IPX 11 + APPLETALK 12 + DECNET_IV 13 + BANYAN_VINES 14 + E164_NSAP 15 + + +@enum Acct-Authentic + + RADIUS 1 + LOCAL 2 + REMOTE 3 + DIAMETER 4 + +@enum Accounting-Auth-Method + + PAP 1 + CHAP 2 + MS-CHAP-1 3 + MS-CHAP-2 4 + EAP 5 + NONE 7 + +@enum Termination-Cause + + USER_REQUEST 11 + LOST_CARRIER 12 + LOST_SERVICE 13 + IDLE_TIMEOUT 14 + SESSION_TIMEOUT 15 + ADMIN_RESET 16 + ADMIN_REBOOT 17 + PORT_ERROR 18 + NAS_ERROR 19 + NAS_REQUEST 20 + NAS_REBOOT 21 + PORT_UNNEEDED 22 + PORT_PREEMPTED 23 + PORT_SUSPENDED 24 + SERVICE_UNAVAILABLE 25 + CALLBACK 26 + USER_ERROR 27 + HOST_REQUEST 28 + SUPPLICANT_RESTART 29 + REAUTHORIZATION_FAILURE 30 + PORT_REINIT 31 + PORT_DISABLED 32 diff --git a/lib/diameter/examples/dict/rfc4006_cc.dia b/lib/diameter/examples/dict/rfc4006_cc.dia new file mode 100644 index 0000000000..b723e4ddbb --- /dev/null +++ b/lib/diameter/examples/dict/rfc4006_cc.dia @@ -0,0 +1,349 @@ +;; +;; %CopyrightBegin% +;; +;; Copyright Ericsson AB 2010-2011. 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% +;; + +;; +;; RFC 4006, Diameter Credit-Control Application +;; + +@id 4 + +@inherits rfc3588_base +@inherits rfc4005_nas Filter-Id + +;; =========================================================================== + +@avp_types + + CC-Correlation-Id 411 OctetString - + CC-Input-Octets 412 Unsigned64 M + CC-Money 413 Grouped M + CC-Output-Octets 414 Unsigned64 M + CC-Request-Number 415 Unsigned32 M + CC-Request-Type 416 Enumerated M + CC-Service-Specific-Units 417 Unsigned64 M + CC-Session-Failover 418 Enumerated M + CC-Sub-Session-Id 419 Unsigned64 M + CC-Time 420 Unsigned32 M + CC-Total-Octets 421 Unsigned64 M + CC-Unit-Type 454 Enumerated M + Check-Balance-Result 422 Enumerated M + Cost-Information 423 Grouped M + Cost-Unit 424 UTF8String M + Credit-Control 426 Enumerated M + Credit-Control-Failure-Handling 427 Enumerated M + Currency-Code 425 Unsigned32 M + Direct-Debiting-Failure-Handling 428 Enumerated M + Exponent 429 Integer32 M + Final-Unit-Action 449 Enumerated M + Final-Unit-Indication 430 Grouped M + Granted-Service-Unit 431 Grouped M + G-S-U-Pool-Identifier 453 Unsigned32 M + G-S-U-Pool-Reference 457 Grouped M + Multiple-Services-Credit-Control 456 Grouped M + Multiple-Services-Indicator 455 Enumerated M + Rating-Group 432 Unsigned32 M + Redirect-Address-Type 433 Enumerated M + Redirect-Server 434 Grouped M + Redirect-Server-Address 435 UTF8String M + Requested-Action 436 Enumerated M + Requested-Service-Unit 437 Grouped M + Restriction-Filter-Rule 438 IPFilterRule M + Service-Context-Id 461 UTF8String M + Service-Identifier 439 Unsigned32 M + Service-Parameter-Info 440 Grouped - + Service-Parameter-Type 441 Unsigned32 - + Service-Parameter-Value 442 OctetString - + Subscription-Id 443 Grouped M + Subscription-Id-Data 444 UTF8String M + Subscription-Id-Type 450 Enumerated M + Tariff-Change-Usage 452 Enumerated M + Tariff-Time-Change 451 Time M + Unit-Value 445 Grouped M + Used-Service-Unit 446 Grouped M + User-Equipment-Info 458 Grouped - + User-Equipment-Info-Type 459 Enumerated - + User-Equipment-Info-Value 460 OctetString - + Value-Digits 447 Integer64 M + Validity-Time 448 Unsigned32 M + +;; =========================================================================== + +@messages + + CCR ::= < Diameter Header: 272, REQ, PXY > + + < Session-Id > + { Origin-Host } + { Origin-Realm } + { Destination-Realm } + { Auth-Application-Id } + { Service-Context-Id } + { CC-Request-Type } + { CC-Request-Number } + [ Destination-Host ] + [ User-Name ] + [ CC-Sub-Session-Id ] + [ Acct-Multi-Session-Id ] + [ Origin-State-Id ] + [ Event-Timestamp ] + * [ Subscription-Id ] + [ Service-Identifier ] + [ Termination-Cause ] + [ Requested-Service-Unit ] + [ Requested-Action ] + * [ Used-Service-Unit ] + [ Multiple-Services-Indicator ] + * [ Multiple-Services-Credit-Control ] + * [ Service-Parameter-Info ] + [ CC-Correlation-Id ] + [ User-Equipment-Info ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + CCA ::= < Diameter Header: 272, PXY > + + < Session-Id > + { Result-Code } + { Origin-Host } + { Origin-Realm } + { Auth-Application-Id } + { CC-Request-Type } + { CC-Request-Number } + [ User-Name ] + [ CC-Session-Failover ] + [ CC-Sub-Session-Id ] + [ Acct-Multi-Session-Id ] + [ Origin-State-Id ] + [ Event-Timestamp ] + [ Granted-Service-Unit ] + * [ Multiple-Services-Credit-Control ] + [ Cost-Information] + [ Final-Unit-Indication ] + [ Check-Balance-Result ] + [ Credit-Control-Failure-Handling ] + [ Direct-Debiting-Failure-Handling ] + [ Validity-Time] + * [ Redirect-Host] + [ Redirect-Host-Usage ] + [ Redirect-Max-Cache-Time ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ Failed-AVP ] + * [ AVP ] + +;; =========================================================================== + +@grouped + + Cost-Information ::= < AVP Header: 423 > + + { Unit-Value } + { Currency-Code } + [ Cost-Unit ] + + Unit-Value ::= < AVP Header: 445 > + + { Value-Digits } + [ Exponent ] + + Multiple-Services-Credit-Control ::= < AVP Header: 456 > + + [ Granted-Service-Unit ] + [ Requested-Service-Unit ] + * [ Used-Service-Unit ] + [ Tariff-Change-Usage ] + * [ Service-Identifier ] + [ Rating-Group ] + * [ G-S-U-Pool-Reference ] + [ Validity-Time ] + [ Result-Code ] + [ Final-Unit-Indication ] + * [ AVP ] + + Granted-Service-Unit ::= < AVP Header: 431 > + + [ Tariff-Time-Change ] + [ CC-Time ] + [ CC-Money ] + [ CC-Total-Octets ] + [ CC-Input-Octets ] + [ CC-Output-Octets ] + [ CC-Service-Specific-Units ] + * [ AVP ] + + Requested-Service-Unit ::= < AVP Header: 437 > + + [ CC-Time ] + [ CC-Money ] + [ CC-Total-Octets ] + [ CC-Input-Octets ] + [ CC-Output-Octets ] + [ CC-Service-Specific-Units ] + * [ AVP ] + + Used-Service-Unit ::= < AVP Header: 446 > + + [ Tariff-Change-Usage ] + [ CC-Time ] + [ CC-Money ] + [ CC-Total-Octets ] + [ CC-Input-Octets ] + [ CC-Output-Octets ] + [ CC-Service-Specific-Units ] + * [ AVP ] + + CC-Money ::= < AVP Header: 413 > + + { Unit-Value } + [ Currency-Code ] + + G-S-U-Pool-Reference ::= < AVP Header: 457 > + + { G-S-U-Pool-Identifier } + { CC-Unit-Type } + { Unit-Value } + + Final-Unit-Indication ::= < AVP Header: 430 > + + { Final-Unit-Action } + * [ Restriction-Filter-Rule ] + * [ Filter-Id ] + [ Redirect-Server ] + + Redirect-Server ::= < AVP Header: 434 > + + { Redirect-Address-Type } + { Redirect-Server-Address } + + Service-Parameter-Info ::= < AVP Header: 440 > + + { Service-Parameter-Type } + { Service-Parameter-Value } + + Subscription-Id ::= < AVP Header: 443 > + + { Subscription-Id-Type } + { Subscription-Id-Data } + + User-Equipment-Info ::= < AVP Header: 458 > + + { User-Equipment-Info-Type } + { User-Equipment-Info-Value } + +;; =========================================================================== + +@enum CC-Request-Type + + INITIAL_REQUEST 1 + UPDATE_REQUEST 2 + TERMINATION_REQUEST 3 + EVENT_REQUEST 4 + +@enum CC-Session-Failover + + NOT_SUPPORTED 0 + SUPPORTED 1 + +@enum Check-Balance-Result + + ENOUGH_CREDIT 0 + NO_CREDIT 1 + +@enum Credit-Control + + AUTHORIZATION 0 + RE_AUTHORIZATION 1 + +@enum Credit-Control-Failure-Handling + + TERMINATE 0 + CONTINUE 1 + RETRY_AND_TERMINATE 2 + +@enum Direct-Debiting-Failure-Handling + + TERMINATE_OR_BUFFER 0 + CONTINUE 1 + +@enum Tariff-Change-Usage + + UNIT_BEFORE_TARIFF_CHANGE 0 + UNIT_AFTER_TARIFF_CHANGE 1 + UNIT_INDETERMINATE 2 + +@enum CC-Unit-Type + + TIME 0 + MONEY 1 + TOTAL-OCTETS 2 + INPUT-OCTETS 3 + OUTPUT-OCTETS 4 + SERVICE-SPECIFIC-UNITS 5 + +@enum Final-Unit-Action + + TERMINATE 0 + REDIRECT 1 + RESTRICT_ACCESS 2 + +@enum Redirect-Address-Type + + IPV4 0 + IPV6 1 + URL 2 + SIP_URI 3 + +@enum Multiple-Services-Indicator + + NOT_SUPPORTED 0 + SUPPORTED 1 + +@enum Requested-Action + + DIRECT_DEBITING 0 + REFUND_ACCOUNT 1 + CHECK_BALANCE 2 + PRICE_ENQUIRY 3 + +@enum Subscription-Id-Type + + END_USER_E164 0 + END_USER_IMSI 1 + END_USER_SIP_URI 2 + END_USER_NAI 3 + END_USER_PRIVATE 4 + +@enum User-Equipment-Info-Type + + IMEISV 0 + MAC 1 + EUI64 2 + MODIFIED_EUI64 3 + +;; =========================================================================== + +@define Result-Code + + END_USER_SERVICE_DENIED 4010 + CREDIT_CONTROL_NOT_APPLICABLE 4011 + CREDIT_LIMIT_REACHED 4012 + + USER_UNKNOWN 5030 + RATING_FAILED 5031 diff --git a/lib/diameter/examples/dict/rfc4072_eap.dia b/lib/diameter/examples/dict/rfc4072_eap.dia new file mode 100644 index 0000000000..111516b347 --- /dev/null +++ b/lib/diameter/examples/dict/rfc4072_eap.dia @@ -0,0 +1,150 @@ +;; +;; %CopyrightBegin% +;; +;; Copyright Ericsson AB 2010-2011. 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% +;; + +;; +;; RFC 4072, Diameter Extensible Authentication Protocol (EAP) Application +;; +;; Edits: +;; +;; - Move EAP-Payload to not break fixed/required/optional order +;; - Framed-Appletalk-Link -> Framed-AppleTalk-Link +;; - Framed-Appletalk-Network -> Framed-AppleTalk-Network +;; - Framed-Appletalk-Zone -> Framed-AppleTalk-Zone +;; + +@id 5 + +@inherits rfc3588_base +@inherits rfc4005_nas + +;; =========================================================================== + +@avp_types + + EAP-Master-Session-Key 464 OctetString - + EAP-Key-Name 102 OctetString - + EAP-Payload 462 OctetString - + EAP-Reissued-Payload 463 OctetString - + Accounting-EAP-Auth-Method 465 Unsigned64 - + +;; =========================================================================== + +@messages + + DER ::= < Diameter Header: 268, REQ, PXY > + + < Session-Id > + { Auth-Application-Id } + { Origin-Host } + { Origin-Realm } + { Destination-Realm } + { Auth-Request-Type } + { EAP-Payload } + [ Destination-Host ] + [ NAS-Identifier ] + [ NAS-IP-Address ] + [ NAS-IPv6-Address ] + [ NAS-Port ] + [ NAS-Port-Id ] + [ NAS-Port-Type ] + [ Origin-State-Id ] + [ Port-Limit ] + [ User-Name ] + [ EAP-Key-Name ] + [ Service-Type ] + [ State ] + [ Authorization-Lifetime ] + [ Auth-Grace-Period ] + [ Auth-Session-State ] + [ Callback-Number ] + [ Called-Station-Id ] + [ Calling-Station-Id ] + [ Originating-Line-Info ] + [ Connect-Info ] + * [ Framed-Compression ] + [ Framed-Interface-Id ] + [ Framed-IP-Address ] + * [ Framed-IPv6-Prefix ] + [ Framed-IP-Netmask ] + [ Framed-MTU ] + [ Framed-Protocol ] + * [ Tunneling ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + DEA ::= < Diameter Header: 268, PXY > + + < Session-Id > + { Auth-Application-Id } + { Auth-Request-Type } + { Result-Code } + { Origin-Host } + { Origin-Realm } + [ User-Name ] + [ EAP-Payload ] + [ EAP-Reissued-Payload ] + [ EAP-Master-Session-Key ] + [ EAP-Key-Name ] + [ Multi-Round-Time-Out ] + [ Accounting-EAP-Auth-Method ] + [ Service-Type ] + * [ Class ] + * [ Configuration-Token ] + [ Acct-Interim-Interval ] + [ Error-Message ] + [ Error-Reporting-Host ] + * [ Failed-AVP ] + [ Idle-Timeout ] + [ Authorization-Lifetime ] + [ Auth-Grace-Period ] + [ Auth-Session-State ] + [ Re-Auth-Request-Type ] + [ Session-Timeout ] + [ State ] + * [ Reply-Message ] + [ Origin-State-Id ] + * [ Filter-Id ] + [ Port-Limit ] + [ Callback-Id ] + [ Callback-Number ] + [ Framed-AppleTalk-Link ] + * [ Framed-AppleTalk-Network ] + [ Framed-AppleTalk-Zone ] + * [ Framed-Compression ] + [ Framed-Interface-Id ] + [ Framed-IP-Address ] + * [ Framed-IPv6-Prefix ] + [ Framed-IPv6-Pool ] + * [ Framed-IPv6-Route ] + [ Framed-IP-Netmask ] + * [ Framed-Route ] + [ Framed-Pool ] + [ Framed-IPX-Network ] + [ Framed-MTU ] + [ Framed-Protocol ] + [ Framed-Routing ] + * [ NAS-Filter-Rule ] + * [ QoS-Filter-Rule ] + * [ Tunneling ] + * [ Redirect-Host ] + [ Redirect-Host-Usage ] + [ Redirect-Max-Cache-Time ] + * [ Proxy-Info ] + * [ AVP ] diff --git a/lib/diameter/examples/dict/rfc4590_digest.dia b/lib/diameter/examples/dict/rfc4590_digest.dia new file mode 100644 index 0000000000..a4ebe0c456 --- /dev/null +++ b/lib/diameter/examples/dict/rfc4590_digest.dia @@ -0,0 +1,45 @@ +;; +;; %CopyrightBegin% +;; +;; Copyright Ericsson AB 2010-2011. 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% +;; + +;; +;; RFC 4590, RADIUS Extension for Digest Authentication +;; + +@avp_types + + Digest-Response 103 OctetString - + Digest-Realm 104 OctetString - + Digest-Nonce 105 OctetString - + Digest-Response-Auth 106 OctetString - + Digest-Nextnonce 107 OctetString - + Digest-Method 108 OctetString - + Digest-URI 109 OctetString - + Digest-Qop 110 OctetString - + Digest-Algorithm 111 OctetString - + Digest-Entity-Body-Hash 112 OctetString - + Digest-CNonce 113 OctetString - + Digest-Nonce-Count 114 OctetString - + Digest-Username 115 OctetString - + Digest-Opaque 116 OctetString - + Digest-Auth-Param 117 OctetString - + Digest-AKA-Auts 118 OctetString - + Digest-Domain 119 OctetString - + Digest-Stale 120 OctetString - + Digest-HA1 121 OctetString - + SIP-AOR 122 OctetString - diff --git a/lib/diameter/examples/dict/rfc4740_sip.dia b/lib/diameter/examples/dict/rfc4740_sip.dia new file mode 100644 index 0000000000..8c21882649 --- /dev/null +++ b/lib/diameter/examples/dict/rfc4740_sip.dia @@ -0,0 +1,446 @@ +;; +;; %CopyrightBegin% +;; +;; Copyright Ericsson AB 2010-2011. 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% +;; + +;; +;; RFC 4740, Diameter Session Initiation Protocol (SIP) Application +;; + +@id 6 + +@inherits rfc3588_base +@inherits rfc4590_digest + +;; =========================================================================== + +@avp_types + + SIP-Accounting-Information 368 Grouped M + SIP-Accounting-Server-URI 369 DiameterURI M + SIP-Credit-Control-Server-URI 370 DiameterURI M + SIP-Server-URI 371 UTF8String M + SIP-Server-Capabilities 372 Grouped M + SIP-Mandatory-Capability 373 Unsigned32 M + SIP-Optional-Capability 374 Unsigned32 M + SIP-Server-Assignment-Type 375 Enumerated M + SIP-Auth-Data-Item 376 Grouped M + SIP-Authentication-Scheme 377 Enumerated M + SIP-Item-Number 378 Unsigned32 M + SIP-Authenticate 379 Grouped M + SIP-Authorization 380 Grouped M + SIP-Authentication-Info 381 Grouped M + SIP-Number-Auth-Items 382 Unsigned32 M + SIP-Deregistration-Reason 383 Grouped M + SIP-Reason-Code 384 Enumerated M + SIP-Reason-Info 385 UTF8String M + SIP-Visited-Network-Id 386 UTF8String M + SIP-User-Authorization-Type 387 Enumerated M + SIP-Supported-User-Data-Type 388 UTF8String M + SIP-User-Data 389 Grouped M + SIP-User-Data-Type 390 UTF8String M + SIP-User-Data-Contents 391 OctetString M + SIP-User-Data-Already-Available 392 Enumerated M + SIP-Method 393 UTF8String M + +;; =========================================================================== + +@messages + + ;; 8.1. User-Authorization-Request + + UAR ::= < Diameter Header: 283, REQ, PXY > + + < Session-Id > + { Auth-Application-Id } + { Auth-Session-State } + { Origin-Host } + { Origin-Realm } + { Destination-Realm } + { SIP-AOR } + [ Destination-Host ] + [ User-Name ] + [ SIP-Visited-Network-Id ] + [ SIP-User-Authorization-Type ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + ;; 8.2. User-Authorization-Answer + + UAA ::= < Diameter Header: 283, PXY > + + < Session-Id > + { Auth-Application-Id } + { Auth-Session-State } + { Result-Code } + { Origin-Host } + { Origin-Realm } + [ SIP-Server-URI ] + [ SIP-Server-Capabilities ] + [ Authorization-Lifetime ] + [ Auth-Grace-Period ] + [ Redirect-Host ] + [ Redirect-Host-Usage ] + [ Redirect-Max-Cache-Time ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + ;; 8.3. Server-Assignment-Request + + SAR ::= < Diameter Header: 284, REQ, PXY > + + < Session-Id > + { Auth-Application-Id } + { Auth-Session-State } + { Origin-Host } + { Origin-Realm } + { Destination-Realm } + { SIP-Server-Assignment-Type } + { SIP-User-Data-Already-Available } + [ Destination-Host ] + [ User-Name ] + [ SIP-Server-URI ] + * [ SIP-Supported-User-Data-Type ] + * [ SIP-AOR ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + ;; 8.4. Server-Assignment-Answer + + SAA ::= < Diameter Header: 284, PXY > + + < Session-Id > + { Auth-Application-Id } + { Result-Code } + { Auth-Session-State } + { Origin-Host } + { Origin-Realm } + * [ SIP-User-Data ] + [ SIP-Accounting-Information ] + * [ SIP-Supported-User-Data-Type ] + [ User-Name ] + [ Auth-Grace-Period ] + [ Authorization-Lifetime ] + [ Redirect-Host ] + [ Redirect-Host-Usage ] + [ Redirect-Max-Cache-Time ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + ;; 8.5. Location-Info-Request + + LIR ::= < Diameter Header: 285, REQ, PXY > + + < Session-Id > + { Auth-Application-Id } + { Auth-Session-State } + { Origin-Host } + { Origin-Realm } + { Destination-Realm } + { SIP-AOR } + [ Destination-Host ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + ;; 8.6. Location-Info-Answer + + LIA ::= < Diameter Header: 285, PXY > + + < Session-Id > + { Auth-Application-Id } + { Result-Code } + { Auth-Session-State } + { Origin-Host } + { Origin-Realm } + [ SIP-Server-URI ] + [ SIP-Server-Capabilities ] + [ Auth-Grace-Period ] + [ Authorization-Lifetime ] + [ Redirect-Host ] + [ Redirect-Host-Usage ] + [ Redirect-Max-Cache-Time ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + ;; 8.7. Multimedia-Auth-Request + + MAR ::= < Diameter Header: 286, REQ, PXY > + + < Session-Id > + { Auth-Application-Id } + { Auth-Session-State } + { Origin-Host } + { Origin-Realm } + { Destination-Realm } + { SIP-AOR } + { SIP-Method } + [ Destination-Host ] + [ User-Name ] + [ SIP-Server-URI ] + [ SIP-Number-Auth-Items ] + [ SIP-Auth-Data-Item ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + ;; 8.8. Multimedia-Auth-Answer + + MAA ::= < Diameter Header: 286, PXY > + + < Session-Id > + { Auth-Application-Id } + { Result-Code } + { Auth-Session-State } + { Origin-Host } + { Origin-Realm } + [ User-Name ] + [ SIP-AOR ] + [ SIP-Number-Auth-Items ] + * [ SIP-Auth-Data-Item ] + [ Authorization-Lifetime ] + [ Auth-Grace-Period ] + [ Redirect-Host ] + [ Redirect-Host-Usage ] + [ Redirect-Max-Cache-Time ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + ;; 8.9. Registration-Termination-Request + + RTR ::= < Diameter Header: 287, REQ, PXY > + + < Session-Id > + { Auth-Application-Id } + { Auth-Session-State } + { Origin-Host } + { Origin-Realm } + { Destination-Host } + { SIP-Deregistration-Reason } + [ Destination-Realm ] + [ User-Name ] + * [ SIP-AOR ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + ;; 8.10. Registration-Termination-Answer + + RTA ::= < Diameter Header: 287, PXY > + + < Session-Id > + { Auth-Application-Id } + { Result-Code } + { Auth-Session-State } + { Origin-Host } + { Origin-Realm } + [ Authorization-Lifetime ] + [ Auth-Grace-Period ] + [ Redirect-Host ] + [ Redirect-Host-Usage ] + [ Redirect-Max-Cache-Time ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + ;; 8.11. Push-Profile-Request + + PPR ::= < Diameter Header: 288, REQ, PXY > + + < Session-Id > + { Auth-Application-Id } + { Auth-Session-State } + { Origin-Host } + { Origin-Realm } + { Destination-Realm } + { User-Name } + * [ SIP-User-Data ] + [ SIP-Accounting-Information ] + [ Destination-Host ] + [ Authorization-Lifetime ] + [ Auth-Grace-Period ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + ;; 8.12. Push-Profile-Answer + + PPA ::= < Diameter Header: 288, PXY > + + < Session-Id > + { Auth-Application-Id } + { Result-Code } + { Auth-Session-State } + { Origin-Host } + { Origin-Realm } + [ Redirect-Host ] + [ Redirect-Host-Usage ] + [ Redirect-Max-Cache-Time ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + +;; =========================================================================== + +@grouped + + SIP-Accounting-Information ::= < AVP Header: 368 > + + * [ SIP-Accounting-Server-URI ] + * [ SIP-Credit-Control-Server-URI ] + * [ AVP] + + SIP-Server-Capabilities ::= < AVP Header: 372 > + + * [ SIP-Mandatory-Capability ] + * [ SIP-Optional-Capability ] + * [ SIP-Server-URI ] + * [ AVP ] + + SIP-Auth-Data-Item ::= < AVP Header: 376 > + + { SIP-Authentication-Scheme } + [ SIP-Item-Number ] + [ SIP-Authenticate ] + [ SIP-Authorization ] + [ SIP-Authentication-Info ] + * [ AVP ] + + SIP-Authenticate ::= < AVP Header: 379 > + + { Digest-Realm } + { Digest-Nonce } + [ Digest-Domain ] + [ Digest-Opaque ] + [ Digest-Stale ] + [ Digest-Algorithm ] + [ Digest-Qop ] + [ Digest-HA1] + * [ Digest-Auth-Param ] + * [ AVP ] + + SIP-Authorization ::= < AVP Header: 380 > + + { Digest-Username } + { Digest-Realm } + { Digest-Nonce } + { Digest-URI } + { Digest-Response } + [ Digest-Algorithm ] + [ Digest-CNonce ] + [ Digest-Opaque ] + [ Digest-Qop ] + [ Digest-Nonce-Count ] + [ Digest-Method] + [ Digest-Entity-Body-Hash ] + * [ Digest-Auth-Param ] + * [ AVP ] + + SIP-Authentication-Info ::= < AVP Header: 381 > + + [ Digest-Nextnonce ] + [ Digest-Qop ] + [ Digest-Response-Auth ] + [ Digest-CNonce ] + [ Digest-Nonce-Count ] + * [ AVP ] + + SIP-Deregistration-Reason ::= < AVP Header: 383 > + + { SIP-Reason-Code } + [ SIP-Reason-Info ] + * [ AVP ] + + SIP-User-Data ::= < AVP Header: 389 > + + { SIP-User-Data-Type } + { SIP-User-Data-Contents } + * [ AVP ] + +;; =========================================================================== + +@enum SIP-Server-Assignment-Type + + NO_ASSIGNMENT 0 + REGISTRATION 1 + RE_REGISTRATION 2 + UNREGISTERED_USER 3 + TIMEOUT_DEREGISTRATION 4 + USER_DEREGISTRATION 5 + TIMEOUT_DEREGISTRATION_STORE 6 + USER_DEREGISTRATION_STORE 7 + ADMINISTRATIVE_DEREGISTRATION 8 + AUTHENTICATION_FAILURE 9 + AUTHENTICATION_TIMEOUT 10 + DEREGISTRATION_TOO_MUCH_DATA 11 + +@enum SIP-Authentication-Scheme + + DIGEST 0 + +@enum SIP-Reason-Code + + PERMANENT_TERMINATION 0 + NEW_SIP_SERVER_ASSIGNED 1 + SIP_SERVER_CHANGE 2 + REMOVE_SIP_SERVER 3 + +@enum SIP-User-Authorization-Type + + REGISTRATION 0 + DEREGISTRATION 1 + REGISTRATION_AND_CAPABILITIES 2 + +@enum SIP-User-Data-Already-Available + + USER_DATA_NOT_AVAILABLE 0 + USER_DATA_ALREADY_AVAILABLE 1 + +;; =========================================================================== + +@define Result-Code + + ;; Success + + FIRST_REGISTRATION 2003 + SUBSEQUENT_REGISTRATION 2004 + UNREGISTERED_SERVICE 2005 + SUCCESS_SERVER_NAME_NOT_STORED 2006 + SERVER_SELECTION 2007 + SUCCESS_AUTH_SENT_SERVER_NOT_STORED 2008 + + ;; Transient Failures + + USER_NAME_REQUIRED 4013 + + ;; Permanent Failures + + USER_UNKNOWN 5032 + IDENTITIES_DONT_MATCH 5033 + IDENTITY_NOT_REGISTERED 5034 + ROAMING_NOT_ALLOWED 5035 + IDENTITY_ALREADY_REGISTERED 5036 + AUTH_SCHEME_NOT_SUPPORTED 5037 + IN_ASSIGNMENT_TYPE 5038 + TOO_MUCH_DATA 5039 + NOT_SUPPORTED_USER_DATA 5040 diff --git a/lib/diameter/include/diameter.hrl b/lib/diameter/include/diameter.hrl index 0fa7fd406f..beb577afaf 100644 --- a/lib/diameter/include/diameter.hrl +++ b/lib/diameter/include/diameter.hrl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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,6 +107,21 @@ transport = sctp, %% | tcp, protocol = diameter}). %% | radius | 'tacacs+' +%% A diameter_callback record can be specified as an application +%% module in order to selectively receive callbacks or alter their +%% form. +-record(diameter_callback, + {peer_up, + peer_down, + pick_peer, + prepare_request, + prepare_retransmit, + handle_request, + handle_answer, + handle_error, + default, + extra = []}). + %% The diameter service and diameter_apps records are only passed %% through the transport interface when starting a transport process, %% although typically a transport implementation will (and probably @@ -124,7 +139,6 @@ init_state, %% option 'state', initial callback state id, %% 32-bit unsigned application identifier = Dict:id() mutable = false, %% boolean(), do traffic callbacks modify state? - answer_errors = report}). %% | callback | discard - %% how to handle containing errors? + options = [{answer_errors, report}]}). %% | callback | discard -endif. %% -ifdef(diameter_hrl). diff --git a/lib/diameter/include/diameter_gen.hrl b/lib/diameter/include/diameter_gen.hrl index d037e1044a..13a6c462af 100644 --- a/lib/diameter/include/diameter_gen.hrl +++ b/lib/diameter/include/diameter_gen.hrl @@ -40,14 +40,14 @@ encode_avps(Name, Rec) -> list_to_binary(encode(Name, Rec)) catch throw: {?MODULE, Reason} -> - diameter_dbg:log({encode, error}, + diameter_lib:log({encode, error}, ?MODULE, ?LINE, {Reason, Name, Rec}), erlang:error(list_to_tuple(Reason ++ [Name])); error: Reason -> Stack = erlang:get_stacktrace(), - diameter_dbg:log({encode, failure}, + diameter_lib:log({encode, failure}, ?MODULE, ?LINE, {Reason, Name, Rec, Stack}), @@ -159,7 +159,7 @@ d_rc(Name, {Avps, {Rec, [] = Failed}}) -> {Rec, Avps, Failed} catch throw: {?MODULE, {AvpName, Reason}} -> - diameter_dbg:log({decode, error}, + diameter_lib:log({decode, error}, ?MODULE, ?LINE, {AvpName, Reason, Rec}), @@ -260,7 +260,7 @@ d(Name, Avp, {Avps, Acc}) -> %% respond sensibly to. Log the occurence for traceability, %% but the peer will also receive info in the resulting %% answer-message. - diameter_dbg:log({decode, failure}, + diameter_lib:log({decode, failure}, ?MODULE, ?LINE, {Reason, Avp, erlang:get_stacktrace()}), diff --git a/lib/diameter/make/release_targets.mk b/lib/diameter/make/release_targets.mk deleted file mode 100644 index 5a3b585cbc..0000000000 --- a/lib/diameter/make/release_targets.mk +++ /dev/null @@ -1,92 +0,0 @@ -# -# %CopyrightBegin% -# -# Copyright Ericsson AB 1997-2011. 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% -# - -ifeq ($(TOPDOC),) -$(HTMLDIR)/index.html: $(XML_FILES) - date=`date +"%B %e %Y"`; \ - $(XSLTPROC) --noout --stringparam outdir $(HTMLDIR) --stringparam docgen "$(DOCGEN)" --stringparam topdocdir "$(TOPDOCDIR)" \ - --stringparam pdfdir "$(PDFDIR)" \ - --stringparam gendate "$$date" --stringparam appname "$(APPLICATION)" --stringparam appver "$(VSN)" --xinclude \ - -path $(DOCGEN)/priv/docbuilder_dtd -path $(DOCGEN)/priv/dtd_html_entities $(DOCGEN)/priv/xsl/db_html.xsl book.xml -endif - -$(HTMLDIR)/users_guide.html: $(XML_FILES) - date=`date +"%B %e %Y"`; \ - $(XSLTPROC) --noout --stringparam outdir $(HTMLDIR) --stringparam docgen "$(DOCGEN)" --stringparam topdocdir "$(TOPDOCDIR)" \ - --stringparam pdfdir "$(PDFDIR)" \ - --stringparam gendate "$$date" --stringparam appname "$(APPLICATION)" --stringparam appver "$(VSN)" --xinclude \ - -path $(DOCGEN)/priv/docbuilder_dtd -path $(DOCGEN)/priv/dtd_html_entities $(DOCGEN)/priv/xsl/db_html.xsl book.xml - - -%.fo: $(XML_FILES) - date=`date +"%B %e %Y"`; \ - $(XSLTPROC) --stringparam docgen "$(DOCGEN)" --stringparam gendate "$$date" --stringparam appname "$(APPLICATION)" \ - --stringparam appver "$(VSN)" --xinclude \ - -path $(DOCGEN)/priv/docbuilder_dtd -path $(DOCGEN)/priv/dtd_html_entities $(DOCGEN)/priv/xsl/db_pdf.xsl book.xml > $@ - - - -# ------------------------------------------------------------------------ -# The following targets just exist in the documentation directory -# ------------------------------------------------------------------------ -ifneq ($(XML_FILES),) - -# ---------------------------------------------------- -# Generation of application index data -# ---------------------------------------------------- -$(HTMLDIR)/$(APPLICATION).eix: $(XML_FILES) - date=`date +"%B %e %Y"`; \ - $(XSLTPROC) --stringparam docgen "$(DOCGEN)" \ - --stringparam gendate "$$date" --stringparam appname "$(APPLICATION)" --stringparam appver "$(VSN)" --xinclude \ - -path $(DOCGEN)/priv/docbuilder_dtd -path $(DOCGEN)/priv/dtd_html_entities $(DOCGEN)/priv/xsl/db_eix.xsl book.xml > $@ - -docs: -#docs: $(HTMLDIR)/$(APPLICATION).eix - -# ---------------------------------------------------- -# Local documentation target for testing -# ---------------------------------------------------- -local_docs: TOPDOCDIR=. -local_docs: local_copy_of_topdefs docs - -local_html: TOPDOCDIR=. -local_html: local_copy_of_topdefs html - -local_copy_of_topdefs: - $(INSTALL) $(DOCGEN)/priv/css/otp_doc.css $(HTMLDIR) - $(INSTALL) $(DOCGEN)/priv/images/erlang-logo.png $(HTMLDIR) - $(INSTALL) $(DOCGEN)/priv/images/erlang-logo.gif $(HTMLDIR) - $(INSTALL_DIR) $(HTMLDIR)/js/flipmenu - $(INSTALL) $(DOCGEN)/priv/js/flipmenu/flip_closed.gif \ - $(DOCGEN)/priv/js/flipmenu/flip_open.gif \ - $(DOCGEN)/priv/js/flipmenu/flip_static.gif \ - $(DOCGEN)/priv/js/flipmenu/flipmenu.js $(HTMLDIR)/js/flipmenu - -endif - -# ---------------------------------------------------- -# Standard release target -# ---------------------------------------------------- - -ifneq ($(PREFIX),) - -release release_docs release_tests release_html: - $(MAKE) $(MFLAGS) RELEASE_PATH=$(PREFIX) $(TARGET_MAKEFILE) $@_spec - -endif diff --git a/lib/diameter/make/rules.mk.in b/lib/diameter/make/rules.mk.in deleted file mode 100644 index 6318f2bc9c..0000000000 --- a/lib/diameter/make/rules.mk.in +++ /dev/null @@ -1,195 +0,0 @@ -#-*-makefile-*- ; force emacs to enter makefile-mode -# ---------------------------------------------------- -# %CopyrightBegin% -# -# Copyright Ericsson AB 2009-2011. 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% - -.SUFFIXES: .erl .beam .yrl .hrl .xml .xmlsrc .html \ - .3 .1 .pdf .fo .el .elc - -# ---------------------------------------------------- -# Common macros -# ---------------------------------------------------- -DEFAULT_TARGETS = opt debug release release_docs clean docs - - -# Slash separated list of return values from $(origin VAR) -# that are untrusted - set default in this file instead. -# The list is not space separated since some return values -# contain space, and we want to use $(findstring ...) to -# search the list. -DUBIOUS_ORIGINS = /undefined/environment/ - - -# # ---------------------------------------------------- -# # TARGET definition -# # ---------------------------------------------------- -# # TARGET = @TARGET@ -# ifneq ($(OVERRIDE_TARGET),) -# ifneq ($(TARGET), $(OVERRIDE_TARGET)) -# $(warning overriding $$(TARGET) = \ -# "$(TARGET)" \ -# with \ -# $$(OVERRIDE_TARGET) = \ -# "$(OVERRIDE_TARGET)") -# override TARGET := $(OVERRIDE_TARGET) -# endif -# endif -# - -# ---------------------------------------------------- -# Command macros -# ---------------------------------------------------- -PREFIX = @prefix@ -INSTALL = @INSTALL@ -INSTALL_DIR = @INSTALL_DIR@ -INSTALL_PROGRAM = @INSTALL_PROGRAM@ -INSTALL_SCRIPT = @INSTALL_SCRIPT@ -INSTALL_DATA = @INSTALL_DATA@ - - -# ---------------------------------------------------- -# Erlang language section -# ---------------------------------------------------- -ERL_ROOT_DIR = @ERLANG_ROOT_DIR@ -ERL_LIB_DIR = @ERLANG_LIB_DIR@ -DOCGEN_DIR = @ERLANG_LIB_DIR_erl_docgen@ -TEST_SERVER_DIR = @ERLANG_LIB_VER_test_server@ -EMULATOR = beam -ERL_COMPILE_FLAGS += +debug_info -ERLC_WFLAGS = -W -ERLC = $(ERL_ROOT_DIR)/bin/erlc $(ERLC_WFLAGS) $(ERLC_FLAGS) -ERL = $(ERL_ROOT_DIR)/bin/erl -boot start_clean -#ERLC = @ERLC@ $(ERLC_WFLAGS) $(ERLC_FLAGS) -#ERL = @ERL@ -boot start_clean - -ifneq (,$(findstring $(origin EBIN),$(DUBIOUS_ORIGINS))) -EBIN = ../../ebin -endif - -# Generated (non ebin) files... -ifneq (,$(findstring $(origin EGEN),$(DUBIOUS_ORIGINS))) -EGEN = . -endif - -ifneq (,$(findstring $(origin ESRC),$(DUBIOUS_ORIGINS))) -ESRC = . -endif - -$(EBIN)/%.beam: $(EGEN)/%.erl - $(ERLC) $(ERL_COMPILE_FLAGS) -o$(EBIN) $< - -$(EBIN)/%.beam: $(ESRC)/%.erl - $(ERLC) $(ERL_COMPILE_FLAGS) -o$(EBIN) $< - -.erl.beam: - $(ERLC) $(ERL_COMPILE_FLAGS) -o$(dir $@) $< - - -# -# When .erl files are automatically created GNU make removes them if -# they were the result of a chain of implicit rules. To prevent this -# we say that all .erl files are "precious". -# -.PRECIOUS: %.erl %.fo - - -# ---------------------------------------------------- -# Documentation section -# ---------------------------------------------------- -# export VSN - -# DOCSUPPORT = 1 - -# TOPDOCDIR=../../../../doc - -DOCDIR = .. - -PDFDIR=$(DOCDIR)/pdf - -HTMLDIR = $(DOCDIR)/html - -MAN1DIR = $(DOCDIR)/man1 -MAN2DIR = $(DOCDIR)/man2 -MAN3DIR = $(DOCDIR)/man3 -MAN4DIR = $(DOCDIR)/man4 -MAN6DIR = $(DOCDIR)/man6 -MAN9DIR = $(DOCDIR)/man9 - -# HTML & GIF files that always are generated and must be delivered -XML_COLL_FILES = $(XML_APPLICATION_FILES) $(XML_PART_FILES) -DEFAULT_HTML_FILES = \ - $(XML_COLL_FILES:%.xml=$(HTMLDIR)/%_frame.html) \ - $(XML_COLL_FILES:%.xml=$(HTMLDIR)/%_first.html) \ - $(XML_COLL_FILES:%.xml=$(HTMLDIR)/%_term.html) \ - $(XML_COLL_FILES:%.xml=$(HTMLDIR)/%_cite.html) \ - $(XML_APPLICATION_FILES:%.xml=$(HTMLDIR)/%_index.html) \ - $(XML_APPLICATION_FILES:%.xml=$(HTMLDIR)/%.kwc) \ - $(HTMLDIR)/index.html - -DEFAULT_GIF_FILES = $(HTMLDIR)/min_head.gif - -# -# Flags & Commands -# -XSLTPROC = @XSLTPROC@ -FOP = @FOP@ - -DOCGEN=$(DOCGEN_DIR) - -$(MAN1DIR)/%.1:: %.xml - date=`date +"%B %e %Y"`; \ - xsltproc --output "$@" --stringparam company "Ericsson AB" --stringparam docgen "$(DOCGEN)" --stringparam gendate "$$date" --stringparam appname "$(APPLICATION)" --stringparam appver "$(VSN)" --xinclude -path $(DOCGEN)/priv/docbuilder_dtd -path $(DOCGEN)/priv/dtd_man_entities $(DOCGEN)/priv/xsl/db_man.xsl $< - - -$(MAN2DIR)/%.2:: %.xml - date=`date +"%B %e %Y"`; \ - xsltproc --output "$@" --stringparam company "Ericsson AB" --stringparam docgen "$(DOCGEN)" --stringparam gendate "$$date" --stringparam appname "$(APPLICATION)" --stringparam appver "$(VSN)" --xinclude -path $(DOCGEN)/priv/docbuilder_dtd -path $(DOCGEN)/priv/dtd_man_entities $(DOCGEN)/priv/xsl/db_man.xsl $< - - -$(MAN3DIR)/%.3:: %.xml - date=`date +"%B %e %Y"`; \ - xsltproc --output "$@" --stringparam company "Ericsson AB" --stringparam docgen "$(DOCGEN)" --stringparam gendate "$$date" --stringparam appname "$(APPLICATION)" --stringparam appver "$(VSN)" --xinclude -path $(DOCGEN)/priv/docbuilder_dtd -path $(DOCGEN)/priv/dtd_man_entities $(DOCGEN)/priv/xsl/db_man.xsl $< - -# left for compatibility -$(MAN4DIR)/%.4:: %.xml - date=`date +"%B %e %Y"`; \ - xsltproc --output "$@" --stringparam company "Ericsson AB" --stringparam docgen "$(DOCGEN)" --stringparam gendate "$$date" --stringparam appname "$(APPLICATION)" --stringparam appver "$(VSN)" --xinclude -path $(DOCGEN)/priv/docbuilder_dtd -path $(DOCGEN)/priv/dtd_man_entities $(DOCGEN)/priv/xsl/db_man.xsl $< - -$(MAN4DIR)/%.5:: %.xml - date=`date +"%B %e %Y"`; \ - xsltproc --output "$@" --stringparam company "Ericsson AB" --stringparam docgen "$(DOCGEN)" --stringparam gendate "$$date" --stringparam appname "$(APPLICATION)" --stringparam appver "$(VSN)" --xinclude -path $(DOCGEN)/priv/docbuilder_dtd -path $(DOCGEN)/priv/dtd_man_entities $(DOCGEN)/priv/xsl/db_man.xsl $< - -# left for compatibility -$(MAN6DIR)/%.6:: %_app.xml - date=`date +"%B %e %Y"`; \ - xsltproc --output "$@" --stringparam company "Ericsson AB" --stringparam docgen "$(DOCGEN)" --stringparam gendate "$$date" --stringparam appname "$(APPLICATION)" --stringparam appver "$(VSN)" --xinclude -path $(DOCGEN)/priv/docbuilder_dtd -path $(DOCGEN)/priv/dtd_man_entities $(DOCGEN)/priv/xsl/db_man.xsl $< - -$(MAN6DIR)/%.7:: %_app.xml - date=`date +"%B %e %Y"`; \ - xsltproc --output "$@" --stringparam company "Ericsson AB" --stringparam docgen "$(DOCGEN)" --stringparam gendate "$$date" --stringparam appname "$(APPLICATION)" --stringparam appver "$(VSN)" --xinclude -path $(DOCGEN)/priv/docbuilder_dtd -path $(DOCGEN)/priv/dtd_man_entities $(DOCGEN)/priv/xsl/db_man.xsl $< - -$(MAN9DIR)/%.9:: %.xml - date=`date +"%B %e %Y"`; \ - xsltproc --output "$@" --stringparam company "Ericsson AB" --stringparam docgen "$(DOCGEN)" --stringparam gendate "$$date" --stringparam appname "$(APPLICATION)" --stringparam appver "$(VSN)" --xinclude -path $(DOCGEN)/priv/docbuilder_dtd -path $(DOCGEN)/priv/dtd_man_entities $(DOCGEN)/priv/xsl/db_man.xsl $< - - -.xmlsrc.xml: - escript $(DOCGEN)/priv/bin/codeline_preprocessing.escript $< $@ - -.fo.pdf: - $(FOP) -fo $< -pdf $@ - diff --git a/lib/diameter/make/subdir.mk b/lib/diameter/make/subdir.mk deleted file mode 100644 index 24b08080ae..0000000000 --- a/lib/diameter/make/subdir.mk +++ /dev/null @@ -1,53 +0,0 @@ -# -# %CopyrightBegin% -# -# Copyright Ericsson AB 1997-2011. 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% -# -# Make include file for otp - -.PHONY: debug opt release docs release_docs tests release_tests \ - clean depend valgrind - -# -# Targets that don't affect documentation directories -# -opt debug release docs release_docs tests release_tests clean depend valgrind: - @set -e ; \ - app_pwd=`pwd` ; \ - if test -f vsn.mk; then \ - echo "=== Entering application" `basename $$app_pwd` ; \ - fi ; \ - case "$(MAKE)" in *clearmake*) tflag="-T";; *) tflag="";; esac; \ - for d in $(SUB_DIRS); do \ - if test -f $$d/SKIP ; then \ - echo "=== Skipping subdir $$d, reason:" ; \ - cat $$d/SKIP ; \ - echo "===" ; \ - else \ - if test ! -d $$d ; then \ - echo "=== Skipping subdir $$d, it is missing" ; \ - else \ - xflag="" ; \ - if test -f $$d/ignore_config_record.inf; then \ - xflag=$$tflag ; \ - fi ; \ - (cd $$d && $(MAKE) $$xflag $@) || exit $$? ; \ - fi ; \ - fi ; \ - done ; \ - if test -f vsn.mk; then \ - echo "=== Leaving application" `basename $$app_pwd` ; \ - fi diff --git a/lib/diameter/make/target.mk b/lib/diameter/make/target.mk deleted file mode 100644 index 4ae470b9e2..0000000000 --- a/lib/diameter/make/target.mk +++ /dev/null @@ -1,33 +0,0 @@ -ifeq ($(OVERRIDE_TARGET),) - -ifeq ($(TARGET),) - -TARGET := $(shell $(DIAMETER_TOP)/autoconf/config.guess) - -else - -endif - -else - -ifneq ($(TARGET),) - -ifneq ($(TARGET), $(OVERRIDE_TARGET)) -$(warning overriding $$(TARGET) = \ - "$(TARGET)" \ - with \ - $$(OVERRIDE_TARGET) = \ - "$(OVERRIDE_TARGET)") -else -endif - -override TARGET := $(OVERRIDE_TARGET) - -else - -TARGET := $(OVERRIDE_TARGET) - -endif - -endif - diff --git a/lib/diameter/src/compiler/.gitignore b/lib/diameter/src/.gitignore index d9f072e262..cc06720fd1 100644 --- a/lib/diameter/src/compiler/.gitignore +++ b/lib/diameter/src/.gitignore @@ -1,3 +1,3 @@ /depend.mk - +/otp.plt diff --git a/lib/diameter/src/Makefile b/lib/diameter/src/Makefile index 6935eb053e..060659bce9 100644 --- a/lib/diameter/src/Makefile +++ b/lib/diameter/src/Makefile @@ -1,7 +1,7 @@ # # %CopyrightBegin% # -# Copyright Ericsson AB 2010-2011. All Rights Reserved. +# Copyright Ericsson AB 2010-2012. 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 @@ -16,28 +16,268 @@ # # %CopyrightEnd% -ifneq ($(ERL_TOP),) include $(ERL_TOP)/make/target.mk include $(ERL_TOP)/make/$(TARGET)/otp.mk -else -include $(DIAMETER_TOP)/make/target.mk -include $(DIAMETER_TOP)/make/$(TARGET)/rules.mk -endif # ---------------------------------------------------- -# Common Macros +# Application version +# ---------------------------------------------------- + +include ../vsn.mk + +VSN = $(DIAMETER_VSN) + # ---------------------------------------------------- +# Release directory specification +# ---------------------------------------------------- + +RELSYSDIR = $(RELEASE_PATH)/lib/diameter-$(VSN) + +# Where to put/find things. +EBIN = ../ebin +INCDIR = ../include + +# Dumbed down to make 3.80. In 3.81 and later it's just $(realpath $(EBIN)). +ABS_EBIN := $(shell cd $(EBIN) && pwd) + +# Where make should look for dependencies. +VPATH = .:base:compiler:transport:gen + +# ---------------------------------------------------- +# Target specs +# ---------------------------------------------------- + +include modules.mk + +# Modules generated from dictionary specifications. +DICT_MODULES = $(DICTS:%=gen/diameter_gen_%) +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) + +# All handwritten modules from which a depend.mk is generated. +MODULES = \ + $(RT_MODULES) \ + $(CT_MODULES) -include subdirs.mk +# Modules whose names are inserted into the app file. +APP_MODULES = \ + $(RT_MODULES) \ + $(DICT_MODULES) -SPECIAL_TARGETS = +# Modules for which to build beams. +TARGET_MODULES = \ + $(APP_MODULES) \ + $(CT_MODULES) \ + $(DICT_YRL:%=gen/%) + +# What to build for the 'opt' target. +TARGET_FILES = \ + $(patsubst %, $(EBIN)/%.$(EMULATOR), $(notdir $(TARGET_MODULES))) \ + $(APP_TARGET) \ + $(APPUP_TARGET) + +# Subdirectories of src to release modules into. +TARGET_DIRS = $(sort $(dir $(TARGET_MODULES))) + +# Ditto for examples. +EXAMPLE_DIRS = $(sort $(dir $(EXAMPLES))) + +APP_FILE = diameter.app +APP_SRC = $(APP_FILE).src +APP_TARGET = $(EBIN)/$(APP_FILE) + +APPUP_FILE = diameter.appup +APPUP_SRC = $(APPUP_FILE).src +APPUP_TARGET = $(EBIN)/$(APPUP_FILE) # ---------------------------------------------------- -# Default Subdir Targets +# Flags # ---------------------------------------------------- -ifneq ($(ERL_TOP),) -include $(ERL_TOP)/make/otp_subdir.mk -else -include $(DIAMETER_TOP)/make/subdir.mk + +ifeq ($(TYPE),debug) +ERL_COMPILE_FLAGS += -Ddebug endif -#include ../make/subdir.mk + +ERL_COMPILE_FLAGS += \ + +'{parse_transform,sys_pre_attributes}' \ + +'{attribute,insert,app_vsn,$(APP_VSN)}' \ + +warn_export_vars \ + +warn_unused_vars \ + -pa $(ABS_EBIN) \ + -I $(INCDIR) \ + -I gen +# -pa is to be able to include_lib from the include directory: the +# path must contain the application name. + +# ---------------------------------------------------- +# Targets +# ---------------------------------------------------- + +# erl/hrl from dictionary file. +gen/diameter_gen_%.erl gen/diameter_gen_%.hrl: dict/%.dia + ../bin/diameterc -o gen -i $(EBIN) $< + +opt: $(TARGET_FILES) + +debug: + @$(MAKE) TYPE=debug opt + +# The dictionary parser. +gen/$(DICT_YRL).erl: compiler/$(DICT_YRL).yrl + $(ERLC) -Werror -o $(@D) $< + +# Generate the app file. +$(APP_TARGET): $(APP_SRC) ../vsn.mk modules.mk + M=`echo $(notdir $(APP_MODULES)) | tr ' ' ,`; \ + sed -e 's;%VSN%;$(VSN);' \ + -e "s;%MODULES%;$$M;" \ + $< > $@ + +$(APPUP_TARGET): $(APPUP_SRC) ../vsn.mk + sed -e 's;%VSN%;$(VSN);' $< > $@ + +app: $(APP_TARGET) $(APPUP_TARGET) +dict: $(DICT_ERLS) + +docs: + +list = echo $(1):; echo $($(1)) | tr ' ' '\n' | sort | sed 's@^@ @' + +info: + @echo ======================================== + @$(call list,DICTS) + @echo + @$(call list,DICT_YRL) + @echo + @$(call list,RT_MODULES) + @echo + @$(call list,CT_MODULES) + @echo + @$(call list,TARGET_MODULES) + @echo + @$(call list,TARGET_DIRS) + @echo + @$(call list,EXTERNAL_HRLS) + @echo + @$(call list,INTERNAL_HRLS) + @echo + @$(call list,EXAMPLES) + @echo + @$(call list,EXAMPLE_DIRS) + @echo + @$(call list,BINS) + @echo ======================================== + +clean: + rm -f $(TARGET_FILES) gen/* + rm -f depend.mk + +realclean: clean + rm -f ../ebin/* +# Not $(EBIN) just to be a bit paranoid + +PLT = ./otp.plt + +plt: + dialyzer --build_plt \ + --apps erts stdlib kernel \ + xmerl ssl public_key crypto \ + compiler syntax_tools runtime_tools \ + --output_plt $(PLT) \ + --verbose + +dialyze: opt $(PLT) + dialyzer --plt $(PLT) \ + --verbose \ + -Wno_improper_lists \ + $(EBIN)/diameter_gen_base_rfc3588.$(EMULATOR) \ + $(patsubst %, $(EBIN)/%.$(EMULATOR), \ + $(notdir $(RT_MODULES) $(CT_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. + +# ---------------------------------------------------- +# Release targets +# ---------------------------------------------------- + +include $(ERL_TOP)/make/otp_release_targets.mk + +# Can't $(INSTALL_DIR) more than one directory at a time on Solaris. + +release_spec: opt + for d in bin ebin include src/dict; do \ + $(INSTALL_DIR) "$(RELSYSDIR)/$$d"; \ + done + $(INSTALL_SCRIPT) $(BINS:%=../bin/%) "$(RELSYSDIR)/bin" + $(INSTALL_DATA) $(TARGET_FILES) "$(RELSYSDIR)/ebin" + $(INSTALL_DATA) $(EXTERNAL_HRLS:%=../include/%) $(DICT_HRLS) \ + "$(RELSYSDIR)/include" + $(INSTALL_DATA) $(DICTS:%=dict/%.dia) "$(RELSYSDIR)/src/dict" + $(MAKE) $(TARGET_DIRS:%/=release_src_%) + $(MAKE) $(EXAMPLE_DIRS:%/=release_examples_%) + +$(TARGET_DIRS:%/=release_src_%): release_src_%: + $(INSTALL_DIR) "$(RELSYSDIR)/src/$*" + $(INSTALL_DATA) $(filter $*/%, $(TARGET_MODULES:%=%.erl) \ + $(INTERNAL_HRLS)) \ + $(filter $*/%, compiler/$(DICT_YRL).yrl) \ + "$(RELSYSDIR)/src/$*" + +$(EXAMPLE_DIRS:%/=release_examples_%): release_examples_%: + $(INSTALL_DIR) "$(RELSYSDIR)/examples/$*" + $(INSTALL_DATA) $(patsubst %, ../examples/%, $(filter $*/%, $(EXAMPLES))) \ + "$(RELSYSDIR)/examples/$*" + +release_docs_spec: + +# ---------------------------------------------------- +# Dependencies +# ---------------------------------------------------- + +gen/diameter_gen_base_accounting.erl gen/diameter_gen_relay.erl \ +gen/diameter_gen_base_accounting.hrl gen/diameter_gen_relay.hrl: \ + $(EBIN)/diameter_gen_base_rfc3588.$(EMULATOR) + +gen/diameter_gen_base_rfc3588.erl gen/diameter_gen_base_rfc3588.hrl: \ + $(COMPILER_MODULES:%=$(EBIN)/%.$(EMULATOR)) + +$(DICT_MODULES:gen/%=$(EBIN)/%.$(EMULATOR)): \ + $(INCDIR)/diameter.hrl \ + $(INCDIR)/diameter_gen.hrl + +depend: depend.mk + +# Generate dependencies makefile. +depend.mk: depend.sed $(MODULES:%=%.erl) Makefile + (for f in $(MODULES); do \ + (echo $$f; cat $$f.erl) | sed -f $<; \ + done) \ + > $@ + +-include depend.mk + +.PHONY: app clean realclean depend dict info release_subdir +.PHONY: debug opt release_docs_spec release_spec +.PHONY: $(TARGET_DIRS:%/=%) $(TARGET_DIRS:%/=release_src_%) +.PHONY: $(EXAMPLE_DIRS:%/=release_examples_%) +.PHONY: plt dialyze + +# Keep intermediate files. +.SECONDARY: $(DICT_ERLS) $(DICT_HRLS) gen/$(DICT_YRL:%=%.erl) + +# ---------------------------------------------------- +# Targets using secondary expansion (make >= 3.81) +# ---------------------------------------------------- + +.SECONDEXPANSION: + +# Make beams from a subdirectory. +$(TARGET_DIRS:%/=%): \ + $$(patsubst $$@/%, \ + $(EBIN)/%.$(EMULATOR), \ + $$(filter $$@/%, $(TARGET_MODULES) compiler/$(DICT_YRL))) diff --git a/lib/diameter/src/app/.gitignore b/lib/diameter/src/app/.gitignore deleted file mode 100644 index d388e61877..0000000000 --- a/lib/diameter/src/app/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ - -/diameter_gen_*.erl -/diameter_gen_*.hrl -/depend.mk -/diameter.mk - diff --git a/lib/diameter/src/app/Makefile b/lib/diameter/src/app/Makefile deleted file mode 100644 index a75c70d71c..0000000000 --- a/lib/diameter/src/app/Makefile +++ /dev/null @@ -1,212 +0,0 @@ -# -# %CopyrightBegin% -# -# Copyright Ericsson AB 2010-2011. 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% -# -# - -ifneq ($(ERL_TOP),) -include $(ERL_TOP)/make/target.mk -EBIN = ../../ebin -include $(ERL_TOP)/make/$(TARGET)/otp.mk -else -include $(DIAMETER_TOP)/make/target.mk -EBIN = ../../ebin -include $(DIAMETER_TOP)/make/$(TARGET)/rules.mk -endif - - - -# ---------------------------------------------------- -# Application version -# ---------------------------------------------------- - -include ../../vsn.mk - -VSN=$(DIAMETER_VSN) - -# ---------------------------------------------------- -# Release directory specification -# ---------------------------------------------------- - -RELSYSDIR = $(RELEASE_PATH)/lib/diameter-$(VSN) - -INCDIR = ../../include - -# ---------------------------------------------------- -# Target Specs -# ---------------------------------------------------- - -include modules.mk - -SPEC_MODULES = \ - $(SPEC_FILES:%.dia=%) - -SPEC_ERL_FILES = \ - $(SPEC_FILES:%.dia=%.erl) - -SPEC_HRL_FILES = \ - $(SPEC_FILES:%.dia=%.hrl) - -MODULES = \ - $(RUNTIME_MODULES) \ - $(HELP_MODULES) - -APP_MODULES = \ - $(RUNTIME_MODULES) \ - $(SPEC_MODULES) - -TARGET_MODULES = \ - $(APP_MODULES) \ - $(HELP_MODULES) - -TARGET_FILES = \ - $(TARGET_MODULES:%=$(EBIN)/%.$(EMULATOR)) \ - $(APP_TARGET) \ - $(APPUP_TARGET) - -ESCRIPT_FILES = \ - ../../bin/diameterc - -APP_FILE = diameter.app -APP_SRC = $(APP_FILE).src -APP_TARGET = $(EBIN)/$(APP_FILE) - -APPUP_FILE = diameter.appup -APPUP_SRC = $(APPUP_FILE).src -APPUP_TARGET = $(EBIN)/$(APPUP_FILE) - -# ---------------------------------------------------- -# FLAGS -# ---------------------------------------------------- - -ifeq ($(TYPE),debug) -ERL_COMPILE_FLAGS += -Ddebug -endif - -include diameter.mk - -ERL_COMPILE_FLAGS += \ - $(DIAMETER_ERL_COMPILE_FLAGS) \ - -I$(INCDIR) - -# ---------------------------------------------------- -# Targets -# ---------------------------------------------------- - -debug: - @$(MAKE) TYPE=debug opt - -opt: $(TARGET_FILES) - -clean: - rm -f $(TARGET_FILES) $(SPEC_ERL_FILES) $(SPEC_HRL_FILES) - rm -f $(APP_TARGET) $(APPUP_TARGET) - rm -f errs core *~ diameter_gen_*.forms diameter_gen_*.spec - rm -f depend.mk - -docs: - -info: - @echo "" - @echo "SPEC_FILES = $(FILES)" - @echo "MODULES = $(MODULES)" - @echo "" - @echo "EXTERNAL_HRL_FILES = $(EXTERNAL_HRL_FILES)" - @echo "INTERNAL_HRL_FILES = $(INTERNAL_HRL_FILES)" - @echo "" - @echo "EXAMPLE_FILES = $(EXAMPLE_FILES)" - @echo "" - -# ---------------------------------------------------- -# Special Build Targets -# ---------------------------------------------------- - -# Generate the app file and then modules into in. This shouldn't know -# about ../transport but good enough for now. -$(APP_TARGET): $(APP_SRC) \ - ../../vsn.mk \ - modules.mk \ - ../transport/modules.mk - sed -e 's;%VSN%;$(VSN);' $< > $@ - M=`echo $(APP_MODULES) | sed -e 's/^ *//' -e 's/ *$$//' -e 'y/ /,/'`; \ - echo "/%APP_MODULES%/s//$$M/;w;q" | tr ';' '\n' \ - | ed -s $@ - $(MAKE) -C ../transport $(APP_TARGET) APP_TARGET=$(APP_TARGET) - -$(APPUP_TARGET): $(APPUP_SRC) ../../vsn.mk - sed -e 's;%VSN%;$(VSN);' $< > $@ - -compiler: - $(MAKE) -C ../$@ - -app: $(APP_TARGET) $(APPUP_TARGET) - -# erl/hrl from application spec -diameter_gen_%.erl diameter_gen_%.hrl: diameter_gen_%.dia - ../../bin/diameterc -i $(EBIN) -o $(@D) $< - -# ---------------------------------------------------- -# Release Target -# ---------------------------------------------------- - -ifneq ($(ERL_TOP),) -include $(ERL_TOP)/make/otp_release_targets.mk -else -include $(DIAMETER_TOP)/make/release_targets.mk -endif - -release_spec: opt - $(INSTALL_DIR) $(RELSYSDIR)/bin - $(INSTALL_DIR) $(RELSYSDIR)/ebin - $(INSTALL_DIR) $(RELSYSDIR)/src/app - $(INSTALL_DIR) $(RELSYSDIR)/include - $(INSTALL_DIR) $(RELSYSDIR)/examples - $(INSTALL_SCRIPT) $(ESCRIPT_FILES) $(RELSYSDIR)/bin - $(INSTALL_DATA) $(TARGET_FILES) $(RELSYSDIR)/ebin - $(INSTALL_DATA) $(MODULES:%=%.erl) $(SPEC_ERL_FILES) $(RELSYSDIR)/src/app - $(INSTALL_DATA) $(SPEC_FILES) $(RELSYSDIR)/src/app - $(INSTALL_DATA) $(INTERNAL_HRL_FILES) $(RELSYSDIR)/src/app - $(INSTALL_DATA) $(EXTERNAL_HRL_FILES) $(SPEC_HRL_FILES) $(RELSYSDIR)/include - $(INSTALL_DATA) $(EXAMPLE_FILES) $(RELSYSDIR)/examples - -release_docs_spec: - -# ---------------------------------------------------- -# Dependencies -# ---------------------------------------------------- - -$(SPEC_MODULES:%=$(EBIN)/%.$(EMULATOR)): \ - $(EBIN)/diameter_exprecs.$(EMULATOR) \ - $(DIAMETER_TOP)/include/diameter.hrl \ - $(DIAMETER_TOP)/include/diameter_gen.hrl - -depend: depend.mk - -# Generate dependencies makefile. It's assumed that the compile target -# has already been made since it's currently not smart enough to not -# force a rebuild of those beams dependent on generated hrls, and this -# is a no-no at make release. -depend.mk: depend.sed $(MODULES:%=%.erl) Makefile - (for f in $(MODULES); do \ - sed -f $< $$f.erl | sed "s@/@/$$f@"; \ - done) \ - > $@ - --include depend.mk - -.PRECIOUS: $(SPEC_ERL_FILES) $(SPEC_HRL_FILES) -.PHONY: app clean debug depend info opt compiler release_spec release_docs_spec diff --git a/lib/diameter/src/app/diameter.appup.src b/lib/diameter/src/app/diameter.appup.src deleted file mode 100644 index 6d8ceadb92..0000000000 --- a/lib/diameter/src/app/diameter.appup.src +++ /dev/null @@ -1,47 +0,0 @@ -%% This is an -*- erlang -*- file. -%% -%% %CopyrightBegin% -%% -%% Copyright Ericsson AB 2010-2011. 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% -%% - -{"%VSN%", - [ - {"0.9", - [ - {load_module, diameter, soft_purge, soft_purge, []}, - {load_module, diameter_capx, soft_purge, soft_purge, []}, - {load_module, diameter_codec, soft_purge, soft_purge, [diameter_lib]}, - {load_module, diameter_lib, soft_purge, soft_purge, []}, - {load_module, diameter_types, soft_purge, soft_purge, []}, - {load_module, diameter_gen_base_accounting, soft_purge, soft_purge, []}, - {load_module, diameter_gen_base_rfc3588, soft_purge, soft_purge, []}, - {load_module, diameter_gen_relay, soft_purge, soft_purge, []}, - {update, diameter_service, soft, soft_purge, soft_purge, [diameter_lib]}, - {update, diameter_config, soft, soft_purge, soft_purge, []}, - {update, diameter_peer, soft, soft_purge, soft_purge, []}, - {update, diameter_peer_fsm, soft, soft_purge, soft_purge, [diameter_lib]}, - {update, diameter_reg, soft, soft_purge, soft_purge, []}, - {update, diameter_sctp, soft, soft_purge, soft_purge, []}, - {update, diameter_stats, soft, soft_purge, soft_purge, []}, - {update, diameter_sync, soft, soft_purge, soft_purge, []}, - {update, diameter_watchdog, soft, soft_purge, soft_purge, [diameter_lib]} - ] - } - ], - [ - ] -}. diff --git a/lib/diameter/src/app/diameter.erl b/lib/diameter/src/app/diameter.erl deleted file mode 100644 index 2f721421d8..0000000000 --- a/lib/diameter/src/app/diameter.erl +++ /dev/null @@ -1,190 +0,0 @@ -%% -%% %CopyrightBegin% -%% -%% Copyright Ericsson AB 2010-2011. 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% -%% - --module(diameter). - -%% Configuration. --export([start_service/2, - stop_service/1, - add_transport/2, - remove_transport/2, - subscribe/1, - unsubscribe/1]). - -%% Traffic. --export([session_id/1, - origin_state_id/0, - call/3, - call/4]). - -%% Information. --export([services/0, - service_info/2]). - -%% Start/stop the application. In a "real" application this should -%% typically be a consequence of specifying diameter in a release file -%% rather than by calling start/stop explicitly. --export([start/0, - stop/0]). - --include("diameter_internal.hrl"). --include("diameter_types.hrl"). - -%%% -------------------------------------------------------------------------- -%%% start/0 -%%% -------------------------------------------------------------------------- - --spec start() - -> ok - | {error, term()}. - -start() -> - application:start(?APPLICATION). - -%%% -------------------------------------------------------------------------- -%%% stop/0 -%%% -------------------------------------------------------------------------- - --spec stop() - -> ok - | {error, term()}. - -stop() -> - application:stop(?APPLICATION). - -%%% -------------------------------------------------------------------------- -%%% start_service/2 -%%% -------------------------------------------------------------------------- - --spec start_service(service_name(), [service_opt()]) - -> ok - | {error, term()}. - -start_service(SvcName, Opts) - when is_list(Opts) -> - diameter_config:start_service(SvcName, Opts). - -%%% -------------------------------------------------------------------------- -%%% stop_service/1 -%%% -------------------------------------------------------------------------- - --spec stop_service(service_name()) - -> ok - | {error, term()}. - -stop_service(SvcName) -> - diameter_config:stop_service(SvcName). - -%%% -------------------------------------------------------------------------- -%%% services/0 -%%% -------------------------------------------------------------------------- - --spec services() - -> [service_name()]. - -services() -> - [Name || {Name, _} <- diameter_service:services()]. - -%%% -------------------------------------------------------------------------- -%%% service_info/2 -%%% -------------------------------------------------------------------------- - --spec service_info(service_name(), atom() | [atom()]) - -> any(). - -service_info(SvcName, Option) -> - diameter_service:info(SvcName, Option). - -%%% -------------------------------------------------------------------------- -%%% add_transport/3 -%%% -------------------------------------------------------------------------- - --spec add_transport(service_name(), {listen|connect, [transport_opt()]}) - -> {ok, transport_ref()} - | {error, term()}. - -add_transport(SvcName, {T, Opts} = Cfg) - when is_list(Opts), (T == connect orelse T == listen) -> - diameter_config:add_transport(SvcName, Cfg). - -%%% -------------------------------------------------------------------------- -%%% remove_transport/2 -%%% -------------------------------------------------------------------------- - --spec remove_transport(service_name(), transport_pred()) - -> ok | {error, term()}. - -remove_transport(SvcName, Pred) -> - diameter_config:remove_transport(SvcName, Pred). - -%%% -------------------------------------------------------------------------- -%%% # subscribe(SvcName) -%%% -%%% Description: Subscribe to #diameter_event{} messages for the specified -%%% service. -%%% -------------------------------------------------------------------------- - --spec subscribe(service_name()) - -> true. - -subscribe(SvcName) -> - diameter_service:subscribe(SvcName). - -%%% -------------------------------------------------------------------------- -%%% # unsubscribe(SvcName) -%%% -------------------------------------------------------------------------- - --spec unsubscribe(service_name()) - -> true. - -unsubscribe(SvcName) -> - diameter_service:unsubscribe(SvcName). - -%%% ---------------------------------------------------------- -%%% # session_id/1 -%%% ---------------------------------------------------------- - --spec session_id('DiameterIdentity'()) - -> 'OctetString'(). - -session_id(Ident) -> - diameter_session:session_id(Ident). - -%%% ---------------------------------------------------------- -%%% # origin_state_id/0 -%%% ---------------------------------------------------------- - --spec origin_state_id() - -> 'Unsigned32'(). - -origin_state_id() -> - diameter_session:origin_state_id(). - -%%% -------------------------------------------------------------------------- -%%% # call/[34] -%%% -------------------------------------------------------------------------- - --spec call(service_name(), app_alias(), any(), [call_opt()]) - -> any(). - -call(SvcName, App, Message, Options) -> - diameter_service:call(SvcName, {alias, App}, Message, Options). - -call(SvcName, App, Message) -> - call(SvcName, App, Message, []). diff --git a/lib/diameter/src/app/diameter.mk.in b/lib/diameter/src/app/diameter.mk.in deleted file mode 100644 index c161064303..0000000000 --- a/lib/diameter/src/app/diameter.mk.in +++ /dev/null @@ -1,47 +0,0 @@ -#-*-makefile-*- ; force emacs to enter makefile-mode - -# %CopyrightBegin% -# -# Copyright Ericsson AB 2010-2011. 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% - -DIAMETER_TOP = @DIAMETER_TOP@ - -# ifneq ($(PREFIX),) -# ifeq ($(TESTROOT),) -# TESTROOT = $(PREFIX) -# endif -# endif - -ifeq ($(USE_DIAMETER_TEST_CODE), true) -ERL_COMPILE_FLAGS += -DDIAMETER_TEST_CODE=mona_lisa_spelar_doom -endif - -ifeq ($(USE_DIAMETER_HIPE), true) -ERL_COMPILE_FLAGS += +native -endif - -ifeq ($(WARN_UNUSED_WARS), true) -ERL_COMPILE_FLAGS += +warn_unused_vars -endif - -DIAMETER_APP_VSN_COMPILE_FLAGS = \ - +'{parse_transform,sys_pre_attributes}' \ - +'{attribute,insert,app_vsn,$(APP_VSN)}' - -DIAMETER_ERL_COMPILE_FLAGS += \ - -pa $(DIAMETER_TOP)/ebin \ - $(DIAMETER_APP_VSN_COMPILE_FLAGS) - diff --git a/lib/diameter/src/app/diameter_callback.erl b/lib/diameter/src/app/diameter_callback.erl deleted file mode 100644 index 6d5c8cdca1..0000000000 --- a/lib/diameter/src/app/diameter_callback.erl +++ /dev/null @@ -1,91 +0,0 @@ -%% -%% %CopyrightBegin% -%% -%% Copyright Ericsson AB 2010-2011. 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 minimal application callback module. -%% - --module(diameter_callback). - --export([peer_up/3, - peer_down/3, - pick_peer/4, - prepare_request/3, - prepare_retransmit/3, - handle_request/3, - handle_answer/4, - handle_error/4]). - --include_lib("diameter/include/diameter.hrl"). - -%%% ---------------------------------------------------------- -%%% # peer_up/3 -%%% ---------------------------------------------------------- - -peer_up(_Svc, _Peer, State) -> - State. - -%%% ---------------------------------------------------------- -%%% # peer_down/3 -%%% ---------------------------------------------------------- - -peer_down(_SvcName, _Peer, State) -> - State. - -%%% ---------------------------------------------------------- -%%% # pick_peer/4 -%%% ---------------------------------------------------------- - -pick_peer([Peer|_], _, _SvcName, _State) -> - {ok, Peer}. - -%%% ---------------------------------------------------------- -%%% # prepare_request/3 -%%% ---------------------------------------------------------- - -prepare_request(Pkt, _SvcName, _Peer) -> - {send, Pkt}. - -%%% ---------------------------------------------------------- -%%% # prepare_retransmit/3 -%%% ---------------------------------------------------------- - -prepare_retransmit(Pkt, _SvcName, _Peer) -> - {send, Pkt}. - -%%% ---------------------------------------------------------- -%%% # handle_request/3 -%%% ---------------------------------------------------------- - -handle_request(_Pkt, _SvcName, _Peer) -> - {protocol_error, 3001}. %% DIAMETER_COMMAND_UNSUPPORTED - -%%% ---------------------------------------------------------- -%%% # handle_answer/4 -%%% ---------------------------------------------------------- - -handle_answer(#diameter_packet{msg = Ans}, _Req, _SvcName, _Peer) -> - Ans. - -%%% --------------------------------------------------------------------------- -%%% # handle_error/4 -%%% --------------------------------------------------------------------------- - -handle_error(Reason, _Req, _SvcName, _Peer) -> - {error, Reason}. diff --git a/lib/diameter/src/app/diameter_gen_base_accounting.dia b/lib/diameter/src/app/diameter_gen_base_accounting.dia deleted file mode 100644 index 64e95dddb5..0000000000 --- a/lib/diameter/src/app/diameter_gen_base_accounting.dia +++ /dev/null @@ -1,68 +0,0 @@ -;; -;; %CopyrightBegin% -;; -;; Copyright Ericsson AB 2010-2011. 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% -;; - -@id 3 -@prefix diameter_base_accounting -@vendor 0 IETF - -@inherits diameter_gen_base_rfc3588 - -@messages - - ACR ::= < Diameter Header: 271, REQ, PXY > - < Session-Id > - { Origin-Host } - { Origin-Realm } - { Destination-Realm } - { Accounting-Record-Type } - { Accounting-Record-Number } - [ Acct-Application-Id ] - [ Vendor-Specific-Application-Id ] - [ User-Name ] - [ Accounting-Sub-Session-Id ] - [ Acct-Session-Id ] - [ Acct-Multi-Session-Id ] - [ Acct-Interim-Interval ] - [ Accounting-Realtime-Required ] - [ Origin-State-Id ] - [ Event-Timestamp ] - * [ Proxy-Info ] - * [ Route-Record ] - * [ AVP ] - - ACA ::= < Diameter Header: 271, PXY > - < Session-Id > - { Result-Code } - { Origin-Host } - { Origin-Realm } - { Accounting-Record-Type } - { Accounting-Record-Number } - [ Acct-Application-Id ] - [ Vendor-Specific-Application-Id ] - [ User-Name ] - [ Accounting-Sub-Session-Id ] - [ Acct-Session-Id ] - [ Acct-Multi-Session-Id ] - [ Error-Reporting-Host ] - [ Acct-Interim-Interval ] - [ Accounting-Realtime-Required ] - [ Origin-State-Id ] - [ Event-Timestamp ] - * [ Proxy-Info ] - * [ AVP ] diff --git a/lib/diameter/src/app/diameter_gen_base_rfc3588.dia b/lib/diameter/src/app/diameter_gen_base_rfc3588.dia deleted file mode 100644 index 4a12e21acd..0000000000 --- a/lib/diameter/src/app/diameter_gen_base_rfc3588.dia +++ /dev/null @@ -1,413 +0,0 @@ -;; -;; %CopyrightBegin% -;; -;; Copyright Ericsson AB 2010-2011. 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% -;; - -@id 0 -@prefix diameter_base -@vendor 0 IETF - -@avp_types - - Acct-Interim-Interval 85 Unsigned32 M - Accounting-Realtime-Required 483 Enumerated M - Acct-Multi-Session-Id 50 UTF8String M - Accounting-Record-Number 485 Unsigned32 M - Accounting-Record-Type 480 Enumerated M - Acct-Session-Id 44 OctetString M - Accounting-Sub-Session-Id 287 Unsigned64 M - Acct-Application-Id 259 Unsigned32 M - Auth-Application-Id 258 Unsigned32 M - Auth-Request-Type 274 Enumerated M - Authorization-Lifetime 291 Unsigned32 M - Auth-Grace-Period 276 Unsigned32 M - Auth-Session-State 277 Enumerated M - Re-Auth-Request-Type 285 Enumerated M - Class 25 OctetString M - Destination-Host 293 DiamIdent M - Destination-Realm 283 DiamIdent M - Disconnect-Cause 273 Enumerated M - E2E-Sequence 300 Grouped M - Error-Message 281 UTF8String - - Error-Reporting-Host 294 DiamIdent - - Event-Timestamp 55 Time M - Experimental-Result 297 Grouped M - Experimental-Result-Code 298 Unsigned32 M - Failed-AVP 279 Grouped M - Firmware-Revision 267 Unsigned32 - - Host-IP-Address 257 Address M - Inband-Security-Id 299 Unsigned32 M - Multi-Round-Time-Out 272 Unsigned32 M - Origin-Host 264 DiamIdent M - Origin-Realm 296 DiamIdent M - Origin-State-Id 278 Unsigned32 M - Product-Name 269 UTF8String - - Proxy-Host 280 DiamIdent M - Proxy-Info 284 Grouped M - Proxy-State 33 OctetString M - Redirect-Host 292 DiamURI M - Redirect-Host-Usage 261 Enumerated M - Redirect-Max-Cache-Time 262 Unsigned32 M - Result-Code 268 Unsigned32 M - Route-Record 282 DiamIdent M - Session-Id 263 UTF8String M - Session-Timeout 27 Unsigned32 M - Session-Binding 270 Unsigned32 M - Session-Server-Failover 271 Enumerated M - Supported-Vendor-Id 265 Unsigned32 M - Termination-Cause 295 Enumerated M - User-Name 1 UTF8String M - Vendor-Id 266 Unsigned32 M - Vendor-Specific-Application-Id 260 Grouped M - -@messages - - CER ::= < Diameter Header: 257, REQ > - { Origin-Host } - { Origin-Realm } - 1* { Host-IP-Address } - { Vendor-Id } - { Product-Name } - [ Origin-State-Id ] - * [ Supported-Vendor-Id ] - * [ Auth-Application-Id ] - * [ Inband-Security-Id ] - * [ Acct-Application-Id ] - * [ Vendor-Specific-Application-Id ] - [ Firmware-Revision ] - * [ AVP ] - - CEA ::= < Diameter Header: 257 > - { Result-Code } - { Origin-Host } - { Origin-Realm } - 1* { Host-IP-Address } - { Vendor-Id } - { Product-Name } - [ Origin-State-Id ] - [ Error-Message ] - * [ Failed-AVP ] - * [ Supported-Vendor-Id ] - * [ Auth-Application-Id ] - * [ Inband-Security-Id ] - * [ Acct-Application-Id ] - * [ Vendor-Specific-Application-Id ] - [ Firmware-Revision ] - * [ AVP ] - - DPR ::= < Diameter Header: 282, REQ > - { Origin-Host } - { Origin-Realm } - { Disconnect-Cause } - - DPA ::= < Diameter Header: 282 > - { Result-Code } - { Origin-Host } - { Origin-Realm } - [ Error-Message ] - * [ Failed-AVP ] - - DWR ::= < Diameter Header: 280, REQ > - { Origin-Host } - { Origin-Realm } - [ Origin-State-Id ] - - DWA ::= < Diameter Header: 280 > - { Result-Code } - { Origin-Host } - { Origin-Realm } - [ Error-Message ] - * [ Failed-AVP ] - [ Origin-State-Id ] - - answer-message ::= < Diameter Header: code, ERR [PXY] > - 0*1< Session-Id > - { Origin-Host } - { Origin-Realm } - { Result-Code } - [ Origin-State-Id ] - [ Error-Reporting-Host ] - [ Proxy-Info ] - * [ AVP ] - - RAR ::= < Diameter Header: 258, REQ, PXY > - < Session-Id > - { Origin-Host } - { Origin-Realm } - { Destination-Realm } - { Destination-Host } - { Auth-Application-Id } - { Re-Auth-Request-Type } - [ User-Name ] - [ Origin-State-Id ] - * [ Proxy-Info ] - * [ Route-Record ] - * [ AVP ] - - RAA ::= < Diameter Header: 258, PXY > - < Session-Id > - { Result-Code } - { Origin-Host } - { Origin-Realm } - [ User-Name ] - [ Origin-State-Id ] - [ Error-Message ] - [ Error-Reporting-Host ] - * [ Failed-AVP ] - * [ Redirect-Host ] - [ Redirect-Host-Usage ] - [ Redirect-Max-Cache-Time ] - * [ Proxy-Info ] - * [ AVP ] - - STR ::= < Diameter Header: 275, REQ, PXY > - < Session-Id > - { Origin-Host } - { Origin-Realm } - { Destination-Realm } - { Auth-Application-Id } - { Termination-Cause } - [ User-Name ] - [ Destination-Host ] - * [ Class ] - [ Origin-State-Id ] - * [ Proxy-Info ] - * [ Route-Record ] - * [ AVP ] - - STA ::= < Diameter Header: 275, PXY > - < Session-Id > - { Result-Code } - { Origin-Host } - { Origin-Realm } - [ User-Name ] - * [ Class ] - [ Error-Message ] - [ Error-Reporting-Host ] - * [ Failed-AVP ] - [ Origin-State-Id ] - * [ Redirect-Host ] - [ Redirect-Host-Usage ] - [ Redirect-Max-Cache-Time ] - * [ Proxy-Info ] - * [ AVP ] - - ASR ::= < Diameter Header: 274, REQ, PXY > - < Session-Id > - { Origin-Host } - { Origin-Realm } - { Destination-Realm } - { Destination-Host } - { Auth-Application-Id } - [ User-Name ] - [ Origin-State-Id ] - * [ Proxy-Info ] - * [ Route-Record ] - * [ AVP ] - - ASA ::= < Diameter Header: 274, PXY > - < Session-Id > - { Result-Code } - { Origin-Host } - { Origin-Realm } - [ User-Name ] - [ Origin-State-Id ] - [ Error-Message ] - [ Error-Reporting-Host ] - * [ Failed-AVP ] - * [ Redirect-Host ] - [ Redirect-Host-Usage ] - [ Redirect-Max-Cache-Time ] - * [ Proxy-Info ] - * [ AVP ] - - ACR ::= < Diameter Header: 271, REQ, PXY > - < Session-Id > - { Origin-Host } - { Origin-Realm } - { Destination-Realm } - { Accounting-Record-Type } - { Accounting-Record-Number } - [ Acct-Application-Id ] - [ Vendor-Specific-Application-Id ] - [ User-Name ] - [ Accounting-Sub-Session-Id ] - [ Acct-Session-Id ] - [ Acct-Multi-Session-Id ] - [ Acct-Interim-Interval ] - [ Accounting-Realtime-Required ] - [ Origin-State-Id ] - [ Event-Timestamp ] - * [ Proxy-Info ] - * [ Route-Record ] - * [ AVP ] - - ACA ::= < Diameter Header: 271, PXY > - < Session-Id > - { Result-Code } - { Origin-Host } - { Origin-Realm } - { Accounting-Record-Type } - { Accounting-Record-Number } - [ Acct-Application-Id ] - [ Vendor-Specific-Application-Id ] - [ User-Name ] - [ Accounting-Sub-Session-Id ] - [ Acct-Session-Id ] - [ Acct-Multi-Session-Id ] - [ Error-Reporting-Host ] - [ Acct-Interim-Interval ] - [ Accounting-Realtime-Required ] - [ Origin-State-Id ] - [ Event-Timestamp ] - * [ Proxy-Info ] - * [ AVP ] - -@enum Disconnect-Cause - - REBOOTING 0 - BUSY 1 - DO_NOT_WANT_TO_TALK_TO_YOU 2 - -@enum Redirect-Host-Usage - - DONT_CACHE 0 - ALL_SESSION 1 - ALL_REALM 2 - REALM_AND_APPLICATION 3 - ALL_APPLICATION 4 - ALL_HOST 5 - ALL_USER 6 - -@enum Auth-Request-Type - - AUTHENTICATE_ONLY 1 - AUTHORIZE_ONLY 2 - AUTHORIZE_AUTHENTICATE 3 - -@enum Auth-Session-State - - STATE_MAINTAINED 0 - NO_STATE_MAINTAINED 1 - -@enum Re-Auth-Request-Type - - AUTHORIZE_ONLY 0 - AUTHORIZE_AUTHENTICATE 1 - -@enum Termination-Cause - - DIAMETER_LOGOUT 1 - DIAMETER_SERVICE_NOT_PROVIDED 2 - DIAMETER_BAD_ANSWER 3 - DIAMETER_ADMINISTRATIVE 4 - DIAMETER_LINK_BROKEN 5 - DIAMETER_AUTH_EXPIRED 6 - DIAMETER_USER_MOVED 7 - DIAMETER_SESSION_TIMEOUT 8 - -@enum Session-Server-Failover - - REFUSE_SERVICE 0 - TRY_AGAIN 1 - ALLOW_SERVICE 2 - TRY_AGAIN_ALLOW_SERVICE 3 - -@enum Accounting-Record-Type - - EVENT_RECORD 1 - START_RECORD 2 - INTERIM_RECORD 3 - STOP_RECORD 4 - -@enum Accounting-Realtime-Required - - DELIVER_AND_GRANT 1 - GRANT_AND_STORE 2 - GRANT_AND_LOSE 3 - -@result_code Result-Code - -;; 7.1.1. Informational - DIAMETER_MULTI_ROUND_AUTH 1001 - -;; 7.1.2. Success - DIAMETER_SUCCESS 2001 - DIAMETER_LIMITED_SUCCESS 2002 - -;; 7.1.3. Protocol Errors - DIAMETER_COMMAND_UNSUPPORTED 3001 - DIAMETER_UNABLE_TO_DELIVER 3002 - DIAMETER_REALM_NOT_SERVED 3003 - DIAMETER_TOO_BUSY 3004 - DIAMETER_LOOP_DETECTED 3005 - DIAMETER_REDIRECT_INDICATION 3006 - DIAMETER_APPLICATION_UNSUPPORTED 3007 - DIAMETER_INVALID_HDR_BITS 3008 - DIAMETER_INVALID_AVP_BITS 3009 - DIAMETER_UNKNOWN_PEER 3010 - -;; 7.1.4. Transient Failures - DIAMETER_AUTHENTICATION_REJECTED 4001 - DIAMETER_OUT_OF_SPACE 4002 - ELECTION_LOST 4003 - -;; 7.1.5. Permanent Failures - DIAMETER_AVP_UNSUPPORTED 5001 - DIAMETER_UNKNOWN_SESSION_ID 5002 - DIAMETER_AUTHORIZATION_REJECTED 5003 - DIAMETER_INVALID_AVP_VALUE 5004 - DIAMETER_MISSING_AVP 5005 - DIAMETER_RESOURCES_EXCEEDED 5006 - DIAMETER_CONTRADICTING_AVPS 5007 - DIAMETER_AVP_NOT_ALLOWED 5008 - DIAMETER_AVP_OCCURS_TOO_MANY_TIMES 5009 - DIAMETER_NO_COMMON_APPLICATION 5010 - DIAMETER_UNSUPPORTED_VERSION 5011 - DIAMETER_UNABLE_TO_COMPLY 5012 - DIAMETER_INVALID_BIT_IN_HEADER 5013 - DIAMETER_INVALID_AVP_LENGTH 5014 - DIAMETER_INVALID_MESSAGE_LENGTH 5015 - DIAMETER_INVALID_AVP_BIT_COMBO 5016 - DIAMETER_NO_COMMON_SECURITY 5017 - -@grouped - - Proxy-Info ::= < AVP Header: 284 > - { Proxy-Host } - { Proxy-State } - * [ AVP ] - - Failed-AVP ::= < AVP Header: 279 > - 1* {AVP} - - Experimental-Result ::= < AVP Header: 297 > - { Vendor-Id } - { Experimental-Result-Code } - - Vendor-Specific-Application-Id ::= < AVP Header: 260 > - 1* { Vendor-Id } - [ Auth-Application-Id ] - [ Acct-Application-Id ] - -;; The E2E-Sequence AVP is defined in RFC 3588 as Grouped, but -;; there is no definition of the group - only an informal text stating -;; that there should be a nonce (an OctetString) and a counter -;; (integer) -;; - E2E-Sequence ::= <AVP Header: 300 > - 2* { AVP } diff --git a/lib/diameter/src/app/diameter_peer_fsm.erl b/lib/diameter/src/app/diameter_peer_fsm.erl deleted file mode 100644 index 0252fb3809..0000000000 --- a/lib/diameter/src/app/diameter_peer_fsm.erl +++ /dev/null @@ -1,746 +0,0 @@ -%% -%% %CopyrightBegin% -%% -%% Copyright Ericsson AB 2010-2011. 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% -%% - -%% -%% This module implements (as a process) the RFC 3588 Peer State -%% Machine modulo the necessity of adapting the peer election to the -%% fact that we don't know the identity of a peer until we've -%% received a CER/CEA from it. -%% - --module(diameter_peer_fsm). --behaviour(gen_server). - -%% Interface towards diameter_watchdog. --export([start/3]). - -%% gen_server callbacks --export([init/1, - handle_call/3, - handle_cast/2, - handle_info/2, - terminate/2, - code_change/3]). - -%% diameter_peer_fsm_sup callback --export([start_link/1]). - -%% internal callbacks --export([match/1]). - --include_lib("diameter/include/diameter.hrl"). --include("diameter_internal.hrl"). --include("diameter_types.hrl"). --include("diameter_gen_base_rfc3588.hrl"). - --define(GOAWAY, ?'DIAMETER_BASE_DISCONNECT-CAUSE_DO_NOT_WANT_TO_TALK_TO_YOU'). --define(REBOOT, ?'DIAMETER_BASE_DISCONNECT-CAUSE_REBOOTING'). - --define(LOOP_TIMEOUT, 2000). - -%% RFC 3588: -%% -%% Timeout An application-defined timer has expired while waiting -%% for some event. -%% --define(EVENT_TIMEOUT, 10000). - -%% How long to wait for a DPA in response to DPR before simply -%% aborting. Used to distinguish between shutdown and not but there's -%% not really any need. Stopping a service will require a timeout if -%% the peer doesn't answer DPR so the value should be short-ish. --define(DPA_TIMEOUT, 1000). - --record(state, - {state = 'Wait-Conn-Ack' %% state of RFC 3588 Peer State Machine - :: 'Wait-Conn-Ack' | recv_CER | 'Wait-CEA' | 'Open', - mode :: accept | connect | {connect, reference()}, - parent :: pid(), - transport :: pid(), - service :: #diameter_service{}, - dpr = false :: false | {'Unsigned32'(), 'Unsigned32'()}}). - %% | hop by hop and end to end identifiers - -%% 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 -%% know who we're talking to until either a CER or CEA has been -%% received. The CEA problem in particular makes it impossible to -%% follow the state machine exactly as documented in 3588: there can -%% be no election until the CEA arrives and we have an Origin-Host to -%% elect. - -%% -%% Once upon a time start/2 started a process akin to that started by -%% start/3 below, which in turn started a watchdog/transport process -%% with the result that the watchdog could send DWR/DWA regardless of -%% whether or not the corresponding Peer State Machine was in its open -%% state; that is, before capabilities exchange had taken place. This -%% is not what RFC's 3588 and 3539 say (albeit not very clearly). -%% Watchdog messages are only exchanged on *open* connections, so the -%% 3539 state machine is more naturally placed on top of the 3588 Peer -%% State Machine rather than closer to the transport. This is what we -%% now do below: connect/accept call diameter_watchdog and return the -%% pid of the watchdog process, and the watchdog in turn calls start/3 -%% below to start the process implementing the Peer State Machine. The -%% former is a "peer" in diameter_service while the latter is a -%% "conn". In a sense, diameter_service sees the watchdog as -%% implementing the Peer State Machine and the process implemented -%% here as being the transport, not being aware of the watchdog at -%% all. -%% - -%%% --------------------------------------------------------------------------- -%%% # start({connect|accept, Ref}, Opts, Service) -%%% -%%% Output: Pid -%%% --------------------------------------------------------------------------- - -%% diameter_config requires a non-empty list of applications on the -%% service but diameter_service then constrains the list to any -%% specified on the transport in question. Check here that the list is -%% still non-empty. - -start({_, Ref} = Type, Opts, #diameter_service{applications = Apps} = Svc) -> - [] /= Apps orelse ?ERROR({no_apps, Type, Opts}), - T = {self(), Type, Opts, Svc}, - {ok, Pid} = diameter_peer_fsm_sup:start_child(T), - diameter_stats:reg(Pid, Ref), - Pid. - -start_link(T) -> - {ok, _} = proc_lib:start_link(?MODULE, - init, - [T], - infinity, - diameter_lib:spawn_opts(server, [])). - -%%% --------------------------------------------------------------------------- -%%% --------------------------------------------------------------------------- - -%% init/1 - -init(T) -> - proc_lib:init_ack({ok, self()}), - gen_server:enter_loop(?MODULE, [], i(T)). - -i({WPid, {M, _} = T, Opts, #diameter_service{capabilities = Caps} = Svc0}) -> - putr(dwa, dwa(Caps)), - {ok, TPid, Svc} = start_transport(T, Opts, Svc0), - erlang:monitor(process, TPid), - erlang:monitor(process, WPid), - #state{parent = WPid, - transport = TPid, - mode = M, - service = Svc}. -%% 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 -%% sending capabilities exchange messages. -%% -%% Invalid transport config may cause us to crash but note that the -%% watchdog start (start/2) succeeds regardless so as not to crash the -%% service. - -start_transport(T, Opts, Svc) -> - case diameter_peer:start(T, Opts, Svc) of - {ok, TPid} -> - {ok, TPid, Svc}; - {ok, TPid, [_|_] = Addrs} -> - #diameter_service{capabilities = Caps0} = Svc, - Caps = Caps0#diameter_caps{host_ip_address = Addrs}, - {ok, TPid, Svc#diameter_service{capabilities = Caps}}; - No -> - exit({shutdown, No}) - end. - -%% handle_call/3 - -handle_call(_, _, State) -> - {reply, nok, State}. - -%% handle_cast/2 - -handle_cast(_, State) -> - {noreply, State}. - -%% handle_info/1 - -handle_info(T, #state{} = State) -> - try transition(T, State) of - ok -> - {noreply, State}; - #state{state = X} = S -> - ?LOGC(X =/= State#state.state, transition, X), - {noreply, S}; - {stop, Reason} -> - ?LOG(stop, Reason), - x(Reason, State); - stop -> - ?LOG(stop, T), - x(T, State) - catch - throw: {?MODULE, close = C, Reason} -> - ?LOG(C, {Reason, T}), - x(Reason, State); - throw: {?MODULE, abort, Reason} -> - {stop, {shutdown, Reason}, State} - end. - -x(Reason, #state{} = S) -> - close_wd(Reason, S), - {stop, {shutdown, Reason}, S}. - -%% terminate/2 - -terminate(_, _) -> - ok. - -%% code_change/3 - -code_change(_, State, _) -> - {ok, State}. - -%%% --------------------------------------------------------------------------- -%%% --------------------------------------------------------------------------- - -putr(Key, Val) -> - put({?MODULE, Key}, Val). - -getr(Key) -> - get({?MODULE, Key}). - -%% transition/2 - -%% Connection to peer. -transition({diameter, {TPid, connected, Remote}}, - #state{state = PS, - mode = M} - = S) -> - 'Wait-Conn-Ack' = PS, %% assert - connect = M, %% - send_CER(S#state{mode = {M, Remote}, - transport = TPid}); - -%% Connection from peer. -transition({diameter, {TPid, connected}}, - #state{state = PS, - mode = M, - parent = Pid} - = S) -> - 'Wait-Conn-Ack' = PS, %% assert - accept = M, %% - Pid ! {accepted, self()}, - start_timer(S#state{state = recv_CER, - transport = TPid}); - -%% Incoming message from the transport. -transition({diameter, {recv, Pkt}}, S) -> - recv(Pkt, S); - -%% Timeout when still in the same state ... -transition({timeout, PS}, #state{state = PS}) -> - stop; - -%% ... or not. -transition({timeout, _}, _) -> - ok; - -%% Outgoing message. -transition({send, Msg}, #state{transport = TPid}) -> - send(TPid, Msg), - ok; - -%% Request for graceful shutdown. -transition({shutdown, Pid}, #state{parent = Pid, dpr = false} = S) -> - dpr(?GOAWAY, S); -transition({shutdown, Pid}, #state{parent = Pid}) -> - ok; - -%% Application shutdown. -transition(shutdown, #state{dpr = false} = S) -> - dpr(?REBOOT, S); -transition(shutdown, _) -> %% DPR already send: ensure expected timeout - dpa_timer(), - ok; - -%% Request to close the transport connection. -transition({close = T, Pid}, #state{parent = Pid, - transport = TPid} - = S) -> - diameter_peer:close(TPid), - close(T,S); - -%% DPA reception has timed out. -transition(dpa_timeout, _) -> - stop; - -%% Someone wants to know a resolved port: forward to the transport process. -transition({resolve_port, _Pid} = T, #state{transport = TPid}) -> - TPid ! T, - ok; - -%% Parent or transport has died. -transition({'DOWN', _, process, P, _}, - #state{parent = Pid, - transport = TPid}) - when P == Pid; - P == TPid -> - stop; - -%% State query. -transition({state, Pid}, #state{state = S, transport = TPid}) -> - Pid ! {self(), [S, TPid]}, - ok. - -%% Crash on anything unexpected. - -%% send_CER/1 - -send_CER(#state{mode = {connect, Remote}, - service = #diameter_service{capabilities = Caps}, - transport = TPid} - = S) -> - req_send_CER(Caps#diameter_caps.origin_host, Remote) - orelse - close(connected, S), - CER = build_CER(S), - ?LOG(send, 'CER'), - send(TPid, encode(CER)), - start_timer(S#state{state = 'Wait-CEA'}). - -%% Register ourselves as connecting to the remote endpoint in -%% question. This isn't strictly necessary since a peer implementing -%% the 3588 Peer State Machine should reject duplicate connection's -%% from the same peer but there's little point in us setting up a -%% duplicate connection in the first place. This could also include -%% the transport protocol being used but since we're blind to -%% transport just avoid duplicate connections to the same host/port. -req_send_CER(OriginHost, Remote) -> - register_everywhere({?MODULE, connection, OriginHost, {remote, Remote}}). - -%% start_timer/1 - -start_timer(#state{state = PS} = S) -> - erlang:send_after(?EVENT_TIMEOUT, self(), {timeout, PS}), - S. - -%% build_CER/1 - -build_CER(#state{service = #diameter_service{capabilities = Caps}}) -> - {ok, CER} = diameter_capx:build_CER(Caps), - CER. - -%% encode/1 - -encode(Rec) -> - #diameter_packet{bin = Bin} = diameter_codec:encode(?BASE, Rec), - Bin. - -%% recv/2 - -%% RFC 3588 has result code 5015 for an invalid length but if a -%% transport is detecting message boundaries using the length header -%% then a length error will likely lead to further errors. - -recv(#diameter_packet{header = #diameter_header{length = Len} - = Hdr, - bin = Bin}, - S) - when Len < 20; - (0 /= Len rem 4 orelse bit_size(Bin) /= 8*Len) -> - discard(invalid_message_length, recv, [size(Bin), - bit_size(Bin) rem 8, - Hdr, - S]); - -recv(#diameter_packet{header = #diameter_header{} = Hdr} - = Pkt, - #state{parent = Pid} - = S) -> - Name = diameter_codec:msg_name(Hdr), - Pid ! {recv, self(), Name, Pkt}, - diameter_stats:incr({msg_id(Name, Hdr), recv}), %% count received - rcv(Name, Pkt, S); - -recv(#diameter_packet{header = undefined, - bin = Bin} - = Pkt, - S) -> - recv(Pkt#diameter_packet{header = diameter_codec:decode_header(Bin)}, S); - -recv(Bin, S) - when is_binary(Bin) -> - recv(#diameter_packet{bin = Bin}, S); - -recv(#diameter_packet{header = false} = Pkt, S) -> - discard(truncated_header, recv, [Pkt, S]). - -msg_id({_,_,_} = T, _) -> - T; -msg_id(_, Hdr) -> - diameter_codec:msg_id(Hdr). - -%% Treat invalid length as a transport error and die. Especially in -%% the TCP case, in which there's no telling where the next message -%% begins in the incoming byte stream, keeping a crippled connection -%% alive may just make things worse. - -discard(Reason, F, A) -> - diameter_stats:incr(Reason), - diameter_lib:warning_report(Reason, {?MODULE, F, A}), - throw({?MODULE, abort, Reason}). - -%% rcv/3 - -%% Incoming CEA. -rcv('CEA', Pkt, #state{state = 'Wait-CEA'} = S) -> - handle_CEA(Pkt, S); - -%% Incoming CER -rcv('CER' = N, Pkt, #state{state = recv_CER} = S) -> - handle_request(N, Pkt, S); - -%% Anything but CER/CEA in a non-Open state is an error, as is -%% CER/CEA in anything but recv_CER/Wait-CEA. -rcv(Name, _, #state{state = PS} = S) - when PS /= 'Open'; - Name == 'CER'; - Name == 'CEA' -> - close({Name, PS}, S); - -rcv(N, Pkt, S) - when N == 'DWR'; - N == 'DPR' -> - handle_request(N, Pkt, S); - -%% DPA even though we haven't sent DPR: ignore. -rcv('DPA', _Pkt, #state{dpr = false}) -> - ok; - -%% DPA in response to DPR. We could check the sequence numbers but -%% don't bother, just close. -rcv('DPA' = N, _Pkt, #state{transport = TPid}) -> - diameter_peer:close(TPid), - {stop, N}; - -rcv(_, _, _) -> - ok. - -%% 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). - -%% handle_request/3 - -handle_request(Type, #diameter_packet{} = Pkt, S) -> - ?LOG(recv, Type), - send_answer(Type, diameter_codec:decode(?BASE, Pkt), S). - -%% send_answer/3 - -send_answer(Type, ReqPkt, #state{transport = TPid} = S) -> - #diameter_packet{header = #diameter_header{version = V, - end_to_end_id = Eid, - hop_by_hop_id = Hid, - is_proxiable = P}, - transport_data = TD} - = ReqPkt, - - {Answer, PostF} = build_answer(Type, V, ReqPkt, S), - - Pkt = #diameter_packet{header = #diameter_header{version = V, - end_to_end_id = Eid, - hop_by_hop_id = Hid, - is_proxiable = P}, - msg = Answer, - transport_data = TD}, - - send(TPid, diameter_codec:encode(?BASE, Pkt)), - eval(PostF, S). - -eval([F|A], S) -> - apply(F, A ++ [S]); -eval(ok, S) -> - S. - -%% build_answer/4 - -build_answer('CER', - ?DIAMETER_VERSION, - #diameter_packet{msg = CER, - header = #diameter_header{is_error = false}, - errors = []} - = Pkt, - #state{service = Svc} - = S) -> - #diameter_service{capabilities = #diameter_caps{origin_host = OH}} - = Svc, - - {SupportedApps, #diameter_caps{origin_host = DH} = RCaps, CEA} - = recv_CER(CER, S), - - try - [] == SupportedApps - andalso ?THROW({no_common_application, 5010}), - register_everywhere({?MODULE, connection, OH, DH}) - orelse ?THROW({election_lost, 4003}), - {CEA, [fun open/4, Pkt, SupportedApps, RCaps]} - catch - ?FAILURE({Reason, RC}) -> - {answer('CER', S) ++ [{'Result-Code', RC}], - [fun close/2, {'CER', Reason, DH}]} - end; - -%% The error checks below are similar to those in diameter_service for -%% other messages. Should factor out the commonality. - -build_answer(Type, V, #diameter_packet{header = H, errors = Es} = Pkt, S) -> - FailedAvp = failed_avp([A || {_,A} <- Es]), - Ans = answer(answer(Type, S), V, H, Es), - {set(Ans, FailedAvp), if 'CER' == Type -> - [fun close/2, {Type, V, Pkt}]; - true -> - ok - end}. - -failed_avp([] = No) -> - No; -failed_avp(Avps) -> - [{'Failed-AVP', [[{'AVP', Avps}]]}]. - -set(Ans, []) -> - Ans; -set(['answer-message' | _] = Ans, FailedAvp) -> - Ans ++ [{'AVP', [FailedAvp]}]; -set([_|_] = Ans, FailedAvp) -> - Ans ++ FailedAvp. - -answer([_, OH, OR | _], _, #diameter_header{is_error = true}, _) -> - ['answer-message', OH, OR, {'Result-Code', 3008}]; - -answer([_, OH, OR | _], _, _, [Bs|_]) - when is_bitstring(Bs) -> - ['answer-message', OH, OR, {'Result-Code', 3009}]; - -answer(Ans, ?DIAMETER_VERSION, _, Es) -> - Ans ++ [{'Result-Code', rc(Es)}]; - -answer(Ans, _, _, _) -> - Ans ++ [{'Result-Code', 5011}]. %% DIAMETER_UNSUPPORTED_VERSION - -rc([]) -> - 2001; %% DIAMETER_SUCCESS -rc([{RC,_}|_]) -> - RC; -rc([RC|_]) -> - RC. - -%% DIAMETER_INVALID_HDR_BITS 3008 -%% A request was received whose bits in the Diameter header were -%% either set to an invalid combination, or to a value that is -%% inconsistent with the command code's definition. - -%% 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. - -%% ELECTION_LOST 4003 -%% The peer has determined that it has lost the election process and -%% has therefore disconnected the transport connection. - -%% DIAMETER_NO_COMMON_APPLICATION 5010 -%% This error is returned when a CER message is received, and there -%% are no common applications supported between the peers. - -%% DIAMETER_UNSUPPORTED_VERSION 5011 -%% This error is returned when a request was received, whose version -%% number is unsupported. - -%% answer/2 - -answer('DWR', _) -> - getr(dwa); - -answer(Name, #state{service = #diameter_service{capabilities = Caps}}) -> - a(Name, Caps). - -a('CER', #diameter_caps{vendor_id = Vid, - origin_host = Host, - origin_realm = Realm, - host_ip_address = Addrs, - product_name = Name}) -> - ['CEA', {'Origin-Host', Host}, - {'Origin-Realm', Realm}, - {'Host-IP-Address', Addrs}, - {'Vendor-Id', Vid}, - {'Product-Name', Name}]; - -a('DPR', #diameter_caps{origin_host = Host, - origin_realm = Realm}) -> - ['DPA', {'Origin-Host', Host}, - {'Origin-Realm', Realm}]. - -%% recv_CER/2 - -recv_CER(CER, #state{service = Svc}) -> - {ok, T} = diameter_capx:recv_CER(CER, Svc), - T. - -%% handle_CEA/1 - -handle_CEA(#diameter_packet{header = #diameter_header{version = V}, - bin = Bin} - = Pkt, - #state{service = Svc} - = S) - when is_binary(Bin) -> - ?LOG(recv, 'CEA'), - - ?DIAMETER_VERSION == V orelse close({version, V}, S), - - #diameter_packet{msg = CEA, errors = Errors} - = DPkt - = diameter_codec:decode(?BASE, Pkt), - - [] == Errors orelse close({errors, Errors}, S), - - {SApps, #diameter_caps{origin_host = DH} = RCaps} = recv_CEA(CEA, S), - - %% 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 - %% receive a CER/CEA, the first that arrives wins the right to a - %% connection with the peer. - - #diameter_service{capabilities = #diameter_caps{origin_host = OH}} - = Svc, - - register_everywhere({?MODULE, connection, OH, DH}) - orelse - close({'CEA', DH}, S), - - open(DPkt, SApps, RCaps, S). - -%% recv_CEA/2 - -recv_CEA(CEA, #state{service = Svc} = S) -> - case diameter_capx:recv_CEA(CEA, Svc) of - {ok, {[], _}} -> - close({'CEA', no_common_application}, S); - {ok, T} -> - T; - {error, Reason} -> - close({'CEA', Reason}, S) - end. - -%% open/4 - -open(Pkt, SupportedApps, RCaps, #state{parent = Pid, - service = Svc} - = S) -> - #diameter_service{capabilities = #diameter_caps{origin_host = OH} - = LCaps} - = Svc, - #diameter_caps{origin_host = DH} - = RCaps, - Pid ! {open, self(), {OH,DH}, {capz(LCaps, RCaps), SupportedApps, Pkt}}, - S#state{state = 'Open'}. - -capz(#diameter_caps{} = L, #diameter_caps{} = R) -> - #diameter_caps{} - = list_to_tuple([diameter_caps | lists:zip(tl(tuple_to_list(L)), - tl(tuple_to_list(R)))]). - -%% close/2 - -%% Tell the watchdog that our death isn't due to transport failure. -close(Reason, #state{parent = Pid}) -> - close_wd(Reason, Pid), - throw({?MODULE, close, Reason}). - -%% close_wd/2 - -%% Ensure the watchdog dies if DPR has been sent ... -close_wd(_, #state{dpr = false}) -> - ok; -close_wd(Reason, #state{parent = Pid}) -> - close_wd(Reason, Pid); - -%% ... or otherwise -close_wd(Reason, Pid) -> - Pid ! {close, self(), Reason}. - -%% 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 - -dpr(Cause, #state{transport = TPid, - service = #diameter_service{capabilities = Caps}} - = S) -> - #diameter_caps{origin_host = OH, - origin_realm = OR} - = Caps, - - Bin = encode(['DPR', {'Origin-Host', OH}, - {'Origin-Realm', OR}, - {'Disconnect-Cause', Cause}]), - send(TPid, Bin), - dpa_timer(), - ?LOG(send, 'DPR'), - S#state{dpr = diameter_codec:sequence_numbers(Bin)}. - -dpa_timer() -> - erlang:send_after(?DPA_TIMEOUT, self(), dpa_timeout). - -%% register_everywhere/1 -%% -%% Register a term and ensure it's not registered elsewhere. Note that -%% two process that simultaneously register the same term may well -%% both fail to do so this isn't foolproof. - -register_everywhere(T) -> - diameter_reg:add_new(T) - andalso unregistered(T). - -unregistered(T) -> - {ResL, _} = rpc:multicall(?MODULE, match, [{node(), T}]), - lists:all(fun(L) -> [] == L end, ResL). - -match({Node, _}) - when Node == node() -> - []; -match({_, T}) -> - try - diameter_reg:match(T) - catch - _:_ -> [] - end. diff --git a/lib/diameter/src/app/diameter_reg.erl b/lib/diameter/src/app/diameter_reg.erl deleted file mode 100644 index 882b9da238..0000000000 --- a/lib/diameter/src/app/diameter_reg.erl +++ /dev/null @@ -1,327 +0,0 @@ -%% -%% %CopyrightBegin% -%% -%% Copyright Ericsson AB 2010-2011. 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% -%% - -%% -%% The module implements a simple term -> pid registry. -%% - --module(diameter_reg). --compile({no_auto_import, [monitor/2]}). - --behaviour(gen_server). - --export([add/1, - add_new/1, - del/1, - repl/2, - match/1]). - --export([start_link/0]). - -%% gen_server callbacks --export([init/1, - terminate/2, - handle_call/3, - handle_cast/2, - handle_info/2, - code_change/3]). - -%% test --export([pids/0, - terms/0]). - -%% debug --export([state/0, - uptime/0]). - --include("diameter_internal.hrl"). - --define(SERVER, ?MODULE). --define(TABLE, ?MODULE). - -%% Table entry used to keep from starting more than one monitor on the -%% same process. This isn't a problem but there's no point in starting -%% multiple monitors if we can avoid it. Note that we can't have a 2-tuple -%% keyed on Pid since a registered term can be anything. Want the entry -%% keyed on Pid so that lookup is fast. --define(MONITOR(Pid, MRef), {Pid, monitor, MRef}). - -%% Table entry containing the Term -> Pid mapping. --define(MAPPING(Term, Pid), {Term, Pid}). - --record(state, {id = now()}). - -%%% ---------------------------------------------------------- -%%% # add(T) -%%% -%%% Input: Term = term() -%%% -%%% Output: true -%%% -%%% Description: Associate the specified term with self(). The list of pids -%%% having this or other assocations can be retrieved using -%%% match/1. -%%% -%%% An association is removed when the calling process dies -%%% or as a result of calling del/1. Adding the same term -%%% more than once is equivalent to adding it exactly once. -%%% -%%% Note that since match/1 takes a pattern as argument, -%%% specifying a term that contains match variables is -%%% probably not a good idea -%%% ---------------------------------------------------------- - --spec add(any()) - -> true. - -add(T) -> - call({add, fun ets:insert/2, T, self()}). - -%%% ---------------------------------------------------------- -%%% # add_new(T) -%%% -%%% Input: T = term() -%%% -%%% Output: true | false -%%% -%%% Description: Like add/1 but only one process is allowed to have the -%%% the association, false being returned if an association -%%% already exists. -%%% ---------------------------------------------------------- - --spec add_new(any()) - -> boolean(). - -add_new(T) -> - call({add, fun insert_new/2, T, self()}). - -%%% ---------------------------------------------------------- -%%% # repl(T, NewT) -%%% -%%% Input: T, NewT = term() -%%% -%%% Output: true | false -%%% -%%% Description: Like add/1 but only replace an existing association on T, -%%% false being returned if it doesn't exist. -%%% ---------------------------------------------------------- - --spec repl(any(), any()) - -> boolean(). - -repl(T, U) -> - call({repl, T, U, self()}). - -%%% ---------------------------------------------------------- -%%% # del(Term) -%%% -%%% Input: Term = term() -%%% -%%% Output: true -%%% -%%% Description: Remove any existing association of Term with self(). -%%% ---------------------------------------------------------- - --spec del(any()) - -> true. - -del(T) -> - call({del, T, self()}). - -%%% ---------------------------------------------------------- -%%% # match(Pat) -%%% -%%% Input: Pat = pattern in the sense of ets:match_object/2. -%%% -%%% Output: list of {Term, Pid} -%%% -%%% Description: Return the list of associations whose Term, as specified -%%% to add/1 or add_new/1, matches the specified pattern. -%%% -%%% Note that there's no guarantee that the returned processes -%%% are still alive. (Although one that isn't will soon have -%%% its associations removed.) -%%% ---------------------------------------------------------- - --spec match(tuple()) - -> [{term(), pid()}]. - -match(Pat) -> - ets:match_object(?TABLE, ?MAPPING(Pat, '_')). - -%% --------------------------------------------------------- -%% EXPORTED INTERNAL FUNCTIONS -%% --------------------------------------------------------- - -start_link() -> - ServerName = {local, ?SERVER}, - Options = [{spawn_opt, diameter_lib:spawn_opts(server, [])}], - gen_server:start_link(ServerName, ?MODULE, [], Options). - -state() -> - call(state). - -uptime() -> - call(uptime). - -%% pids/0 -%% -%% Output: list of {Pid, [Term, ...]} - -pids() -> - to_list(fun swap/1). - -to_list(Fun) -> - ets:foldl(fun(T,A) -> acc(Fun, T, A) end, orddict:new(), ?TABLE). - -acc(Fun, ?MAPPING(Term, Pid), Dict) -> - append(Fun({Term, Pid}), Dict); -acc(_, _, Dict) -> - Dict. - -append({K,V}, Dict) -> - orddict:append(K, V, Dict). - -id(T) -> T. - -%% terms/0 -%% -%% Output: list of {Term, [Pid, ...]} - -terms() -> - to_list(fun id/1). - -swap({X,Y}) -> {Y,X}. - -%%% ---------------------------------------------------------- -%%% # init(Role) -%%% -%%% Output: {ok, State} -%%% ---------------------------------------------------------- - -init(_) -> - ets:new(?TABLE, [bag, named_table]), - {ok, #state{}}. - -%%% ---------------------------------------------------------- -%%% # handle_call(Request, From, State) -%%% ---------------------------------------------------------- - -handle_call({add, Fun, Key, Pid}, _, State) -> - B = Fun(?TABLE, {Key, Pid}), - monitor(B andalso no_monitor(Pid), Pid), - {reply, B, State}; - -handle_call({del, Key, Pid}, _, State) -> - {reply, ets:delete_object(?TABLE, ?MAPPING(Key, Pid)), State}; - -handle_call({repl, T, U, Pid}, _, State) -> - MatchSpec = [{?MAPPING('$1', Pid), - [{'=:=', '$1', {const, T}}], - ['$_']}], - {reply, repl(ets:select(?TABLE, MatchSpec), U, Pid), State}; - -handle_call(state, _, State) -> - {reply, State, State}; - -handle_call(uptime, _, #state{id = Time} = State) -> - {reply, diameter_lib:now_diff(Time), State}; - -handle_call(Req, From, State) -> - ?UNEXPECTED([Req, From]), - {reply, nok, State}. - -%%% ---------------------------------------------------------- -%%% # handle_cast(Request, State) -%%% ---------------------------------------------------------- - -handle_cast(Msg, State)-> - ?UNEXPECTED([Msg]), - {noreply, State}. - -%%% ---------------------------------------------------------- -%%% # handle_info(Request, State) -%%% ---------------------------------------------------------- - -handle_info({'DOWN', MRef, process, Pid, _}, State) -> - ets:delete_object(?TABLE, ?MONITOR(Pid, MRef)), - ets:match_delete(?TABLE, ?MAPPING('_', Pid)), - {noreply, State}; - -handle_info(Info, State) -> - ?UNEXPECTED([Info]), - {noreply, State}. - -%%% ---------------------------------------------------------- -%%% # terminate(Reason, State) -%%% ---------------------------------------------------------- - -terminate(_Reason, _State)-> - ok. - -%%% ---------------------------------------------------------- -%%% # code_change(OldVsn, State, Extra) -%%% ---------------------------------------------------------- - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%% --------------------------------------------------------- -%% INTERNAL FUNCTIONS -%% --------------------------------------------------------- - -monitor(true, Pid) -> - ets:insert(?TABLE, ?MONITOR(Pid, erlang:monitor(process, Pid))); -monitor(false, _) -> - ok. - -%% Do we need a monitor for the specified Pid? -no_monitor(Pid) -> - [] == ets:match_object(?TABLE, ?MONITOR(Pid, '_')). - -%% insert_new/2 - -insert_new(?TABLE, {Key, _} = T) -> - flush(ets:lookup(?TABLE, Key)), - ets:insert_new(?TABLE, T). - -%% Remove any processes that are dead but for which we may not have -%% received 'DOWN' yet. This is to ensure that add_new can be used -%% to register a unique name each time a process restarts. -flush(List) -> - lists:foreach(fun({_,P} = T) -> - del(erlang:is_process_alive(P), T) - end, - List). - -del(Alive, T) -> - Alive orelse ets:delete_object(?TABLE, T). - -%% repl/3 - -repl([?MAPPING(_, Pid) = M], Key, Pid) -> - ets:delete_object(?TABLE, M), - true = ets:insert(?TABLE, ?MAPPING(Key, Pid)); -repl([], _, _) -> - false. - -%% call/1 - -call(Request) -> - gen_server:call(?SERVER, Request, infinity). diff --git a/lib/diameter/src/app/diameter_stats.erl b/lib/diameter/src/app/diameter_stats.erl deleted file mode 100644 index 71479afa95..0000000000 --- a/lib/diameter/src/app/diameter_stats.erl +++ /dev/null @@ -1,342 +0,0 @@ -%% -%% %CopyrightBegin% -%% -%% Copyright Ericsson AB 2010-2011. 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% -%% - -%% -%% Statistics collector. -%% - --module(diameter_stats). --compile({no_auto_import, [monitor/2]}). - --behaviour(gen_server). - --export([reg/1, reg/2, - incr/1, incr/2, incr/3, - read/1, - flush/0, flush/1]). - -%% supervisor callback --export([start_link/0]). - -%% gen_server callbacks --export([init/1, - terminate/2, - handle_call/3, - handle_cast/2, - handle_info/2, - code_change/3]). - -%% debug --export([state/0, - uptime/0]). - --include("diameter_internal.hrl"). - -%% ets table containing stats. reg(Pid, Ref) inserts a {Pid, Ref}, -%% incr(Counter, X, N) updates the counter keyed at {Counter, X}, and -%% Pid death causes counters keyed on {Counter, Pid} to be deleted and -%% added to those keyed on {Counter, Ref}. --define(TABLE, ?MODULE). - -%% Name of registered server. --define(SERVER, ?MODULE). - -%% Entries in the table. --define(REC(Key, Value), {Key, Value}). - -%% Server state. --record(state, {id = now()}). - --type counter() :: any(). --type contrib() :: any(). - -%%% --------------------------------------------------------------------------- -%%% # reg(Pid, Contrib) -%%% -%%% Description: Register a process as a contributor of statistics -%%% associated with a specified term. Statistics can be -%%% contributed by specifying either Pid or Contrib as -%%% the second argument to incr/3. Statistics contributed -%%% by Pid are folded into the corresponding entry for -%%% Contrib when the process dies. -%%% -%%% Contrib can be any term but should not be a pid -%%% passed as the first argument to reg/2. Subsequent -%%% registrations for the same Pid overwrite the association -%%% --------------------------------------------------------------------------- - --spec reg(pid(), contrib()) - -> true. - -reg(Pid, Contrib) - when is_pid(Pid) -> - call({reg, Pid, Contrib}). - --spec reg(contrib()) - -> true. - -reg(Ref) -> - reg(self(), Ref). - -%%% --------------------------------------------------------------------------- -%%% # incr(Counter, Contrib, N) -%%% -%%% Description: Increment a counter for the specified contributor. -%%% -%%% Contrib will typically be an argument passed to reg/2 -%%% but there's nothing that requires this. In particular, -%%% if Contrib is a pid that hasn't been registered then -%%% counters are unaffected by the death of the process. -%%% --------------------------------------------------------------------------- - --spec incr(counter(), contrib(), integer()) - -> integer(). - -incr(Ctr, Contrib, N) -> - update_counter({Ctr, Contrib}, N). - -incr(Ctr, N) - when is_integer(N) -> - incr(Ctr, self(), N); - -incr(Ctr, Contrib) -> - incr(Ctr, Contrib, 1). - -incr(Ctr) -> - incr(Ctr, self(), 1). - -%%% --------------------------------------------------------------------------- -%%% # read(Contribs) -%%% -%%% Description: Retrieve counters for the specified contributors. -%%% --------------------------------------------------------------------------- - --spec read([contrib()]) - -> [{contrib(), [{counter(), integer()}]}]. - -read(Contribs) -> - lists:foldl(fun(?REC({T,C}, N), D) -> orddict:append(C, {T,N}, D) end, - orddict:new(), - ets:select(?TABLE, [{?REC({'_', '$1'}, '_'), - [?ORCOND([{'=:=', '$1', {const, C}} - || C <- Contribs])], - ['$_']}])). - -%%% --------------------------------------------------------------------------- -%%% # flush(Contrib) -%%% -%%% Description: Retrieve and delete statistics for the specified -%%% contributor. -%%% -%%% If Contrib is a pid registered with reg/2 then statistics -%%% for both and its associated contributor are retrieved. -%%% --------------------------------------------------------------------------- - --spec flush(contrib()) - -> [{counter(), integer()}]. - -flush(Contrib) -> - try - call({flush, Contrib}) - catch - exit: _ -> - [] - end. - -flush() -> - flush(self()). - -%%% --------------------------------------------------------- -%%% EXPORTED INTERNAL FUNCTIONS -%%% --------------------------------------------------------- - -start_link() -> - ServerName = {local, ?SERVER}, - Module = ?MODULE, - Args = [], - Options = [{spawn_opt, diameter_lib:spawn_opts(server, [])}], - gen_server:start_link(ServerName, Module, Args, Options). - -state() -> - call(state). - -uptime() -> - call(uptime). - -%%% ---------------------------------------------------------- -%%% # init(_) -%%% -%%% Output: {ok, State} -%%% ---------------------------------------------------------- - -init([]) -> - ets:new(?TABLE, [named_table, ordered_set, public]), - {ok, #state{}}. - -%% ---------------------------------------------------------- -%% handle_call(Request, From, State) -%% ---------------------------------------------------------- - -handle_call(state, _, State) -> - {reply, State, State}; - -handle_call(uptime, _, #state{id = Time} = State) -> - {reply, diameter_lib:now_diff(Time), State}; - -handle_call({reg, Pid, Contrib}, _From, State) -> - monitor(not ets:member(?TABLE, Pid), Pid), - {reply, insert(?REC(Pid, Contrib)), State}; - -handle_call({flush, Contrib}, _From, State) -> - {reply, fetch(Contrib), State}; - -handle_call(Req, From, State) -> - ?UNEXPECTED([Req, From]), - {reply, nok, State}. - -%% ---------------------------------------------------------- -%% handle_cast(Request, State) -%% ---------------------------------------------------------- - -handle_cast({incr, Rec}, State) -> - update_counter(Rec), - {noreply, State}; - -handle_cast(Msg, State) -> - ?UNEXPECTED([Msg]), - {noreply, State}. - -%% ---------------------------------------------------------- -%% handle_info(Request, State) -%% ---------------------------------------------------------- - -handle_info({'DOWN', _MRef, process, Pid, _}, State) -> - down(Pid), - {noreply, State}; - -handle_info(Info, State) -> - ?UNEXPECTED([Info]), - {noreply, State}. - -%% ---------------------------------------------------------- -%% terminate(Reason, State) -%% ---------------------------------------------------------- - -terminate(_Reason, _State) -> - ok. - -%% ---------------------------------------------------------- -%% code_change(OldVsn, State, Extra) -%% ---------------------------------------------------------- - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%%% --------------------------------------------------------- -%%% INTERNAL FUNCTIONS -%%% --------------------------------------------------------- - -%% monitor/2 - -monitor(true, Pid) -> - erlang:monitor(process, Pid); -monitor(false = No, _) -> - No. - -%% down/1 - -down(Pid) -> - L = ets:match_object(?TABLE, ?REC({'_', Pid}, '_')), - [?REC(_, Ref) = T] = lookup(Pid), - fold(Ref, L), - delete_object(T), - delete(L). - -%% Fold Pid-based entries into Ref-based ones. -fold(Ref, L) -> - lists:foreach(fun(?REC({K, _}, V)) -> update_counter({{K, Ref}, V}) end, - L). - -delete(Objs) -> - lists:foreach(fun delete_object/1, Objs). - -%% fetch/1 - -fetch(X) -> - MatchSpec = [{?REC({'_', '$1'}, '_'), - [?ORCOND([{'==', '$1', {const, T}} || T <- [X | ref(X)]])], - ['$_']}], - L = ets:select(?TABLE, MatchSpec), - delete(L), - D = lists:foldl(fun sum/2, dict:new(), L), - dict:to_list(D). - -sum({{Ctr, _}, N}, Dict) -> - dict:update(Ctr, fun(V) -> V+N end, N, Dict). - -ref(Pid) - when is_pid(Pid) -> - ets:select(?TABLE, [{?REC(Pid, '$1'), [], ['$1']}]); -ref(_) -> - []. - -%% update_counter/2 -%% -%% From an arbitrary request process. Cast to the server process to -%% insert a new element if the counter doesn't exists so that two -%% processes don't do so simultaneously. - -update_counter(Key, N) -> - try - ets:update_counter(?TABLE, Key, N) - catch - error: badarg -> - cast({incr, ?REC(Key, N)}) - end. - -%% update_counter/1 -%% -%% From the server process. - -update_counter(?REC(Key, N) = T) -> - try - ets:update_counter(?TABLE, Key, N) - catch - error: badarg -> - insert(T) - end. - -insert(T) -> - ets:insert(?TABLE, T). - -lookup(Key) -> - ets:lookup(?TABLE, Key). - -delete_object(T) -> - ets:delete_object(?TABLE, T). - -%% cast/1 - -cast(Msg) -> - gen_server:cast(?SERVER, Msg). - -%% call/1 - -call(Request) -> - gen_server:call(?SERVER, Request, infinity). diff --git a/lib/diameter/src/app/diameter_types.hrl b/lib/diameter/src/app/diameter_types.hrl deleted file mode 100644 index 02bf8a74dd..0000000000 --- a/lib/diameter/src/app/diameter_types.hrl +++ /dev/null @@ -1,139 +0,0 @@ -%% -%% %CopyrightBegin% -%% -%% Copyright Ericsson AB 2010-2011. 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% -%% - -%% -%% Types for function specifications, primarily in diameter.erl. This -%% has nothing specifically to do with diameter_types.erl. -%% - --type evaluable() - :: {module(), atom(), list()} - | fun() - | nonempty_improper_list(evaluable(), list()). %% [evaluable() | Args] - --type app_alias() - :: any(). - --type service_name() - :: any(). - -%% Diameter basic types - --type 'OctetString'() :: iolist(). --type 'Integer32'() :: -2147483647..2147483647. --type 'Integer64'() :: -9223372036854775807..9223372036854775807. --type 'Unsigned32'() :: 0..4294967295. --type 'Unsigned64'() :: 0..18446744073709551615. --type 'Float32'() :: '-infinity' | float() | infinity. --type 'Float64'() :: '-infinity' | float() | infinity. --type 'Grouped'() :: list() | tuple(). - -%% Diameter derived types - --type 'Address'() - :: inet:ip_address() - | string(). - --type 'Time'() :: {{integer(), 1..12, 1..31}, - {0..23, 0..59, 0..59}}. --type 'UTF8String'() :: iolist(). --type 'DiameterIdentity'() :: 'OctetString'(). --type 'DiameterURI'() :: 'OctetString'(). --type 'Enumerated'() :: 'Integer32'(). --type 'IPFilterRule'() :: 'OctetString'(). --type 'QoSFilterRule'() :: 'OctetString'(). - -%% Capabilities options/avps on start_service/2 and/or add_transport/2 - --type capability() - :: {'Origin-Host', 'DiameterIdentity'()} - | {'Origin-Realm', 'DiameterIdentity'()} - | {'Host-IP-Address', ['Address'()]} - | {'Vendor-Id', 'Unsigned32'()} - | {'Product-Name', 'UTF8String'()} - | {'Supported-Vendor-Id', ['Unsigned32'()]} - | {'Auth-Application-Id', ['Unsigned32'()]} - | {'Vendor-Specific-Application-Id', ['Grouped'()]} - | {'Firmware-Revision', 'Unsigned32'()}. - -%% Filters for call/4 - --type peer_filter() - :: none - | host - | realm - | {host, any|'DiameterIdentity'()} - | {realm, any|'DiameterIdentity'()} - | {eval, evaluable()} - | {neg, peer_filter()} - | {all, [peer_filter()]} - | {any, [peer_filter()]}. - -%% Options passed to start_service/2 - --type service_opt() - :: capability() - | {application, [application_opt()]}. - --type application_opt() - :: {alias, app_alias()} - | {dictionary, module()} - | {module, app_module()} - | {state, any()} - | {call_mutates_state, boolean()} - | {answer_errors, callback|report|discard}. - --type app_module() - :: module() - | nonempty_improper_list(module(), list()). %% list with module() head - -%% Identifier returned by add_transport/2 - --type transport_ref() - :: reference(). - -%% Options passed to add_transport/2 - --type transport_opt() - :: {transport_module, atom()} - | {transport_config, any()} - | {applications, [app_alias()]} - | {capabilities, [capability()]} - | {watchdog_timer, 'Unsigned32'() | {module(), atom(), list()}} - | {reconnect_timer, 'Unsigned32'()} - | {private, any()}. - -%% Predicate passed to remove_transport/2 - --type transport_pred() - :: fun((reference(), connect|listen, list()) -> boolean()) - | fun((reference(), list()) -> boolean()) - | fun((list()) -> boolean()) - | reference() - | list() - | {connect|listen, transport_pred()} - | {atom(), atom(), list()}. - -%% Options passed to call/4 - --type call_opt() - :: {extra, list()} - | {filter, peer_filter()} - | {timeout, 'Unsigned32'()} - | detach. diff --git a/lib/diameter/src/app/modules.mk b/lib/diameter/src/app/modules.mk deleted file mode 100644 index c133e6f64e..0000000000 --- a/lib/diameter/src/app/modules.mk +++ /dev/null @@ -1,70 +0,0 @@ -#-*-makefile-*- ; force emacs to enter makefile-mode - -# %CopyrightBegin% -# -# Copyright Ericsson AB 2010-2011. 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% - -SPEC_FILES = \ - diameter_gen_base_rfc3588.dia \ - diameter_gen_base_accounting.dia \ - diameter_gen_relay.dia - -RUNTIME_MODULES = \ - diameter \ - diameter_app \ - diameter_capx \ - diameter_config \ - diameter_codec \ - diameter_dict \ - diameter_lib \ - diameter_misc_sup \ - diameter_peer \ - diameter_peer_fsm \ - diameter_peer_fsm_sup \ - diameter_reg \ - diameter_service \ - diameter_service_sup \ - diameter_session \ - diameter_stats \ - diameter_sup \ - diameter_sync \ - diameter_types \ - diameter_watchdog \ - diameter_watchdog_sup - -HELP_MODULES = \ - diameter_callback \ - diameter_exprecs \ - diameter_dbg \ - diameter_info - -INTERNAL_HRL_FILES = \ - diameter_internal.hrl \ - diameter_types.hrl - -EXTERNAL_HRL_FILES = \ - ../../include/diameter.hrl \ - ../../include/diameter_gen.hrl - -EXAMPLE_FILES = \ - ../../examples/GNUmakefile \ - ../../examples/peer.erl \ - ../../examples/client.erl \ - ../../examples/client_cb.erl \ - ../../examples/server.erl \ - ../../examples/server_cb.erl \ - ../../examples/relay.erl \ - ../../examples/relay_cb.erl diff --git a/lib/diameter/src/app/diameter.app.src b/lib/diameter/src/base/diameter.app.src index a806b5c78a..c092fdb022 100644 --- a/lib/diameter/src/app/diameter.app.src +++ b/lib/diameter/src/base/diameter.app.src @@ -20,7 +20,7 @@ {application, diameter, [{description, "Diameter protocol"}, {vsn, "%VSN%"}, - {modules, [%APP_MODULES%,%TRANSPORT_MODULES%]}, + {modules, [%MODULES%]}, {registered, []}, {applications, [stdlib, kernel]}, {env, []}, diff --git a/lib/diameter/src/base/diameter.appup.src b/lib/diameter/src/base/diameter.appup.src new file mode 100644 index 0000000000..a04a387918 --- /dev/null +++ b/lib/diameter/src/base/diameter.appup.src @@ -0,0 +1,40 @@ +%% This is an -*- erlang -*- file. +%% +%% %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% +%% + +{"%VSN%", + [ + {"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", [{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", [{load_module, diameter_service}]} + ] +}. diff --git a/lib/diameter/src/base/diameter.erl b/lib/diameter/src/base/diameter.erl new file mode 100644 index 0000000000..8f9901907a --- /dev/null +++ b/lib/diameter/src/base/diameter.erl @@ -0,0 +1,357 @@ +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2010-2012. 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% +%% + +-module(diameter). + +%% Configuration. +-export([start_service/2, + stop_service/1, + add_transport/2, + remove_transport/2, + subscribe/1, + unsubscribe/1]). + +%% Traffic. +-export([session_id/1, + origin_state_id/0, + call/3, + call/4]). + +%% Information. +-export([services/0, + service_info/2]). + +%% Start/stop the application. In a "real" application this should +%% typically be a consequence of a release file rather than by calling +%% start/stop explicitly. +-export([start/0, + stop/0]). + +-export_type([evaluable/0, + restriction/0, + sequence/0, + app_alias/0, + service_name/0, + capability/0, + peer_filter/0, + service_opt/0, + application_opt/0, + app_module/0, + transport_ref/0, + transport_opt/0, + transport_pred/0, + call_opt/0]). + +-export_type(['OctetString'/0, + 'Integer32'/0, + 'Integer64'/0, + 'Unsigned32'/0, + 'Unsigned64'/0, + 'Float32'/0, + 'Float64'/0, + 'Grouped'/0, + 'Address'/0, + 'Time'/0, + 'UTF8String'/0, + 'DiameterIdentity'/0, + 'DiameterURI'/0, + 'Enumerated'/0, + 'IPFilterRule'/0, + 'QoSFilterRule'/0]). + +-include_lib("diameter/include/diameter.hrl"). +-include("diameter_internal.hrl"). + +%% --------------------------------------------------------------------------- +%% start/0 +%% --------------------------------------------------------------------------- + +-spec start() + -> ok + | {error, term()}. + +start() -> + application:start(?APPLICATION). + +%% --------------------------------------------------------------------------- +%% stop/0 +%% --------------------------------------------------------------------------- + +-spec stop() + -> ok + | {error, term()}. + +stop() -> + application:stop(?APPLICATION). + +%% --------------------------------------------------------------------------- +%% start_service/2 +%% --------------------------------------------------------------------------- + +-spec start_service(service_name(), [service_opt()]) + -> ok + | {error, term()}. + +start_service(SvcName, Opts) + when is_list(Opts) -> + diameter_config:start_service(SvcName, Opts). + +%% --------------------------------------------------------------------------- +%% stop_service/1 +%% --------------------------------------------------------------------------- + +-spec stop_service(service_name()) + -> ok + | {error, term()}. + +stop_service(SvcName) -> + diameter_config:stop_service(SvcName). + +%% --------------------------------------------------------------------------- +%% services/0 +%% --------------------------------------------------------------------------- + +-spec services() + -> [service_name()]. + +services() -> + [Name || {Name, _} <- diameter_service:services()]. + +%% --------------------------------------------------------------------------- +%% service_info/2 +%% --------------------------------------------------------------------------- + +-spec service_info(service_name(), atom() | [atom()]) + -> any(). + +service_info(SvcName, Option) -> + diameter_service:info(SvcName, Option). + +%% --------------------------------------------------------------------------- +%% add_transport/3 +%% --------------------------------------------------------------------------- + +-spec add_transport(service_name(), {listen|connect, [transport_opt()]}) + -> {ok, transport_ref()} + | {error, term()}. + +add_transport(SvcName, {T, Opts} = Cfg) + when is_list(Opts), (T == connect orelse T == listen) -> + diameter_config:add_transport(SvcName, Cfg). + +%% --------------------------------------------------------------------------- +%% remove_transport/2 +%% --------------------------------------------------------------------------- + +-spec remove_transport(service_name(), transport_pred()) + -> ok | {error, term()}. + +remove_transport(SvcName, Pred) -> + diameter_config:remove_transport(SvcName, Pred). + +%% --------------------------------------------------------------------------- +%% subscribe/1 +%% --------------------------------------------------------------------------- + +-spec subscribe(service_name()) + -> true. + +subscribe(SvcName) -> + diameter_service:subscribe(SvcName). + +%% --------------------------------------------------------------------------- +%% unsubscribe/1 +%% --------------------------------------------------------------------------- + +-spec unsubscribe(service_name()) + -> true. + +unsubscribe(SvcName) -> + diameter_service:unsubscribe(SvcName). + +%% --------------------------------------------------------------------------- +%% session_id/1 +%% --------------------------------------------------------------------------- + +-spec session_id('DiameterIdentity'()) + -> 'OctetString'(). + +session_id(Ident) -> + diameter_session:session_id(Ident). + +%% --------------------------------------------------------------------------- +%% origin_state_id/0 +%% --------------------------------------------------------------------------- + +-spec origin_state_id() + -> 'Unsigned32'(). + +origin_state_id() -> + diameter_session:origin_state_id(). + +%% --------------------------------------------------------------------------- +%% call/3,4 +%% --------------------------------------------------------------------------- + +-spec call(service_name(), app_alias(), any(), [call_opt()]) + -> any(). + +call(SvcName, App, Message, Options) -> + diameter_service:call(SvcName, {alias, App}, Message, Options). + +call(SvcName, App, Message) -> + call(SvcName, App, Message, []). + +%% =========================================================================== + +%% Diameter basic types + +-type 'OctetString'() :: iolist(). +-type 'Integer32'() :: -2147483647..2147483647. +-type 'Integer64'() :: -9223372036854775807..9223372036854775807. +-type 'Unsigned32'() :: 0..4294967295. +-type 'Unsigned64'() :: 0..18446744073709551615. +-type 'Float32'() :: '-infinity' | float() | infinity. +-type 'Float64'() :: '-infinity' | float() | infinity. +-type 'Grouped'() :: list() | tuple(). + +%% Diameter derived types + +-type 'Address'() + :: inet:ip_address() + | string(). + +-type 'Time'() :: {{integer(), 1..12, 1..31}, + {0..23, 0..59, 0..59}}. +-type 'UTF8String'() :: iolist(). +-type 'DiameterIdentity'() :: 'OctetString'(). +-type 'DiameterURI'() :: 'OctetString'(). +-type 'Enumerated'() :: 'Integer32'(). +-type 'IPFilterRule'() :: 'OctetString'(). +-type 'QoSFilterRule'() :: 'OctetString'(). + +%% The handle to a service. + +-type service_name() + :: any(). + +%% Capabilities options/avps on start_service/2 and/or add_transport/2 + +-type capability() + :: {'Origin-Host', 'DiameterIdentity'()} + | {'Origin-Realm', 'DiameterIdentity'()} + | {'Host-IP-Address', ['Address'()]} + | {'Vendor-Id', 'Unsigned32'()} + | {'Product-Name', 'UTF8String'()} + | {'Supported-Vendor-Id', ['Unsigned32'()]} + | {'Auth-Application-Id', ['Unsigned32'()]} + | {'Vendor-Specific-Application-Id', ['Grouped'()]} + | {'Firmware-Revision', 'Unsigned32'()}. + +%% Filters for call/4 + +-type peer_filter() + :: none + | host + | realm + | {host, any|'DiameterIdentity'()} + | {realm, any|'DiameterIdentity'()} + | {eval, evaluable()} + | {neg, peer_filter()} + | {all, [peer_filter()]} + | {any, [peer_filter()]}. + +-type evaluable() + :: {module(), atom(), list()} + | fun() + | maybe_improper_list(evaluable(), list()). + +-type sequence() + :: {'Unsigned32'(), 0..32}. + +-type restriction() + :: false + | node + | nodes + | [node()] + | evaluable(). + +%% Options passed to start_service/2 + +-type service_opt() + :: capability() + | {application, [application_opt()]} + | {restrict_connections, restriction()} + | {sequence, sequence() | evaluable()}. + +-type application_opt() + :: {alias, app_alias()} + | {dictionary, module()} + | {module, app_module()} + | {state, any()} + | {call_mutates_state, boolean()} + | {answer_errors, callback|report|discard}. + +-type app_alias() + :: any(). + +-type app_module() + :: module() + | maybe_improper_list(module(), list()) + | #diameter_callback{}. + +%% Identifier returned by add_transport/2 + +-type transport_ref() + :: reference(). + +%% Options passed to add_transport/2 + +-type transport_opt() + :: {transport_module, atom()} + | {transport_config, any()} + | {transport_config, any(), non_neg_integer() | infinity} + | {applications, [app_alias()]} + | {capabilities, [capability()]} + | {capabilities_cb, evaluable()} + | {capx_timeout, 'Unsigned32'()} + | {disconnect_cb, evaluable()} + | {watchdog_timer, 'Unsigned32'() | {module(), atom(), list()}} + | {reconnect_timer, 'Unsigned32'()} + | {private, any()}. + +%% Predicate passed to remove_transport/2 + +-type transport_pred() + :: fun((transport_ref(), connect|listen, list()) -> boolean()) + | fun((transport_ref(), list()) -> boolean()) + | fun((list()) -> boolean()) + | transport_ref() + | boolean() + | list() + | {connect|listen, transport_pred()} + | {atom(), atom(), list()}. + +%% Options passed to call/4 + +-type call_opt() + :: {extra, list()} + | {filter, peer_filter()} + | {timeout, 'Unsigned32'()} + | detach. diff --git a/lib/diameter/src/app/diameter_app.erl b/lib/diameter/src/base/diameter_app.erl index 600f7ff04d..600f7ff04d 100644 --- a/lib/diameter/src/app/diameter_app.erl +++ b/lib/diameter/src/base/diameter_app.erl diff --git a/lib/diameter/src/base/diameter_callback.erl b/lib/diameter/src/base/diameter_callback.erl new file mode 100644 index 0000000000..90431099b0 --- /dev/null +++ b/lib/diameter/src/base/diameter_callback.erl @@ -0,0 +1,234 @@ +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2010-2011. 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 diameter callback module that can redirect selected callbacks, +%% providing reasonable default implementations otherwise. +%% +%% To order alternate callbacks, configure a #diameter_callback record +%% as the Diameter application callback in question. The record has +%% one field for each callback function as well as 'default' and +%% 'extra' fields. A function-specific field can be set to a +%% diameter:evaluable() in order to redirect the callback +%% corresponding to that field, or to 'false' to request the default +%% callback implemented in this module. If neither of these fields are +%% set then the 'default' field determines the form of the callback: a +%% module name results in the usual callback as if the module had been +%% configured directly as the callback module, a diameter_evaluable() +%% in a callback applied to the atom-valued callback name and argument +%% list. For all callbacks not to this module, the 'extra' field is a +%% list of additional arguments, following arguments supplied by +%% diameter but preceeding those of the diameter:evaluable() being +%% applied. +%% +%% For example, the following config to diameter:start_service/2, in +%% an 'application' tuple, would result in only a mymod:peer_down/3 +%% callback, this module implementing the remaining callbacks. +%% +%% {module, #diameter_callback{peer_down = {mymod, down, []}}} +%% +%% Equivalently, this can also be specified with a [Mod | Args] +%% field/value list as follows. +%% +%% {module, [diameter_callback, {peer_down, {mymod, down, []}}]} +%% +%% The following would result in this module suppying peer_up and +%% peer_down callback, others taking place in module mymod. +%% +%% {module, #diameter_callback{peer_up = false, +%% peer_down = false, +%% default = mymod}} +%% +%% The following would result in all callbacks taking place as +%% calls to mymod:diameter/2. +%% +%% {module, #diameter_callback{default = {mymod, diameter, []}}} +%% +%% The following are equivalent and result in all callbacks being +%% provided by this module. +%% +%% {module, #diameter_callback{}} +%% {module, diameter_callback} +%% + +-module(diameter_callback). + +%% Default callbacks when no aleternate is specified. +-export([peer_up/3, + peer_down/3, + pick_peer/4, + prepare_request/3, + prepare_retransmit/3, + handle_request/3, + handle_answer/4, + handle_error/4]). + +%% Callbacks taking a #diameter_callback record. +-export([peer_up/4, + peer_down/4, + pick_peer/5, + prepare_request/4, + prepare_retransmit/4, + handle_request/4, + handle_answer/5, + handle_error/5]). + +-include_lib("diameter/include/diameter.hrl"). + +%%% ---------------------------------------------------------- +%%% # peer_up/3 +%%% ---------------------------------------------------------- + +peer_up(_Svc, _Peer, State) -> + State. + +peer_up(Svc, Peer, State, D) -> + cb(peer_up, + [Svc, Peer, State], + D#diameter_callback.peer_up, + D). + +%%% ---------------------------------------------------------- +%%% # peer_down/3 +%%% ---------------------------------------------------------- + +peer_down(_Svc, _Peer, State) -> + State. + +peer_down(Svc, Peer, State, D) -> + cb(peer_down, + [Svc, Peer, State], + D#diameter_callback.peer_down, + D). + +%%% ---------------------------------------------------------- +%%% # pick_peer/4 +%%% ---------------------------------------------------------- + +pick_peer([Peer|_], _, _Svc, _State) -> + {ok, Peer}; +pick_peer([], _, _Svc, _State) -> + false. + +pick_peer(PeersL, PeersR, Svc, State, D) -> + cb(pick_peer, + [PeersL, PeersR, Svc, State], + D#diameter_callback.pick_peer, + D). + +%%% ---------------------------------------------------------- +%%% # prepare_request/3 +%%% ---------------------------------------------------------- + +prepare_request(Pkt, _Svc, _Peer) -> + {send, Pkt}. + +prepare_request(Pkt, Svc, Peer, D) -> + cb(prepare_request, + [Pkt, Svc, Peer], + D#diameter_callback.prepare_request, + D). + +%%% ---------------------------------------------------------- +%%% # prepare_retransmit/3 +%%% ---------------------------------------------------------- + +prepare_retransmit(Pkt, _Svc, _Peer) -> + {send, Pkt}. + +prepare_retransmit(Pkt, Svc, Peer, D) -> + cb(prepare_retransmit, + [Pkt, Svc, Peer], + D#diameter_callback.prepare_retransmit, + D). + +%%% ---------------------------------------------------------- +%%% # handle_request/3 +%%% ---------------------------------------------------------- + +handle_request(_Pkt, _Svc, _Peer) -> + {protocol_error, 3001}. %% DIAMETER_COMMAND_UNSUPPORTED + +handle_request(Pkt, Svc, Peer, D) -> + cb(handle_request, + [Pkt, Svc, Peer], + D#diameter_callback.handle_request, + D). + +%%% ---------------------------------------------------------- +%%% # handle_answer/4 +%%% ---------------------------------------------------------- + +handle_answer(#diameter_packet{msg = Ans, errors = []}, _Req, _Svc, _Peer) -> + Ans; +handle_answer(#diameter_packet{msg = Ans, errors = Es}, _Req, _Svc, _Peer) -> + [Ans | Es]. + +handle_answer(Pkt, Req, Svc, Peer, D) -> + cb(handle_answer, + [Pkt, Req, Svc, Peer], + D#diameter_callback.handle_answer, + D). + +%%% --------------------------------------------------------------------------- +%%% # handle_error/4 +%%% --------------------------------------------------------------------------- + +handle_error(Reason, _Req, _Svc, _Peer) -> + {error, Reason}. + +handle_error(Reason, Req, Svc, Peer, D) -> + cb(handle_error, + [Reason, Req, Svc, Peer], + D#diameter_callback.handle_error, + D). + +%% =========================================================================== + +%% cb/4 + +%% Unspecified callback: use default field to determine something +%% appropriate. +cb(CB, Args, undefined, D) -> + cb(CB, Args, D); + +%% Explicitly requested default. +cb(CB, Args, false, _) -> + apply(?MODULE, CB, Args); + +%% A specified callback. +cb(_, Args, F, #diameter_callback{extra = X}) -> + diameter_lib:eval([[F|X] | Args]). + +%% cb/3 + +%% No user-supplied default: call ours. +cb(CB, Args, #diameter_callback{default = undefined}) -> + apply(?MODULE, CB, Args); + +%% Default is a module name: make the usual callback. +cb(CB, Args, #diameter_callback{default = M, + extra = X}) + when is_atom(M) -> + apply(M, CB, Args ++ X); + +%% Default is something else: apply if to callback name and arguments. +cb(CB, Args, #diameter_callback{default = F, + extra = X}) -> + diameter_lib:eval([F, CB, Args | X]). diff --git a/lib/diameter/src/app/diameter_capx.erl b/lib/diameter/src/base/diameter_capx.erl index aa5318e79d..c6c3d2934d 100644 --- a/lib/diameter/src/app/diameter_capx.erl +++ b/lib/diameter/src/base/diameter_capx.erl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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,14 +54,14 @@ -include_lib("diameter/include/diameter.hrl"). -include("diameter_internal.hrl"). --include("diameter_types.hrl"). -include("diameter_gen_base_rfc3588.hrl"). --define(SUCCESS, ?'DIAMETER_BASE_RESULT-CODE_DIAMETER_SUCCESS'). --define(NOAPP, ?'DIAMETER_BASE_RESULT-CODE_DIAMETER_NO_COMMON_APPLICATION'). --define(NOSECURITY, ?'DIAMETER_BASE_RESULT-CODE_DIAMETER_NO_COMMON_SECURITY'). +-define(SUCCESS, 2001). %% DIAMETER_SUCCESS +-define(NOAPP, 5010). %% DIAMETER_NO_COMMON_APPLICATION +-define(NOSECURITY, 5017). %% DIAMETER_NO_COMMON_SECURITY -define(NO_INBAND_SECURITY, 0). +-define(TLS, 1). %% =========================================================================== @@ -74,13 +74,17 @@ build_CER(Caps) -> try_it([fun bCER/1, Caps]). -spec recv_CER(#diameter_base_CER{}, #diameter_service{}) - -> tried({['Unsigned32'()], #diameter_caps{}, #diameter_base_CEA{}}). + -> tried({[diameter:'Unsigned32'()], + #diameter_caps{}, + #diameter_base_CEA{}}). recv_CER(CER, Svc) -> try_it([fun rCER/2, CER, Svc]). -spec recv_CEA(#diameter_base_CEA{}, #diameter_service{}) - -> tried({['Unsigned32'()], #diameter_caps{}}). + -> tried({[diameter:'Unsigned32'()], + [diameter:'Unsigned32'()], + #diameter_caps{}}). recv_CEA(CEA, Svc) -> try_it([fun rCEA/2, CEA, Svc]). @@ -95,7 +99,7 @@ try_it([Fun | Args]) -> try apply(Fun, Args) of T -> {ok, T} catch - throw: ?FAILURE(Reason) -> {error, {Reason, Args}} + throw: ?FAILURE(Reason) -> {error, Reason} end. %% mk_caps/2 @@ -126,28 +130,28 @@ mk_caps(Caps0, Opts) -> set_cap({Key, _}, _) -> ?THROW({duplicate, Key}). -cap(K, V) when K == 'Origin-Host'; - K == 'Origin-Realm'; - K == 'Vendor-Id'; - K == 'Product-Name' -> +cap(K, V) + when K == 'Origin-Host'; + K == 'Origin-Realm'; + K == 'Vendor-Id'; + K == 'Product-Name' -> V; cap('Host-IP-Address', Vs) when is_list(Vs) -> lists:map(fun ipaddr/1, Vs); -cap('Firmware-Revision', V) -> +cap(K, V) + when K == 'Firmware-Revision'; + K == 'Origin-State-Id' -> [V]; -%% Not documented but accept it as long as it's what we support. -cap('Inband-Security-Id', [0] = Vs) -> %% NO_INBAND_SECURITY - Vs; - -cap(K, Vs) when K /= 'Inband-Security-Id', is_list(Vs) -> +cap(_, Vs) + when is_list(Vs) -> Vs; cap(K, V) -> - ?THROW({invalid, K, V}). + ?THROW({invalid, {K,V}}). ipaddr(A) -> try @@ -161,28 +165,10 @@ ipaddr(A) -> %% %% Build a CER record to send to a remote peer. -bCER(#diameter_caps{origin_host = Host, - origin_realm = Realm, - host_ip_address = Addrs, - vendor_id = Vid, - product_name = Name, - origin_state_id = OSI, - supported_vendor_id = SVid, - auth_application_id = AuId, - acct_application_id = AcId, - vendor_specific_application_id = VSA, - firmware_revision = Rev}) -> - #diameter_base_CER{'Origin-Host' = Host, - 'Origin-Realm' = Realm, - 'Host-IP-Address' = Addrs, - 'Vendor-Id' = Vid, - 'Product-Name' = Name, - 'Origin-State-Id' = OSI, - 'Supported-Vendor-Id' = SVid, - 'Auth-Application-Id' = AuId, - 'Acct-Application-Id' = AcId, - 'Vendor-Specific-Application-Id' = VSA, - 'Firmware-Revision' = Rev}. +%% Use the fact that diameter_caps has the same field names as CER. +bCER(#diameter_caps{} = Rec) -> + #diameter_base_CER{} + = list_to_tuple([diameter_base_CER | tl(tuple_to_list(Rec))]). %% rCER/2 %% @@ -219,19 +205,16 @@ bCER(#diameter_caps{origin_host = Host, %% That is, each side sends all of its capabilities and is responsible for %% not sending commands that the peer doesn't support. -%% TODO: Make it an option to send only common applications in CEA to -%% allow backwards compatibility, and also because there are likely -%% servers that expect this. Or maybe a callback. - %% 6.10. Inband-Security-Id AVP %% %% NO_INBAND_SECURITY 0 %% This peer does not support TLS. This is the default value, if the %% AVP is omitted. +%% +%% TLS 1 +%% This node supports TLS security, as defined by [TLS]. rCER(CER, #diameter_service{capabilities = LCaps} = Svc) -> - #diameter_base_CER{'Inband-Security-Id' = RIS} - = CER, #diameter_base_CEA{} = CEA = cea_from_cer(bCER(LCaps)), @@ -241,59 +224,81 @@ rCER(CER, #diameter_service{capabilities = LCaps} = Svc) -> {SApps, RCaps, - build_CEA([] == SApps, - RIS, - lists:member(?NO_INBAND_SECURITY, RIS), - CEA#diameter_base_CEA{'Result-Code' = ?SUCCESS, - 'Inband-Security-Id' = []})}. - -%% TODO: 5.3 of RFC3588 says we MUST return DIAMETER_NO_COMMON_APPLICATION -%% in the CEA and SHOULD disconnect the transport. However, we have -%% no way to guarantee the send before disconnecting. + build_CEA(SApps, + LCaps, + RCaps, + CEA#diameter_base_CEA{'Result-Code' = ?SUCCESS})}. -build_CEA(true, _, _, CEA) -> +build_CEA([], _, _, CEA) -> CEA#diameter_base_CEA{'Result-Code' = ?NOAPP}; -build_CEA(false, [_|_], false, CEA) -> - CEA#diameter_base_CEA{'Result-Code' = ?NOSECURITY}; -build_CEA(false, [_|_], true, CEA) -> - CEA#diameter_base_CEA{'Inband-Security-Id' = [?NO_INBAND_SECURITY]}; -build_CEA(false, [], false, CEA) -> - CEA. + +build_CEA(_, LCaps, RCaps, CEA) -> + case common_security(LCaps, RCaps) of + [] -> + CEA#diameter_base_CEA{'Result-Code' = ?NOSECURITY}; + [_] = IS -> + CEA#diameter_base_CEA{'Inband-Security-Id' = IS} + end. + +%% common_security/2 + +common_security(#diameter_caps{inband_security_id = LS}, + #diameter_caps{inband_security_id = RS}) -> + cs(LS, RS). + +%% Unspecified is equivalent to NO_INBAND_SECURITY. +cs([], RS) -> + cs([?NO_INBAND_SECURITY], RS); +cs(LS, []) -> + cs(LS, [?NO_INBAND_SECURITY]); + +%% Agree on TLS if both parties support it. When sending CEA, this is +%% to ensure the peer is clear that we will be expecting a TLS +%% handshake since there is no ssl:maybe_accept that would allow the +%% peer to choose between TLS or not upon reception of our CEA. When +%% receiving CEA it deals with a server that isn't explicit about its choice. +%% TODO: Make the choice configurable. +cs(LS, RS) -> + Is = ordsets:to_list(ordsets:intersection(ordsets:from_list(LS), + ordsets:from_list(RS))), + case lists:member(?TLS, Is) of + true -> + [?TLS]; + false when [] == Is -> + Is; + false -> + [hd(Is)] %% probably NO_INBAND_SECURITY + end. +%% The only two values defined by RFC 3588 are NO_INBAND_SECURITY and +%% TLS but don't enforce this. In theory this allows some other +%% security mechanism we don't have to know about, although in +%% practice something there may be a need for more synchronization +%% than notification by way of an event subscription offers. %% cea_from_cer/1 +%% CER is a subset of CEA, the latter adding Result-Code and a few +%% more AVP's. cea_from_cer(#diameter_base_CER{} = CER) -> lists:foldl(fun(F,A) -> to_cea(CER, F, A) end, #diameter_base_CEA{}, record_info(fields, diameter_base_CER)). to_cea(CER, Field, CEA) -> - try ?BASE:'#info-'(diameter_base_CEA, {index, Field}) of - N -> - setelement(N, CEA, ?BASE:'#get-'(Field, CER)) + try ?BASE:'#get-'(Field, CER) of + V -> ?BASE:'#set-'({Field, V}, CEA) catch - error: _ -> - CEA + error: _ -> CEA end. - + %% rCEA/2 -rCEA(CEA, #diameter_service{capabilities = LCaps} = Svc) - when is_record(CEA, diameter_base_CEA) -> - #diameter_base_CEA{'Result-Code' = RC} - = CEA, - - RC == ?SUCCESS orelse ?THROW({'Result-Code', RC}), - +rCEA(CEA, #diameter_service{capabilities = LCaps} = Svc) -> RCaps = capx_to_caps(CEA), SApps = common_applications(LCaps, RCaps, Svc), + IS = common_security(LCaps, RCaps), - [] == SApps andalso ?THROW({no_common_apps, LCaps, RCaps}), - - {SApps, RCaps}; - -rCEA(CEA, _Svc) -> - ?THROW({invalid, CEA}). + {SApps, IS, RCaps}. %% capx_to_caps/1 diff --git a/lib/diameter/src/app/diameter_codec.erl b/lib/diameter/src/base/diameter_codec.erl index d88f42fb7c..a94d37f7a8 100644 --- a/lib/diameter/src/app/diameter_codec.erl +++ b/lib/diameter/src/base/diameter_codec.erl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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 @@ -63,9 +63,9 @@ encode(Mod, #diameter_packet{} = Pkt) -> e(Mod, Pkt) catch error: Reason -> - %% Be verbose rather than letting the emulator truncate the - %% error report. - X = {Reason, ?STACK}, + %% 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) end; @@ -91,7 +91,8 @@ e(_, #diameter_packet{msg = [#diameter_header{} = Hdr | As]} = Pkt) -> Flags = make_flags(0, Hdr), - Pkt#diameter_packet{bin = <<Vsn:8, Length:24, + Pkt#diameter_packet{header = Hdr, + bin = <<Vsn:8, Length:24, Flags:8, Code:24, Aid:32, Hid:32, @@ -190,26 +191,13 @@ encode_avps(Avps) -> %% msg_header/3 -msg_header(Mod, MsgName, Header) -> - {Code, Flags, ApplId} = h(Mod, MsgName, Header), - {Code, p(Flags, Header), ApplId}. - -%% 6.2 of 3588 requires the same 'P' bit on an answer as on the -%% request. - -p(Flags, #diameter_header{is_request = true, - is_proxiable = P}) -> - Flags band (2#10110000 bor choose(P, 2#01000000, 0)); -p(Flags, _) -> - Flags. - -h(Mod, 'answer-message' = MsgName, Header) -> +msg_header(Mod, 'answer-message' = MsgName, Header) -> ?BASE = Mod, #diameter_header{cmd_code = Code} = Header, {_, Flags, ApplId} = ?BASE:msg_header(MsgName), {Code, Flags, ApplId}; -h(Mod, MsgName, _) -> +msg_header(Mod, MsgName, _) -> Mod:msg_header(MsgName). %% rec2msg/2 @@ -345,6 +333,9 @@ decode_header(_) -> %% wraparound counter. The 8-bit counter is incremented each time the %% system is restarted. +sequence_numbers({_,_} = T) -> + T; + sequence_numbers(#diameter_packet{bin = Bin}) when is_binary(Bin) -> sequence_numbers(Bin); @@ -554,8 +545,3 @@ pack_avp(Code, Flags, Vid, Sz, Bin) -> pack_avp(Code, Flags, Sz, Bin) -> Length = Sz + 8, <<Code:32, Flags:8, Length:24, Bin/binary>>. - -%% =========================================================================== - -choose(true, X, _) -> X; -choose(false, _, X) -> X. diff --git a/lib/diameter/src/app/diameter_config.erl b/lib/diameter/src/base/diameter_config.erl index a6b48fe65b..63d28f25a2 100644 --- a/lib/diameter/src/app/diameter_config.erl +++ b/lib/diameter/src/base/diameter_config.erl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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 @@ -97,6 +97,9 @@ -record(monitor, {mref = make_ref() :: reference(), service}). %% name +%% The default sequence mask. +-define(NOMASK, {0,32}). + %% Time to lay low before restarting a dead service. -define(RESTART_SLEEP, 2000). @@ -519,6 +522,7 @@ rm(SvcName, L) -> Refs = lists:map(fun(#transport{ref = R}) -> R end, L), case stop_transport(SvcName, Refs) of ok -> + diameter_stats:flush(Refs), lists:foreach(fun delete_object/1, L); {error, _} = No -> No @@ -548,9 +552,11 @@ make_config(SvcName, Opts) -> ok = encode_CER(COpts), - Os = split(Opts, [{[fun erlang:is_boolean/1], false, share_peers}, - {[fun erlang:is_boolean/1], false, use_shared_peers}, - {[fun erlang:is_pid/1, false], false, monitor}]), + Os = split(Opts, fun opt/2, [{false, share_peers}, + {false, use_shared_peers}, + {false, monitor}, + {?NOMASK, sequence}, + {nodes, restrict_connections}]), %% share_peers and use_shared_peers are currently undocumented. #service{name = SvcName, @@ -558,11 +564,66 @@ make_config(SvcName, Opts) -> capabilities = Caps}, options = Os}. +split(Opts, F, Defs) -> + [{K, F(K, get_opt(K, Opts, D))} || {D,K} <- Defs]. + +opt(K, false = B) + when K /= sequence -> + B; + +opt(K, true = B) + when K == share_peer; + K == use_shared_peers -> + B; + +opt(monitor, P) + when is_pid(P) -> + P; + +opt(restrict_connections, T) + when T == node; + T == nodes; + T == []; + is_atom(hd(T)) -> + T; + +opt(restrict_connections = K, F) -> + try diameter_lib:eval(F) of %% no guarantee that it won't fail later + Nodes when is_list(Nodes) -> + F; + V -> + ?THROW({value, {K,V}}) + catch + E:R -> + ?THROW({value, {K, E, R, ?STACK}}) + end; + +opt(sequence, {_,_} = T) -> + sequence(T); + +opt(sequence = K, F) -> + try diameter_lib:eval(F) of + T -> sequence(T) + catch + E:R -> + ?THROW({value, {K, E, R, ?STACK}}) + end; + +opt(K, _) -> + ?THROW({value, K}). + +sequence({H,N} = T) + when 0 =< N, N =< 32, 0 =< H, 0 == H bsr N -> + T; + +sequence(_) -> + ?THROW({value, sequence}). + make_caps(Caps, Opts) -> case diameter_capx:make_caps(Caps, Opts) of {ok, T} -> T; - {error, {Reason, _}} -> + {error, Reason} -> ?THROW(Reason) end. @@ -600,11 +661,18 @@ app_acc({application, Opts}, Acc) -> module = init_mod(Mod), init_state = ModS, mutable = init_mutable(M), - answer_errors = init_answers(A)} + options = [{answer_errors, init_answers(A)}]} | Acc]; app_acc(_, Acc) -> Acc. +init_mod(#diameter_callback{} = R) -> + init_mod([diameter_callback, R]); +init_mod([diameter_callback, #diameter_callback{}] = L) -> + L; +init_mod([diameter_callback = M | L]) + when is_list(L) -> + [M, init_cb(L)]; init_mod(M) when is_atom(M) -> [M]; @@ -614,6 +682,14 @@ init_mod([M|_] = L) init_mod(M) -> ?THROW({module, M}). +init_cb(List) -> + Fields = record_info(fields, diameter_callback), + Defaults = lists:zip(Fields, tl(tuple_to_list(#diameter_callback{}))), + Values = [V || F <- Fields, + D <- [proplists:get_value(F, Defaults)], + V <- [proplists:get_value(F, List, D)]], + #diameter_callback{} = list_to_tuple([diameter_callback | Values]). + init_mutable(M) when M == true; M == false -> @@ -647,21 +723,6 @@ get_opt(Key, List, Def) -> _ -> ?THROW({arity, Key}) end. -split(Opts, Defs) -> - [{K, value(D, Opts)} || {_,_,K} = D <- Defs]. - -value({Preds, Def, Key}, Opts) -> - V = get_opt(Key, Opts, Def), - lists:any(fun(P) -> pred(P,V) end, Preds) - orelse ?THROW({value, Key}), - V. - -pred(F, V) - when is_function(F) -> - F(V); -pred(T, V) -> - T == V. - cb(M,F) -> try M:F() of V -> V diff --git a/lib/diameter/src/app/diameter_dbg.erl b/lib/diameter/src/base/diameter_dbg.erl index 5b0ac3a3b6..5b0ac3a3b6 100644 --- a/lib/diameter/src/app/diameter_dbg.erl +++ b/lib/diameter/src/base/diameter_dbg.erl diff --git a/lib/diameter/src/app/diameter_dict.erl b/lib/diameter/src/base/diameter_dict.erl index 3b9ba00a3f..3b9ba00a3f 100644 --- a/lib/diameter/src/app/diameter_dict.erl +++ b/lib/diameter/src/base/diameter_dict.erl diff --git a/lib/diameter/src/app/diameter_info.erl b/lib/diameter/src/base/diameter_info.erl index 39d32d07cd..39d32d07cd 100644 --- a/lib/diameter/src/app/diameter_info.erl +++ b/lib/diameter/src/base/diameter_info.erl diff --git a/lib/diameter/src/app/diameter_internal.hrl b/lib/diameter/src/base/diameter_internal.hrl index 63b35550a8..63b35550a8 100644 --- a/lib/diameter/src/app/diameter_internal.hrl +++ b/lib/diameter/src/base/diameter_internal.hrl diff --git a/lib/diameter/src/app/diameter_lib.erl b/lib/diameter/src/base/diameter_lib.erl index 362d593b24..362d593b24 100644 --- a/lib/diameter/src/app/diameter_lib.erl +++ b/lib/diameter/src/base/diameter_lib.erl diff --git a/lib/diameter/src/app/diameter_misc_sup.erl b/lib/diameter/src/base/diameter_misc_sup.erl index 4e40476f14..4e40476f14 100644 --- a/lib/diameter/src/app/diameter_misc_sup.erl +++ b/lib/diameter/src/base/diameter_misc_sup.erl diff --git a/lib/diameter/src/app/diameter_peer.erl b/lib/diameter/src/base/diameter_peer.erl index 3e78c4caef..1b2f32ddff 100644 --- a/lib/diameter/src/app/diameter_peer.erl +++ b/lib/diameter/src/base/diameter_peer.erl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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 @@ -27,12 +27,15 @@ up/2]). %% ... and the stack. --export([start/3, +-export([start/1, send/2, close/1, abort/1, notify/2]). +%% Old interface only called from old code. +-export([start/3]). %% < diameter-1.2 (R15B02) + %% Server start. -export([start_link/0]). @@ -57,6 +60,11 @@ %% Server state. -record(state, {id = now()}). +%% Default transport_module/config. +-define(DEFAULT_TMOD, diameter_tcp). +-define(DEFAULT_TCFG, []). +-define(DEFAULT_TTMO, infinity). + %%% --------------------------------------------------------------------------- %%% # notify/2 %%% --------------------------------------------------------------------------- @@ -68,9 +76,119 @@ notify(SvcName, T) -> %%% # start/3 %%% --------------------------------------------------------------------------- -start(T, Opts, #diameter_service{} = Svc) -> - {Mod, Cfg} = split_transport(Opts), - apply(Mod, start, [T, Svc, Cfg]). +%% From old code: make it restart. +start(_T, _Opts, #diameter_service{}) -> + {error, restart}. + +%%% --------------------------------------------------------------------------- +%%% # start/1 +%%% --------------------------------------------------------------------------- + +-spec start({T, [Opt], #diameter_service{}}) + -> {TPid, [Addr], Tmo, Data} + | {error, [term()]} + when T :: {connect|accept, diameter:transport_ref()}, + Opt :: diameter:transport_opt(), + TPid :: pid(), + Addr :: inet:ip_address(), + Tmo :: non_neg_integer() | infinity, + Data :: {{T, Mod, Cfg}, [Mod], [{T, [Mod], Cfg}], [Err]}, + Mod :: module(), + Cfg :: term(), + Err :: term() + ; ({#diameter_service{}, Tmo, Data}) + -> {TPid, [Addr], Tmo, Data} + | {error, [term()]} + when TPid :: pid(), + Addr :: inet:ip_address(), + Tmo :: non_neg_integer() | infinity, + Data :: {{T, Mod, Cfg}, [Mod], [{T, [Mod], Cfg}], [Err]}, + T :: {connect|accept, diameter:transport_ref()}, + Mod :: module(), + Cfg :: term(), + Err :: term(). + +%% Initial start. +start({T, Opts, #diameter_service{} = Svc}) -> + start(T, Svc, pair(Opts, [], []), []); + +%% Subsequent start. +start({#diameter_service{} = Svc, Tmo, {{T, _, Cfg}, Ms, Rest, Errs}}) -> + start(T, Ms, Cfg, Svc, Tmo, Rest, Errs). + +%% pair/3 +%% +%% Pair transport modules with config. + +%% Another transport_module: accumulate it. +pair([{transport_module, M} | Rest], Mods, Acc) -> + pair(Rest, [M|Mods], Acc); + +%% Another transport_config: accumulate another tuple. +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], Mods, Acc) -> + pair(Rest, Mods, Acc); + +%% No transport_module or transport_config: defaults. +pair([], [], []) -> + [{[?DEFAULT_TMOD], ?DEFAULT_TCFG, ?DEFAULT_TTMO}]; + +%% One transport_module, one transport_config. +pair([], [M], [{[], Cfg, Tmo}]) -> + [{[M], Cfg, Tmo}]; + +%% Trailing transport_module: default transport_config. +pair([], [_|_] = Mods, Acc) -> + lists:reverse(acc({Mods, ?DEFAULT_TCFG, ?DEFAULT_TTMO}, Acc)); + +pair([], [], Acc) -> + lists:reverse(def(Acc)). + +%% acc/2 + +acc(T, Acc) -> + [T | def(Acc)]. + +%% def/1 +%% +%% Default module of previous pair if none were specified. + +def([{[], Cfg, Tmo} | Acc]) -> + [{[?DEFAULT_TMOD], Cfg, Tmo} | Acc]; +def(Acc) -> + Acc. + +%% start/4 + +start(T, Svc, [{Ms, Cfg, Tmo} | Rest], Errs) -> + start(T, Ms, Cfg, Svc, Tmo, Rest, Errs); + +start(_, _, [], Errs) -> + {error, Errs}. + +%% start/7 + +start(T, [], _, Svc, _, Rest, Errs) -> + start(T, Svc, Rest, Errs); + +start(T, [M|Ms], Cfg, Svc, Tmo, Rest, Errs) -> + case start(M, [T, Svc, Cfg]) of + {ok, TPid} -> + {TPid, [], Tmo, {{T, M, Cfg}, Ms, Rest, Errs}}; + {ok, TPid, [_|_] = Addrs} -> + {TPid, Addrs, Tmo, {{T, M, Cfg}, Ms, Rest, Errs}}; + E -> + start(T, Ms, Cfg, Svc, Tmo, Rest, [E|Errs]) + end. + +%% start/2 + +start(Mod, Args) -> + apply(Mod, start, Args). %%% --------------------------------------------------------------------------- %%% # up/[12] @@ -204,21 +322,6 @@ bang(undefined = No, _) -> bang(Pid, T) -> Pid ! T. -%% split_transport/1 -%% -%% Split options into transport module, transport config and -%% remaining options. - -split_transport(Opts) -> - {[M,C], _} = proplists:split(Opts, [transport_module, - transport_config]), - {value(M, diameter_tcp), value(C, [])}. - -value([{_,V}], _) -> - V; -value([], V) -> - V. - %% call/1 call(Request) -> diff --git a/lib/diameter/src/base/diameter_peer_fsm.erl b/lib/diameter/src/base/diameter_peer_fsm.erl new file mode 100644 index 0000000000..c4320fcb99 --- /dev/null +++ b/lib/diameter/src/base/diameter_peer_fsm.erl @@ -0,0 +1,1162 @@ +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2010-2012. 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% +%% + +%% +%% This module implements (as a process) the RFC 3588 Peer State +%% Machine modulo the necessity of adapting the peer election to the +%% fact that we don't know the identity of a peer until we've +%% received a CER/CEA from it. +%% + +-module(diameter_peer_fsm). +-behaviour(gen_server). + +%% Interface towards diameter_watchdog. +-export([start/3]). + +%% gen_server callbacks +-export([init/1, + handle_call/3, + handle_cast/2, + handle_info/2, + terminate/2, + code_change/3]). + +%% diameter_peer_fsm_sup callback +-export([start_link/1]). + +%% internal callbacks +-export([match/1]). + +-include_lib("diameter/include/diameter.hrl"). +-include("diameter_internal.hrl"). +-include("diameter_gen_base_rfc3588.hrl"). + +%% Values of Disconnect-Cause in DPR. +-define(GOAWAY, ?'DIAMETER_BASE_DISCONNECT-CAUSE_DO_NOT_WANT_TO_TALK_TO_YOU'). +-define(REBOOT, ?'DIAMETER_BASE_DISCONNECT-CAUSE_REBOOTING'). +-define(BUSY, ?'DIAMETER_BASE_DISCONNECT-CAUSE_BUSY'). + +-define(NO_INBAND_SECURITY, 0). +-define(TLS, 1). + +%% Keys in process dictionary. +-define(CB_KEY, cb). %% capabilities callback +-define(DPR_KEY, dpr). %% disconnect callback +-define(DWA_KEY, dwa). %% outgoing DWA +-define(REF_KEY, ref). %% transport_ref() +-define(Q_KEY, q). %% transport start queue +-define(START_KEY, start). %% start of connected transport +-define(SEQUENCE_KEY, mask). %% mask for sequence numbers +-define(RESTRICT_KEY, restrict). %% nodes for connection check + +%% The default sequence mask. +-define(NOMASK, {0,32}). + +%% A 2xxx series Result-Code. Not necessarily 2001. +-define(IS_SUCCESS(N), 2 == (N) div 1000). + +%% Guards. +-define(IS_UINT32(N), (is_integer(N) andalso 0 =< N andalso 0 == N bsr 32)). +-define(IS_TIMEOUT(N), ?IS_UINT32(N)). +-define(IS_CAUSE(N), N == ?REBOOT; N == rebooting; + N == ?GOAWAY; N == goaway; + N == ?BUSY; N == busy). + +%% RFC 3588: +%% +%% Timeout An application-defined timer has expired while waiting +%% for some event. +%% +-define(EVENT_TIMEOUT, 10000). +%% Default timeout for reception of CER/CEA. + +%% Default timeout for DPA in response to DPR. A bit short but the +%% timeout used to be hardcoded. (So it could be worse.) +-define(DPA_TIMEOUT, 1000). + +-type uint32() :: diameter:'Unsigned32'(). + +-record(state, + {state %% of RFC 3588 Peer State Machine + :: 'Wait-Conn-Ack' %% old code + | {'Wait-Conn-Ack', uint32()} + | recv_CER + | 'Wait-CEA' %% old code + | {'Wait-CEA', uint32(), uint32()} + | 'Open', + mode :: accept | connect | {connect, reference()}, + parent :: pid(), %% watchdog process + transport :: pid(), %% transport process + service :: #diameter_service{}, + dpr = false :: false | {uint32(), uint32()}}). + %% | hop by hop and end to end identifiers + +%% 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 +%% know who we're talking to until either a CER or CEA has been +%% received. The CEA problem in particular makes it impossible to +%% follow the state machine exactly as documented in 3588: there can +%% be no election until the CEA arrives and we have an Origin-Host to +%% elect. + +%% +%% Once upon a time start/2 started a process akin to that started by +%% start/3 below, which in turn started a watchdog/transport process +%% with the result that the watchdog could send DWR/DWA regardless of +%% whether or not the corresponding Peer State Machine was in its open +%% state; that is, before capabilities exchange had taken place. This +%% is not what RFC's 3588 and 3539 say (albeit not very clearly). +%% Watchdog messages are only exchanged on *open* connections, so the +%% 3539 state machine is more naturally placed on top of the 3588 Peer +%% State Machine rather than closer to the transport. This is what we +%% now do below: connect/accept call diameter_watchdog and return the +%% pid of the watchdog process, and the watchdog in turn calls start/3 +%% below to start the process implementing the Peer State Machine. The +%% former is a "peer" in diameter_service while the latter is a +%% "conn". In a sense, diameter_service sees the watchdog as +%% implementing the Peer State Machine and the process implemented +%% here as being the transport, not being aware of the watchdog at +%% all. +%% + +%%% --------------------------------------------------------------------------- +%%% # start({connect|accept, Ref}, Opts, Service) +%%% +%%% Output: Pid +%%% --------------------------------------------------------------------------- + +-spec start(T, [Opt], #diameter_service{} %% from old code + | {diameter:sequence(), + diameter:restriction(), + #diameter_service{}}) + -> pid() + when T :: {connect|accept, diameter:transport_ref()}, + Opt :: diameter:transport_opt(). + +%% diameter_config requires a non-empty list of applications on the +%% service but diameter_service then constrains the list to any +%% specified on the transport in question. Check here that the list is +%% still non-empty. + +start({_,_} = Type, Opts, MS) -> + {ok, Pid} = diameter_peer_fsm_sup:start_child({self(), Type, Opts, MS}), + Pid. + +start_link(T) -> + {ok, _} = proc_lib:start_link(?MODULE, + init, + [T], + infinity, + diameter_lib:spawn_opts(server, [])). + +%%% --------------------------------------------------------------------------- +%%% --------------------------------------------------------------------------- + +%% init/1 + +init(T) -> + proc_lib:init_ack({ok, self()}), + gen_server:enter_loop(?MODULE, [], i(T)). + +i({WPid, Type, Opts, #diameter_service{} = Svc}) -> %% from old code + i({WPid, Type, Opts, {?NOMASK, [node() | nodes()], Svc}}); + +i({WPid, T, Opts, {Mask, Nodes, #diameter_service{applications = Apps, + capabilities = LCaps} + = Svc}}) -> + [] /= Apps orelse ?ERROR({no_apps, T, Opts}), + putr(?DWA_KEY, dwa(LCaps)), + {M, Ref} = T, + diameter_stats:reg(Ref), + {[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), + erlang:monitor(process, WPid), + {TPid, Addrs} = start_transport(T, Rest, Svc), + Tmo = proplists:get_value(capx_timeout, Opts, ?EVENT_TIMEOUT), + ?IS_TIMEOUT(Tmo) orelse ?ERROR({invalid, {capx_timeout, Tmo}}), + #state{state = {'Wait-Conn-Ack', Tmo}, + parent = WPid, + transport = TPid, + mode = M, + service = svc(Svc, Addrs)}. +%% 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 +%% sending capabilities exchange messages. +%% +%% Invalid transport config may cause us to crash but note that the +%% watchdog start (start/2) succeeds regardless so as not to crash the +%% service. + +start_transport(T, Opts, #diameter_service{capabilities = LCaps} = Svc) -> + Addrs0 = LCaps#diameter_caps.host_ip_address, + start_transport(Addrs0, {T, Opts, Svc}). + +start_transport(Addrs0, T) -> + case diameter_peer:start(T) of + {TPid, Addrs, Tmo, Data} -> + erlang:monitor(process, TPid), + q_next(TPid, Addrs0, Tmo, Data), + {TPid, addrs(Addrs, Addrs0)}; + No -> + exit({shutdown, No}) + end. + +addrs([], Addrs0) -> + Addrs0; +addrs(Addrs, _) -> + Addrs. + +svc(Svc, []) -> + Svc; +svc(Svc, Addrs) -> + readdr(Svc, Addrs). + +readdr(#diameter_service{capabilities = LCaps0} = Svc, Addrs) -> + LCaps = LCaps0#diameter_caps{host_ip_address = Addrs}, + Svc#diameter_service{capabilities = LCaps}. + +%% The 4-tuple Data returned from diameter_peer:start/1 identifies the +%% transport module/config use to start the transport process in +%% question as well as any alternates to try if a connection isn't +%% established within Tmo. +q_next(TPid, Addrs0, Tmo, {_,_,_,_} = Data) -> + send_after(Tmo, {connection_timeout, TPid}), + putr(?Q_KEY, {Addrs0, Tmo, Data}). + +%% Connection has been established: retain the started +%% pid/module/config in the process dictionary. This is a part of the +%% interface defined by this module, so that the transport pid can be +%% found when constructing service_info (in order to extract further +%% information from it). +keep_transport(TPid) -> + {_, _, {{_,_,_} = T, _, _, _}} = eraser(?Q_KEY), + putr(?START_KEY, {TPid, T}). + +send_after(infinity, _) -> + ok; +send_after(Tmo, T) -> + erlang:send_after(Tmo, self(), T). + +%% handle_call/3 + +handle_call(_, _, State) -> + {reply, nok, State}. + +%% handle_cast/2 + +handle_cast(_, State) -> + {noreply, State}. + +%% handle_info/1 + +handle_info(T, #state{} = State) -> + try transition(T, State) of + ok -> + {noreply, State}; + #state{state = X} = S -> + ?LOGC(X =/= State#state.state, transition, X), + {noreply, S}; + {stop, Reason} -> + ?LOG(stop, Reason), + x(Reason, State); + stop -> + ?LOG(stop, T), + x(T, State) + catch + exit: {diameter_codec, encode, _} = Reason -> + close_wd(Reason, State#state.parent), + ?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}), + {stop, {shutdown, Reason}, State} + 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. + +%% 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 +%% since this can be called before creating the service. + +x(Reason, #state{} = S) -> + close_wd(Reason, S), + {stop, {shutdown, Reason}, S}. + +%% terminate/2 + +terminate(_, _) -> + ok. + +%% code_change/3 + +code_change(_, State, _) -> + {ok, State}. + +%%% --------------------------------------------------------------------------- +%%% --------------------------------------------------------------------------- + +putr(Key, Val) -> + put({?MODULE, Key}, Val). + +getr(Key) -> + get({?MODULE, Key}). + +eraser(Key) -> + erase({?MODULE, Key}). + +%% transition/2 + +%% Started in old code. +transition(T, #state{state = 'Wait-Conn-Ack' = PS} = S) -> + transition(T, S#state{state = {PS, ?EVENT_TIMEOUT}}); + +%% Connection to peer. +transition({diameter, {TPid, connected, Remote}}, + #state{transport = TPid, + state = PS, + mode = M} + = S) -> + {'Wait-Conn-Ack', _} = PS, %% assert + connect = M, %% + keep_transport(TPid), + send_CER(S#state{mode = {M, Remote}}); + +%% Connection from peer. +transition({diameter, {TPid, connected}}, + #state{transport = TPid, + state = PS, + mode = M, + parent = Pid} + = S) -> + {'Wait-Conn-Ack', Tmo} = PS, %% assert + accept = M, %% + keep_transport(TPid), + Pid ! {accepted, self()}, + start_timer(Tmo, S#state{state = recv_CER}); + +%% Connection established after receiving a connection_timeout +%% 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}; + +%% Connection has timed out: start an alternate. +transition({connection_timeout = T, TPid}, + #state{transport = TPid, + state = {'Wait-Conn-Ack', _}} + = S) -> + exit(TPid, {shutdown, T}), + start_next(S); + +%% Connect timeout after connection or alternate start: ignore. +transition({connection_timeout, _}, _) -> + ok; + +%% Incoming message from the transport. +transition({diameter, {recv, Pkt}}, S) -> + recv(Pkt, S); + +%% Timeout when still in the same state ... +transition({timeout, PS}, #state{state = PS}) -> + {stop, {capx(PS), timeout}}; + +%% ... or not. +transition({timeout, _}, _) -> + ok; + +%% Outgoing message. +transition({send, Msg}, #state{transport = TPid}) -> + send(TPid, Msg), + ok; + +%% Messages from old (diameter_service) code. +transition(shutdown = T, #state{parent = Pid} = S) -> + transition({T, Pid, service}, S); %% Reason irrelevant: old code has no cb + +%% Request for graceful shutdown at remove_transport, stop_service of +%% application shutdown. +transition({shutdown = T, Pid}, S) -> + transition({T, Pid, transport}, S); +transition({shutdown, Pid, Reason}, #state{parent = Pid, dpr = false} = S) -> + dpr(Reason, S); +transition({shutdown, Pid, _}, #state{parent = Pid}) -> + ok; + +%% DPA reception has timed out. +transition(dpa_timeout, _) -> + stop; + +%% Someone wants to know a resolved port: forward to the transport process. +transition({resolve_port, _Pid} = T, #state{transport = TPid}) -> + TPid ! T, + ok; + +%% Parent has died. +transition({'DOWN', _, process, WPid, _}, + #state{parent = WPid}) -> + stop; + +%% Transport has died before connection timeout. +transition({'DOWN', _, process, TPid, _}, + #state{transport = TPid} + = S) -> + start_next(S); + +%% Transport has died after connection timeout. +transition({'DOWN', _, process, _, _}, _) -> + ok; + +%% State query. +transition({state, Pid}, #state{state = S, transport = TPid}) -> + Pid ! {self(), [S, TPid]}, + ok. + +%% Crash on anything unexpected. + +capx(recv_CER) -> + 'CER'; +capx({'Wait-CEA', _, _}) -> + 'CEA'. + +%% start_next/1 + +start_next(#state{service = Svc0} = S) -> + case getr(?Q_KEY) of + {Addrs0, Tmo, Data} -> + Svc = readdr(Svc0, Addrs0), + {TPid, Addrs} = start_transport(Addrs0, {Svc, Tmo, Data}), + S#state{transport = TPid, + service = svc(Svc, Addrs)}; + undefined -> + stop + end. + +%% send_CER/1 + +send_CER(#state{state = {'Wait-Conn-Ack', Tmo}, + mode = {connect, Remote}, + service = #diameter_service{capabilities = LCaps}, + transport = TPid} + = S) -> + OH = LCaps#diameter_caps.origin_host, + req_send_CER(OH, Remote) + orelse + close({already_connected, Remote, LCaps}, S), + 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), + send(TPid, Pkt), + start_timer(Tmo, S#state{state = {'Wait-CEA', Hid, Eid}}). + +%% Register ourselves as connecting to the remote endpoint in +%% question. This isn't strictly necessary since a peer implementing +%% the 3588 Peer State Machine should reject duplicate connection's +%% from the same peer but there's little point in us setting up a +%% duplicate connection in the first place. This could also include +%% the transport protocol being used but since we're blind to +%% transport just avoid duplicate connections to the same host/port. +req_send_CER(OriginHost, Remote) -> + register_everywhere({?MODULE, connection, OriginHost, {remote, Remote}}). + +%% start_timer/2 + +start_timer(Tmo, #state{state = PS} = S) -> + erlang:send_after(Tmo, self(), {timeout, PS}), + S. + +%% build_CER/1 + +build_CER(#state{service = #diameter_service{capabilities = LCaps}}) -> + {ok, CER} = diameter_capx:build_CER(LCaps), + CER. + +%% encode/1 + +encode(Rec) -> + Seq = diameter_session:sequence(sequence()), + Hdr = #diameter_header{version = ?DIAMETER_VERSION, + end_to_end_id = Seq, + hop_by_hop_id = Seq}, + diameter_codec:encode(?BASE, #diameter_packet{header = Hdr, + msg = Rec}). + +sequence() -> + case getr(?SEQUENCE_KEY) of + {_,_} = Mask -> + Mask; + undefined -> %% started in old code + putr(?SEQUENCE_KEY, ?NOMASK), + ?NOMASK + end. + +%% recv/2 + +%% RFC 3588 has result code 5015 for an invalid length but if a +%% transport is detecting message boundaries using the length header +%% then a length error will likely lead to further errors. + +recv(#diameter_packet{header = #diameter_header{length = Len} + = Hdr, + bin = Bin}, + S) + when Len < 20; + (0 /= Len rem 4 orelse bit_size(Bin) /= 8*Len) -> + discard(invalid_message_length, recv, [size(Bin), + bit_size(Bin) rem 8, + Hdr, + S]); + +recv(#diameter_packet{header = #diameter_header{} = Hdr} + = Pkt, + #state{parent = Pid} + = S) -> + Name = diameter_codec:msg_name(Hdr), + Pid ! {recv, self(), Name, Pkt}, + diameter_stats:incr({msg_id(Name, Hdr), recv}), %% count received + rcv(Name, Pkt, S); + +recv(#diameter_packet{header = undefined, + bin = Bin} + = Pkt, + S) -> + recv(Pkt#diameter_packet{header = diameter_codec:decode_header(Bin)}, S); + +recv(Bin, S) + when is_binary(Bin) -> + recv(#diameter_packet{bin = Bin}, S); + +recv(#diameter_packet{header = false} = Pkt, S) -> + discard(truncated_header, recv, [Pkt, S]). + +msg_id({_,_,_} = T, _) -> + T; +msg_id(_, Hdr) -> + diameter_codec:msg_id(Hdr). + +%% Treat invalid length as a transport error and die. Especially in +%% the TCP case, in which there's no telling where the next message +%% begins in the incoming byte stream, keeping a crippled connection +%% alive may just make things worse. + +discard(Reason, F, A) -> + diameter_stats:incr(Reason), + diameter_lib:warning_report(Reason, {?MODULE, F, A}), + throw({?MODULE, abort, Reason}). + +%% rcv/3 + +%% Incoming CEA. +rcv('CEA', + #diameter_packet{header = #diameter_header{end_to_end_id = Eid, + hop_by_hop_id = Hid}} + = Pkt, + #state{state = {'Wait-CEA' = T, Hid, Eid}} + = S) -> + handle_CEA(Pkt, S#state{state = T}); +rcv('CEA', Pkt, #state{state = 'Wait-CEA'} = S) -> %% old code + handle_CEA(Pkt, S); + +%% Incoming CER +rcv('CER' = N, Pkt, #state{state = recv_CER} = S) -> + handle_request(N, Pkt, S); + +%% Anything but CER/CEA in a non-Open state is an error, as is +%% CER/CEA in anything but recv_CER/Wait-CEA. +rcv(Name, _, #state{state = PS}) + when PS /= 'Open'; + Name == 'CER'; + Name == 'CEA' -> + {stop, {Name, PS}}; + +rcv(N, Pkt, S) + when N == 'DWR'; + N == 'DPR' -> + handle_request(N, Pkt, S); + +%% DPA in response to DPR and 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}}) -> + diameter_peer:close(TPid), + {stop, N}; + +%% Ignore anything else, an unsolicited DPA in particular. +rcv(_, _, _) -> + ok. + +%% 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). + +%% handle_request/3 + +handle_request(Type, #diameter_packet{} = Pkt, S) -> + ?LOG(recv, Type), + send_answer(Type, diameter_codec:decode(?BASE, Pkt), S). + +%% send_answer/3 + +send_answer(Type, ReqPkt, #state{transport = TPid} = S) -> + #diameter_packet{header = H, + transport_data = TD} + = ReqPkt, + + {Msg, PostF} = build_answer(Type, ReqPkt, S), + + %% An answer message clears the R and T flags and retains the P + %% flag. The E flag is set at encode. + Pkt = #diameter_packet{header + = H#diameter_header{version = ?DIAMETER_VERSION, + is_request = false, + is_error = undefined, + is_retransmitted = false}, + msg = Msg, + transport_data = TD}, + + send(TPid, diameter_codec:encode(?BASE, Pkt)), + eval(PostF, S). + +eval([F|A], S) -> + apply(F, A ++ [S]); +eval(ok, S) -> + S. + +%% build_answer/3 + +build_answer('CER', + #diameter_packet{msg = CER, + header = #diameter_header{version + = ?DIAMETER_VERSION, + is_error = false}, + errors = []} + = Pkt, + S) -> + {SupportedApps, RCaps, #diameter_base_CEA{'Result-Code' = RC, + 'Inband-Security-Id' = IS} + = CEA} + = recv_CER(CER, S), + + #diameter_caps{origin_host = {OH, DH}} + = Caps + = capz(caps(S), RCaps), + + try + 2001 == RC %% DIAMETER_SUCCESS + orelse ?THROW(RC), + register_everywhere({?MODULE, connection, OH, DH}) + orelse ?THROW(4003), %% DIAMETER_ELECTION_LOST + caps_cb(Caps) + of + N -> {cea(CEA, N), [fun open/5, Pkt, + SupportedApps, + Caps, + {accept, hd([_] = IS)}]} + catch + ?FAILURE(Reason) -> + rejected(Reason, {'CER', Reason, Caps, Pkt}, S) + end; + +%% The error checks below are similar to those in diameter_service for +%% other messages. Should factor out the commonality. + +build_answer(Type, + #diameter_packet{header = H, + errors = Es} + = Pkt, + S) -> + RC = rc(H, Es), + {answer(Type, RC, Es, S), post(Type, RC, Pkt, S)}. + +cea(CEA, ok) -> + CEA; +cea(CEA, 2001) -> + CEA; +cea(CEA, RC) -> + CEA#diameter_base_CEA{'Result-Code' = RC}. + +post('CER' = T, RC, Pkt, S) -> + [fun close/2, {T, caps(S), {RC, Pkt}}]; +post(_, _, _, _) -> + ok. + +rejected({capabilities_cb, _F, Reason}, T, S) -> + rejected(Reason, T, S); + +rejected(discard, T, S) -> + close(T, S); +rejected({N, Es}, T, S) -> + {answer('CER', N, Es, S), [fun close/2, T]}; +rejected(N, T, S) -> + rejected({N, []}, T, S). + +answer(Type, RC, Es, S) -> + set(answer(Type, RC, S), failed_avp([A || {_,A} <- Es])). + +answer(Type, RC, S) -> + answer_message(answer(Type, S), RC). + +%% answer_message/2 + +answer_message([_ | Avps], RC) + when 3000 =< RC, RC < 4000 -> + ['answer-message', {'Result-Code', RC} + | lists:filter(fun is_origin/1, Avps)]; + +answer_message(Msg, RC) -> + Msg ++ [{'Result-Code', RC}]. + +is_origin({N, _}) -> + N == 'Origin-Host' + orelse N == 'Origin-Realm' + orelse N == 'Origin-State-Id'. + +%% failed_avp/1 + +failed_avp([] = No) -> + No; +failed_avp(Avps) -> + [{'Failed-AVP', [[{'AVP', Avps}]]}]. + +%% set/2 + +set(Ans, []) -> + Ans; +set(['answer-message' | _] = Ans, FailedAvp) -> + Ans ++ [{'AVP', [FailedAvp]}]; +set([_|_] = Ans, FailedAvp) -> + Ans ++ FailedAvp. + +%% rc/2 + +rc(#diameter_header{is_error = true}, _) -> + 3008; %% DIAMETER_INVALID_HDR_BITS + +rc(_, [Bs|_]) + when is_bitstring(Bs) -> + 3009; %% DIAMETER_INVALID_HDR_BITS + +rc(#diameter_header{version = ?DIAMETER_VERSION}, Es) -> + rc(Es); + +rc(_, _) -> + 5011. %% DIAMETER_UNSUPPORTED_VERSION + +%% rc/1 + +rc([]) -> + 2001; %% DIAMETER_SUCCESS +rc([{RC,_}|_]) -> + RC; +rc([RC|_]) -> + RC. + +%% DIAMETER_INVALID_HDR_BITS 3008 +%% A request was received whose bits in the Diameter header were +%% either set to an invalid combination, or to a value that is +%% inconsistent with the command code's definition. + +%% 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. + +%% ELECTION_LOST 4003 +%% The peer has determined that it has lost the election process and +%% has therefore disconnected the transport connection. + +%% DIAMETER_NO_COMMON_APPLICATION 5010 +%% This error is returned when a CER message is received, and there +%% are no common applications supported between the peers. + +%% DIAMETER_UNSUPPORTED_VERSION 5011 +%% This error is returned when a request was received, whose version +%% number is unsupported. + +%% answer/2 + +answer('DWR', _) -> + getr(?DWA_KEY); + +answer(Name, #state{service = #diameter_service{capabilities = Caps}}) -> + a(Name, Caps). + +a('CER', #diameter_caps{vendor_id = Vid, + origin_host = Host, + origin_realm = Realm, + host_ip_address = Addrs, + product_name = Name, + origin_state_id = OSI}) -> + ['CEA', {'Origin-Host', Host}, + {'Origin-Realm', Realm}, + {'Host-IP-Address', Addrs}, + {'Vendor-Id', Vid}, + {'Product-Name', Name}, + {'Origin-State-Id', OSI}]; + +a('DPR', #diameter_caps{origin_host = {Host, _}, + origin_realm = {Realm, _}}) -> + ['DPA', {'Origin-Host', Host}, + {'Origin-Realm', Realm}]. + +%% recv_CER/2 + +recv_CER(CER, #state{service = Svc}) -> + {ok, T} = diameter_capx:recv_CER(CER, Svc), + T. + +%% handle_CEA/1 + +handle_CEA(#diameter_packet{bin = Bin} + = Pkt, + #state{service = #diameter_service{capabilities = LCaps}} + = S) + when is_binary(Bin) -> + ?LOG(recv, 'CEA'), + + #diameter_packet{msg = CEA} + = DPkt + = diameter_codec:decode(?BASE, Pkt), + + {SApps, IS, RCaps} = recv_CEA(DPkt, S), + + #diameter_caps{origin_host = {OH, DH}} + = Caps + = capz(LCaps, RCaps), + + #diameter_base_CEA{'Result-Code' = RC} + = 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 + %% receive a CER/CEA, the first that arrives wins the right to a + %% connection with the peer. + + try + ?IS_SUCCESS(RC) + orelse ?THROW(RC), + [] == SApps + andalso ?THROW(no_common_application), + [] == IS + andalso ?THROW(no_common_security), + register_everywhere({?MODULE, connection, OH, DH}) + orelse ?THROW(election_lost), + caps_cb(Caps) + of + _ -> open(DPkt, SApps, Caps, {connect, hd([_] = IS)}, S) + catch + ?FAILURE(Reason) -> close({'CEA', Reason, Caps, DPkt}, S) + end. +%% Check more than the result code since the peer could send success +%% regardless. If not 2001 then a peer_up callback could do anything +%% required. It's not unimaginable that a peer agreeing to TLS after +%% capabilities exchange could send DIAMETER_LIMITED_SUCCESS = 2002, +%% even if this isn't required by RFC 3588. + +%% recv_CEA/2 + +recv_CEA(#diameter_packet{header = #diameter_header{version + = ?DIAMETER_VERSION, + is_error = false}, + msg = CEA, + errors = []}, + #state{service = Svc}) -> + {ok, T} = diameter_capx:recv_CEA(CEA, Svc), + T; + +recv_CEA(Pkt, S) -> + close({'CEA', caps(S), Pkt}, S). + +caps(#diameter_service{capabilities = Caps}) -> + Caps; +caps(#state{service = Svc}) -> + caps(Svc). + +%% caps_cb/1 + +caps_cb(Caps) -> + {Ref, Ts} = eraser(?CB_KEY), + caps_cb(Ts, [Ref, Caps]). + +caps_cb([], _) -> + ok; +caps_cb([F | Rest], T) -> + case diameter_lib:eval([F|T]) of + ok -> + caps_cb(Rest, T); + N when ?IS_SUCCESS(N) -> %% 2xxx result code: accept immediately + N; + Res -> + ?THROW({capabilities_cb, F, rejected(Res)}) + end. +%% Note that returning 2xxx causes the capabilities exchange to be +%% accepted directly, without further callbacks. + +rejected(discard = T) -> + T; +rejected(unknown) -> + 3010; %% DIAMETER_UNKNOWN_PEER +rejected(N) + when is_integer(N) -> + N. + +%% open/5 + +open(Pkt, SupportedApps, Caps, {Type, IS}, #state{parent = Pid, + service = Svc} + = S) -> + #diameter_caps{origin_host = {_,_} = H, + inband_security_id = {LS,_}} + = Caps, + + tls_ack(lists:member(?TLS, LS), Caps, Type, IS, S), + Pid ! {open, self(), H, {Caps, SupportedApps, Pkt}}, + + %% Replace capabilities record with local/remote pairs. + S#state{state = 'Open', + service = Svc#diameter_service{capabilities = Caps}}. + +%% We've advertised TLS support: tell the transport the result +%% and expect a reply when the handshake is complete. +tls_ack(true, Caps, Type, IS, #state{transport = TPid} = S) -> + Ref = make_ref(), + TPid ! {diameter, {tls, Ref, Type, IS == ?TLS}}, + receive + {diameter, {tls, Ref}} -> + ok; + {'DOWN', _, process, TPid, Reason} -> + close({tls_ack, Reason, Caps}, S) + end; + +%% Or not. Don't send anything to the transport so that transports +%% not supporting TLS work as before without modification. +tls_ack(false, _, _, _, _) -> + ok. + +capz(#diameter_caps{} = L, #diameter_caps{} = R) -> + #diameter_caps{} + = list_to_tuple([diameter_caps | lists:zip(tl(tuple_to_list(L)), + tl(tuple_to_list(R)))]). + +%% close/2 + +%% Tell the watchdog that our death isn't due to transport failure. +close(Reason, #state{parent = Pid}) -> + close_wd(Reason, Pid), + throw({?MODULE, close, Reason}). + +%% close_wd/2 + +%% Ensure the watchdog dies if DPR has been sent ... +close_wd(_, #state{dpr = false}) -> + ok; +close_wd(Reason, #state{parent = Pid}) -> + close_wd(Reason, Pid); + +%% ... or otherwise +close_wd(Reason, Pid) -> + Pid ! {close, self(), Reason}. + +%% 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 +%% 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 +%% yet reached Open. + +%% Connection is open, DPR has not been sent. +dpr(Reason, #state{state = 'Open', + dpr = false, + service = #diameter_service{capabilities = Caps}} + = S) -> + case getr(?DPR_KEY) of + CBs when is_list(CBs) -> + Ref = getr(?REF_KEY), + Peer = {self(), Caps}, + dpr(CBs, [Reason, Ref, Peer], S); + undefined -> %% started in old code + send_dpr(Reason, [], S) + end; + +%% Connection is open, DPR already sent. +dpr(_, #state{state = 'Open'}) -> + ok; + +%% Connection not open. +dpr(_Reason, _S) -> + stop. + +%% dpr/3 +%% +%% Note that an implementation that wants to do something +%% transport_module-specific can lookup the pid of the transport +%% process and contact it. (eg. diameter:service_info/2) + +dpr([CB|Rest], [Reason | _] = Args, S) -> + try diameter_lib:eval([CB | Args]) of + {dpr, Opts} when is_list(Opts) -> + send_dpr(Reason, Opts, S); + dpr -> + send_dpr(Reason, [], S); + close = T -> + {stop, {disconnect_cb, T}}; + 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} + end; + +dpr([], [Reason | _], S) -> + send_dpr(Reason, [], S). + +-record(opts, {cause, timeout = ?DPA_TIMEOUT}). + +send_dpr(Reason, Opts, #state{transport = TPid, + service = #diameter_service{capabilities = Caps}} + = S) -> + #opts{cause = Cause, timeout = Tmo} + = lists:foldl(fun opt/2, + #opts{cause = case Reason of + transport -> ?GOAWAY; + _ -> ?REBOOT + end, + 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}, + {'Origin-Realm', OR}, + {'Disconnect-Cause', Cause}]), + send(TPid, Pkt), + dpa_timer(Tmo), + ?LOG(send, 'DPR'), + S#state{dpr = {Hid, Eid}}. + +opt({timeout, Tmo}, Rec) + when ?IS_TIMEOUT(Tmo) -> + Rec#opts{timeout = Tmo}; +opt({cause, Cause}, Rec) + when ?IS_CAUSE(Cause) -> + Rec#opts{cause = cause(Cause)}; +opt(T, _) -> + ?ERROR({invalid_option, T}). + +cause(rebooting) -> ?REBOOT; +cause(goaway) -> ?GOAWAY; +cause(busy) -> ?BUSY; +cause(N) + when ?IS_CAUSE(N) -> + N; +cause(N) -> + ?ERROR({invalid_cause, N}). + +dpa_timer(Tmo) -> + erlang:send_after(Tmo, self(), dpa_timeout). + +%% register_everywhere/1 +%% +%% Register a term and ensure it's not registered elsewhere. Note that +%% two process that simultaneously register the same term may well +%% both fail to do so this isn't foolproof. +%% +%% Everywhere is no longer everywhere, it's where a +%% restrict_connections service_opt() specifies. + +register_everywhere(T) -> + reg(getr(?RESTRICT_KEY), T). + +reg(Nodes, T) -> + add(lists:member(node(), Nodes), T) andalso unregistered(Nodes, T). + +add(true, T) -> + diameter_reg:add_new(T); +add(false, T) -> + diameter_reg:add(T). + +%% unregistered +%% +%% Ensure that the term in question isn't registered on other nodes. + +unregistered(Nodes, T) -> + {ResL, _} = rpc:multicall(Nodes, ?MODULE, match, [{node(), T}]), + lists:all(fun nomatch/1, ResL). + +nomatch({badrpc, {'EXIT', {undef, _}}}) -> %% no diameter on remote node + true; +nomatch(L) -> + [] == L. + +%% match/1 + +match({Node, _}) + when Node == node() -> + []; +match({_, T}) -> + try + diameter_reg:match(T) + catch + _:_ -> [] + end. diff --git a/lib/diameter/src/app/diameter_peer_fsm_sup.erl b/lib/diameter/src/base/diameter_peer_fsm_sup.erl index 995eaf74d0..995eaf74d0 100644 --- a/lib/diameter/src/app/diameter_peer_fsm_sup.erl +++ b/lib/diameter/src/base/diameter_peer_fsm_sup.erl diff --git a/lib/diameter/src/base/diameter_reg.erl b/lib/diameter/src/base/diameter_reg.erl new file mode 100644 index 0000000000..619b12ecad --- /dev/null +++ b/lib/diameter/src/base/diameter_reg.erl @@ -0,0 +1,356 @@ +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2010-2012. 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% +%% + +%% +%% The module implements a simple term -> pid registry. +%% + +-module(diameter_reg). +-compile({no_auto_import, [monitor/2]}). + +-behaviour(gen_server). + +-export([add/1, + add_new/1, + del/1, + repl/2, + match/1, + wait/1]). + +-export([start_link/0]). + +%% gen_server callbacks +-export([init/1, + terminate/2, + handle_call/3, + handle_cast/2, + handle_info/2, + code_change/3]). + +%% test +-export([pids/0, + terms/0]). + +%% debug +-export([state/0, + uptime/0]). + +-include("diameter_internal.hrl"). + +-define(SERVER, ?MODULE). +-define(TABLE, ?MODULE). + +%% Table entry used to keep from starting more than one monitor on the +%% same process. This isn't a problem but there's no point in starting +%% multiple monitors if we can avoid it. Note that we can't have a 2-tuple +%% keyed on Pid since a registered term can be anything. Want the entry +%% keyed on Pid so that lookup is fast. +-define(MONITOR(Pid, MRef), {Pid, monitor, MRef}). + +%% Table entry containing the Term -> Pid mapping. +-define(MAPPING(Term, Pid), {Term, Pid}). + +-record(state, {id = now(), + q = []}). %% [{From, Pat}] + +%% =========================================================================== +%% # add(T) +%% +%% Associate the specified term with self(). The list of pids having +%% this or other assocations can be retrieved using match/1. +%% +%% An association is removed when the calling process dies or as a +%% result of calling del/1. Adding the same term more than once is +%% equivalent to adding it exactly once. +%% +%% Note that since match/1 takes a pattern as argument, specifying a +%% term that contains match variables is probably not a good idea +%% =========================================================================== + +-spec add(any()) + -> true. + +add(T) -> + call({add, fun ets:insert/2, T, self()}). + +%% =========================================================================== +%% # add_new(T) +%% +%% Like add/1 but only one process is allowed to have the the +%% association, false being returned if an association already exists. +%% =========================================================================== + +-spec add_new(any()) + -> boolean(). + +add_new(T) -> + call({add, fun insert_new/2, T, self()}). + +%% =========================================================================== +%% # repl(T, NewT) +%% +%% Like add/1 but only replace an existing association on T, false +%% being returned if it doesn't exist. +%% =========================================================================== + +-spec repl(any(), any()) + -> boolean(). + +repl(T, U) -> + call({repl, T, U, self()}). + +%% =========================================================================== +%% # del(Term) +%% +%% Remove any existing association of Term with self(). +%% =========================================================================== + +-spec del(any()) + -> true. + +del(T) -> + call({del, T, self()}). + +%% =========================================================================== +%% # match(Pat) +%% +%% Return the list of associations whose Term, as specified to add/1 +%% or add_new/1, matches the specified pattern. +%% +%% Note that there's no guarantee that the returned processes are +%% still alive. (Although one that isn't will soon have its +%% associations removed.) +%% =========================================================================== + +-spec match(tuple()) + -> [{term(), pid()}]. + +match(Pat) -> + ets:match_object(?TABLE, ?MAPPING(Pat, '_')). + +%% =========================================================================== +%% # wait(Pat) +%% +%% Like match/1 but return only when the result is non-empty or fails. +%% It's up to the caller to ensure that the wait won't be forever. +%% =========================================================================== + +wait(Pat) -> + call({wait, Pat}). + +%% =========================================================================== + +start_link() -> + ServerName = {local, ?SERVER}, + Options = [{spawn_opt, diameter_lib:spawn_opts(server, [])}], + gen_server:start_link(ServerName, ?MODULE, [], Options). + +state() -> + call(state). + +uptime() -> + call(uptime). + +%% pids/0 +%% +%% Return: list of {Pid, [Term, ...]} + +pids() -> + to_list(fun swap/1). + +to_list(Fun) -> + ets:foldl(fun(T,A) -> acc(Fun, T, A) end, orddict:new(), ?TABLE). + +acc(Fun, ?MAPPING(Term, Pid), Dict) -> + append(Fun({Term, Pid}), Dict); +acc(_, _, Dict) -> + Dict. + +append({K,V}, Dict) -> + orddict:append(K, V, Dict). + +id(T) -> T. + +%% terms/0 +%% +%% Return: list of {Term, [Pid, ...]} + +terms() -> + to_list(fun id/1). + +swap({X,Y}) -> {Y,X}. + +%% ---------------------------------------------------------- +%% # init/1 +%% ---------------------------------------------------------- + +init(_) -> + ets:new(?TABLE, [bag, named_table]), + {ok, #state{}}. + +%% ---------------------------------------------------------- +%% # handle_call/3 +%% ---------------------------------------------------------- + +handle_call(Req, From, S) + when not is_record(S, state) -> + handle_call(Req, From, upgrade(S)); + +handle_call({add, Fun, Key, Pid}, _, S) -> + B = Fun(?TABLE, {Key, Pid}), + monitor(B andalso no_monitor(Pid), Pid), + {reply, B, pending(B, S)}; + +handle_call({del, Key, Pid}, _, S) -> + {reply, ets:delete_object(?TABLE, ?MAPPING(Key, Pid)), S}; + +handle_call({repl, T, U, Pid}, _, S) -> + MatchSpec = [{?MAPPING('$1', Pid), + [{'=:=', '$1', {const, T}}], + ['$_']}], + {reply, repl(ets:select(?TABLE, MatchSpec), U, Pid), S}; + +handle_call({wait, Pat}, From, #state{q = Q} = S) -> + case find(Pat) of + {ok, L} -> + {reply, L, S}; + false -> + {noreply, S#state{q = [{From, Pat} | Q]}} + end; + +handle_call(state, _, S) -> + {reply, S, S}; + +handle_call(uptime, _, #state{id = Time} = S) -> + {reply, diameter_lib:now_diff(Time), S}; + +handle_call(Req, From, S) -> + ?UNEXPECTED([Req, From]), + {reply, nok, S}. + +%% ---------------------------------------------------------- +%% # handle_cast/2 +%% ---------------------------------------------------------- + +handle_cast(Msg, S)-> + ?UNEXPECTED([Msg]), + {noreply, S}. + +%% ---------------------------------------------------------- +%% # handle_info/2 +%% ---------------------------------------------------------- + +handle_info({'DOWN', MRef, process, Pid, _}, S) -> + ets:delete_object(?TABLE, ?MONITOR(Pid, MRef)), + ets:match_delete(?TABLE, ?MAPPING('_', Pid)), + {noreply, S}; + +handle_info(Info, S) -> + ?UNEXPECTED([Info]), + {noreply, S}. + +%% ---------------------------------------------------------- +%% # terminate/2 +%% ---------------------------------------------------------- + +terminate(_Reason, _State)-> + ok. + +%% ---------------------------------------------------------- +%% # code_change/3 +%% ---------------------------------------------------------- + +code_change(_OldVsn, State, _Extra) -> + {ok, State}. + +%% =========================================================================== + +upgrade(S) -> + #state{} = list_to_tuple(tuple_to_list(S) ++ [[]]). + +monitor(true, Pid) -> + ets:insert(?TABLE, ?MONITOR(Pid, erlang:monitor(process, Pid))); +monitor(false, _) -> + ok. + +%% Do we need a monitor for the specified Pid? +no_monitor(Pid) -> + [] == ets:match_object(?TABLE, ?MONITOR(Pid, '_')). + +%% insert_new/2 + +insert_new(?TABLE, {Key, _} = T) -> + flush(ets:lookup(?TABLE, Key)), + ets:insert_new(?TABLE, T). + +%% Remove any processes that are dead but for which we may not have +%% received 'DOWN' yet. This is to ensure that add_new can be used +%% to register a unique name each time a process restarts. +flush(List) -> + lists:foreach(fun({_,P} = T) -> + del(erlang:is_process_alive(P), T) + end, + List). + +del(Alive, T) -> + Alive orelse ets:delete_object(?TABLE, T). + +%% repl/3 + +repl([?MAPPING(_, Pid) = M], Key, Pid) -> + ets:delete_object(?TABLE, M), + true = ets:insert(?TABLE, ?MAPPING(Key, Pid)); +repl([], _, _) -> + false. + +%% pending/1 + +pending(true, #state{q = [_|_] = Q} = S) -> + S#state{q = q(lists:reverse(Q), [])}; %% retain reply order +pending(_, S) -> + S. + +q([], Q) -> + Q; +q([{From, Pat} = T | Rest], Q) -> + case find(Pat) of + {ok, L} -> + gen_server:reply(From, L), + q(Rest, Q); + false -> + q(Rest, [T|Q]) + end. + +%% find/1 + +find(Pat) -> + try match(Pat) of + [] -> + false; + L -> + {ok, L} + catch + _:_ -> + {ok, []} + end. + +%% call/1 + +call(Request) -> + gen_server:call(?SERVER, Request, infinity). diff --git a/lib/diameter/src/app/diameter_service.erl b/lib/diameter/src/base/diameter_service.erl index 421e36ccf5..66c526b379 100644 --- a/lib/diameter/src/app/diameter_service.erl +++ b/lib/diameter/src/base/diameter_service.erl @@ -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 @@ -43,8 +43,7 @@ subscriptions/0, services/0, services/1, - whois/1, - flush_stats/1]). + whois/1]). %% test/debug -export([call_module/3, @@ -64,15 +63,34 @@ -include_lib("diameter/include/diameter.hrl"). -include("diameter_internal.hrl"). --include("diameter_types.hrl"). +%% The states mirrored by peer_up/peer_down callbacks. -define(STATE_UP, up). -define(STATE_DOWN, down). +-type op_state() :: ?STATE_UP + | ?STATE_DOWN. + +%% The RFC 3539 watchdog states that are now maintained, albeit +%% along with the old up/down. okay = up, else down. +-define(WD_INITIAL, initial). +-define(WD_OKAY, okay). +-define(WD_SUSPECT, suspect). +-define(WD_DOWN, down). +-define(WD_REOPEN, reopen). + +-type wd_state() :: ?WD_INITIAL + | ?WD_OKAY + | ?WD_SUSPECT + | ?WD_DOWN + | ?WD_REOPEN. + -define(DEFAULT_TC, 30000). %% RFC 3588 ch 2.1 -define(DEFAULT_TIMEOUT, 5000). %% for outgoing requests -define(RESTART_TC, 1000). %% if restart was this recent +-define(RELAY, ?DIAMETER_DICT_RELAY). + %% 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 @@ -89,6 +107,12 @@ %% process. -define(STATE_TABLE, ?MODULE). +%% The default sequence mask. +-define(NOMASK, {0,32}). + +%% The default restrict_connections. +-define(RESTRICT, nodes). + %% Workaround for dialyzer's lack of understanding of match specs. -type match(T) :: T | '_' | '$1' | '$2' | '$3' | '$4'. @@ -96,15 +120,18 @@ %% State of service gen_server. -record(state, {id = now(), - service_name, %% as passed to start_service/2, key in ?STATE_TABLE + service_name, %% as passed to start_service/2, key in ?STATE_TABLE service :: #diameter_service{}, - peerT = ets_new(peers) :: ets:tid(), %% #peer{} at start_fsm - connT = ets_new(conns) :: ets:tid(), %% #conn{} at connection_up - share_peers = false :: boolean(), %% broadcast peers to remote nodes? - use_shared_peers = false :: boolean(), %% use broadcasted peers? + peerT = ets_new(peers) :: ets:tid(),%% #peer{} at start_fsm + connT = ets_new(conns) :: ets:tid(),%% #conn{} at connection_up/reopen shared_peers = ?Dict:new(), %% Alias -> [{TPid, Caps}, ...] local_peers = ?Dict:new(), %% Alias -> [{TPid, Caps}, ...] - monitor = false :: false | pid()}). %% process to die with + monitor = false :: false | pid(), %% process to die with + options + :: [{sequence, diameter:sequence()} %% sequence mask + | {restrict_connections, diameter:restriction()} + | {share_peers, boolean()} %% broadcast peers to remote nodes? + | {use_shared_peers, boolean()}]}).%% use broadcasted peers? %% shared_peers reflects the peers broadcast from remote nodes. Note %% that the state term itself doesn't change, which is relevant for %% the stateless application callbacks since the state is retrieved @@ -112,21 +139,33 @@ %% service record is used to determine whether or not we need to call %% the process for a pick_peer callback. -%% Record representing a watchdog process. +%% Record representing a watchdog process as implemented by +%% diameter_watchdog. The term "peer" here is historical, made +%% especially confusing by the fact that a peer_ref() in the +%% documentation is the key of a #conn{} record, not a #peer{} record. +%% The name is also unfortunate given the meaning of peer in the +%% Diameter sense. -record(peer, {pid :: match(pid()), type :: match(connect | accept), ref :: match(reference()), %% key into diameter_config - options :: match([transport_opt()]), %% as passed to start_transport - op_state = ?STATE_DOWN :: match(?STATE_DOWN | ?STATE_UP), + options :: match([diameter:transport_opt()]),%% from start_transport + op_state = {?STATE_DOWN, ?WD_INITIAL} + :: match(op_state() | {op_state(), wd_state()}), started = now(), %% at process start conn = false :: match(boolean() | pid())}). - %% true at accept, pid() at connection_up (connT key) - -%% Record representing a peer_fsm process. + %% true at accepted, pid() at connection_up or reopen + +%% Record representing a peer process as implemented by +%% diameter_peer_fsm. The term "conn" is historical. Despite the name +%% here, comments refer to watchdog and peer processes, that are keys +%% in #peer{} and #conn{} records respectively. To add to the +%% confusion, a #request.transport is a peer process = key in a +%% #conn{} record. The actual transport process (that the peer process +%% knows about and that has a transport connection) isn't seen here. -record(conn, {pid :: pid(), - apps :: [{0..16#FFFFFFFF, app_alias()}], %% {Id, Alias} + apps :: [{0..16#FFFFFFFF, diameter:app_alias()}], %% {Id, Alias} caps :: #diameter_caps{}, started = now(), %% at process start peer :: pid()}). %% key into peerT @@ -137,34 +176,19 @@ handler :: match(pid()), %% request process transport :: match(pid()), %% peer process caps :: match(#diameter_caps{}), - app :: match(app_alias()), %% #diameter_app.alias - dictionary :: match(module()), %% #diameter_app.dictionary - module :: match(nonempty_improper_list(module(), list())), - %% #diameter_app.module - filter :: match(peer_filter()), + app :: match(diameter:app_alias()),%% #diameter_app.alias + dictionary :: match(module()), %% #diameter_app.dictionary + module :: match([module() | list()]), %% #diameter_app.module + filter :: match(diameter:peer_filter()), packet :: match(#diameter_packet{})}). %% Record call/4 options are parsed into. -record(options, - {filter = none :: peer_filter(), + {filter = none :: diameter:peer_filter(), extra = [] :: list(), timeout = ?DEFAULT_TIMEOUT :: 0..16#FFFFFFFF, detach = false :: boolean()}). -%% Since RFC 3588 requires that a Diameter agent not modify End-to-End -%% Identifiers, the possibility of explicitly setting an End-to-End -%% Identifier would be needed to be able to implement an agent in -%% which one side of the communication is not implemented on top of -%% diameter. For example, Diameter being sent or received encapsulated -%% in some other protocol, or even another Diameter stack in a -%% non-Erlang environment. (Not that this is likely to be a normal -%% case.) -%% -%% The implemented solution is not an option but to respect any header -%% values set in a diameter_header record returned from a -%% prepare_request callback. A call to diameter:call/4 can communicate -%% values to the callback using the 'extra' option if so desired. - %%% --------------------------------------------------------------------------- %%% # start(SvcName) %%% --------------------------------------------------------------------------- @@ -217,20 +241,20 @@ stop_transport(SvcName, [_|_] = Refs) -> %%% --------------------------------------------------------------------------- info(SvcName, Item) -> - info_rc(call_service_by_name(SvcName, {info, Item})). - -info_rc({error, _}) -> - undefined; -info_rc(Info) -> - Info. + case find_state(SvcName) of + #state{} = S -> + service_info(Item, S); + false -> + undefined + end. %%% --------------------------------------------------------------------------- %%% # receive_message(TPid, Pkt, MessageData) %%% --------------------------------------------------------------------------- -%% Handle an incoming message in the watchdog process. This used to -%% come through the service process but this avoids that becoming a -%% bottleneck. +%% Handle an incoming Diameter message in the watchdog process. This +%% used to come through the service process but this avoids that +%% becoming a bottleneck. receive_message(TPid, Pkt, T) when is_pid(TPid) -> @@ -310,21 +334,39 @@ call_rc(_, _, Sent) -> %% In the process spawned for the outgoing request. call(SvcName, App, Msg, Opts, Caller) -> - c(ets:lookup(?STATE_TABLE, SvcName), App, Msg, Opts, Caller). + c(find_state(SvcName), App, Msg, Opts, Caller). -c([#state{service_name = SvcName} = S], App, Msg, Opts, Caller) -> +c(#state{service_name = Svc, options = [{_, Mask} | _]} = S, + App, + Msg, + Opts, + Caller) -> case find_transport(App, Msg, Opts, S) of {_,_,_} = T -> - send_request(T, Msg, Opts, Caller, SvcName); + send_request(T, Mask, Msg, Opts, Caller, Svc); false -> {error, no_connection}; {error, _} = No -> No end; -c([], _, _, _, _) -> +c(false, _, _, _, _) -> {error, no_service}. +%% find_state/1 + +find_state(SvcName) -> + fs(ets:lookup(?STATE_TABLE, SvcName)). + +fs([#state{} = S]) -> + S; + +fs([S]) -> %% inserted from old code + upgrade(S); + +fs([]) -> + false. + %% make_options/1 make_options(Options) -> @@ -389,15 +431,6 @@ whois(SvcName) -> undefined end. -%%% --------------------------------------------------------------------------- -%%% # flush_stats/1 -%%% -%%% Output: list of {{SvcName, Alias, Counter}, Value} -%%% --------------------------------------------------------------------------- - -flush_stats(TPid) -> - diameter_stats:flush(TPid). - %% =========================================================================== %% =========================================================================== @@ -429,6 +462,10 @@ i(_, false) -> %%% # handle_call(Req, From, State) %%% --------------------------------------------------------------------------- +handle_call(T, From, S) + when not is_record(S, state) -> + handle_call(T, From, upgrade(S)); + handle_call(state, _, S) -> {reply, S, S}; @@ -452,16 +489,25 @@ handle_call({pick_peer, Local, Remote, App}, _From, S) -> handle_call({call_module, AppMod, Req}, From, S) -> call_module(AppMod, Req, From, S); +%% Call from old code. handle_call({info, Item}, _From, S) -> {reply, service_info(Item, S), S}; handle_call(stop, _From, S) -> - shutdown(S), + shutdown(service, S), {stop, normal, ok, S}; %% The server currently isn't guaranteed to be dead when the caller %% gets the reply. We deal with this in the call to the server, %% stating a monitor that waits for DOWN before returning. +%% Watchdog is asking for the sequence mask. +handle_call(sequence, _From, #state{options = [{_, Mask} | _]} = S) -> + {reply, Mask, S}; + +%% Watchdog is asking for the nodes restriction. +handle_call(restriction, _From, #state{options = [_,_,_,{_,R} | _]} = S) -> + {reply, R, S}; + handle_call(Req, From, S) -> unexpected(handle_call, [Req, From], S), {reply, nok, S}. @@ -478,15 +524,16 @@ handle_cast(Req, S) -> %%% # handle_info(Req, State) %%% --------------------------------------------------------------------------- -handle_info(T,S) -> +handle_info(T, #state{} = S) -> case transition(T,S) of ok -> {noreply, S}; - #state{} = NS -> - {noreply, NS}; {stop, Reason} -> {stop, {shutdown, Reason}, S} - end. + end; + +handle_info(T, S) -> + handle_info(T, upgrade(S)). %% transition/2 @@ -497,15 +544,26 @@ transition({accepted, Pid, TPid}, S) -> %% Peer process has a new open connection. transition({connection_up, Pid, T}, S) -> - connection_up(Pid, T, S); + connection_up(Pid, T, S), + ok; -%% Peer process has left state open. +%% Watchdog has a new connection that will be opened after DW[RA] +%% exchange. This message was added long after connection_up, to +%% communicate the information as soon as it's available. Leave +%% connection_up as is it for now, duplicated information and all. +transition({reopen, Pid, T}, S) -> + reopen(Pid, T, S), + ok; + +%% Watchdog has left state OKAY. transition({connection_down, Pid}, S) -> - connection_down(Pid, S); + connection_down(Pid, S), + ok; -%% Peer process has returned to state open. +%% Watchdog has returned to state OKAY. transition({connection_up, Pid}, S) -> - connection_up(Pid, S); + connection_up(Pid, S), + ok; %% Accepting transport has lost connectivity. transition({close, Pid}, S) -> @@ -517,29 +575,61 @@ transition({reconnect, Pid}, S) -> reconnect(Pid, S), ok; +%% Watchdog is sending notification of a state transition. Note that +%% the connection_up/down messages are pre-date this message and are +%% still used. A watchdog message will follow these and communicate +%% the same state as was set in handling connection_up/down. +transition({watchdog, Pid, {TPid, From, To}}, #state{service_name = SvcName, + peerT = PeerT}) -> + #peer{ref = Ref, type = T, options = Opts, op_state = {OS,_}} + = P + = fetch(PeerT, Pid), + insert(PeerT, P#peer{op_state = {OS, To}}), + send_event(SvcName, {watchdog, Ref, TPid, {From, To}, {T, Opts}}), + ok; +%% Death of a watchdog process (#peer.pid) results in the removal of +%% it's peer and any associated conn record when 'DOWN' is received +%% (after this) but the states will be {?STATE_UP, ?WD_DOWN} for a +%% short time. (No real problem since ?WD_* is only used in +%% service_info.) We set ?WD_OKAY as a consequence of connection_up +%% since we know a watchdog is coming. We can't set anything at +%% connection_down since we don't know if the subsequent watchdog +%% message will be ?WD_DOWN or ?WD_SUSPECT. We don't (yet) set +%% ?STATE_* as a consequence of a watchdog message since this requires +%% changing some of the matching on ?STATE_*. +%% +%% Death of a peer process process (#conn.pid, #peer.conn) results in +%% connection_down followed by watchdog ?WD_DOWN. The latter doesn't +%% result in the conn record being deleted since 'DOWN' from death of +%% its watchdog doesn't (yet) deal with the record having been +%% removed. + %% Monitor process has died. Just die with a reason that tells %% diameter_config about the happening. If a cleaner shutdown is %% required then someone should stop us. transition({'DOWN', MRef, process, _, Reason}, #state{monitor = MRef}) -> {stop, {monitor, Reason}}; -%% Local peer process has died. +%% Local watchdog process has died. transition({'DOWN', _, process, Pid, Reason}, S) when node(Pid) == node() -> - peer_down(Pid, Reason, S); + peer_down(Pid, Reason, S), + ok; -%% Remote service wants to know about shared transports. +%% Remote service wants to know about shared peers. transition({service, Pid}, S) -> share_peers(Pid, S), ok; %% Remote service is communicating a shared peer. transition({peer, TPid, Aliases, Caps}, S) -> - remote_peer_up(TPid, Aliases, Caps, S); + remote_peer_up(TPid, Aliases, Caps, S), + ok; %% Remote peer process has died. transition({'DOWN', _, process, TPid, _}, S) -> - remote_peer_down(TPid, S); + remote_peer_down(TPid, S), + ok; %% Restart after tc expiry. transition({tc_timeout, T}, S) -> @@ -553,18 +643,48 @@ transition({failover, TRef, Seqs}, S) -> failover(TRef, Seqs, S), ok; +%% Ensure upgraded state is stored in state table. +transition(upgrade, _) -> + ok; + transition(Req, S) -> unexpected(handle_info, [Req], S), ok. +%% upgrade/1 + +upgrade({state, Id, Svc, Name, Svc, PT, CT, SB, UB, SD, LD, MPid}) -> + S = #state{id = Id, + service_name = Name, + service = Svc, + peerT = PT, + connT = CT, + shared_peers = SD, + local_peers = LD, + monitor = MPid, + options = [{sequence, ?NOMASK}, + {share_peers, SB}, + {use_shared_peers, UB}, + {restrict_connections, ?RESTRICT}]}, + upgrade_insert(S), + S. + +upgrade_insert(#state{service = #diameter_service{pid = Pid}} = S) -> + if Pid == self() -> + ets:insert(?STATE_TABLE, S); + true -> + Pid ! upgrade + end. + %%% --------------------------------------------------------------------------- %%% # terminate(Reason, State) %%% --------------------------------------------------------------------------- terminate(Reason, #state{service_name = Name} = S) -> + send_event(Name, stop), ets:delete(?STATE_TABLE, Name), shutdown == Reason %% application shutdown - andalso shutdown(S). + andalso shutdown(application, S). %%% --------------------------------------------------------------------------- %%% # code_change(FromVsn, State, Extra) @@ -630,10 +750,6 @@ insert(Tbl, Rec) -> ets:insert(Tbl, Rec), Rec. -monitor(Pid) -> - erlang:monitor(process, Pid), - Pid. - %% 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 @@ -647,50 +763,53 @@ mod_state(Alias) -> mod_state(Alias, ModS) -> put({?MODULE, mod_state, Alias}, ModS). -%% have_transport/2 - -have_transport(SvcName, Ref) -> - [] /= diameter_config:have_transport(SvcName, Ref). - %%% --------------------------------------------------------------------------- %%% # shutdown/2 %%% --------------------------------------------------------------------------- -shutdown(Refs, #state{peerT = PeerT}) -> - ets:foldl(fun(P,ok) -> s(P, Refs), ok end, ok, PeerT). - -s(#peer{ref = Ref, pid = Pid}, Refs) -> - s(lists:member(Ref, Refs), Pid); +%% remove_transport: ask watchdogs to terminate their transport. +shutdown(Refs, #state{peerT = PeerT}) + when is_list(Refs) -> + ets:foldl(fun(P,ok) -> sp(P, Refs), ok end, ok, PeerT); -s(true, Pid) -> - Pid ! {shutdown, self()}; %% 'DOWN' will cleanup as usual -s(false, _) -> - ok. - -%%% --------------------------------------------------------------------------- -%%% # shutdown/1 -%%% --------------------------------------------------------------------------- - -shutdown(#state{peerT = PeerT}) -> +%% application/service shutdown: ask transports to terminate themselves. +shutdown(Reason, #state{peerT = PeerT}) -> %% A transport might not be alive to receive the shutdown request %% but give those that are a chance to shutdown gracefully. - wait(fun st/2, PeerT), + shutdown(conn, Reason, PeerT), %% Kill the watchdogs explicitly in case there was no transport. - wait(fun sw/2, PeerT). + shutdown(peer, Reason, PeerT). -wait(Fun, T) -> - diameter_lib:wait(ets:foldl(Fun, [], T)). +%% sp/2 -st(#peer{conn = B}, Acc) - when is_boolean(B) -> - Acc; -st(#peer{conn = Pid}, Acc) -> - Pid ! shutdown, - [Pid | Acc]. +sp(#peer{ref = Ref, pid = Pid}, Refs) -> + lists:member(Ref, Refs) + andalso (Pid ! {shutdown, self()}). %% 'DOWN' cleans up + +%% shutdown/3 + +shutdown(Who, Reason, T) -> + diameter_lib:wait(ets:foldl(fun(X,A) -> shutdown(Who, X, Reason, A) end, + [], + T)). -sw(#peer{pid = Pid}, Acc) -> +shutdown(conn = Who, #peer{op_state = {OS,_}} = P, Reason, Acc) -> + shutdown(Who, P#peer{op_state = OS}, Reason, Acc); + +shutdown(conn, + #peer{pid = Pid, op_state = ?STATE_UP, conn = TPid}, + Reason, + Acc) -> + TPid ! {shutdown, Pid, Reason}, + [TPid | Acc]; + +shutdown(peer, #peer{pid = Pid}, _Reason, Acc) + when is_pid(Pid) -> exit(Pid, shutdown), - [Pid | Acc]. + [Pid | Acc]; + +shutdown(_, #peer{}, _, Acc) -> + Acc. %%% --------------------------------------------------------------------------- %%% # call_service/2 @@ -743,6 +862,7 @@ i(SvcName) -> lists:foreach(fun(T) -> start_fsm(T,S) end, CL), init_shared(S), + send_event(SvcName, start), S. cfg_acc({SvcName, #diameter_service{applications = Apps} = Rec, Opts}, @@ -750,9 +870,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()}, - share_peers = get_value(share_peers, Opts), - use_shared_peers = get_value(use_shared_peers, Opts), - monitor = mref(get_value(monitor, Opts))}, + monitor = mref(get_value(monitor, Opts)), + options = service_options(Opts)}, {S, Acc}; cfg_acc({_Ref, Type, _Opts} = T, {S, Acc}) @@ -760,15 +879,24 @@ cfg_acc({_Ref, Type, _Opts} = T, {S, Acc}) Type == listen -> {S, [T | Acc]}. +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)}]. +%% The order of options is significant since we match against the list. + mref(false = No) -> No; mref(P) -> erlang:monitor(process, P). -init_shared(#state{use_shared_peers = true, +init_shared(#state{options = [_, _, {_, true} | _], service_name = Svc}) -> diameter_peer:notify(Svc, {service, self()}); -init_shared(#state{use_shared_peers = false}) -> +init_shared(#state{options = [_, _, {_, false} | _]}) -> ok. init_mod(#diameter_app{alias = Alias, @@ -820,10 +948,10 @@ start(Ref, Type, Opts, #state{peerT = PeerT, service = Svc}) when Type == connect; Type == accept -> - Pid = monitor(s(Type, Ref, {ConnT, - Opts, - SvcName, - merge_service(Opts, Svc)})), + Pid = s(Type, Ref, {ConnT, + Opts, + SvcName, + merge_service(Opts, Svc)}), insert(PeerT, #peer{pid = Pid, type = Type, ref = Ref, @@ -831,12 +959,17 @@ start(Ref, Type, Opts, #state{peerT = PeerT, Pid. %% Note that the service record passed into the watchdog is the merged -%% record so that each watchdog (and peer_fsm) may get a different -%% record. This record is what is passed back into application -%% callbacks. +%% record so that each watchdog may get a different record. This +%% record is what is passed back into application callbacks. s(Type, Ref, T) -> - diameter_watchdog:start({Type, Ref}, T). + case diameter_watchdog:start({Type, Ref}, T) of + {_MRef, Pid} -> + Pid; + Pid when is_pid(Pid) -> %% from old code + erlang:monitor(process, Pid), + Pid + end. %% merge_service/2 @@ -878,20 +1011,25 @@ accepted(Pid, _TPid, #state{peerT = PeerT} = S) -> #peer{ref = Ref, type = accept = T, conn = false, options = Opts} = P = fetch(PeerT, Pid), - insert(PeerT, P#peer{conn = true}), %% mark replacement transport started - start(Ref, T, Opts, S). %% start new peer + insert(PeerT, P#peer{conn = true}), %% mark replacement as started + start(Ref, T, Opts, S). %% start new watchdog fetch(Tid, Key) -> [T] = ets:lookup(Tid, Key), - T. + case T of + #peer{op_state = ?STATE_UP} = P -> + P#peer{op_state = {?STATE_UP, ?WD_OKAY}}; + #peer{op_state = ?STATE_DOWN} = P -> + P#peer{op_state = {?STATE_DOWN, ?WD_DOWN}}; + _ -> + T + end. %%% --------------------------------------------------------------------------- %%% # connection_up/3 -%%% -%%% Output: #state{} %%% --------------------------------------------------------------------------- -%% Peer process has reached the open state. +%% Watchdog process has reached state OKAY. connection_up(Pid, {TPid, {Caps, SApps, Pkt}}, #state{peerT = PeerT, connT = ConnT} @@ -906,9 +1044,29 @@ connection_up(Pid, {TPid, {Caps, SApps, Pkt}}, #state{peerT = PeerT, connection_up([Pkt], P#peer{conn = TPid}, C, S). %%% --------------------------------------------------------------------------- +%%% # reopen/3 +%%% --------------------------------------------------------------------------- + +%% Note that this connection_up/3 rewrites the same #conn{} now +%% written here. Both do so in case reopen has not happened in old +%% code. + +reopen(Pid, {TPid, {Caps, SApps, _Pkt}}, #state{peerT = PeerT, + connT = ConnT}) -> + P = fetch(PeerT, Pid), + C = #conn{pid = TPid, + apps = SApps, + caps = Caps, + peer = Pid}, + + insert(ConnT, C), + #peer{op_state = {?STATE_DOWN, _}} + = P, + insert(PeerT, P#peer{op_state = {?STATE_DOWN, ?WD_REOPEN}, + conn = TPid}). + +%%% --------------------------------------------------------------------------- %%% # connection_up/2 -%%% -%%% Output: #state{} %%% --------------------------------------------------------------------------- %% Peer process has transitioned back into the open state. Note that there @@ -929,18 +1087,16 @@ connection_up(T, P, C, #state{peerT = PeerT, service = #diameter_service{applications = Apps}} = S) -> - #peer{conn = TPid, op_state = ?STATE_DOWN} + #peer{conn = TPid, op_state = {?STATE_DOWN, _}} = P, #conn{apps = SApps, caps = Caps} = C, - insert(PeerT, P#peer{op_state = ?STATE_UP}), + insert(PeerT, P#peer{op_state = {?STATE_UP, ?WD_OKAY}}), request_peer_up(TPid), - report_status(up, P, C, S, T), - S#state{local_peers = insert_local_peer(SApps, - {{TPid, Caps}, {SvcName, Apps}}, - LDict)}. + insert_local_peer(SApps, {{TPid, Caps}, {SvcName, Apps}}, LDict), + report_status(up, P, C, S, T). insert_local_peer(SApps, T, LDict) -> lists:foldl(fun(A,D) -> ilp(A, T, D) end, LDict, SApps). @@ -949,52 +1105,62 @@ ilp({Id, Alias}, {TC, SA}, LDict) -> init_conn(Id, Alias, TC, SA), ?Dict:append(Alias, TC, LDict). -init_conn(Id, Alias, TC, {SvcName, Apps}) -> +init_conn(Id, Alias, {TPid, _} = TC, {SvcName, Apps}) -> #diameter_app{module = ModX, id = Id} %% assert = find_app(Alias, Apps), - peer_cb({ModX, peer_up, [SvcName, TC]}, Alias). + peer_cb({ModX, peer_up, [SvcName, TC]}, Alias) + orelse exit(TPid, kill). %% fake transport failure + +%% find_app/2 find_app(Alias, Apps) -> - lists:keyfind(Alias, #diameter_app.alias, Apps). + case lists:keyfind(Alias, #diameter_app.alias, Apps) of + #diameter_app{options = E} = A when is_atom(E) -> %% upgrade + A#diameter_app{options = [{answer_errors, E}]}; + A -> + A + end. -%% A failing peer callback brings down the service. In the case of -%% peer_up we could just kill the transport and emit an error but for -%% peer_down we have no way to cleanup any state change that peer_up -%% may have introduced. +%% Don't bring down the service (and all associated connections) +%% regardless of what happens. peer_cb(MFA, Alias) -> try state_cb(MFA, Alias) of ModS -> - mod_state(Alias, ModS) + mod_state(Alias, ModS), + true catch - E: Reason -> - ?ERROR({E, Reason, MFA, ?STACK}) + E:R -> + diameter_lib:error_report({failure, {E, R, Alias, ?STACK}}, MFA), + false end. %%% --------------------------------------------------------------------------- %%% # connection_down/2 -%%% -%%% Output: #state{} %%% --------------------------------------------------------------------------- -%% Peer process has transitioned out of the open state. +%% Watchdog has transitioned out of state OKAY. connection_down(Pid, #state{peerT = PeerT, connT = ConnT} = S) -> - #peer{conn = TPid} + #peer{op_state = {?STATE_UP, WS}, %% assert + conn = TPid} = P = fetch(PeerT, Pid), C = fetch(ConnT, TPid), - insert(PeerT, P#peer{op_state = ?STATE_DOWN}), + insert(PeerT, P#peer{op_state = {?STATE_DOWN, WS}}), connection_down(P,C,S). %% connection_down/3 +connection_down(#peer{op_state = {?STATE_DOWN, _}}, _, _) -> + ok; + connection_down(#peer{conn = TPid, - op_state = ?STATE_UP} + op_state = {?STATE_UP, _}} = P, #conn{caps = Caps, apps = SApps} @@ -1004,12 +1170,8 @@ connection_down(#peer{conn = TPid, local_peers = LDict} = S) -> report_status(down, P, C, S, []), - NewS = S#state{local_peers - = remove_local_peer(SApps, - {{TPid, Caps}, {SvcName, Apps}}, - LDict)}, - request_peer_down(TPid, NewS), - NewS. + remove_local_peer(SApps, {{TPid, Caps}, {SvcName, Apps}}, LDict), + request_peer_down(TPid, S). remove_local_peer(SApps, T, LDict) -> lists:foldl(fun(A,D) -> rlp(A, T, D) end, LDict, SApps). @@ -1028,47 +1190,37 @@ down_conn(Id, Alias, TC, {SvcName, Apps}) -> %%% --------------------------------------------------------------------------- %%% # peer_down/3 -%%% -%%% Output: #state{} %%% --------------------------------------------------------------------------- -%% Peer process has died. +%% Watchdog process has died. -peer_down(Pid, _Reason, #state{peerT = PeerT} = S) -> +peer_down(Pid, Reason, #state{peerT = PeerT} = S) -> P = fetch(PeerT, Pid), ets:delete_object(PeerT, P), + closed(Reason, P, S), restart(P,S), peer_down(P,S). -%% peer_down/2 +%% Send an event at connection establishment failure. +closed({shutdown, {close, _TPid, Reason}}, + #peer{op_state = {?STATE_DOWN, _}, + ref = Ref, + type = Type, + options = Opts}, + #state{service_name = SvcName}) -> + send_event(SvcName, {closed, Ref, Reason, {type(Type), Opts}}); +closed(_, _, _) -> + ok. -%% The peer has never come up ... -peer_down(#peer{conn = B}, S) +%% The watchdog has never reached OKAY ... +peer_down(#peer{conn = B}, _) when is_boolean(B) -> - S; + ok; -%% ... or it has. -peer_down(#peer{ref = Ref, - conn = TPid, - type = Type, - options = Opts} - = P, - #state{service_name = SvcName, - connT = ConnT} - = S) -> - #conn{caps = Caps} - = C - = fetch(ConnT, TPid), +%% ... or maybe it has. +peer_down(#peer{conn = TPid} = P, #state{connT = ConnT} = S) -> + #conn{} = C = fetch(ConnT, TPid), ets:delete_object(ConnT, C), - try - pd(P,C,S) - after - send_event(SvcName, {closed, Ref, {TPid, Caps}, {type(Type), Opts}}) - end. - -pd(#peer{op_state = ?STATE_DOWN}, _, S) -> - S; -pd(#peer{op_state = ?STATE_UP} = P, C, S) -> connection_down(P,C,S). %% restart/2 @@ -1093,7 +1245,7 @@ restart(#peer{ref = Ref, started = Time}) -> {Time, {Ref, T, Opts}}; -%% ... or it has: a replacement transport has already been spawned. +%% ... or it has: a replacement has already been spawned. restart(#peer{type = accept}) -> false. @@ -1119,8 +1271,8 @@ default_tc(connect, Opts) -> default_tc(accept, _) -> 0. -%% Bound tc below if the peer was restarted recently to avoid -%% continuous in case of faulty config or other problems. +%% Bound tc below if the watchdog was restarted recently to avoid +%% continuous restarted in case of faulty config or other problems. tc(Time, Tc) -> choose(Tc > ?RESTART_TC orelse timer:now_diff(now(), Time) > 1000*?RESTART_TC, @@ -1135,7 +1287,7 @@ start_tc(Tc, T, _) -> %% tc_timeout/2 tc_timeout({Ref, _Type, _Opts} = T, #state{service_name = SvcName} = S) -> - tc(have_transport(SvcName, Ref), T, S). + tc(diameter_config:have_transport(SvcName, Ref), T, S). tc(true, {Ref, Type, Opts}, #state{service_name = SvcName} = S) -> @@ -1163,7 +1315,7 @@ close(Pid, #state{service_name = SvcName, options = Opts} = fetch(PeerT, Pid), - c(Pid, have_transport(SvcName, Ref), Opts). + c(Pid, diameter_config:have_transport(SvcName, Ref), Opts). %% Tell watchdog to (maybe) die later ... c(Pid, true, Opts) -> @@ -1242,7 +1394,7 @@ cm([_,_|_], _, _, _) -> multiple. %%% --------------------------------------------------------------------------- -%%% # send_request/5 +%%% # send_request/6 %%% --------------------------------------------------------------------------- %% Send an outgoing request in its dedicated process. @@ -1255,93 +1407,114 @@ cm([_,_|_], _, _, _) -> %% The mod field of the #diameter_app{} here includes any extra %% arguments passed to diameter:call/2. -send_request({TPid, Caps, App}, Msg, Opts, Caller, SvcName) -> +send_request({TPid, Caps, App} = T, Mask, Msg, Opts, Caller, SvcName) -> #diameter_app{module = ModX} = App, - Pkt = make_packet(Msg), - - case cb(ModX, prepare_request, [Pkt, SvcName, {TPid, Caps}]) of - {send, P} -> - send_request(make_packet(P, Pkt), - TPid, - Caps, - App, - Opts, - Caller, - SvcName); - {discard, Reason} -> - {error, Reason}; - discard -> - {error, discarded}; - T -> - ?ERROR({invalid_return, prepare_request, App, T}) - end. + Pkt = make_prepare_packet(Mask, Msg), + + send_req(cb(ModX, prepare_request, [Pkt, SvcName, {TPid, Caps}]), + Pkt, + T, + Opts, + Caller, + SvcName, + []). + +send_req({send, P}, Pkt, T, Opts, Caller, SvcName, Fs) -> + send_req(make_request_packet(P, Pkt), T, Opts, Caller, SvcName, Fs); + +send_req({discard, Reason} , _, _, _, _, _, _) -> + {error, Reason}; + +send_req(discard, _, _, _, _, _, _) -> + {error, discarded}; + +send_req({eval_packet, RC, F}, Pkt, T, Opts, Caller, SvcName, Fs) -> + send_req(RC, Pkt, T, Opts, Caller, SvcName, [F|Fs]); -%% make_packet/1 +send_req(E, _, {_, _, App}, _, _, _, _) -> + ?ERROR({invalid_return, prepare_request, App, E}). + +%% make_prepare_packet/2 %% %% Turn an outgoing request as passed to call/4 into a diameter_packet %% record in preparation for a prepare_request callback. -make_packet(Bin) +make_prepare_packet(_, Bin) when is_binary(Bin) -> #diameter_packet{header = diameter_codec:decode_header(Bin), bin = Bin}; -make_packet(#diameter_packet{msg = [#diameter_header{} = Hdr | Avps]} = Pkt) -> - Pkt#diameter_packet{msg = [make_header(Hdr) | Avps]}; +make_prepare_packet(Mask, #diameter_packet{msg = [#diameter_header{} = Hdr + | Avps]} + = Pkt) -> + Pkt#diameter_packet{msg = [make_prepare_header(Mask, Hdr) | Avps]}; + +make_prepare_packet(Mask, #diameter_packet{header = Hdr} = Pkt) -> + Pkt#diameter_packet{header = make_prepare_header(Mask, Hdr)}; + +make_prepare_packet(Mask, Msg) -> + make_prepare_packet(Mask, #diameter_packet{msg = Msg}). + +%% make_prepare_header/1 -make_packet(#diameter_packet{header = Hdr} = Pkt) -> - Pkt#diameter_packet{header = make_header(Hdr)}; +make_prepare_header(Mask, undefined) -> + Seq = diameter_session:sequence(Mask), + make_prepare_header(#diameter_header{end_to_end_id = Seq, + hop_by_hop_id = Seq}); -make_packet(Msg) -> - make_packet(#diameter_packet{msg = Msg}). +make_prepare_header(Mask, #diameter_header{end_to_end_id = undefined, + hop_by_hop_id = undefined}) -> + Seq = diameter_session:sequence(Mask), + make_prepare_header(#diameter_header{end_to_end_id = Seq, + hop_by_hop_id = Seq}); -%% make_header/1 +make_prepare_header(Mask, #diameter_header{end_to_end_id = undefined} = H) -> + Seq = diameter_session:sequence(Mask), + make_prepare_header(H#diameter_header{end_to_end_id = Seq}); -make_header(undefined) -> - Seq = diameter_session:sequence(), - make_header(#diameter_header{end_to_end_id = Seq, - hop_by_hop_id = Seq}); +make_prepare_header(Mask, #diameter_header{hop_by_hop_id = undefined} = H) -> + Seq = diameter_session:sequence(Mask), + make_prepare_header(H#diameter_header{hop_by_hop_id = Seq}); -make_header(#diameter_header{version = undefined} = Hdr) -> - make_header(Hdr#diameter_header{version = ?DIAMETER_VERSION}); +make_prepare_header(_, Hdr) -> + make_prepare_header(Hdr). -make_header(#diameter_header{end_to_end_id = undefined} = H) -> - Seq = diameter_session:sequence(), - make_header(H#diameter_header{end_to_end_id = Seq}); +%% make_prepare_header/1 -make_header(#diameter_header{hop_by_hop_id = undefined} = H) -> - Seq = diameter_session:sequence(), - make_header(H#diameter_header{hop_by_hop_id = Seq}); +make_prepare_header(#diameter_header{version = undefined} = Hdr) -> + make_prepare_header(Hdr#diameter_header{version = ?DIAMETER_VERSION}); -make_header(#diameter_header{} = Hdr) -> +make_prepare_header(#diameter_header{} = Hdr) -> Hdr; -make_header(T) -> +make_prepare_header(T) -> ?ERROR({invalid_header, T}). -%% make_packet/2 +%% make_request_packet/2 %% %% Reconstruct a diameter_packet from the return value of %% prepare_request or prepare_retransmit callback. -make_packet(Bin, _) +make_request_packet(Bin, _) when is_binary(Bin) -> - make_packet(Bin); + make_prepare_packet(false, Bin); -make_packet(#diameter_packet{msg = [#diameter_header{} | _]} = Pkt, _) -> +make_request_packet(#diameter_packet{msg = [#diameter_header{} | _]} + = Pkt, + _) -> Pkt; %% Returning a diameter_packet with no header from a prepare_request %% or prepare_retransmit callback retains the header passed into it. %% This is primarily so that the end to end and hop by hop identifiers %% are retained. -make_packet(#diameter_packet{header = Hdr} = Pkt, - #diameter_packet{header = Hdr0}) -> +make_request_packet(#diameter_packet{header = Hdr} = Pkt, + #diameter_packet{header = Hdr0}) -> Pkt#diameter_packet{header = fold_record(Hdr0, Hdr)}; -make_packet(Msg, Pkt) -> +make_request_packet(Msg, Pkt) -> Pkt#diameter_packet{msg = Msg}. %% fold_record/2 @@ -1351,16 +1524,16 @@ fold_record(undefined, R) -> fold_record(Rec, R) -> diameter_lib:fold_tuple(2, Rec, R). -%% send_request/7 +%% send_req/6 -send_request(Pkt, TPid, Caps, App, Opts, Caller, SvcName) -> +send_req(Pkt, {TPid, Caps, App}, Opts, Caller, SvcName, Fs) -> #diameter_app{alias = Alias, dictionary = Dict, module = ModX, - answer_errors = AE} + options = [{answer_errors, AE} | _]} = App, - EPkt = encode(Dict, Pkt), + EPkt = encode(Dict, Pkt, Fs), #options{filter = Filter, timeout = Timeout} @@ -1441,6 +1614,13 @@ msg(#diameter_packet{msg = undefined, bin = Bin}) -> msg(#diameter_packet{msg = Msg}) -> Msg. +%% encode/3 + +encode(Dict, Pkt, Fs) -> + P = encode(Dict, Pkt), + eval_packet(P, Fs), + P. + %% encode/2 %% Note that prepare_request can return a diameter_packet containing @@ -1491,7 +1671,7 @@ pd([], _) -> send_request(TPid, #diameter_packet{bin = Bin} = Pkt, Req, Timeout) when node() == node(TPid) -> %% Store the outgoing request before sending to avoid a race with - %% reply reception. + %% reply reception. TRef = store_request(TPid, Bin, Req, Timeout), send(TPid, Pkt), TRef; @@ -1522,38 +1702,47 @@ send(Pid, Pkt) -> %% retransmit/4 -retransmit({TPid, Caps, #diameter_app{alias = Alias} = App}, - #request{app = Alias, - packet = Pkt} +retransmit({TPid, Caps, #diameter_app{alias = Alias} = App} = T, + #request{app = Alias, packet = Pkt} = Req, SvcName, Timeout) -> have_request(Pkt, TPid) %% Don't failover to a peer we've andalso ?THROW(timeout), %% already sent to. - case cb(App, prepare_retransmit, [Pkt, SvcName, {TPid, Caps}]) of - {send, P} -> - retransmit(make_packet(P, Pkt), TPid, Caps, Req, Timeout); - {discard, Reason} -> - ?THROW(Reason); - discard -> - ?THROW(discarded); - T -> - ?ERROR({invalid_return, prepare_retransmit, App, T}) - end. + resend_req(cb(App, prepare_retransmit, [Pkt, SvcName, {TPid, Caps}]), + T, + Req, + Timeout, + []). + +resend_req({send, P}, T, #request{packet = Pkt} = Req, Timeout, Fs) -> + retransmit(make_request_packet(P, Pkt), T, Req, Timeout, Fs); + +resend_req({discard, Reason}, _, _, _, _) -> + ?THROW(Reason); -%% retransmit/5 +resend_req(discard, _, _, _, _) -> + ?THROW(discarded); -retransmit(Pkt, TPid, Caps, #request{dictionary = Dict} = Req, Timeout) -> - EPkt = encode(Dict, Pkt), +resend_req({eval_packet, RC, F}, T, Req, Timeout, Fs) -> + resend_req(RC, T, Req, Timeout, [F|Fs]); + +resend_req(T, {_, _, App}, _, _, _) -> + ?ERROR({invalid_return, prepare_retransmit, App, T}). - NewReq = Req#request{transport = TPid, - packet = Pkt, - caps = Caps}, +%% retransmit/6 - ?LOG(retransmission, NewReq), - TRef = send_request(TPid, EPkt, NewReq, Timeout), - {TRef, NewReq}. +retransmit(Pkt, {TPid, Caps, _}, #request{dictionary = D} = Req0, Tmo, Fs) -> + EPkt = encode(D, Pkt, Fs), + + Req = Req0#request{transport = TPid, + packet = Pkt, + caps = Caps}, + + ?LOG(retransmission, Req), + TRef = send_request(TPid, EPkt, Req, Tmo), + {TRef, Req}. %% store_request/4 @@ -1625,10 +1814,13 @@ request_peer_down(TPid, S) -> %%% recv_request/3 %%% --------------------------------------------------------------------------- -recv_request(TPid, Pkt, {ConnT, SvcName, Apps}) -> +recv_request(TPid, Pkt, {ConnT, SvcName, Apps}) -> %% upgrade + recv_request(TPid, Pkt, {ConnT, SvcName, Apps, ?NOMASK}); + +recv_request(TPid, Pkt, {ConnT, SvcName, Apps, Mask}) -> try ets:lookup(ConnT, TPid) of [C] -> - recv_request(C, TPid, Pkt, SvcName, Apps); + recv_request(C, TPid, Pkt, SvcName, Apps, Mask); [] -> %% transport has gone down ok catch @@ -1638,7 +1830,12 @@ recv_request(TPid, Pkt, {ConnT, SvcName, Apps}) -> %% recv_request/5 -recv_request(#conn{apps = SApps, caps = Caps}, TPid, Pkt, SvcName, Apps) -> +recv_request(#conn{apps = SApps, caps = Caps}, + TPid, + Pkt, + SvcName, + Apps, + Mask) -> #diameter_caps{origin_host = {OH,_}, origin_realm = {OR,_}} = Caps, @@ -1650,6 +1847,7 @@ recv_request(#conn{apps = SApps, caps = Caps}, TPid, Pkt, SvcName, Apps) -> {SvcName, OH, OR}, TPid, Apps, + Mask, Caps, Pkt). @@ -1675,20 +1873,24 @@ keyfind([Key | Rest], Pos, L) -> T end. -%% recv_request/6 +%% recv_request/7 -recv_request({Id, Alias}, T, TPid, Apps, Caps, Pkt) -> +recv_request({Id, Alias}, T, TPid, Apps, Mask, Caps, Pkt) -> #diameter_app{dictionary = Dict} = A = find_app(Alias, Apps), - recv_request(T, {TPid, Caps}, A, diameter_codec:decode(Id, Dict, Pkt)); + recv_request(T, + {TPid, Caps}, + A, + Mask, + diameter_codec:decode(Id, Dict, Pkt)); %% Note that the decode is different depending on whether or not Id is %% ?APP_ID_RELAY. %% DIAMETER_APPLICATION_UNSUPPORTED 3007 %% A request was sent for an application that is not supported. -recv_request(false, T, TPid, _, _, Pkt) -> +recv_request(false, T, TPid, _, _, _, Pkt) -> As = collect_avps(Pkt), protocol_error(3007, T, TPid, Pkt#diameter_packet{avps = As}). @@ -1700,7 +1902,7 @@ collect_avps(Pkt) -> As end. -%% recv_request/4 +%% recv_request/5 %% Wrong number of bits somewhere in the message: reply. %% @@ -1709,7 +1911,7 @@ collect_avps(Pkt) -> %% set to an unrecognized value, or that is inconsistent with the %% AVP's definition. %% -recv_request(T, {TPid, _}, _, #diameter_packet{errors = [Bs | _]} = Pkt) +recv_request(T, {TPid, _}, _, _, #diameter_packet{errors = [Bs | _]} = Pkt) when is_bitstring(Bs) -> protocol_error(3009, T, TPid, Pkt); @@ -1724,6 +1926,7 @@ recv_request(T, {TPid, _}, _, #diameter_packet{errors = [Bs | _]} = Pkt) recv_request(T, {TPid, _}, #diameter_app{id = Id}, + _, #diameter_packet{header = #diameter_header{is_proxiable = P}, msg = M} = Pkt) @@ -1741,6 +1944,7 @@ recv_request(T, recv_request(T, {TPid, _}, _, + _, #diameter_packet{header = #diameter_header{is_error = true}} = Pkt) -> protocol_error(3008, T, TPid, Pkt); @@ -1749,14 +1953,20 @@ recv_request(T, %% in the relay application. Don't distinguish between the two since %% each application has its own callback config. That is, the user can %% easily distinguish between the two cases. -recv_request(T, TC, App, Pkt) -> - request_cb(T, TC, App, examine(Pkt)). +recv_request(T, TC, App, Mask, Pkt) -> + request_cb(T, TC, App, Mask, examine(Pkt)). %% Note that there may still be errors but these aren't protocol %% (3xxx) errors that lead to an answer-message. -request_cb({SvcName, _OH, _OR} = T, TC, App, Pkt) -> - request_cb(cb(App, handle_request, [Pkt, SvcName, TC]), App, T, TC, Pkt). +request_cb({SvcName, _OH, _OR} = T, TC, App, Mask, Pkt) -> + request_cb(cb(App, handle_request, [Pkt, SvcName, TC]), + App, + Mask, + T, + TC, + [], + Pkt). %% examine/1 %% @@ -1776,7 +1986,7 @@ examine(#diameter_packet{errors = Es} = Pkt) -> Pkt#diameter_packet{errors = [5011 | Es]}. %% It's odd/unfortunate that this isn't a protocol error. -%% request_cb/5 +%% request_cb/7 %% A reply may be an answer-message, constructed either here or by %% the handle_request callback. The header from the incoming request @@ -1786,21 +1996,23 @@ examine(#diameter_packet{errors = Es} = Pkt) -> request_cb({reply, Ans}, #diameter_app{dictionary = Dict}, _, + _, {TPid, _}, + Fs, Pkt) -> - reply(Ans, Dict, TPid, Pkt); + reply(Ans, Dict, TPid, Fs, Pkt); %% An 3xxx result code, for which the E-bit is set in the header. -request_cb({protocol_error, RC}, _, T, {TPid, _}, Pkt) +request_cb({protocol_error, RC}, _, _, T, {TPid, _}, Fs, Pkt) when 3000 =< RC, RC < 4000 -> - protocol_error(RC, T, TPid, Pkt); + protocol_error(RC, T, TPid, Fs, Pkt); %% RFC 3588 says we must reply 3001 to anything unrecognized or %% unsupported. 'noreply' is undocumented (and inappropriately named) %% backwards compatibility for this, protocol_error the documented %% alternative. -request_cb(noreply, _, T, {TPid, _}, Pkt) -> - protocol_error(3001, T, TPid, Pkt); +request_cb(noreply, _, _, T, {TPid, _}, Fs, Pkt) -> + protocol_error(3001, T, TPid, Fs, Pkt); %% Relay a request to another peer. This is equivalent to doing an %% explicit call/4 with the message in question except that (1) a loop @@ -1820,38 +2032,51 @@ request_cb(noreply, _, T, {TPid, _}, Pkt) -> request_cb({A, Opts}, #diameter_app{id = Id} = App, + Mask, T, TC, + Fs, Pkt) when A == relay, Id == ?APP_ID_RELAY; A == proxy, Id /= ?APP_ID_RELAY; A == resend -> - resend(Opts, App, T, TC, Pkt); + resend(Opts, App, Mask, T, TC, Fs, Pkt); -request_cb(discard, _, _, _, _) -> +request_cb(discard, _, _, _, _, _, _) -> ok; -request_cb({eval, RC, F}, App, T, TC, Pkt) -> - request_cb(RC, App, T, TC, Pkt), +request_cb({eval_packet, RC, F}, App, Mask, T, TC, Fs, Pkt) -> + request_cb(RC, App, Mask, T, TC, [F|Fs], Pkt); + +request_cb({eval, RC, F}, App, Mask, T, TC, Fs, Pkt) -> + request_cb(RC, App, Mask, T, TC, Fs, Pkt), diameter_lib:eval(F). -%% protocol_error/4 +%% protocol_error/5 -protocol_error(RC, {_, OH, OR}, TPid, #diameter_packet{avps = Avps} = Pkt) -> +protocol_error(RC, {_, OH, OR}, TPid, Fs, Pkt) -> + #diameter_packet{avps = Avps} = Pkt, ?LOG({error, RC}, Pkt), - reply(answer_message({OH, OR, RC}, Avps), ?BASE, TPid, Pkt). + reply(answer_message({OH, OR, RC}, Avps), ?BASE, TPid, Fs, Pkt). -%% resend/5 +%% protocol_error/4 + +protocol_error(RC, T, TPid, Pkt) -> + protocol_error(RC, T, TPid, [], Pkt). + +%% resend/7 %% %% Resend a message as a relay or proxy agent. resend(Opts, #diameter_app{} = App, + Mask, {_SvcName, OH, _OR} = T, {_TPid, _Caps} = TC, + Fs, #diameter_packet{avps = Avps} = Pkt) -> {Code, _Flags, Vid} = ?BASE:avp_header('Route-Record'), - resend(is_loop(Code, Vid, OH, Avps), Opts, App, T, TC, Pkt). + resend(is_loop(Code, Vid, OH, Avps), Opts, App, Mask, T, TC, Fs, Pkt). %% DIAMETER_LOOP_DETECTED 3005 %% An agent detected a loop while trying to get the message to the @@ -1859,8 +2084,8 @@ resend(Opts, %% if one is available, but the peer reporting the error has %% identified a configuration problem. -resend(true, _, _, T, {TPid, _}, Pkt) -> %% Route-Record loop - protocol_error(3005, T, TPid, Pkt); +resend(true, _, _, _, T, {TPid, _}, Fs, Pkt) -> %% Route-Record loop + protocol_error(3005, T, TPid, Fs, Pkt); %% 6.1.8. Relaying and Proxying Requests %% @@ -1871,16 +2096,18 @@ resend(true, _, _, T, {TPid, _}, Pkt) -> %% Route-Record loop resend(false, Opts, App, + Mask, {SvcName, _, _} = T, {TPid, #diameter_caps{origin_host = {_, OH}}}, + Fs, #diameter_packet{header = Hdr0, avps = Avps} = Pkt) -> Route = #diameter_avp{data = {?BASE, 'Route-Record', OH}}, - Seq = diameter_session:sequence(), + Seq = diameter_session:sequence(Mask), Hdr = Hdr0#diameter_header{hop_by_hop_id = Seq}, Msg = [Hdr, Route | Avps], - resend(call(SvcName, App, Msg, Opts), T, TPid, Pkt). + resend(call(SvcName, App, Msg, Opts), T, TPid, Fs, Pkt). %% The incoming request is relayed with the addition of a %% Route-Record. Note the requirement on the return from call/4 below, %% which places a requirement on the value returned by the @@ -1906,15 +2133,18 @@ resend(#diameter_packet{bin = B} = Pkt, _, TPid, + Fs, #diameter_packet{header = #diameter_header{hop_by_hop_id = Id}, transport_data = TD}) -> - send(TPid, Pkt#diameter_packet{bin = diameter_codec:hop_by_hop_id(Id, B), - transport_data = TD}); + P = Pkt#diameter_packet{bin = diameter_codec:hop_by_hop_id(Id, B), + transport_data = TD}, + eval_packet(P, Fs), + send(TPid, P); %% TODO: counters %% Or not: DIAMETER_UNABLE_TO_DELIVER. -resend(_, T, TPid, Pkt) -> - protocol_error(3002, T, TPid, Pkt). +resend(_, T, TPid, Fs, Pkt) -> + protocol_error(3002, T, TPid, Fs, Pkt). %% is_loop/4 %% @@ -1936,45 +2166,68 @@ is_loop(Code, Vid, OH, [_ | Avps]) is_loop(Code, Vid, OH, Avps) -> is_loop(Code, Vid, ?BASE:avp(encode, OH, 'Route-Record'), Avps). -%% reply/4 +%% reply/5 %% %% Send a locally originating reply. +%% Skip the setting of Result-Code and Failed-AVP's below. +reply([Msg], Dict, TPid, Fs, Pkt) + when is_list(Msg); + is_tuple(Msg) -> + reply(Msg, Dict, TPid, Fs, Pkt#diameter_packet{errors = []}); + %% No errors or a diameter_header/avp list. -reply(Msg, Dict, TPid, #diameter_packet{errors = Es, - transport_data = TD} - = ReqPkt) +reply(Msg, Dict, TPid, Fs, #diameter_packet{errors = Es} = ReqPkt) when [] == Es; is_record(hd(Msg), diameter_header) -> - Pkt = diameter_codec:encode(Dict, make_reply_packet(Msg, ReqPkt)), + Pkt = diameter_codec:encode(Dict, make_answer_packet(Msg, ReqPkt)), + eval_packet(Pkt, Fs), incr(send, Pkt, Dict, TPid), %% count result codes in sent answers - send(TPid, Pkt#diameter_packet{transport_data = TD}); + send(TPid, Pkt); %% Or not: set Result-Code and Failed-AVP AVP's. -reply(Msg, Dict, TPid, #diameter_packet{errors = [H|_] = Es} = Pkt) -> +reply(Msg, Dict, TPid, Fs, #diameter_packet{errors = [H|_] = Es} = Pkt) -> reply(rc(Msg, rc(H), [A || {_,A} <- Es], Dict), Dict, TPid, + Fs, Pkt#diameter_packet{errors = []}). -%% make_reply_packet/2 +eval_packet(Pkt, Fs) -> + lists:foreach(fun(F) -> diameter_lib:eval([F,Pkt]) end, Fs). + +%% make_answer_packet/2 + +%% A reply message clears the R and T flags and retains the P flag. +%% The E flag will be set at encode. 6.2 of 3588 requires the same P +%% flag on an answer as on the request. A #diameter_packet{} returned +%% from a handle_request callback can circumvent this by setting its +%% own header values. +make_answer_packet(#diameter_packet{header = Hdr, + msg = Msg, + transport_data = TD}, + #diameter_packet{header = ReqHdr}) -> + Hdr0 = ReqHdr#diameter_header{version = ?DIAMETER_VERSION, + is_request = false, + is_error = undefined, + is_retransmitted = false}, + #diameter_packet{header = fold_record(Hdr0, Hdr), + msg = Msg, + transport_data = TD}; %% Binaries and header/avp lists are sent as-is. -make_reply_packet(Bin, _) +make_answer_packet(Bin, #diameter_packet{transport_data = TD}) when is_binary(Bin) -> - #diameter_packet{bin = Bin}; -make_reply_packet([#diameter_header{} | _] = Msg, _) -> - #diameter_packet{msg = Msg}; - -%% Otherwise a reply message clears the R and T flags and retains the -%% P flag. The E flag will be set at encode. -make_reply_packet(Msg, #diameter_packet{header = ReqHdr}) -> - Hdr = ReqHdr#diameter_header{version = ?DIAMETER_VERSION, - is_request = false, - is_error = undefined, - is_retransmitted = false}, - #diameter_packet{header = Hdr, - msg = Msg}. + #diameter_packet{bin = Bin, + transport_data = TD}; +make_answer_packet([#diameter_header{} | _] = Msg, + #diameter_packet{transport_data = TD}) -> + #diameter_packet{msg = Msg, + transport_data = TD}; + +%% Otherwise, preserve transport_data. +make_answer_packet(Msg, #diameter_packet{transport_data = TD} = Pkt) -> + make_answer_packet(#diameter_packet{msg = Msg, transport_data = TD}, Pkt). %% rc/1 @@ -1987,7 +2240,10 @@ rc(RC) -> rc(Rec, RC, Failed, Dict) when is_integer(RC) -> - set(Rec, [{'Result-Code', RC} | failed_avp(Rec, Failed, Dict)], Dict). + set(Rec, + lists:append([rc(Rec, {'Result-Code', RC}, Dict), + failed_avp(Rec, Failed, Dict)]), + Dict). %% Reply as name and tuple list ... set([_|_] = Ans, Avps, _) -> @@ -1997,6 +2253,22 @@ set([_|_] = Ans, Avps, _) -> set(Rec, Avps, Dict) -> Dict:'#set-'(Avps, Rec). +%% rc/3 +%% +%% Turn the result code into a list if its optional and only set it if +%% the arity is 1 or {0,1}. In other cases (which probably shouldn't +%% exist in practise) we can't know what's appropriate. + +rc([MsgName | _], {'Result-Code' = K, RC} = T, Dict) -> + case Dict:avp_arity(MsgName, 'Result-Code') of + 1 -> [T]; + {0,1} -> [{K, [RC]}]; + _ -> [] + end; + +rc(Rec, T, Dict) -> + rc([Dict:rec2msg(element(1, Rec))], T, Dict). + %% failed_avp/3 failed_avp(_, [] = No, _) -> @@ -2204,45 +2476,39 @@ handle_answer(SvcName, _, {error, Req, Reason}) -> handle_answer(SvcName, AnswerErrors, {answer, #request{dictionary = Dict} = Req, Pkt}) -> - a(examine(diameter_codec:decode(Dict, Pkt)), - SvcName, - AnswerErrors, - Req). + answer(examine(diameter_codec:decode(Dict, Pkt)), + SvcName, + AnswerErrors, + Req). %% We don't really need to do a full decode if we're a relay and will %% just resend with a new hop by hop identifier, but might a proxy %% want to examine the answer? -a(#diameter_packet{errors = []} - = Pkt, - SvcName, - AE, - #request{transport = TPid, - dictionary = Dict, - caps = Caps, - packet = P} - = Req) -> +answer(Pkt, SvcName, AE, #request{transport = TPid, + dictionary = Dict} + = Req) -> try - incr(in, Pkt, Dict, TPid) + incr(recv, Pkt, Dict, TPid) of - _ -> - cb(Req, handle_answer, [Pkt, msg(P), SvcName, {TPid, Caps}]) + _ -> a(Pkt, SvcName, AE, Req) catch exit: {invalid_error_bit, _} = E -> - e(Pkt#diameter_packet{errors = [E]}, SvcName, AE, Req) - end; + a(Pkt#diameter_packet{errors = [E]}, SvcName, AE, Req) + end. -a(#diameter_packet{} = Pkt, SvcName, AE, Req) -> - e(Pkt, SvcName, AE, Req). +a(#diameter_packet{errors = Es} = Pkt, SvcName, AE, #request{transport = TPid, + caps = Caps, + packet = P} + = Req) + when [] == Es; + callback == AE -> + cb(Req, handle_answer, [Pkt, msg(P), SvcName, {TPid, Caps}]); -e(Pkt, SvcName, callback, #request{transport = TPid, - caps = Caps, - packet = Pkt} - = Req) -> - cb(Req, handle_answer, [Pkt, msg(Pkt), SvcName, {TPid, Caps}]); -e(Pkt, SvcName, report, Req) -> +a(Pkt, SvcName, report, Req) -> x(errors, handle_answer, [SvcName, Req, Pkt]); -e(Pkt, SvcName, discard, Req) -> + +a(Pkt, SvcName, discard, Req) -> x({errors, handle_answer, [SvcName, Req, Pkt]}). %% Note that we don't check that the application id in the answer's @@ -2257,15 +2523,16 @@ e(Pkt, SvcName, discard, Req) -> incr(_, #diameter_packet{msg = undefined}, _, _) -> ok; -incr(Dir, Pkt, Dict, TPid) - when is_pid(TPid) -> +incr(recv = D, #diameter_packet{header = H, errors = [_|_]}, _, TPid) -> + incr(TPid, {diameter_codec:msg_id(H), D, error}); + +incr(Dir, Pkt, Dict, TPid) -> #diameter_packet{header = #diameter_header{is_error = E} = Hdr, msg = Rec} = Pkt, - D = choose(E, ?BASE, Dict), - RC = int(get_avp_value(D, 'Result-Code', Rec)), + RC = int(get_avp_value(Dict, 'Result-Code', Rec)), PE = is_protocol_error(RC), %% Check that the E bit is set only for 3xxx result codes. @@ -2273,15 +2540,21 @@ incr(Dir, Pkt, Dict, TPid) orelse (E andalso PE) orelse x({invalid_error_bit, RC}, answer, [Dir, Pkt]), - Ctr = rc_counter(D, Rec, RC), - is_tuple(Ctr) - andalso incr(TPid, {diameter_codec:msg_id(Hdr), Dir, Ctr}). + irc(TPid, Hdr, Dir, rc_counter(Dict, Rec, RC)). + +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). +%% error_counter/2 + %% RFC 3588, 7.6: %% %% All Diameter answer messages defined in vendor-specific @@ -2291,26 +2564,27 @@ incr(TPid, Counter) -> %% Maintain statistics assuming one or the other, not both, which is %% surely the intent of the RFC. -rc_counter(_, _, RC) - when is_integer(RC) -> - {'Result-Code', RC}; -rc_counter(D, Rec, _) -> - rcc(get_avp_value(D, 'Experimental-Result', Rec)). +rc_counter(Dict, Rec, undefined) -> + er(get_avp_value(Dict, 'Experimental-Result', Rec)); +rc_counter(_, _, RC) -> + {'Result-Code', RC}. %% 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. -rcc([{_,_,RC} = T]) - when is_integer(RC) -> +er([{_,_,N} = T | _]) + when is_integer(N) -> T; -rcc({_,_,RC} = T) - when is_integer(RC) -> +er({_,_,N} = T) + when is_integer(N) -> T; -rcc(_) -> +er(_) -> undefined. -int([N]) +%% Extract the first good looking integer. There's no guarantee +%% that what we're looking for has arity 1. +int([N|_]) when is_integer(N) -> N; int(N) @@ -2355,8 +2629,11 @@ rt(#request{packet = #diameter_packet{msg = undefined}}, _) -> false; %% TODO: Not what we should do. %% ... or not. -rt(#request{packet = #diameter_packet{msg = Msg}, dictionary = D} = Req, S) -> - find_transport(get_destination(Msg, D), Req, S). +rt(#request{packet = #diameter_packet{msg = Msg}, + dictionary = Dict} + = Req, + S) -> + find_transport(get_destination(Dict, Msg), Req, S). %%% --------------------------------------------------------------------------- %%% # report_status/5 @@ -2389,7 +2666,7 @@ send_event(#diameter_event{service = SvcName} = E) -> %%% # share_peer/5 %%% --------------------------------------------------------------------------- -share_peer(up, Caps, Aliases, TPid, #state{share_peers = true, +share_peer(up, Caps, Aliases, TPid, #state{options = [_, {_, true} | _], service_name = Svc}) -> diameter_peer:notify(Svc, {peer, TPid, Aliases, Caps}); @@ -2400,11 +2677,11 @@ share_peer(_, _, _, _, _) -> %%% # share_peers/2 %%% --------------------------------------------------------------------------- -share_peers(Pid, #state{share_peers = true, +share_peers(Pid, #state{options = [_, {_, true} | _], local_peers = PDict}) -> ?Dict:fold(fun(A,Ps,ok) -> sp(Pid, A, Ps), ok end, ok, PDict); -share_peers(_, #state{share_peers = false}) -> +share_peers(_, _) -> ok. sp(Pid, Alias, Peers) -> @@ -2414,39 +2691,31 @@ sp(Pid, Alias, Peers) -> %%% # remote_peer_up/4 %%% --------------------------------------------------------------------------- -remote_peer_up(Pid, Aliases, Caps, #state{use_shared_peers = true, +remote_peer_up(Pid, Aliases, Caps, #state{options = [_, _, {_, true} | _], service = Svc, - shared_peers = PDict} - = S) -> + shared_peers = PDict}) -> #diameter_service{applications = Apps} = Svc, - Update = lists:filter(fun(A) -> - lists:keymember(A, #diameter_app.alias, Apps) - end, - Aliases), - S#state{shared_peers = rpu(Pid, Caps, PDict, Update)}; + Key = #diameter_app.alias, + As = lists:filter(fun(A) -> lists:keymember(A, Key, Apps) end, Aliases), + rpu(Pid, Caps, PDict, As); -remote_peer_up(_, _, _, #state{use_shared_peers = false} = S) -> - S. +remote_peer_up(_, _, _, #state{options = [_, _, {_, false} | _]}) -> + ok. rpu(_, _, PDict, []) -> PDict; rpu(Pid, Caps, PDict, Aliases) -> erlang:monitor(process, Pid), T = {Pid, Caps}, - lists:foldl(fun(A,D) -> ?Dict:append(A, T, D) end, - PDict, - Aliases). + lists:foreach(fun(A) -> ?Dict:append(A, T, PDict) end, Aliases). %%% --------------------------------------------------------------------------- %%% # remote_peer_down/2 %%% --------------------------------------------------------------------------- -remote_peer_down(Pid, #state{use_shared_peers = true, - shared_peers = PDict} - = S) -> - S#state{shared_peers = lists:foldl(fun(A,D) -> rpd(Pid, A, D) end, - PDict, - ?Dict:fetch_keys(PDict))}. +remote_peer_down(Pid, #state{options = [_, _, {_, true} | _], + shared_peers = PDict}) -> + lists:foreach(fun(A) -> rpd(Pid, A, PDict) end, ?Dict:fetch_keys(PDict)). rpd(Pid, Alias, PDict) -> ?Dict:update(Alias, fun(Ps) -> lists:keydelete(Pid, 1, Ps) end, PDict). @@ -2468,12 +2737,12 @@ find_transport({alias, Alias}, Msg, Opts, #state{service = Svc} = S) -> find_transport(#diameter_app{} = App, Msg, Opts, S) -> ft(App, Msg, Opts, S). -ft(#diameter_app{module = Mod, dictionary = D} = App, Msg, Opts, S) -> +ft(#diameter_app{module = Mod, dictionary = Dict} = App, Msg, Opts, S) -> #options{filter = Filter, extra = Xtra} = Opts, pick_peer(App#diameter_app{module = Mod ++ Xtra}, - get_destination(Msg, D), + get_destination(Dict, Msg), Filter, S); ft(false = No, _, _, _) -> @@ -2511,7 +2780,7 @@ find_transport([_,_] = RH, %% get_destination/2 -get_destination(Msg, Dict) -> +get_destination(Dict, Msg) -> [str(get_avp_value(Dict, 'Destination-Realm', Msg)), str(get_avp_value(Dict, 'Destination-Host', Msg))]. @@ -2537,6 +2806,15 @@ str(T) -> %% question. The third form allows messages to be sent as is, without %% a dictionary, which is needed in the case of relay agents, for one. +%% Messages will be header/avps list as a relay and the only AVP's we +%% 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); + +%% Message sent as a header/avps list, probably a relay case but not +%% necessarily. get_avp_value(Dict, Name, [#diameter_header{} | Avps]) -> try {Code, _, VId} = Dict:avp_header(Name), @@ -2550,6 +2828,7 @@ get_avp_value(Dict, Name, [#diameter_header{} | Avps]) -> undefined end; +%% Outgoing message as a name/values list. get_avp_value(_, Name, [_MsgName | Avps]) -> case lists:keyfind(Name, 1, Avps) of {_, V} -> @@ -2558,6 +2837,11 @@ get_avp_value(_, Name, [_MsgName | Avps]) -> undefined end; +%% Record might be an answer message in the common dictionary. +get_avp_value(Dict, Name, Rec) + when Dict /= ?BASE, element(1, Rec) == 'diameter_base_answer-message' -> + get_avp_value(?BASE, Name, Rec); + %% Message is typically a record but not necessarily: diameter:call/4 %% can be passed an arbitrary term. get_avp_value(Dict, Name, Rec) -> @@ -2752,20 +3036,59 @@ transports(#state{peerT = PeerT}) -> 'Vendor-Specific-Application-Id', 'Firmware-Revision']). +%% The config returned by diameter:service_info(SvcName, all). -define(ALL_INFO, [capabilities, applications, transport, pending, - statistics]). + options]). + +%% The rest. +-define(OTHER_INFO, [connections, + name, + peers, + statistics]). -service_info(Items, S) - when is_list(Items) -> - [{complete(I), service_info(I,S)} || I <- Items]; service_info(Item, S) when is_atom(Item) -> - service_info(Item, S, true). + case tagged_info(Item, S) of + {_, T} -> T; + undefined = No -> No + end; + +service_info(Items, S) -> + tagged_info(Items, S). -service_info(Item, #state{service = Svc} = S, Complete) -> +tagged_info(Item, S) + when is_atom(Item) -> + case complete(Item) of + {value, I} -> + {I, complete_info(I,S)}; + false -> + undefined + end; + +tagged_info(TPid, #state{peerT = PT, connT = CT}) + when is_pid(TPid) -> + try + [#conn{peer = Pid}] = ets:lookup(CT, TPid), + [#peer{ref = Ref, type = Type, options = Opts}] = ets:lookup(PT, Pid), + [{ref, Ref}, + {type, Type}, + {options, Opts}] + catch + error:_ -> + [] + end; + +tagged_info(Items, S) + when is_list(Items) -> + [T || I <- Items, T <- [tagged_info(I,S)], T /= undefined, T /= []]; + +tagged_info(_, _) -> + undefined. + +complete_info(Item, #state{service = Svc} = S) -> case Item of name -> S#state.service_name; @@ -2808,85 +3131,176 @@ service_info(Item, #state{service = Svc} = S, Complete) -> capabilities -> service_info(?CAP_INFO, S); applications -> info_apps(S); transport -> info_transport(S); + options -> info_options(S); pending -> info_pending(S); - statistics -> info_stats(S); - keys -> ?ALL_INFO ++ ?CAP_INFO; %% mostly for test + keys -> ?ALL_INFO ++ ?CAP_INFO ++ ?OTHER_INFO; all -> service_info(?ALL_INFO, S); - _ when Complete -> service_info(complete(Item), S, false); - _ -> undefined + statistics -> info_stats(S); + connections -> info_connections(S); + peers -> info_peers(S) end. +complete(I) + when I == keys; + I == all -> + {value, I}; complete(Pre) -> P = atom_to_list(Pre), - case [I || I <- [name | ?ALL_INFO] ++ ?CAP_INFO, + case [I || I <- ?ALL_INFO ++ ?CAP_INFO ++ ?OTHER_INFO, lists:prefix(P, atom_to_list(I))] of - [I] -> I; - _ -> Pre + [I] -> {value, I}; + _ -> false end. +%% info_stats/1 + info_stats(#state{peerT = PeerT}) -> - Peers = ets:select(PeerT, [{#peer{ref = '$1', conn = '$2', _ = '_'}, - [{'is_pid', '$2'}], - [['$1', '$2']]}]), - diameter_stats:read(lists:append(Peers)). -%% TODO: include peer identities in return value - -info_transport(#state{peerT = PeerT, connT = ConnT}) -> - dict:fold(fun it/3, + MatchSpec = [{#peer{ref = '$1', conn = '$2', _ = '_'}, + [{'is_pid', '$2'}], + [['$1', '$2']]}], + try ets:select(PeerT, MatchSpec) of + L -> + diameter_stats:read(lists:append(L)) + catch + error: badarg -> [] %% service has gone down + end. + +%% info_transport/1 +%% +%% One entry per configured transport. Statistics for each entry are +%% the accumulated values for the ref and associated peer pids. + +info_transport(S) -> + PeerD = peer_dict(S, config_dict(S)), + RefsD = dict:map(fun(_, Ls) -> [P || L <- Ls, {peer, {P,_}} <- L] end, + PeerD), + Refs = lists:append(dict:fold(fun(R, Ps, A) -> [[R|Ps] | A] end, + [], + RefsD)), + Stats = diameter_stats:read(Refs), + dict:fold(fun(R, Ls, A) -> + Ps = dict:fetch(R, RefsD), + [[{ref, R} | transport(Ls)] ++ [stats([R|Ps], Stats)] + | A] + end, [], - ets:foldl(fun(T,A) -> it_acc(ConnT, A, T) end, - dict:new(), - PeerT)). - -it(Ref, [[{type, connect} | _] = L], Acc) -> - [[{ref, Ref} | L] | Acc]; -it(Ref, [[{type, accept}, {options, Opts} | _] | _] = L, Acc) -> - [[{ref, Ref}, - {type, listen}, - {options, Opts}, - {accept, [lists:nthtail(2,A) || A <- L]}] - | Acc]. -%% Each entry has the same Opts. (TODO) - -it_acc(ConnT, Acc, #peer{pid = Pid, - type = Type, - ref = Ref, - options = Opts, - op_state = OS, - started = T, - conn = TPid}) -> + 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; + +%% 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. (TODO: all entries for the same Ref should share options.) +transport([[{type, accept}, {options, Opts} | _] | _] = Ls) -> + [{type, listen}, + {options, Opts}, + {accept, [lists:nthtail(2,L) || L <- Ls]}]. + +peer_dict(#state{peerT = PeerT, connT = ConnT}, Dict0) -> + try ets:tab2list(PeerT) of + L -> + lists:foldl(fun(T,A) -> peer_acc(ConnT, A, T) end, Dict0, L) + catch + error: badarg -> Dict0 %% service has gone down + end. + +peer_acc(ConnT, Acc, #peer{pid = Pid, + type = Type, + ref = Ref, + options = Opts, + op_state = OS, + started = T, + conn = TPid}) -> + WS = wd_state(OS), dict:append(Ref, [{type, Type}, {options, Opts}, - {watchdog, {Pid, T, OS}} - | info_conn(ConnT, TPid)], + {watchdog, {Pid, T, WS}} + | info_conn(ConnT, TPid, WS /= ?WD_DOWN)], Acc). -info_conn(ConnT, TPid) -> - info_conn(ets:lookup(ConnT, TPid)). +info_conn(ConnT, TPid, true) + when is_pid(TPid) -> + try ets:lookup(ConnT, TPid) of + T -> info_conn(T) + catch + error: badarg -> [] %% service has gone down + end; +info_conn(_, _, _) -> + []. + +%% 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. + +config_dict(#state{service_name = SvcName}) -> + lists:foldl(fun config_acc/2, + dict:new(), + diameter_config:lookup(SvcName)). + +config_acc({Ref, T, Opts}, Dict) + when T == listen; + T == connect -> + dict:store(Ref, [[{type, T}, {options, Opts}]], Dict); +config_acc(_, Dict) -> + Dict. + +wd_state({_,S}) -> + S; +wd_state(?STATE_UP) -> + ?WD_OKAY; +wd_state(?STATE_DOWN) -> + ?WD_DOWN. info_conn([#conn{pid = Pid, apps = SApps, caps = Caps, started = T}]) -> [{peer, {Pid, T}}, {apps, SApps}, - {caps, info_caps(Caps)}]; + {caps, info_caps(Caps)} + | try [{port, info_port(Pid)}] catch _:_ -> [] end]; info_conn([] = No) -> No. +%% Extract information that the processes involved are expected to +%% "publish" in their process dictionaries. Simple but backhanded. +info_port(Pid) -> + {_, PD} = process_info(Pid, dictionary), + {_, T} = lists:keyfind({diameter_peer_fsm, start}, 1, PD), + {TPid, {_Type, TMod, _Cfg}} = T, + {_, TD} = process_info(TPid, dictionary), + {_, Data} = lists:keyfind({TMod, info}, 1, TD), + [{owner, TPid}, + {module, TMod} + | try TMod:info(Data) catch _:_ -> [] end]. + +%% Use the fields names from diameter_caps instead of +%% diameter_base_CER to distinguish between the 2-tuple values +%% compared to the single capabilities values. Note also that the +%% returned list is tagged 'caps' rather than 'capabilities' to +%% emphasize the difference. info_caps(#diameter_caps{} = C) -> lists:zip(record_info(fields, diameter_caps), tl(tuple_to_list(C))). info_apps(#state{service = #diameter_service{applications = Apps}}) -> lists:map(fun mk_app/1, Apps). -mk_app(#diameter_app{alias = Alias, - dictionary = Dict, - module = ModX, - id = Id}) -> - [{alias, Alias}, - {dictionary, Dict}, - {module, ModX}, - {id, Id}]. +mk_app(#diameter_app{} = A) -> + lists:zip(record_info(fields, diameter_app), tl(tuple_to_list(A))). + +%% info_pending/1 +%% +%% One entry for each outgoing request whose answer is outstanding. info_pending(#state{} = S) -> MatchSpec = [{{'$1', @@ -2900,4 +3314,67 @@ info_pending(#state{} = S) -> {{transport, '$2'}}, {{from, '$3'}}]}}]}], - ets:select(?REQUEST_TABLE, MatchSpec). + try + ets:select(?REQUEST_TABLE, MatchSpec) + catch + error: badarg -> [] %% service has gone down + end. + +%% info_connections/1 +%% +%% One entry per transport connection. Statistics for each entry are +%% for the peer pid only. + +info_connections(S) -> + ConnL = conn_list(S), + Stats = diameter_stats:read([P || L <- ConnL, {peer, {P,_}} <- L]), + [L ++ [stats([P], Stats)] || L <- ConnL, {peer, {P,_}} <- L]. + +conn_list(S) -> + lists:append(dict:fold(fun conn_acc/3, [], peer_dict(S, dict:new()))). + +conn_acc(Ref, Peers, Acc) -> + [[[{ref, Ref} | L] || L <- Peers, lists:keymember(peer, 1, L)] + | Acc]. + +stats(Refs, Stats) -> + {statistics, dict:to_list(lists:foldl(fun(R,D) -> + stats_acc(R, D, Stats) + end, + dict:new(), + Refs))}. + +stats_acc(Ref, Dict, Stats) -> + lists:foldl(fun({C,N}, D) -> dict:update_counter(C, N, D) end, + Dict, + proplists:get_value(Ref, Stats, [])). + +%% info_peers/1 +%% +%% One entry per peer Origin-Host. Statistics for each entry are +%% accumulated values for all peer pids. + +info_peers(S) -> + {PeerD, RefD} = lists:foldl(fun peer_acc/2, + {dict:new(), dict:new()}, + conn_list(S)), + Refs = lists:append(dict:fold(fun(_, Rs, A) -> [Rs|A] end, + [], + RefD)), + Stats = diameter_stats:read(Refs), + dict:fold(fun(OH, Cs, A) -> + Rs = dict:fetch(OH, RefD), + [{OH, [{connections, Cs}, stats(Rs, Stats)]} | A] + end, + [], + PeerD). + +peer_acc(Peer, {PeerD, RefD}) -> + [{TPid, _}, [{origin_host, {_, OH}} | _]] + = [proplists:get_value(K, Peer) || K <- [peer, caps]], + {dict:append(OH, Peer, PeerD), dict:append(OH, TPid, RefD)}. + +%% info_options/1 + +info_options(S) -> + S#state.options. diff --git a/lib/diameter/src/app/diameter_service_sup.erl b/lib/diameter/src/base/diameter_service_sup.erl index 153fff902f..153fff902f 100644 --- a/lib/diameter/src/app/diameter_service_sup.erl +++ b/lib/diameter/src/base/diameter_service_sup.erl diff --git a/lib/diameter/src/app/diameter_session.erl b/lib/diameter/src/base/diameter_session.erl index bb91e97f39..3b236f109a 100644 --- a/lib/diameter/src/app/diameter_session.erl +++ b/lib/diameter/src/base/diameter_session.erl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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,19 +20,18 @@ -module(diameter_session). -export([sequence/0, + sequence/1, session_id/1, origin_state_id/0]). %% towards diameter_sup -export([init/0]). --include("diameter_types.hrl"). - -define(INT64, 16#FFFFFFFFFFFFFFFF). -define(INT32, 16#FFFFFFFF). %% --------------------------------------------------------------------------- -%% # sequence/0 +%% # sequence/0-1 %% %% Output: 32-bit %% --------------------------------------------------------------------------- @@ -73,12 +72,21 @@ %% consumed (see Section 6.2) SHOULD be silently discarded. -spec sequence() - -> 'Unsigned32'(). + -> diameter:'Unsigned32'(). sequence() -> Instr = {_Pos = 2, _Incr = 1, _Threshold = ?INT32, _SetVal = 0}, ets:update_counter(diameter_sequence, sequence, Instr). +-spec sequence(diameter:sequence()) + -> diameter:'Unsigned32'(). + +sequence({_,32}) -> + sequence(); + +sequence({H,N}) -> + (H bsl N) bor (sequence() band (1 bsl N - 1)). + %% --------------------------------------------------------------------------- %% # origin_state_id/0 %% --------------------------------------------------------------------------- @@ -97,7 +105,7 @@ sequence() -> %% counter retained in non-volatile memory across restarts. -spec origin_state_id() - -> 'Unsigned32'(). + -> diameter:'Unsigned32'(). origin_state_id() -> ets:lookup_element(diameter_sequence, origin_state_id, 2). @@ -130,8 +138,8 @@ origin_state_id() -> %% <optional value> is implementation specific but may include a modem's %% device Id, a layer 2 address, timestamp, etc. --spec session_id('DiameterIdentity'()) - -> 'OctetString'(). +-spec session_id(diameter:'DiameterIdentity'()) + -> diameter:'OctetString'(). %% Note that Session-Id has type UTF8String and that any OctetString %% is a UTF8String. diff --git a/lib/diameter/src/base/diameter_stats.erl b/lib/diameter/src/base/diameter_stats.erl new file mode 100644 index 0000000000..70727d068e --- /dev/null +++ b/lib/diameter/src/base/diameter_stats.erl @@ -0,0 +1,287 @@ +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2010-2012. 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% +%% + +%% +%% Statistics collector. +%% + +-module(diameter_stats). + +-behaviour(gen_server). + +-export([reg/2, reg/1, + incr/3, incr/1, + read/1, + flush/1]). + +%% supervisor callback +-export([start_link/0]). + +%% gen_server callbacks +-export([init/1, + terminate/2, + handle_call/3, + handle_cast/2, + handle_info/2, + code_change/3]). + +%% debug +-export([state/0, + uptime/0]). + +-include("diameter_internal.hrl"). + +%% ets table containing 2-tuple stats. reg(Pid, Ref) inserts a {Pid, +%% Ref}, incr(Counter, X, N) updates the counter keyed at {Counter, +%% X}, and Pid death causes counters keyed on {Counter, Pid} to be +%% deleted and added to those keyed on {Counter, Ref}. +-define(TABLE, ?MODULE). + +%% Name of registered server. +-define(SERVER, ?MODULE). + +%% Server state. +-record(state, {id = now()}). + +-type counter() :: any(). +-type ref() :: any(). + +%% --------------------------------------------------------------------------- +%% # reg(Pid, Ref) +%% +%% Register a process as a contributor of statistics associated with a +%% specified term. Statistics can be contributed by specifying either +%% Pid or Ref as the second argument to incr/3. Statistics contributed +%% by Pid are folded into the corresponding entry for Ref when the +%% process dies. +%% --------------------------------------------------------------------------- + +-spec reg(pid(), ref()) + -> boolean(). + +reg(Pid, Ref) + when is_pid(Pid) -> + call({reg, Pid, Ref}). + +-spec reg(ref()) + -> true. + +reg(Ref) -> + reg(self(), Ref). + +%% --------------------------------------------------------------------------- +%% # incr(Counter, Ref, N) +%% +%% Increment a counter for the specified contributor. +%% +%% Ref will typically be an argument passed to reg/2 but there's +%% nothing that requires this. Only registered pids can contribute +%% counters however, otherwise incr/3 is a no-op. +%% --------------------------------------------------------------------------- + +-spec incr(counter(), ref(), integer()) + -> integer() | false. + +incr(Ctr, Ref, N) + when is_integer(N) -> + update_counter({Ctr, Ref}, N). + +incr(Ctr) -> + incr(Ctr, self(), 1). + +%% --------------------------------------------------------------------------- +%% # read(Refs) +%% +%% Retrieve counters for the specified contributors. +%% --------------------------------------------------------------------------- + +-spec read([ref()]) + -> [{ref(), [{counter(), integer()}]}]. + +read(Refs) -> + read(Refs, false). + +read(Refs, B) -> + MatchSpec = [{{{'_', '$1'}, '_'}, + [?ORCOND([{'=:=', '$1', {const, R}} + || R <- Refs])], + ['$_']}], + L = ets:select(?TABLE, MatchSpec), + B andalso delete(L), + lists:foldl(fun({{C,R}, N}, D) -> orddict:append(R, {C,N}, D) end, + orddict:new(), + L). + +%% --------------------------------------------------------------------------- +%% # flush(Refs) +%% +%% Retrieve and delete statistics for the specified contributors. +%% --------------------------------------------------------------------------- + +-spec flush([ref()]) + -> [{ref(), {counter(), integer()}}]. + +flush(Refs) -> + try + call({flush, Refs}) + catch + exit: _ -> + [] + end. + +%% =========================================================================== + +start_link() -> + ServerName = {local, ?SERVER}, + Module = ?MODULE, + Args = [], + Options = [{spawn_opt, diameter_lib:spawn_opts(server, [])}], + gen_server:start_link(ServerName, Module, Args, Options). + +state() -> + call(state). + +uptime() -> + call(uptime). + +%% ---------------------------------------------------------- +%% # init/1 +%% ---------------------------------------------------------- + +init([]) -> + ets:new(?TABLE, [named_table, ordered_set, public]), + {ok, #state{}}. + +%% ---------------------------------------------------------- +%% # handle_call/3 +%% ---------------------------------------------------------- + +handle_call(state, _, State) -> + {reply, State, State}; + +handle_call(uptime, _, #state{id = Time} = State) -> + {reply, diameter_lib:now_diff(Time), State}; + +handle_call({incr, T}, _, State) -> + {reply, update_counter(T), State}; + +handle_call({reg, Pid, Ref}, _From, State) -> + B = ets:insert_new(?TABLE, {Pid, Ref}), + B andalso erlang:monitor(process, Pid), + {reply, B, State}; + +handle_call({flush, Refs}, _From, State) -> + {reply, read(Refs, true), State}; + +handle_call(Req, From, State) -> + ?UNEXPECTED([Req, From]), + {reply, nok, State}. + +%% ---------------------------------------------------------- +%% # handle_cast/2 +%% ---------------------------------------------------------- + +handle_cast(Msg, State) -> + ?UNEXPECTED([Msg]), + {noreply, State}. + +%% ---------------------------------------------------------- +%% # handle_info/2 +%% ---------------------------------------------------------- + +handle_info({'DOWN', _MRef, process, Pid, _}, State) -> + down(Pid), + {noreply, State}; + +handle_info(Info, State) -> + ?UNEXPECTED([Info]), + {noreply, State}. + +%% ---------------------------------------------------------- +%% # terminate/2 +%% ---------------------------------------------------------- + +terminate(_Reason, _State) -> + ok. + +%% ---------------------------------------------------------- +%% # code_change/3 +%% ---------------------------------------------------------- + +code_change(_OldVsn, State, _Extra) -> + {ok, State}. + +%% =========================================================================== + +%% down/1 + +down(Pid) -> + down(lookup(Pid), ets:match_object(?TABLE, {{'_', Pid}, '_'})). + +down([{_, Ref} = T], L) -> + fold(Ref, L), + delete([T|L]); +down([], L) -> %% flushed + delete(L). + +%% Fold pid-based entries into ref-based ones. +fold(Ref, L) -> + lists:foreach(fun({{K, _}, V}) -> update_counter({{K, Ref}, V}) end, L). + +%% update_counter/2 +%% +%% From an arbitrary process. Call to the server process to insert a +%% new element if the counter doesn't exists so that two processes +%% don't insert simultaneously. + +update_counter(Key, N) -> + try + ets:update_counter(?TABLE, Key, N) + catch + error: badarg -> + call({incr, {Key, N}}) + end. + +%% update_counter/1 +%% +%% From the server process, when update_counter/2 failed due to a +%% non-existent entry. + +update_counter({{_Ctr, Ref} = Key, N} = T) -> + try + ets:update_counter(?TABLE, Key, N) + catch + error: badarg -> + (not is_pid(Ref) orelse ets:member(?TABLE, Ref)) + andalso begin insert(T), N end + end. + +insert(T) -> + ets:insert(?TABLE, T). + +lookup(Key) -> + ets:lookup(?TABLE, Key). + +delete(Objs) -> + lists:foreach(fun({K,_}) -> ets:delete(?TABLE, K) end, Objs). + +%% call/1 + +call(Request) -> + gen_server:call(?SERVER, Request, infinity). diff --git a/lib/diameter/src/app/diameter_sup.erl b/lib/diameter/src/base/diameter_sup.erl index e5afd23dcd..e5afd23dcd 100644 --- a/lib/diameter/src/app/diameter_sup.erl +++ b/lib/diameter/src/base/diameter_sup.erl diff --git a/lib/diameter/src/app/diameter_sync.erl b/lib/diameter/src/base/diameter_sync.erl index ce2db4b3a2..ce2db4b3a2 100644 --- a/lib/diameter/src/app/diameter_sync.erl +++ b/lib/diameter/src/base/diameter_sync.erl diff --git a/lib/diameter/src/app/diameter_types.erl b/lib/diameter/src/base/diameter_types.erl index 6b1b1b8d39..9ae289034c 100644 --- a/lib/diameter/src/app/diameter_types.erl +++ b/lib/diameter/src/base/diameter_types.erl @@ -42,8 +42,23 @@ 'IPFilterRule'/2, 'QoSFilterRule'/2]). +%% Functions taking the AVP name in question as second parameter. +-export(['OctetString'/3, + 'Integer32'/3, + 'Integer64'/3, + 'Unsigned32'/3, + 'Unsigned64'/3, + 'Float32'/3, + 'Float64'/3, + 'Address'/3, + 'Time'/3, + 'UTF8String'/3, + 'DiameterIdentity'/3, + 'DiameterURI'/3, + 'IPFilterRule'/3, + 'QoSFilterRule'/3]). + -include_lib("diameter/include/diameter.hrl"). --include("diameter_internal.hrl"). -define(UINT(N,X), ((0 =< X) andalso (X < 1 bsl N))). -define(SINT(N,X), ((-1*(1 bsl (N-1)) < X) andalso (X < 1 bsl (N-1)))). @@ -433,6 +448,50 @@ uenc([C | Rest], Acc) -> 'Time'(encode, zero) -> <<0:32>>. +%% ------------------------------------------------------------------------- + +'OctetString'(M, _, Data) -> + 'OctetString'(M, Data). + +'Integer32'(M, _, Data) -> + 'Integer32'(M, Data). + +'Integer64'(M, _, Data) -> + 'Integer64'(M, Data). + +'Unsigned32'(M, _, Data) -> + 'Unsigned32'(M, Data). + +'Unsigned64'(M, _, Data) -> + 'Unsigned64'(M, Data). + +'Float32'(M, _, Data) -> + 'Float32'(M, Data). + +'Float64'(M, _, Data) -> + 'Float64'(M, Data). + +'Address'(M, _, Data) -> + 'Address'(M, Data). + +'Time'(M, _, Data) -> + 'Time'(M, Data). + +'UTF8String'(M, _, Data) -> + 'UTF8String'(M, Data). + +'DiameterIdentity'(M, _, Data) -> + 'DiameterIdentity'(M, Data). + +'DiameterURI'(M, _, Data) -> + 'DiameterURI'(M, Data). + +'IPFilterRule'(M, _, Data) -> + 'IPFilterRule'(M, Data). + +'QoSFilterRule'(M, _, Data) -> + 'QoSFilterRule'(M, Data). + %% =========================================================================== %% =========================================================================== diff --git a/lib/diameter/src/app/diameter_watchdog.erl b/lib/diameter/src/base/diameter_watchdog.erl index b7c1491f4b..243ad0a986 100644 --- a/lib/diameter/src/app/diameter_watchdog.erl +++ b/lib/diameter/src/base/diameter_watchdog.erl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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 @@ -43,26 +43,46 @@ -include("diameter_internal.hrl"). -define(DEFAULT_TW_INIT, 30000). %% RFC 3539 ch 3.4.1 +-define(NOMASK, {0,32}). %% default sequence mask -record(watchdog, {%% PCB - Peer Control Block; see RFC 3539, Appendix A status = initial :: initial | okay | suspect | down | reopen, - pending = false :: boolean(), + pending = false :: boolean(), %% DWA tw :: 6000..16#FFFFFFFF | {module(), atom(), list()}, %% {M,F,A} -> integer() >= 0 num_dwa = 0 :: -1 | non_neg_integer(), %% number of DWAs received during reopen %% end PCB - parent = self() :: pid(), - transport :: pid(), + parent = self() :: pid(), %% service process + transport :: pid() | undefined, %% peer_fsm process tref :: reference(), %% reference for current watchdog timer - message_data}). %% term passed into diameter_service with message + message_data, %% term passed into diameter_service with message + sequence :: diameter:sequence(), %% mask + restrict :: {diameter:restriction(), boolean()}, + shutdown = false :: boolean()}). %% start/2 +%% +%% Start a monitor before the watchdog is allowed to proceed to ensure +%% that a failed capabilities exchange produces the desired exit +%% reason. + +-spec start(Type, {RecvData, [Opt], SvcName, #diameter_service{}}) + -> {reference(), pid()} + when Type :: {connect|accept, diameter:transport_ref()}, + RecvData :: term(), + Opt :: diameter:transport_opt(), + SvcName :: diameter:service_name(). start({_,_} = Type, T) -> - {ok, Pid} = diameter_watchdog_sup:start_child({Type, self(), T}), - Pid. + Ref = make_ref(), + {ok, Pid} = diameter_watchdog_sup:start_child({Ref, {Type, self(), T}}), + try + {erlang:monitor(process, Pid), Pid} + after + Pid ! Ref + end. start_link(T) -> {ok, _} = proc_lib:start_link(?MODULE, @@ -80,19 +100,45 @@ init(T) -> proc_lib:init_ack({ok, self()}), gen_server:enter_loop(?MODULE, [], i(T)). -i({T, Pid, {ConnT, Opts, SvcName, #diameter_service{applications = Apps, - capabilities = Caps} - = Svc}}) -> - {M,S,U} = now(), - random:seed(M,S,U), +i({Ref, {_, Pid, _} = T}) -> + MRef = erlang:monitor(process, Pid), + receive + Ref -> + make_state(T); + {'DOWN', MRef, process, _, _} = D -> + exit({shutdown, D}) + end; + +i({_, Pid, _} = T) -> %% from old code + erlang:monitor(process, Pid), + make_state(T). + +make_state({T, Pid, {RecvData, + Opts, + SvcName, + #diameter_service{applications = Apps, + capabilities = Caps} + = Svc}}) -> + random:seed(now()), putr(restart, {T, Opts, Svc}), %% save seeing it in trace putr(dwr, dwr(Caps)), %% - #watchdog{parent = monitor(Pid), - transport = monitor(diameter_peer_fsm:start(T, Opts, Svc)), + {_,_} = Mask = call(Pid, sequence), + Restrict = call(Pid, restriction), + Nodes = restrict_nodes(Restrict), + #watchdog{parent = Pid, + transport = monitor(diameter_peer_fsm:start(T, + Opts, + {Mask, Nodes, Svc})), tw = proplists:get_value(watchdog_timer, Opts, ?DEFAULT_TW_INIT), - message_data = {ConnT, SvcName, Apps}}. + message_data = {RecvData, SvcName, Apps, Mask}, + sequence = Mask, + restrict = {Restrict, lists:member(node(), Nodes)}}. + +%% Retrieve the sequence mask from the parent from the parent, rather +%% than having it passed into init/1, for upgrade reasons: the call to +%% diameter_service:receive_message/3 passes back the mask. %% handle_call/3 @@ -106,17 +152,46 @@ handle_cast(_, State) -> %% handle_info/2 -handle_info(T, State) -> +handle_info(T, #watchdog{} = State) -> case transition(T, State) of ok -> {noreply, State}; - #watchdog{status = X} = S -> - ?LOGC(X =/= State#watchdog.status, transition, X), + #watchdog{} = S -> + event(State, S), {noreply, S}; stop -> ?LOG(stop, T), + event(State, State#watchdog{status = down}), {stop, {shutdown, T}, State} - end. + end; + +handle_info(T, S) -> + handle_info(T, upgrade(S)). + +upgrade(S) -> + #watchdog{} = list_to_tuple(tuple_to_list(S) + ++ [?NOMASK, {nodes, true}, false]). + +event(#watchdog{status = T}, #watchdog{status = T}) -> + ok; + +event(#watchdog{transport = undefined}, #watchdog{transport = undefined}) -> + ok; + +event(#watchdog{status = From, transport = F, parent = Pid}, + #watchdog{status = To, transport = T}) -> + E = {tpid(F,T), From, To}, + notify(Pid, E), + ?LOG(transition, {self(), E}). + +tpid(_, Pid) + when is_pid(Pid) -> + Pid; +tpid(Pid, _) -> + Pid. + +notify(Pid, E) -> + Pid ! {watchdog, self(), E}. %% terminate/2 @@ -152,9 +227,10 @@ transition({shutdown, Pid}, #watchdog{parent = Pid, down = S, %% sanity check stop; transition({shutdown = T, Pid}, #watchdog{parent = Pid, - transport = TPid}) -> + transport = TPid} + = S) -> TPid ! {T, self()}, - ok; + S#watchdog{shutdown = true}; %% Parent process has died, transition({'DOWN', _, process, Pid, _Reason}, @@ -179,18 +255,19 @@ transition({close, TPid, _Reason}, #watchdog{transport = TPid}) -> %% state okay as the result of the Peer State Machine reaching the %% Open state. %% -%% If we're an acceptor then we may be resuming a connection that went -%% down in another acceptor process, in which case this is the -%% transition below, from down into reopen. That is, it's not until -%% we know the identity of the peer (ie. now) that we know that we're -%% in state down rather than initial. +%% If we're accepting then we may be resuming a connection that went +%% down in another watchdog process, in which case this is the +%% transition below, from down to reopen. That is, it's not until we +%% know the identity of the peer (ie. now) that we know that we're in +%% state down rather than initial. transition({open, TPid, Hosts, T} = Open, #watchdog{transport = TPid, status = initial, - parent = Pid} + parent = Pid, + restrict = {_, R}} = S) -> - case okay(getr(restart), Hosts) of + case okay(getr(restart), Hosts, R) of okay -> open(Pid, {TPid, T}), set_watchdog(S#watchdog{status = okay}); @@ -205,12 +282,15 @@ transition({open, TPid, Hosts, T} = Open, transition({open = P, TPid, _Hosts, T}, #watchdog{transport = TPid, + parent = Pid, status = down} = S) -> %% Store the info we need to notify the parent to reopen the %% connection after the requisite DWA's are received, at which - %% time we eraser(open). + %% time we eraser(open). The reopen message is a later addition, + %% to communicate the new capabilities as soon as they're known. putr(P, {TPid, T}), + Pid ! {reopen, self(), {TPid, T}}, set_watchdog(send_watchdog(S#watchdog{status = reopen, num_dwa = 0})); @@ -224,11 +304,14 @@ transition({open = P, TPid, _Hosts, T}, transition({'DOWN', _, process, TPid, _}, #watchdog{transport = TPid, - status = initial}) -> + status = S, + shutdown = D}) + when S == initial; + D -> stop; -transition({'DOWN', _, process, Pid, _}, - #watchdog{transport = Pid} +transition({'DOWN', _, process, TPid, _}, + #watchdog{transport = TPid} = S) -> failover(S), close(S), @@ -259,6 +342,15 @@ transition({state, Pid}, #watchdog{status = S}) -> %% =========================================================================== +%% Only call "upwards", to the parent service. +call(Pid, Req) -> + try + gen_server:call(Pid, Req, infinity) + catch + exit: Reason -> + exit({shutdown, {Req, Reason}}) + end. + monitor(Pid) -> erlang:monitor(process, Pid), Pid. @@ -272,26 +364,36 @@ getr(Key) -> eraser(Key) -> erase({?MODULE, Key}). -%% encode/1 +%% encode/2 -encode(Msg) -> - #diameter_packet{bin = Bin} = diameter_codec:encode(?BASE, Msg), +encode(Msg, Mask) -> + 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(?BASE, Pkt), Bin. -%% okay/2 +%% okay/3 -okay({{accept, Ref}, _, _}, Hosts) -> +okay({{accept, Ref}, _, _}, Hosts, Restrict) -> T = {?MODULE, connection, Ref, Hosts}, diameter_reg:add(T), - okay(diameter_reg:match(T)); + if Restrict -> + okay(diameter_reg:match(T)); + true -> + okay + end; %% Register before matching so that at least one of two registering -%% processes will match the other. (Which can't happen as long as -%% diameter_peer_fsm guarantees at most one open connection to the same -%% peer.) +%% processes will match the other. -okay({{connect, _}, _, _}, _) -> +okay({{connect, _}, _, _}, _, _) -> okay. +%% okay/2 + %% The peer hasn't been connected recently ... okay([{_,P}]) -> P = self(), %% assert @@ -347,9 +449,10 @@ close(#watchdog{parent = Pid}) -> %% send_watchdog/1 send_watchdog(#watchdog{pending = false, - transport = TPid} + transport = TPid, + sequence = Mask} = S) -> - TPid ! {send, encode(getr(dwr))}, + TPid ! {send, encode(getr(dwr), Mask)}, ?LOG(send, 'DWR'), S#watchdog{pending = true}. @@ -361,7 +464,7 @@ recv(Name, Pkt, S) -> rcv(Name, Pkt, S), NS catch - throw: {?MODULE, throwaway, #watchdog{} = NS} -> + {?MODULE, throwaway, #watchdog{} = NS} -> NS end. @@ -384,6 +487,14 @@ throwaway(S) -> throw({?MODULE, throwaway, S}). %% rcv/2 +%% +%% The lack of Hop-by-Hop and End-to-End Identifiers checks in a +%% received DWA is intentional. The purpose of the message is to +%% demonstrate life but a peer that consistently bungles it by sending +%% the wrong identifiers causes the connection to toggle between OPEN +%% and SUSPECT, with failover and failback as result, despite there +%% being no real problem with connectivity. Thus, relax and accept any +%% incoming DWA as being in response to an outgoing DWR. %% INITIAL Receive DWA Pending = FALSE %% Throwaway() INITIAL @@ -502,7 +613,7 @@ timeout(#watchdog{status = T, = S) when T == suspect; T == reopen, P, N < 0 -> - exit(TPid, shutdown), + exit(TPid, {shutdown, watchdog_timeout}), close(S), S#watchdog{status = down}; @@ -547,19 +658,40 @@ restart(#watchdog{transport = undefined} = S) -> restart(S) -> S. +%% restart/2 +%% %% Only restart the transport in the connecting case. For an accepting -%% transport, we've registered the peer connection when leaving state -%% initial and this is used by a new accepting process to realize that -%% it's actually in state down rather then initial when receiving -%% notification of an open connection. - -restart({{connect, _} = T, Opts, Svc}, #watchdog{parent = Pid} = S) -> +%% transport, there's no guarantee that an accepted connection in a +%% restarted transport if from the peer we've lost contact with so +%% have to be prepared for another watchdog to handle it. This is what +%% the diameter_reg registration in this module is for: the peer +%% connection is registered when leaving state initial and this is +%% used by a new accepting watchdog to realize that it's actually in +%% state down rather then initial when receiving notification of an +%% open connection. + +restart({{connect, _} = T, Opts, Svc}, #watchdog{parent = Pid, + sequence = Mask, + restrict = {R,_}} + = S) -> Pid ! {reconnect, self()}, - S#watchdog{transport = monitor(diameter_peer_fsm:start(T, Opts, Svc))}; + Nodes = restrict_nodes(R), + S#watchdog{transport = monitor(diameter_peer_fsm:start(T, + Opts, + {Mask, Nodes, 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; + +%% Otherwise hang around until told to die. restart({{accept, _}, _, _}, S) -> S. -%% Don't currently use Opts/Svc in the accept case but having them in -%% the process dictionary is helpful if the process dies unexpectedly. + +%% Don't currently use Opts/Svc in the accept case. %% dwr/1 @@ -569,3 +701,22 @@ dwr(#diameter_caps{origin_host = OH, ['DWR', {'Origin-Host', OH}, {'Origin-Realm', OR}, {'Origin-State-Id', OSI}]. + +%% restrict_nodes/1 + +restrict_nodes(false) -> + []; + +restrict_nodes(nodes) -> + [node() | nodes()]; + +restrict_nodes(node) -> + [node()]; + +restrict_nodes(Nodes) + when [] == Nodes; + is_atom(hd(Nodes)) -> + Nodes; + +restrict_nodes(F) -> + diameter_lib:eval(F). diff --git a/lib/diameter/src/app/diameter_watchdog_sup.erl b/lib/diameter/src/base/diameter_watchdog_sup.erl index fc837fe4ef..fc837fe4ef 100644 --- a/lib/diameter/src/app/diameter_watchdog_sup.erl +++ b/lib/diameter/src/base/diameter_watchdog_sup.erl diff --git a/lib/diameter/src/compiler/Makefile b/lib/diameter/src/compiler/Makefile deleted file mode 100644 index 779013bfbc..0000000000 --- a/lib/diameter/src/compiler/Makefile +++ /dev/null @@ -1,131 +0,0 @@ -# -# %CopyrightBegin% -# -# Copyright Ericsson AB 2010-2011. 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% -# -# - -ifneq ($(ERL_TOP),) -include $(ERL_TOP)/make/target.mk -EBIN = ../../ebin -include $(ERL_TOP)/make/$(TARGET)/otp.mk -else -include $(DIAMETER_TOP)/make/target.mk -EBIN = ../../ebin -include $(DIAMETER_TOP)/make/$(TARGET)/rules.mk -endif - - -# ---------------------------------------------------- -# Application version -# ---------------------------------------------------- -include ../../vsn.mk -VSN=$(DIAMETER_VSN) - -# ---------------------------------------------------- -# Release directory specification -# ---------------------------------------------------- - -RELSYSDIR = $(RELEASE_PATH)/lib/diameter-$(VSN) - -INCDIR = ../../include - -# ---------------------------------------------------- -# Target Specs -# ---------------------------------------------------- - -include modules.mk - -ERL_FILES = \ - $(MODULES:%=%.erl) - -TARGET_FILES = \ - $(MODULES:%=$(EBIN)/%.$(EMULATOR)) - -# ---------------------------------------------------- -# FLAGS -# ---------------------------------------------------- - -ifeq ($(TYPE),debug) -ERL_COMPILE_FLAGS += -Ddebug -endif - -include ../app/diameter.mk - -ERL_COMPILE_FLAGS += \ - $(DIAMETER_ERL_COMPILE_FLAGS) \ - -I$(INCDIR) - -# ---------------------------------------------------- -# Targets -# ---------------------------------------------------- - -debug: - @${MAKE} TYPE=debug opt - -opt: $(TARGET_FILES) - -clean: - rm -f $(TARGET_FILES) - rm -f errs core *~ - rm -f depend.mk - -docs: - -info: - @echo "" - @echo "ERL_FILES = $(ERL_FILES)" - @echo "HRL_FILES = $(HRL_FILES)" - @echo "" - @echo "TARGET_FILES = $(TARGET_FILES)" - @echo "" - -# ---------------------------------------------------- -# Release Target -# ---------------------------------------------------- -ifneq ($(ERL_TOP),) -include $(ERL_TOP)/make/otp_release_targets.mk -else -include $(DIAMETER_TOP)/make/release_targets.mk -endif - -release_spec: opt - $(INSTALL_DIR) $(RELSYSDIR)/ebin - $(INSTALL_DATA) $(TARGET_FILES) $(RELSYSDIR)/ebin - $(INSTALL_DIR) $(RELSYSDIR)/src - $(INSTALL_DIR) $(RELSYSDIR)/src/compiler - $(INSTALL_DATA) $(ERL_FILES) $(HRL_FILES) $(RELSYSDIR)/src/compiler - -release_docs_spec: - -force: - -# ---------------------------------------------------- -# Dependencies -# ---------------------------------------------------- - -depend: depend.mk - -# Generate dependencies makefile. -depend.mk: ../app/depend.sed $(ERL_FILES) Makefile - for f in $(MODULES); do \ - sed -f $< $$f.erl | sed "s@/@/$$f@"; \ - done \ - > $@ - --include depend.mk - -.PHONY: clean debug depend docs force info opt release_docs_spec release_spec diff --git a/lib/diameter/src/compiler/diameter_codegen.erl b/lib/diameter/src/compiler/diameter_codegen.erl index a33b07a3d3..1e31c40afe 100644 --- a/lib/diameter/src/compiler/diameter_codegen.erl +++ b/lib/diameter/src/compiler/diameter_codegen.erl @@ -20,17 +20,18 @@ -module(diameter_codegen). %% -%% This module generates .erl and .hrl files for encode/decode -%% modules from the orddict parsed from a .dia (aka spec) file by -%% dis_spec_util. The generated code is very simple (one-liners), the -%% generated functions being called by code included from dis_gen.hrl -%% in order to encode/decode messages and AVPs. The orddict itself is -%% returned by dict/0 in the generated module and dis_spec_util calls -%% this function when importing spec files. (That is, beam has to be -%% compiled from an imported spec file before it can be imported.) +%% This module generates erl/hrl files for encode/decode modules +%% from the orddict parsed from a dictionary file (.dia) by +%% diameter_dict_util. The generated code is simple (one-liners), +%% the generated functions being called by code included iin the +%% generated modules from diameter_gen.hrl. The orddict itself is +%% returned by dict/0 in the generated module and diameter_dict_util +%% calls this function when importing dictionaries as a consequence +%% of @inherits sections. That is, @inherits introduces a dependency +%% on the beam file of another dictionary. %% --export([from_spec/4]). +-export([from_dict/4]). %% Internal exports (for test). -export([file/1, @@ -38,17 +39,23 @@ file/3]). -include("diameter_forms.hrl"). +-include("diameter_vsn.hrl"). -%% Generated functions that could have no generated clauses will have -%% a trailing ?UNEXPECTED clause that should never execute. --define(UNEXPECTED(N), {?clause, [?VAR('_') || _ <- lists:seq(1,N)], - [], - [?APPLY(erlang, - error, - [?TERM({unexpected, getr(module)})])]}). +-define(S, atom_to_list). +-define(A, list_to_atom). +-define(Atom(T), ?ATOM(?A(T))). -from_spec(File, Spec, Opts, Mode) -> +%% =========================================================================== + +-spec from_dict(File, Spec, Opts, Mode) + -> ok + when File :: string(), + Spec :: orddict:orddict(), + Opts :: list(), + Mode :: spec | erl | hrl. + +from_dict(File, Spec, Opts, Mode) -> Outdir = proplists:get_value(outdir, Opts, "."), putr(verbose, lists:member(verbose, Opts)), putr(debug, lists:member(debug, Opts)), @@ -73,7 +80,7 @@ getr(Key) -> %% =========================================================================== %% =========================================================================== -%% Generate from parsed spec in a file. +%% Generate from parsed dictionary in a file. file(F) -> file(F, spec). @@ -83,55 +90,46 @@ file(F, Mode) -> file(F, Outdir, Mode) -> {ok, [Spec]} = file:consult(F), - from_spec(F, Spec, Outdir, Mode). + from_dict(F, Spec, Outdir, Mode). %% =========================================================================== %% =========================================================================== -choose(true, X, _) -> X; -choose(false, _, X) -> X. - get_value(Key, Plist) -> proplists:get_value(Key, Plist, []). -write(Path, [C|_] = Spec) - when is_integer(C) -> - w(Path, Spec, "~s"); -write(Path, Spec) -> - w(Path, Spec, "~p."). +write(Path, Str) -> + w(Path, Str, "~s"). -w(Path, Spec, Fmt) -> +write_term(Path, T) -> + w(Path, T, "~p."). + +w(Path, T, Fmt) -> {ok, Fd} = file:open(Path, [write]), - io:fwrite(Fd, Fmt ++ "~n", [Spec]), + 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, Mod, Path), + gen(Mode, Spec, ?A(Mod), Path), ok. mod(File, error) -> filename:rootname(filename:basename(File)); mod(_, {ok, Mod}) -> - atom_to_list(Mod). + Mod. gen(spec, Spec, _Mod, Path) -> - write(Path ++ ".spec", Spec); + write_term(Path ++ ".spec", [?VERSION | Spec]); gen(hrl, Spec, Mod, Path) -> gen_hrl(Path ++ ".hrl", Mod, Spec); -gen(erl = Mode, Spec, Mod, Path) - when is_list(Mod) -> - gen(Mode, Spec, list_to_atom(Mod), Path); - gen(erl, Spec, Mod, Path) -> - putr(module, Mod), %% used by ?UNEXPECTED. - Forms = [{?attribute, module, Mod}, {?attribute, compile, [{parse_transform, diameter_exprecs}]}, - {?attribute, compile, [nowarn_unused_function]}, + {?attribute, compile, [{parse_transform, diameter_nowarn}]}, {?attribute, export, [{name, 0}, {id, 0}, {vendor_id, 0}, @@ -175,7 +173,7 @@ gen(erl, Spec, Mod, Path) -> gen_erl(Path, insert_hrl_forms(Spec, Forms)). gen_erl(Path, Forms) -> - getr(debug) andalso write(Path ++ ".forms", Forms), + getr(debug) andalso write_term(Path ++ ".forms", Forms), write(Path ++ ".erl", header() ++ erl_prettypr:format(erl_syntax:form_list(Forms))). @@ -224,16 +222,16 @@ a_record(Prefix, ProjF, L) -> lists:map(fun(T) -> a_record(ProjF(T), Prefix) end, L). a_record({Nm, Avps}, Prefix) -> - Name = list_to_atom(Prefix ++ atom_to_list(Nm)), + Name = list_to_atom(Prefix ++ Nm), Fields = lists:map(fun field/1, Avps), {?attribute, record, {Name, Fields}}. field(Avp) -> {Name, Arity} = avp_info(Avp), if 1 == Arity -> - {?record_field, ?ATOM(Name)}; + {?record_field, ?Atom(Name)}; true -> - {?record_field, ?ATOM(Name), ?NIL} + {?record_field, ?Atom(Name), ?NIL} end. %%% ------------------------------------------------------------------------ @@ -256,25 +254,33 @@ c_id({ok, Id}) -> {?clause, [], [], [?INTEGER(Id)]}; c_id(error) -> - ?UNEXPECTED(0). + ?BADARG(0). %%% ------------------------------------------------------------------------ %%% # vendor_id/0 %%% ------------------------------------------------------------------------ f_vendor_id(Spec) -> - {Id, _} = orddict:fetch(vendor, Spec), {?function, vendor_id, 0, - [{?clause, [], [], [?INTEGER(Id)]}]}. + [{?clause, [], [], [b_vendor_id(orddict:find(vendor, Spec))]}]}. + +b_vendor_id({ok, {Id, _}}) -> + ?INTEGER(Id); +b_vendor_id(error) -> + ?APPLY(erlang, error, [?TERM(undefined)]). %%% ------------------------------------------------------------------------ %%% # vendor_name/0 %%% ------------------------------------------------------------------------ f_vendor_name(Spec) -> - {_, Name} = orddict:fetch(vendor, Spec), {?function, vendor_name, 0, - [{?clause, [], [], [?ATOM(Name)]}]}. + [{?clause, [], [], [b_vendor_name(orddict:find(vendor, Spec))]}]}. + +b_vendor_name({ok, {_, Name}}) -> + ?Atom(Name); +b_vendor_name(error) -> + ?APPLY(erlang, error, [?TERM(undefined)]). %%% ------------------------------------------------------------------------ %%% # msg_name/1 @@ -287,22 +293,18 @@ f_msg_name(Spec) -> %% DIAMETER_COMMAND_UNSUPPORTED should be replied. msg_name(Spec) -> - lists:flatmap(fun c_msg_name/1, - proplists:get_value(command_codes, Spec, [])) + lists:flatmap(fun c_msg_name/1, proplists:get_value(command_codes, + Spec, + [])) ++ [{?clause, [?VAR('_'), ?VAR('_')], [], [?ATOM('')]}]. c_msg_name({Code, Req, Ans}) -> [{?clause, [?INTEGER(Code), ?ATOM(true)], [], - [?ATOM(mname(Req))]}, + [?Atom(Req)]}, {?clause, [?INTEGER(Code), ?ATOM(false)], [], - [?ATOM(mname(Ans))]}]. - -mname({N, _Abbr}) -> - N; -mname(N) -> - N. + [?Atom(Ans)]}]. %%% ------------------------------------------------------------------------ %%% # msg2rec/1 @@ -313,30 +315,11 @@ f_msg2rec(Spec) -> msg2rec(Spec) -> Pre = prefix(Spec), - Dict = dict:from_list(lists:flatmap(fun msgs/1, - get_value(command_codes, Spec))), - lists:flatmap(fun(T) -> msg2rec(T, Dict, Pre) end, - get_value(messages, Spec)) - ++ [?UNEXPECTED(1)]. - -msgs({_Code, Req, Ans}) -> - [{mname(Req), Req}, {mname(Ans), Ans}]. - -msg2rec({N,_,_,_,_}, Dict, Pre) -> - c_msg2rec(fetch_names(N, Dict), Pre). - -fetch_names(Name, Dict) -> - case dict:find(Name, Dict) of - {ok, N} -> - N; - error -> - Name - end. + lists:map(fun(T) -> c_msg2rec(T, Pre) end, get_value(messages, Spec)) + ++ [?BADARG(1)]. -c_msg2rec({N,A}, Pre) -> - [c_name2rec(N, N, Pre), c_name2rec(A, N, Pre)]; -c_msg2rec(N, Pre) -> - [c_name2rec(N, N, Pre)]. +c_msg2rec({N,_,_,_,_}, Pre) -> + c_name2rec(N, Pre). %%% ------------------------------------------------------------------------ %%% # rec2msg/1 @@ -348,10 +331,10 @@ f_rec2msg(Spec) -> rec2msg(Spec) -> Pre = prefix(Spec), lists:map(fun(T) -> c_rec2msg(T, Pre) end, get_value(messages, Spec)) - ++ [?UNEXPECTED(1)]. + ++ [?BADARG(1)]. c_rec2msg({N,_,_,_,_}, Pre) -> - {?clause, [?ATOM(rec_name(N, Pre))], [], [?ATOM(N)]}. + {?clause, [?Atom(rec_name(N, Pre))], [], [?Atom(N)]}. %%% ------------------------------------------------------------------------ %%% # name2rec/1 @@ -364,11 +347,11 @@ name2rec(Spec) -> Pre = prefix(Spec), Groups = get_value(grouped, Spec) ++ lists:flatmap(fun avps/1, get_value(import_groups, Spec)), - lists:map(fun({N,_,_,_}) -> c_name2rec(N, N, Pre) end, Groups) + lists:map(fun({N,_,_,_}) -> c_name2rec(N, Pre) end, Groups) ++ [{?clause, [?VAR('T')], [], [?CALL(msg2rec, [?VAR('T')])]}]. -c_name2rec(Name, Rname, Pre) -> - {?clause, [?ATOM(Name)], [], [?ATOM(rec_name(Rname, Pre))]}. +c_name2rec(Name, Pre) -> + {?clause, [?Atom(Name)], [], [?Atom(rec_name(Name, Pre))]}. avps({_Mod, Avps}) -> Avps. @@ -390,32 +373,47 @@ f_avp_name(Spec) -> %% allocated by IANA (see Section 11.1). avp_name(Spec) -> - Avps = get_value(avp_types, Spec) - ++ lists:flatmap(fun avps/1, get_value(import_avps, Spec)), - {Vid, _} = orddict:fetch(vendor, Spec), - Vs = lists:flatmap(fun({V,Ns}) -> [{N,V} || N <- Ns] end, - get_value(avp_vendor_id, Spec)), + Avps = get_value(avp_types, Spec), + Imported = get_value(import_avps, Spec), + Vid = orddict:find(vendor, Spec), + Vs = vendor_id_map(Spec), - lists:map(fun(T) -> c_avp_name(T, Vid, Vs) end, Avps) + lists:map(fun(T) -> c_avp_name(T, Vs, Vid) end, Avps) + ++ lists:flatmap(fun(T) -> c_imported_avp_name(T, Vs) end, Imported) ++ [{?clause, [?VAR('_'), ?VAR('_')], [], [?ATOM('AVP')]}]. -c_avp_name({Name, Code, Type, Flags, _Encr}, Vid, Vs) -> - c_avp_name({Name, Type}, - Code, - lists:member('V', Flags), - Vid, - proplists:get_value(Name, Vs)). +c_avp_name({Name, Code, Type, Flags}, Vs, Vid) -> + c_avp_name_(?TERM({?A(Name), ?A(Type)}), + ?INTEGER(Code), + vid(Name, Flags, Vs, Vid)). -c_avp_name(T, Code, false, _, undefined = U) -> - {?clause, [?INTEGER(Code), ?ATOM(U)], +%% Note that an imported AVP's vendor id is determined by +%% avp_vendor_id in the inheriting module and vendor in the inherited +%% module. In particular, avp_vendor_id in the inherited module is +%% ignored so can't just call Mod:avp_header/1 to retrieve the vendor +%% id. A vendor id specified in @grouped is equivalent to one +%% specified as avp_vendor_id. + +c_imported_avp_name({Mod, Avps}, Vs) -> + lists:map(fun(A) -> c_avp_name(A, Vs, {module, Mod}) end, Avps). + +c_avp_name_(T, Code, undefined = U) -> + {?clause, [Code, ?ATOM(U)], [], - [?TERM(T)]}; + [T]}; -c_avp_name(T, Code, true, Vid, V) - when is_integer(Vid) -> - {?clause, [?INTEGER(Code), ?INTEGER(choose(V == undefined, Vid, V))], +c_avp_name_(T, Code, Vid) -> + {?clause, [Code, ?INTEGER(Vid)], [], - [?TERM(T)]}. + [T]}. + +vendor_id_map(Spec) -> + lists:flatmap(fun({V,Ns}) -> [{N,V} || N <- Ns] end, + get_value(avp_vendor_id, Spec)) + ++ lists:flatmap(fun({_,_,[],_}) -> []; + ({N,_,[V],_}) -> [{N,V}] + end, + get_value(grouped, Spec)). %%% ------------------------------------------------------------------------ %%% # avp_arity/2 @@ -445,60 +443,75 @@ c_avp_arity(Name, Avps) -> c_arity(Name, Avp) -> {AvpName, Arity} = avp_info(Avp), - {?clause, [?ATOM(Name), ?ATOM(AvpName)], [], [?TERM(Arity)]}. + {?clause, [?Atom(Name), ?Atom(AvpName)], [], [?TERM(Arity)]}. %%% ------------------------------------------------------------------------ %%% # avp/3 %%% ------------------------------------------------------------------------ f_avp(Spec) -> - {?function, avp, 3, avp(Spec) ++ [?UNEXPECTED(3)]}. + {?function, avp, 3, avp(Spec) ++ [?BADARG(3)]}. avp(Spec) -> - Native = get_value(avp_types, Spec), - Custom = get_value(custom_types, Spec), - Imported = get_value(import_avps, Spec), - Enums = get_value(enums, Spec), - avp([{N,T} || {N,_,T,_,_} <- Native], Imported, Custom, Enums). + 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(Native, Imported, Custom, Enums) -> - Dict = orddict:from_list(Native), + Custom = lists:map(fun({M,As}) -> {M, custom_types, As} end, + CustomMods) + ++ lists:map(fun({M,As}) -> {M, codecs, As} end, + TypeMods), + avp(types(Native), Imported, Custom, Enums). + +types(Avps) -> + lists:map(fun({N,_,T,_}) -> {N,T} end, Avps). - report(native, Dict), +avp(Native, Imported, Custom, Enums) -> + report(native, Native), report(imported, Imported), report(custom, Custom), - CustomNames = lists:flatmap(fun({_,Ns}) -> Ns end, Custom), + TypeDict = lists:foldl(fun({N,_,T,_}, D) -> orddict:store(N,T,D) end, + orddict:from_list(Native), + lists:flatmap(fun avps/1, Imported)), + + CustomNames = lists:flatmap(fun({_,_,Ns}) -> Ns end, Custom), lists:map(fun c_base_avp/1, - lists:filter(fun({N,_}) -> - false == lists:member(N, CustomNames) - end, + lists:filter(fun({N,_}) -> not_in(CustomNames, N) end, Native)) - ++ lists:flatmap(fun(I) -> cs_imported_avp(I, Enums) end, Imported) - ++ lists:flatmap(fun(C) -> cs_custom_avp(C, Dict) end, Custom). + ++ lists:flatmap(fun(I) -> cs_imported_avp(I, Enums, CustomNames) end, + Imported) + ++ lists:flatmap(fun(C) -> cs_custom_avp(C, TypeDict) end, Custom). + +not_in(List, X) -> + not lists:member(X, List). c_base_avp({AvpName, T}) -> - {?clause, [?VAR('T'), ?VAR('Data'), ?ATOM(AvpName)], + {?clause, [?VAR('T'), ?VAR('Data'), ?Atom(AvpName)], [], - [base_avp(AvpName, T)]}. + [b_base_avp(AvpName, T)]}. -base_avp(AvpName, 'Enumerated') -> - ?CALL(enumerated_avp, [?VAR('T'), ?ATOM(AvpName), ?VAR('Data')]); +b_base_avp(AvpName, "Enumerated") -> + ?CALL(enumerated_avp, [?VAR('T'), ?Atom(AvpName), ?VAR('Data')]); -base_avp(AvpName, 'Grouped') -> - ?CALL(grouped_avp, [?VAR('T'), ?ATOM(AvpName), ?VAR('Data')]); +b_base_avp(AvpName, "Grouped") -> + ?CALL(grouped_avp, [?VAR('T'), ?Atom(AvpName), ?VAR('Data')]); -base_avp(_, Type) -> - ?APPLY(diameter_types, Type, [?VAR('T'), ?VAR('Data')]). +b_base_avp(_, Type) -> + ?APPLY(diameter_types, ?A(Type), [?VAR('T'), ?VAR('Data')]). -cs_imported_avp({Mod, Avps}, Enums) -> - lists:map(fun(A) -> imported_avp(Mod, A, Enums) end, Avps). +cs_imported_avp({Mod, Avps}, Enums, CustomNames) -> + lists:map(fun(A) -> imported_avp(Mod, A, Enums) end, + lists:filter(fun({N,_,_,_}) -> not_in(CustomNames, N) end, + Avps)). -imported_avp(_Mod, {AvpName, _, 'Grouped' = T, _, _}, _) -> +imported_avp(_Mod, {AvpName, _, "Grouped" = T, _}, _) -> c_base_avp({AvpName, T}); -imported_avp(Mod, {AvpName, _, 'Enumerated' = T, _, _}, Enums) -> +imported_avp(Mod, {AvpName, _, "Enumerated" = T, _}, Enums) -> case lists:keymember(AvpName, 1, Enums) of true -> c_base_avp({AvpName, T}); @@ -506,34 +519,40 @@ imported_avp(Mod, {AvpName, _, 'Enumerated' = T, _, _}, Enums) -> c_imported_avp(Mod, AvpName) end; -imported_avp(Mod, {AvpName, _, _, _, _}, _) -> +imported_avp(Mod, {AvpName, _, _, _}, _) -> c_imported_avp(Mod, AvpName). c_imported_avp(Mod, AvpName) -> - {?clause, [?VAR('T'), ?VAR('Data'), ?ATOM(AvpName)], + {?clause, [?VAR('T'), ?VAR('Data'), ?Atom(AvpName)], [], [?APPLY(Mod, avp, [?VAR('T'), ?VAR('Data'), - ?ATOM(AvpName)])]}. + ?Atom(AvpName)])]}. -cs_custom_avp({Mod, Avps}, Dict) -> - lists:map(fun(N) -> c_custom_avp(Mod, N, orddict:fetch(N, Dict)) end, +cs_custom_avp({Mod, Key, Avps}, Dict) -> + lists:map(fun(N) -> c_custom_avp(Mod, Key, N, orddict:fetch(N, Dict)) end, Avps). -c_custom_avp(Mod, AvpName, Type) -> - {?clause, [?VAR('T'), ?VAR('Data'), ?ATOM(AvpName)], +c_custom_avp(Mod, Key, AvpName, Type) -> + {F,A} = custom(Key, AvpName, Type), + {?clause, [?VAR('T'), ?VAR('Data'), ?Atom(AvpName)], [], - [?APPLY(Mod, AvpName, [?VAR('T'), ?ATOM(Type), ?VAR('Data')])]}. + [?APPLY(?A(Mod), ?A(F), [?VAR('T'), ?Atom(A), ?VAR('Data')])]}. + +custom(custom_types, AvpName, Type) -> + {AvpName, Type}; +custom(codecs, AvpName, Type) -> + {Type, AvpName}. %%% ------------------------------------------------------------------------ %%% # enumerated_avp/3 %%% ------------------------------------------------------------------------ f_enumerated_avp(Spec) -> - {?function, enumerated_avp, 3, enumerated_avp(Spec) ++ [?UNEXPECTED(3)]}. + {?function, enumerated_avp, 3, enumerated_avp(Spec) ++ [?BADARG(3)]}. enumerated_avp(Spec) -> - Enums = get_value(enums, Spec), + Enums = get_value(enum, Spec), lists:flatmap(fun cs_enumerated_avp/1, Enums) ++ lists:flatmap(fun({M,Es}) -> enumerated_avp(M, Es, Enums) end, get_value(import_enums, Spec)). @@ -554,11 +573,11 @@ cs_enumerated_avp(false, _, _) -> cs_enumerated_avp({AvpName, Values}) -> lists:flatmap(fun(V) -> c_enumerated_avp(AvpName, V) end, Values). -c_enumerated_avp(AvpName, {I,_}) -> - [{?clause, [?ATOM(decode), ?ATOM(AvpName), ?TERM(<<I:32/integer>>)], +c_enumerated_avp(AvpName, {_,I}) -> + [{?clause, [?ATOM(decode), ?Atom(AvpName), ?TERM(<<I:32/integer>>)], [], [?TERM(I)]}, - {?clause, [?ATOM(encode), ?ATOM(AvpName), ?INTEGER(I)], + {?clause, [?ATOM(encode), ?Atom(AvpName), ?INTEGER(I)], [], [?TERM(<<I:32/integer>>)]}]. @@ -567,7 +586,7 @@ c_enumerated_avp(AvpName, {I,_}) -> %%% ------------------------------------------------------------------------ f_msg_header(Spec) -> - {?function, msg_header, 1, msg_header(Spec) ++ [?UNEXPECTED(1)]}. + {?function, msg_header, 1, msg_header(Spec) ++ [?BADARG(1)]}. msg_header(Spec) -> msg_header(get_value(messages, Spec), Spec). @@ -582,7 +601,7 @@ msg_header(Msgs, Spec) -> %% Note that any application id in the message header spec is ignored. c_msg_header(Name, Code, Flags, ApplId) -> - {?clause, [?ATOM(Name)], + {?clause, [?Atom(Name)], [], [?TERM({Code, encode_msg_flags(Flags), ApplId})]}. @@ -598,50 +617,61 @@ emf('ERR', N) -> N bor 2#00100000. %%% ------------------------------------------------------------------------ f_avp_header(Spec) -> - {?function, avp_header, 1, avp_header(Spec) ++ [?UNEXPECTED(1)]}. + {?function, avp_header, 1, avp_header(Spec) ++ [?BADARG(1)]}. avp_header(Spec) -> Native = get_value(avp_types, Spec), Imported = get_value(import_avps, Spec), - {Vid, _} = orddict:fetch(vendor, Spec), - Vs = lists:flatmap(fun({V,Ns}) -> [{N,V} || N <- Ns] end, - get_value(avp_vendor_id, Spec)), + Vid = orddict:find(vendor, Spec), + Vs = vendor_id_map(Spec), - lists:flatmap(fun(A) -> c_avp_header({Vid, Vs}, A) end, + lists:flatmap(fun(A) -> c_avp_header(A, Vs, Vid) end, Native ++ Imported). -c_avp_header({Vid, Vs}, {Name, Code, _Type, Flags, _Encr}) -> - [{?clause, [?ATOM(Name)], +c_avp_header({Name, Code, _Type, Flags}, Vs, Vid) -> + [{?clause, [?Atom(Name)], [], [?TERM({Code, encode_avp_flags(Flags), vid(Name, Flags, Vs, Vid)})]}]; -c_avp_header({_, Vs}, {Mod, Avps}) -> - lists:map(fun(A) -> c_avp_header(Vs, Mod, A) end, Avps). +c_avp_header({Mod, Avps}, Vs, _Vid) -> + lists:map(fun(A) -> c_imported_avp_header(A, Mod, Vs) end, Avps). -c_avp_header(Vs, Mod, {Name, _, _, Flags, _}) -> - Apply = ?APPLY(Mod, avp_header, [?ATOM(Name)]), - {?clause, [?ATOM(Name)], +%% Note that avp_vendor_id in the inherited dictionary is ignored. The +%% value must be changed in the inheriting dictionary. This is +%% consistent with the semantics of avp_name/2. + +c_imported_avp_header({Name, _Code, _Type, _Flags}, Mod, Vs) -> + Apply = ?APPLY(Mod, avp_header, [?Atom(Name)]), + {?clause, [?Atom(Name)], [], [case proplists:get_value(Name, Vs) of undefined -> Apply; Vid -> - true = lists:member('V', Flags), %% sanity check ?CALL(setelement, [?INTEGER(3), Apply, ?INTEGER(Vid)]) end]}. encode_avp_flags(Fs) -> lists:foldl(fun eaf/2, 0, Fs). -eaf('V', F) -> 2#10000000 bor F; -eaf('M', F) -> 2#01000000 bor F; -eaf('P', F) -> 2#00100000 bor F. +eaf($V, F) -> 2#10000000 bor F; +eaf($M, F) -> 2#01000000 bor F; +eaf($P, F) -> 2#00100000 bor F. vid(Name, Flags, Vs, Vid) -> - v(lists:member('V', Flags), Name, Vs, Vid). + v(lists:member($V, Flags), Name, Vs, Vid). + +v(true = T, Name, Vs, {module, Mod}) -> + v(T, Name, Vs, {ok, {Mod:vendor_id(), Mod:vendor_name()}}); v(true, Name, Vs, Vid) -> - proplists:get_value(Name, Vs, Vid); + case proplists:get_value(Name, Vs) of + undefined -> + {ok, {Id, _}} = Vid, + Id; + Id -> + Id + end; v(false, _, _, _) -> undefined. @@ -656,19 +686,19 @@ 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(enums, Spec), + Enums = [T || {N,_} = T <- get_value(enum, Spec), not lists:keymember(N, 1, Imported)] ++ Imported, lists:map(fun c_empty_value/1, Groups ++ Enums) ++ [{?clause, [?VAR('Name')], [], [?CALL(empty, [?VAR('Name')])]}]. c_empty_value({Name, _, _, _}) -> - {?clause, [?ATOM(Name)], + {?clause, [?Atom(Name)], [], - [?CALL(empty_group, [?ATOM(Name)])]}; + [?CALL(empty_group, [?Atom(Name)])]}; c_empty_value({Name, _}) -> - {?clause, [?ATOM(Name)], + {?clause, [?Atom(Name)], [], [?TERM(<<0:32/integer>>)]}. @@ -678,7 +708,7 @@ c_empty_value({Name, _}) -> f_dict(Spec) -> {?function, dict, 0, - [{?clause, [], [], [?TERM(Spec)]}]}. + [{?clause, [], [], [?TERM([?VERSION | Spec])]}]}. %%% ------------------------------------------------------------------------ %%% # gen_hrl/3 @@ -706,10 +736,10 @@ gen_hrl(Path, Mod, Spec) -> write("ENUM Macros", Fd, - m_enums(PREFIX, false, get_value(enums, Spec))), - write("RESULT CODE Macros", + m_enums(PREFIX, false, get_value(enum, Spec))), + write("DEFINE Macros", Fd, - m_enums(PREFIX, false, get_value(result_codes, Spec))), + m_enums(PREFIX, false, get_value(define, Spec))), lists:foreach(fun({M,Es}) -> write("ENUM Macros from " ++ atom_to_list(M), @@ -751,8 +781,8 @@ m_enums(Prefix, Wrap, Enums) -> m_enum(Prefix, B, {Name, Values}) -> P = Prefix ++ to_upper(Name) ++ "_", - lists:map(fun({I,A}) -> - N = ["'", P, to_upper(z(atom_to_list(A))), "'"], + lists:map(fun({A,I}) -> + N = ["'", P, to_upper(z(A)), "'"], wrap(B, N, ["-define(", N, ", ", integer_to_list(I), ").\n"]) @@ -794,34 +824,34 @@ header() -> "%%\n\n"). hrl_header(Name) -> - header() ++ "-hrl_name('" ++ Name ++ ".hrl').\n". + header() ++ "-hrl_name('" ++ ?S(Name) ++ ".hrl').\n". %% avp_info/1 avp_info(Entry) -> %% {Name, Arity} case Entry of - {'<',A,'>'} -> {A, 1}; - {A} -> {A, 1}; - [A] -> {A, {0,1}}; + {{A}} -> {A, 1}; + {A} -> {A, 1}; + [A] -> {A, {0,1}}; {Q,T} -> {A,_} = avp_info(T), - {A, arity(Q)} + {A, arity(T,Q)} end. %% Normalize arity to 1 or {N,X} where N is an integer. A record field %% for an AVP is list-valued iff the normalized arity is not 1. -arity('*' = Inf) -> {0, Inf}; -arity({'*', N}) -> {0, N}; -arity({1,1}) -> 1; -arity(T) -> T. +arity({{_}}, '*' = Inf) -> {0, Inf}; +arity([_], '*' = Inf) -> {0, Inf}; +arity({_}, '*' = Inf) -> {1, Inf}; +arity(_, {_,_} = Q) -> Q. prefix(Spec) -> case orddict:find(prefix, Spec) of {ok, P} -> - atom_to_list(P) ++ "_"; + P ++ "_"; error -> "" end. rec_name(Name, Prefix) -> - list_to_atom(Prefix ++ atom_to_list(Name)). + Prefix ++ Name. diff --git a/lib/diameter/src/compiler/diameter_dict_parser.yrl b/lib/diameter/src/compiler/diameter_dict_parser.yrl new file mode 100644 index 0000000000..6fd4cedd23 --- /dev/null +++ b/lib/diameter/src/compiler/diameter_dict_parser.yrl @@ -0,0 +1,324 @@ +%% -*- erlang -*- +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2010-2011. 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 grammar for dictionary specification. +%% + +Nonterminals + application_id avp avp_code avp_def avp_defs avp_flags avp_header + avp_header_tok avp_name avp_names avp_ref avp_spec avp_type + avp_vendor avps bit bits command_def command_id diameter_name + dictionary enum_def enum_defs group_def group_defs header header_tok + ident idents message_defs module qual section sections. + +Terminals + avp_types avp_vendor_id codecs custom_types define enum grouped + id inherits messages name prefix vendor + number word + '{' '}' '<' '>' '[' ']' '*' '::=' ':' ',' '-' + code + 'answer-message' + 'AVP' 'AVP-Header' + 'Diameter' 'Diameter-Header' 'Header' + 'REQ' 'PXY' 'ERR'. + +Rootsymbol dictionary. + +Endsymbol '$end'. + +%% =========================================================================== + +dictionary -> sections : '$1'. + +sections -> '$empty' : []. +sections -> section sections : ['$1' | '$2']. + +section -> name ident : ['$1', '$2']. +section -> prefix ident : ['$1', '$2']. +section -> id number : ['$1', '$2']. +section -> vendor number ident : ['$1', '$2', '$3']. +section -> inherits module avp_names : ['$1', '$2' | '$3']. +section -> avp_types avp_defs : ['$1' | '$2']. +section -> avp_vendor_id number avp_names : ['$1', '$2' | '$3']. +section -> custom_types module avp_names : ['$1', '$2' | '$3']. +section -> codecs module avp_names : ['$1', '$2' | '$3']. +section -> messages message_defs : ['$1' | '$2']. +section -> grouped group_defs : ['$1' | '$2']. +section -> enum ident enum_defs : ['$1', '$2' | '$3']. +section -> define ident enum_defs : ['$1', '$2' | '$3']. + +%% ===================================== + +module -> ident : '$1'. + +avp_names -> idents : '$1'. %% Note: not 'AVP' + +avp_defs -> '$empty' : []. +avp_defs -> avp_def avp_defs : ['$1' | '$2']. + +avp_def -> ident number avp_type avp_flags : ['$1', '$2', '$3', '$4']. + +avp_type -> ident : '$1'. + +idents -> '$empty' : []. +idents -> ident idents : ['$1' | '$2']. + +avp_flags -> '-' : + {_, Lineno} = '$1', + {word, Lineno, ""}. +avp_flags -> ident : + '$1'. +%% Could support lowercase here if there's a use for distinguishing +%% between Must and Should in the future in deciding whether or not +%% to set a flag. + +ident -> word : '$1'. + +%% Don't bother mapping reserved words to make these usable in this +%% context. That an AVP can't be named Diameter-Header is probably no +%% great loss, and that it can't be named AVP may even save someone +%% from themselves. (Temporarily at least.) + +group_defs -> '$empty' : []. +group_defs -> group_def group_defs : ['$1' | '$2']. + +message_defs -> '$empty' : []. +message_defs -> command_def message_defs : ['$1' | '$2']. + +enum_defs -> '$empty' : []. +enum_defs -> enum_def enum_defs : ['$1' | '$2']. + +enum_def -> ident number : ['$1', '$2']. + +%% ===================================== +%% 3.2. Command Code ABNF specification +%% +%% Every Command Code defined MUST include a corresponding ABNF +%% specification, which is used to define the AVPs that MUST or MAY be +%% present when sending the message. The following format is used in +%% the definition: + +%% command-def = <command-name> "::=" diameter-message +%% +%% command-name = diameter-name +%% +%% diameter-name = ALPHA *(ALPHA / DIGIT / "-") +%% +%% diameter-message = header [ *fixed] [ *required] [ *optional] + +%% answer-message is a special case. +command_def -> 'answer-message' '::=' '<' header_tok ':' code + ',' 'ERR' '[' 'PXY' ']' '>' + avps + : ['$1', false | '$13']. + +command_def -> diameter_name '::=' header avps + : ['$1', '$3' | '$4']. +%% Ensure the order fixed/required/optional by semantic checks rather +%% than grammatically since the latter requires more lookahead: don't +%% know until after a leading qual which of the three it is that's +%% being parsed. + +diameter_name -> ident : '$1'. + +%% header = "<" "Diameter Header:" command-id +%% [r-bit] [p-bit] [e-bit] [application-id] ">" +%% +%% command-id = 1*DIGIT +%% ; The Command Code assigned to the command +%% +%% r-bit = ", REQ" +%% ; If present, the 'R' bit in the Command +%% ; Flags is set, indicating that the message +%% ; is a request, as opposed to an answer. +%% +%% p-bit = ", PXY" +%% ; If present, the 'P' bit in the Command +%% ; Flags is set, indicating that the message +%% ; is proxiable. +%% +%% e-bit = ", ERR" +%% ; If present, the 'E' bit in the Command +%% ; Flags is set, indicating that the answer +%% ; message contains a Result-Code AVP in +%% ; the "protocol error" class. +%% +%% application-id = 1*DIGIT + +header -> '<' header_tok ':' command_id bits application_id '>' + : ['$4', '$5', '$6']. + +command_id -> number : '$1'. + +%% Accept both the form of the base definition and the typo (fixed in +%% 3588bis) of the grammar. +header_tok -> 'Diameter' 'Header'. +header_tok -> 'Diameter-Header'. + +bits -> '$empty' : []. +bits -> ',' bit bits : ['$2' | '$3']. + +%% ERR only makes sense for answer-message so don't allow it here +%% (despite 3588). +bit -> 'REQ' : '$1'. +bit -> 'PXY' : '$1'. + +application_id -> '$empty' : false. +application_id -> number : '$1'. + +%% fixed = [qual] "<" avp-spec ">" +%% ; Defines the fixed position of an AVP +%% +%% required = [qual] "{" avp-spec "}" +%% ; The AVP MUST be present and can appear +%% ; anywhere in the message. +%% +%% optional = [qual] "[" avp-name "]" +%% ; The avp-name in the 'optional' rule cannot +%% ; evaluate to any AVP Name which is included +%% ; in a fixed or required rule. The AVP can +%% ; appear anywhere in the message. +%% ; +%% ; NOTE: "[" and "]" have a slightly different +%% ; meaning than in ABNF (RFC 5234]). These braces +%% ; cannot be used to express optional fixed rules +%% ; (such as an optional ICV at the end). To do this, +%% ; the convention is '0*1fixed'. + +avps -> '$empty' : []. +avps -> avp avps : ['$1' | '$2']. + +avp -> avp_ref : [false | '$1']. +avp -> qual avp_ref : ['$1' | '$2']. + +avp_ref -> '<' avp_spec '>' : [$<, '$2']. +avp_ref -> '{' avp_name '}' : [${, '$2']. +avp_ref -> '[' avp_name ']' : [$[, '$2']. +%% Note that required can be an avp_name, not just avp_spec. 'AVP' +%% is specified as required by Failed-AVP for example. + +%% qual = [min] "*" [max] +%% ; See ABNF conventions, RFC 5234 Section 4. +%% ; The absence of any qualifiers depends on +%% ; whether it precedes a fixed, required, or +%% ; optional rule. If a fixed or required rule has +%% ; no qualifier, then exactly one such AVP MUST +%% ; be present. If an optional rule has no +%% ; qualifier, then 0 or 1 such AVP may be +%% ; present. If an optional rule has a qualifier, +%% ; then the value of min MUST be 0 if present. +%% +%% min = 1*DIGIT +%% ; The minimum number of times the element may +%% ; be present. If absent, the default value is zero +%% ; for fixed and optional rules and one for required +%% ; rules. The value MUST be at least one for for +%% ; required rules. +%% +%% max = 1*DIGIT +%% ; The maximum number of times the element may +%% ; be present. If absent, the default value is +%% ; infinity. A value of zero implies the AVP MUST +%% ; NOT be present. + +qual -> number '*' number : {'$1', '$3'}. +qual -> number '*' : {'$1', true}. +qual -> '*' number : {true, '$2'}. +qual -> '*' : true. + +%% avp-spec = diameter-name +%% ; The avp-spec has to be an AVP Name, defined +%% ; in the base or extended Diameter +%% ; specifications. + +avp_spec -> diameter_name : '$1'. + +%% avp-name = avp-spec / "AVP" +%% ; The string "AVP" stands for *any* arbitrary AVP +%% ; Name, not otherwise listed in that command code +%% ; definition. Addition this AVP is recommended for +%% ; all command ABNFs to allow for extensibility. + +avp_name -> 'AVP' : '$1'. +avp_name -> avp_spec : '$1'. + +%% The following is a definition of a fictitious command code: +%% +%% Example-Request ::= < Diameter Header: 9999999, REQ, PXY > +%% { User-Name } +%% * { Origin-Host } +%% * [ AVP ] + +%% ===================================== +%% 4.4. Grouped AVP Values +%% +%% The Diameter protocol allows AVP values of type 'Grouped'. This +%% implies that the Data field is actually a sequence of AVPs. It is +%% possible to include an AVP with a Grouped type within a Grouped type, +%% that is, to nest them. AVPs within an AVP of type Grouped have the +%% same padding requirements as non-Grouped AVPs, as defined in Section +%% 4. +%% +%% The AVP Code numbering space of all AVPs included in a Grouped AVP is +%% the same as for non-grouped AVPs. 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. +%% +%% Every Grouped AVP defined MUST include a corresponding grammar, using +%% ABNF [RFC5234] (with modifications), as defined below. + +%% grouped-avp-def = <name> "::=" avp +%% +%% name-fmt = ALPHA *(ALPHA / DIGIT / "-") +%% +%% name = name-fmt +%% ; The name has to be the name of an AVP, +%% ; defined in the base or extended Diameter +%% ; specifications. +%% +%% avp = header [ *fixed] [ *required] [ *optional] + +group_def -> ident '::=' avp_header avps : ['$1', '$3' | '$4']. + +%% header = "<" "AVP-Header:" avpcode [vendor] ">" +%% +%% avpcode = 1*DIGIT +%% ; The AVP Code assigned to the Grouped AVP +%% +%% vendor = 1*DIGIT +%% ; The Vendor-ID assigned to the Grouped AVP. +%% ; If absent, the default value of zero is +%% ; used. + +avp_header -> '<' avp_header_tok ':' avp_code avp_vendor '>' + : ['$4', '$5']. + +avp_header_tok -> 'AVP-Header'. +avp_header_tok -> 'AVP' 'Header'. + +avp_code -> number : '$1'. + +avp_vendor -> '$empty' : false. +avp_vendor -> number : '$1'. diff --git a/lib/diameter/src/compiler/diameter_dict_scanner.erl b/lib/diameter/src/compiler/diameter_dict_scanner.erl new file mode 100644 index 0000000000..45189376fb --- /dev/null +++ b/lib/diameter/src/compiler/diameter_dict_scanner.erl @@ -0,0 +1,276 @@ +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2010-2011. 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% +%% + +-module(diameter_dict_scanner). + +%% +%% A scanner for dictionary files of the form expected by yecc. +%% + +-export([scan/1, + format_error/1]). + +-export([is_name/1]). + +%% ----------------------------------------------------------- +%% # scan/1 +%% ----------------------------------------------------------- + +-spec scan(string() | binary()) + -> {ok, [Token]} + | {error, {string(), string(), Lineno}} + when Token :: {word, Lineno, string()} + | {number, Lineno, non_neg_integer()} + | {Symbol, Lineno}, + Lineno :: pos_integer(), + Symbol :: '{' | '}' | '<' | '>' | '[' | ']' + | '*' | '::=' | ':' | ',' | '-' + | avp_types + | avp_vendor_id + | codecs + | custom_types + | define + | grouped + | id + | inherits + | messages + | name + | prefix + | vendor + | '$end' + | code + | 'answer-message' + | 'AVP' + | 'AVP-Header' + | 'Diameter' + | 'Diameter-Header' + | 'Header' + | 'REQ' + | 'PXY' + | 'ERR'. + +scan(B) + when is_binary(B) -> + scan(binary_to_list(B)); +scan(S) -> + scan(S, {1, []}). + +scan(S, {Lineno, Acc}) -> + case split(S) of + '$end' = E -> + {ok, lists:reverse([{E, Lineno} | Acc])}; + {Tok, Rest} -> + scan(Rest, acc(Tok, Lineno, Acc)); + Reason when is_list(Reason) -> + {error, {Reason, S, Lineno}} + end. + +%% format_error/1 + +format_error({Reason, Input, Lineno}) -> + io_lib:format("~s at line ~p: ~s", + [Reason, Lineno, head(Input, [], 20, true)]). + +%% is_name/1 + +is_name([H|T]) -> + is_alphanum(H) andalso lists:all(fun is_name_ch/1, T). + +%% =========================================================================== + +head(Str, Acc, N, _) + when [] == Str; + 0 == N; + $\r == hd(Str); + $\n == hd(Str) -> + lists:reverse(Acc); +head([C|Rest], Acc, N, true = T) %% skip leading whitespace + when C == $\s; + C == $\t; + C == $\f; + C == $\v -> + head(Rest, Acc, N, T); +head([C|Rest], Acc, N, _) -> + head(Rest, [C|Acc], N-1, false). + +acc(endline, Lineno, Acc) -> + {Lineno + 1, Acc}; +acc(T, Lineno, Acc) -> + {Lineno, [tok(T, Lineno) | Acc]}. + +tok({Cat, Sym}, Lineno) -> + {Cat, Lineno, Sym}; +tok(Sym, Lineno) -> + {Sym, Lineno}. + +%% # split/1 +%% +%% Output: {Token, Rest} | atom() + +%% Finito. +split("") -> + '$end'; + +%% Skip comments. This precludes using semicolon for any other purpose. +split([$;|T]) -> + split(lists:dropwhile(fun(C) -> not is_eol_ch(C) end, T)); + +%% Beginning of a section. +split([$@|T]) -> + {Name, Rest} = lists:splitwith(fun is_name_ch/1, T), + case section(Name) of + false -> + "Unknown section"; + 'end' -> + '$end'; + A -> + {A, Rest} + end; + +split("::=" ++ T) -> + {'::=', T}; + +split([H|T]) + when H == ${; H == $}; + H == $<; H == $>; + H == $[; H == $]; + H == $*; H == $:; H == $,; H == $- -> + {list_to_atom([H]), T}; + +%% RFC 3588 requires various names to begin with a letter but 3GPP (for +%% one) abuses this. (eg 3GPP-Charging-Id in TS32.299.) +split([H|_] = L) when $0 =< H, H =< $9 -> + {P, Rest} = splitwith(fun is_name_ch/1, L), + Tok = try + {number, read_int(P)} + catch + error:_ -> + word(P) + end, + {Tok, Rest}; + +split([H|_] = L) when $a =< H, H =< $z; + $A =< H, H =< $Z -> + {P, Rest} = splitwith(fun is_name_ch/1, L), + {word(P), Rest}; + +split([$'|T]) -> + case lists:splitwith(fun(C) -> not lists:member(C, "'\r\n") end, T) of + {[_|_] = A, [$'|Rest]} -> + {{word, A}, Rest}; + {[], [$'|_]} -> + "Empty string"; + _ -> %% not terminated on same line + "Unterminated string" + end; + +%% Line ending of various forms. +split([$\r,$\n|T]) -> + {endline, T}; +split([C|T]) + when C == $\r; + C == $\n -> + {endline, T}; + +%% Ignore whitespace. +split([C|T]) + when C == $\s; + C == $\t; + C == $\f; + C == $\v -> + split(T); + +split(_) -> + "Unexpected character". + +%% word/1 + +%% Reserved words significant in parsing ... +word(S) + when S == "answer-message"; + S == "code"; + S == "AVP"; + S == "AVP-Header"; + S == "Diameter"; + S == "Diameter-Header"; + S == "Header"; + S == "REQ"; + S == "PXY"; + S == "ERR" -> + list_to_atom(S); + +%% ... or not. +word(S) -> + {word, S}. + +%% section/1 + +section(N) + when N == "avp_types"; + N == "avp_vendor_id"; + N == "codecs"; + N == "custom_types"; + N == "define"; + N == "end"; + N == "enum"; + N == "grouped"; + N == "id"; + N == "inherits"; + N == "messages"; + N == "name"; + N == "prefix"; + N == "vendor" -> + list_to_atom(N); +section(_) -> + false. + +%% read_int/1 + +read_int([$0,X|S]) + when X == $X; + X == $x -> + {ok, [N], []} = io_lib:fread("~16u", S), + N; + +read_int(S) -> + list_to_integer(S). + +%% splitwith/3 + +splitwith(Fun, [H|T]) -> + {SH, ST} = lists:splitwith(Fun, T), + {[H|SH], ST}. + +is_eol_ch(C) -> + C == $\n orelse C == $\r. + +is_name_ch(C) -> + is_alphanum(C) orelse C == $- orelse C == $_. + +is_alphanum(C) -> + is_lower(C) orelse is_upper(C) orelse is_digit(C). + +is_lower(C) -> + $a =< C andalso C =< $z. + +is_upper(C) -> + $A =< C andalso C =< $Z. + +is_digit(C) -> + $0 =< C andalso C =< $9. diff --git a/lib/diameter/src/compiler/diameter_dict_util.erl b/lib/diameter/src/compiler/diameter_dict_util.erl new file mode 100644 index 0000000000..36a6efa294 --- /dev/null +++ b/lib/diameter/src/compiler/diameter_dict_util.erl @@ -0,0 +1,1358 @@ +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2010-2011. 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% +%% + +%% +%% This module turns a dictionary file into the orddict that +%% diameter_codegen.erl in turn morphs into .erl and .hrl files for +%% encode and decode of Diameter messages and AVPs. +%% + +-module(diameter_dict_util). + +-export([parse/2, + format_error/1, + format/1]). + +-include("diameter_vsn.hrl"). + +-define(RETURN(T), throw({T, ?MODULE, ?LINE})). +-define(RETURN(T, Args), ?RETURN({T, Args})). + +-define(A, list_to_atom). +-define(L, atom_to_list). +-define(I, integer_to_list). +-define(F, io_lib:format). + +%% =========================================================================== +%% parse/2 +%% =========================================================================== + +-spec parse(File, Opts) + -> {ok, orddict:orddict()} + | {error, term()} + when File :: {path, string()} + | iolist() + | binary(), + Opts :: list(). + +parse(File, Opts) -> + putr(verbose, lists:member(verbose, Opts)), + try + {ok, do_parse(File, Opts)} + catch + {Reason, ?MODULE, _Line} -> + {error, Reason} + after + eraser(verbose) + end. + +%% =========================================================================== +%% format_error/1 +%% =========================================================================== + +format_error({read, Reason}) -> + file:format_error(Reason); +format_error({scan, Reason}) -> + diameter_dict_scanner:format_error(Reason); +format_error({parse, {Line, _Mod, Reason}}) -> + lists:flatten(["Line ", ?I(Line), ", ", Reason]); + +format_error(T) -> + {Fmt, As} = fmt(T), + lists:flatten(io_lib:format(Fmt, As)). + +fmt({avp_code_already_defined = E, [Code, false, Name, Line, L]}) -> + {fmt(E), [Code, "", Name, Line, L]}; +fmt({avp_code_already_defined = E, [Code, Vid, Name, Line, L]}) -> + {fmt(E), [Code, ?F("/~p", [Vid]), Name, Line, L]}; + +fmt({uint32_out_of_range = E, [id | T]}) -> + {fmt(E), ["@id", "application identifier" | T]}; +fmt({uint32_out_of_range = E, [K | T]}) + when K == vendor; + K == avp_vendor_id -> + {fmt(E), [?F("@~p", [K]), "vendor id" | T]}; +fmt({uint32_out_of_range = E, [K, Name | T]}) + when K == enum; + K == define -> + {fmt(E), [?F("@~p ~s", [K, Name]), "value" | T]}; +fmt({uint32_out_of_range = E, [avp_types, Name | T]}) -> + {fmt(E), ["AVP " ++ Name, "AVP code" | T]}; +fmt({uint32_out_of_range = E, [grouped, Name | T]}) -> + {fmt(E), ["Grouped AVP " ++ Name | T]}; +fmt({uint32_out_of_range = E, [messages, Name | T]}) -> + {fmt(E), ["Message " ++ Name, "command code" | T]}; + +fmt({Reason, As}) -> + {fmt(Reason), As}; + +fmt(avp_code_already_defined) -> + "AVP ~p~s (~s) at line ~p already defined at line ~p"; + +fmt(uint32_out_of_range) -> + "~s specifies ~s ~p at line ~p that is out of range for a value of " + "Diameter type Unsigned32"; + +fmt(imported_avp_already_defined) -> + "AVP ~s imported by @inherits ~p at line ~p defined at line ~p"; +fmt(duplicate_import) -> + "AVP ~s is imported by more than one @inherits, both at line ~p " + "and at line ~p"; + +fmt(duplicate_section) -> + "Section @~s at line ~p already declared at line ~p"; + +fmt(already_declared) -> + "Section @~p ~s at line ~p already declared at line ~p"; + +fmt(inherited_avp_already_defined) -> + "AVP ~s inherited at line ~p defined in @avp_types at line ~p"; +fmt(avp_already_defined) -> + "AVP ~s at line ~p already in @~p at line ~p"; +fmt(key_already_defined) -> + "Value for ~s:~s in @~p at line ~p already provided at line ~p"; + +fmt(messages_without_id) -> + "@messages at line ~p but @id not declared"; + +fmt(avp_name_already_defined) -> + "AVP ~s at line ~p already defined at line ~p"; +fmt(avp_has_unknown_type) -> + "AVP ~s at line ~p defined with unknown type ~s"; +fmt(avp_has_invalid_flag) -> + "AVP ~s at line ~p specifies invalid flag ~c"; +fmt(avp_has_duplicate_flag) -> + "AVP ~s at line ~p specifies duplicate flag ~c"; +fmt(avp_has_vendor_id) -> + "AVP ~s at line ~p does not specify V flag " + "but is assigned vendor id ~p at line ~p"; +fmt(avp_has_no_vendor) -> + "AVP ~s at line ~p specifies V flag " + "but neither @vendor_avp_id nor @vendor supplies a value"; + +fmt(group_already_defined) -> + "Group ~s at line ~p already defined at line ~p"; +fmt(grouped_avp_code_mismatch) -> + "AVP ~s at line ~p has with code ~p " + "but @avp_types specifies ~p at line ~p"; +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_vendor_id_without_flag) -> + "Grouped AVP ~s at line ~p has vendor id " + "but definition at line ~p does not specify V flag"; +fmt(grouped_vendor_id_mismatch) -> + "Grouped AVP ~s at line ~p has vendor id ~p " + "but ~p specified at line ~p"; + +fmt(message_name_already_defined) -> + "Message ~s at line ~p already defined at line ~p"; +fmt(message_code_already_defined) -> + "~s message with code ~p at line ~p already defined at line ~p"; +fmt(message_has_duplicate_flag) -> + "Message ~s has duplicate flag ~s at line ~p"; +fmt(message_application_id_mismatch) -> + "Message ~s has application id ~p at line ~p " + "but @id specifies ~p at line ~p"; + +fmt(invalid_avp_order) -> + "AVP reference ~c~s~c at line ~p breaks fixed/required/optional order"; +fmt(required_avp_has_zero_max_arity) -> + "Required AVP has maximum arity 0 at line ~p"; +fmt(required_avp_has_zero_min_arity) -> + "Required AVP has minimum arity 0 at line ~p"; +fmt(optional_avp_has_nonzero_min_arity) -> + "Optional AVP has non-zero minimum arity at line ~p"; +fmt(qualifier_has_min_greater_than_max) -> + "Qualifier ~p*~p at line ~p has Min > Max"; +fmt(avp_already_referenced) -> + "AVP ~s at line ~p already referenced at line ~p"; + +fmt(message_missing) -> + "~s message at line ~p but no ~s message is defined"; + +fmt(requested_avp_not_found) -> + "@inherit ~s at line ~p requests AVP ~s at line ~p " + "but module does not define that AVP"; + +fmt(enumerated_avp_has_wrong_local_type) -> + "Enumerated AVP ~s in @enum at line ~p defined with type ~s at line ~p"; +fmt(enumerated_avp_has_wrong_inherited_type) -> + "Enumerated AVP ~s in @enum at line ~p " + "inherited with type ~s from module ~s at line ~p"; +fmt(enumerated_avp_not_defined) -> + "Enumerated AVP ~s in @enum at line ~p neither defined nor inherited"; + +fmt(avp_not_defined) -> + "AVP ~s referenced at line ~p neither defined nor inherited"; + +fmt(recompile) -> + "Module ~p appears to have been compiler with an incompatible " + "version of the dictionary compiler and must be recompiled"; +fmt(not_loaded) -> + "Module ~p is not on the code path or could not be loaded"; +fmt(no_dict) -> + "Module ~p does not appear to be a diameter dictionary". + +%% =========================================================================== +%% format/1 +%% +%% Turn dict/0 output back into a dictionary file (with line ending = $\n). + +-spec format(Dict) + -> iolist() + when Dict :: orddict:orddict(). + +-define(KEYS, [id, name, prefix, vendor, + inherits, codecs, custom_types, + avp_types, + messages, + grouped, + enum, define]). + +format(Dict) -> + Io = orddict:fold(fun io/3, [], Dict), + [S || {_,S} <- lists:sort(fun keysort/2, Io)]. + +keysort({A,_}, {B,_}) -> + [HA, HB] = [H || K <- [A,B], + H <- [lists:takewhile(fun(X) -> X /= K end, ?KEYS)]], + HA < HB. + +%% =========================================================================== + +-define(INDENT, " "). +-define(SP, " "). +-define(NL, $\n). + +%% io/3 + +io(K, _, Acc) + when K == command_codes; + K == import_avps; + K == import_groups; + K == import_enums -> + Acc; + +io(Key, Body, Acc) -> + [{Key, io(Key, Body)} | Acc]. + +%% io/2 + +io(K, Id) + when K == id; + K == name; + K == prefix -> + [?NL, section(K), ?SP, tok(Id)]; + +io(vendor = K, {Id, Name}) -> + [?NL, section(K) | [[?SP, tok(X)] || X <- [Id, Name]]]; + +io(avp_types = K, Body) -> + [?NL, ?NL, section(K), ?NL, [body(K,A) || A <- Body]]; + +io(K, Body) + when K == messages; + K == grouped -> + [?NL, ?NL, section(K), [body(K,A) || A <- Body]]; + +io(K, Body) + when K == avp_vendor_id; + K == inherits; + K == custom_types; + K == codecs; + K == enum; + K == define -> + [[?NL, pairs(K, T)] || T <- Body]. + +pairs(K, {Id, Avps}) -> + [?NL, section(K), ?SP, tok(Id), ?NL, [[?NL, body(K, A)] || A <- Avps]]. + +body(K, AvpName) + when K == avp_vendor_id; + K == inherits; + K == custom_types; + K == codecs -> + [?INDENT, word(AvpName)]; + +body(K, {Name, N}) + when K == enum; + K == define -> + [?INDENT, word(Name), ?SP, ?I(N)]; + +body(avp_types = K, {Name, Code, Type, ""}) -> + body(K, {Name, Code, Type, "-"}); +body(avp_types, {Name, Code, Type, Flags}) -> + [?NL, ?INDENT, word(Name), + [[?SP, ?SP, S] || S <- [?I(Code), Type, Flags]]]; + +body(messages, {"answer-message", _, _, [], Avps}) -> + [?NL, ?NL, ?INDENT, + "answer-message ::= < Diameter Header: code, ERR [PXY] >", + f_avps(Avps)]; +body(messages, {Name, Code, Flags, ApplId, Avps}) -> + [?NL, ?NL, ?INDENT, word(Name), " ::= ", header(Code, Flags, ApplId), + f_avps(Avps)]; + +body(grouped, {Name, Code, Vid, Avps}) -> + [?NL, ?NL, ?INDENT, word(Name), " ::= ", avp_header(Code, Vid), + f_avps(Avps)]. + +header(Code, Flags, ApplId) -> + ["< Diameter Header: ", + ?I(Code), + [[", ", ?L(F)] || F <- Flags], + [[" ", ?I(N)] || N <- ApplId], + " >"]. + +avp_header(Code, Vid) -> + ["< AVP Header: ", + ?I(Code), + [[" ", ?I(V)] || V <- Vid], + " >"]. + +f_avps(L) -> + [[?NL, ?INDENT, ?INDENT, f_avp(A)] || A <- L]. + +f_avp({Q, A}) -> + [D | _] = Avp = f_delim(A), + f_avp(f_qual(D, Q), Avp); +f_avp(A) -> + f_avp("", f_delim(A)). + +f_delim({{A}}) -> + [$<, word(A), $>]; +f_delim({A}) -> + [${, word(A), $}]; +f_delim([A]) -> + [$[, word(A), $]]. + +f_avp(Q, [L, Avp, R]) -> + Len = length(lists:flatten([Q])), + [io_lib:format("~*s", [-1*max(Len+1, 6) , Q]), L, " ", Avp, " ", R]. + +f_qual(${, '*') -> + "1*"; %% Equivalent to "*" but the more common/obvious rendition +f_qual(_, '*') -> + "*"; +f_qual(_, {'*', N}) -> + [$*, ?I(N)]; +f_qual(_, {N, '*'}) -> + [?I(N), $*]; +f_qual(_, {M,N}) -> + [?I(M), $*, ?I(N)]. + +section(Key) -> + ["@", ?L(Key)]. + +tok(N) + when is_integer(N) -> + ?I(N); +tok(N) -> + word(N). + +word(Str) -> + word(diameter_dict_scanner:is_name(Str), Str). + +word(true, Str) -> + Str; +word(false, Str) -> + [$', Str, $']. + +%% =========================================================================== + +do_parse(File, Opts) -> + Bin = do([fun read/1, File], read), + Toks = do([fun diameter_dict_scanner:scan/1, Bin], scan), + Tree = do([fun diameter_dict_parser:parse/1, Toks], parse), + make_dict(Tree, Opts). + +do([F|A], E) -> + case apply(F,A) of + {ok, T} -> + T; + {error, Reason} -> + ?RETURN({E, Reason}) + end. + +read({path, Path}) -> + file:read_file(Path); +read(File) -> + {ok, iolist_to_binary([File])}. + +make_dict(Parse, Opts) -> + make_orddict(pass4(pass3(pass2(pass1(reset(make_dict(Parse), + Opts))), + Opts))). + +%% make_orddict/1 + +make_orddict(Dict) -> + dict:fold(fun mo/3, + orddict:from_list([{K,[]} || K <- [avp_types, + messages, + grouped, + inherits, + custom_types, + codecs, + avp_vendor_id, + enum, + define]]), + Dict). + +mo(K, Sects, Dict) + when is_atom(K) -> + orddict:store(K, make(K, Sects), Dict); + +mo(_, _, Dict) -> + Dict. + +make(K, [[_Line, {_, _, X}]]) + when K == id; + K == name; + K == prefix -> + X; + +make(vendor, [[_Line, {_, _, Id}, {_, _, Name}]]) -> + {Id, Name}; + +make(K, T) + when K == command_codes; + K == import_avps; + K == import_groups; + K == import_enums -> + T; + +make(K, Sects) -> + post(K, foldl(fun([_L|B], A) -> make(K,B,A) end, + [], + Sects)). + +post(avp_types, L) -> + lists:sort(L); + +post(K, L) + when K == grouped; + K == messages; + K == enum; + K == define -> + lists:reverse(L); + +post(_, L) -> + L. + +make(K, [{_,_,Name} | Body], Acc) + when K == enum; + K == define; + K == avp_vendor_id; + K == custom_types; + K == inherits; + K == codecs -> + [{Name, mk(K, Body)} | Acc]; + +make(K, Body, Acc) -> + foldl(fun(T,A) -> [mk(K, T) | A] end, Acc, Body). + +mk(avp_types, [{_,_,Name}, {_,_,Code}, {_,_,Type}, {_,_,Flags}]) -> + {Name, Code, type(Type), Flags}; + +mk(messages, [{'answer-message' = A, _}, false | Avps]) -> + {?L(A), -1, ['ERR', 'PXY'], [], make_body(Avps)}; + +mk(messages, [{_,_,Name}, [{_,_,Code}, Flags, ApplId] | Avps]) -> + {Name, + Code, + lists:map(fun({F,_}) -> F end, Flags), + opt(ApplId), + make_body(Avps)}; + +mk(grouped, [{_,_,Name}, [{_,_,Code}, Vid] | Avps]) -> + {Name, Code, opt(Vid), make_body(Avps)}; + +mk(K, Body) + when K == enum; + K == define -> + lists:map(fun([{_,_,Name}, {_,_,Value}]) -> {Name, Value} end, Body); + +mk(K, Avps) + when K == avp_vendor_id; + K == custom_types; + K == inherits; + K == codecs -> + lists:map(fun({_,_,N}) -> N end, Avps). + +opt(false) -> + []; +opt({_,_,X}) -> + [X]. + +make_body(Avps) -> + lists:map(fun avp/1, Avps). + +avp([false, D, Avp]) -> + avp(D, Avp); +avp([Q, D, Avp]) -> + case {qual(D, Q), avp(D, Avp)} of + {{0,1}, A} when D == $[ -> + A; + {{1,1}, A} -> + A; + T -> + T + end. +%% Could just store the qualifier as a pair in all cases but the more +%% compact form is easier to parse visually so live with a bit of +%% mapping. Ditto the use of '*'. + +avp(D, {'AVP', _}) -> + delim(D, "AVP"); +avp(D, {_, _, Name}) -> + delim(D, Name). + +delim($<, N) -> + {{N}}; +delim(${, N) -> + {N}; +delim($[, N) -> + [N]. + +%% There's a difference between max = 0 and not specifying an AVP: +%% reception of an AVP with max = 0 will always be an error, otherwise +%% it depends on the existence of 'AVP' and the M flag. + +qual(${, {{_,L,0}, _}) -> + ?RETURN(required_avp_has_zero_min_arity, [L]); +qual(${, {_, {_,L,0}}) -> + ?RETURN(required_avp_has_zero_max_arity, [L]); + +qual($[, {{_,L,N}, _}) + when 0 < N -> + ?RETURN(optional_avp_has_nonzero_min_arity, [L]); + +qual(_, {{_,L,Min}, {_,_,Max}}) + when Min > Max -> + ?RETURN(qualifier_has_min_greater_than_max, [Min, Max, L]); + +qual(_, true) -> + '*'; + +qual(${, {true, {_,_,N}}) -> + {1, N}; +qual(_, {true, {_,_,N}}) -> + {0, N}; + +qual(D, {{_,_,N}, true}) + when D == ${, N == 1; + D /= ${, N == 0 -> + '*'; +qual(_, {{_,_,N}, true}) -> + {N, '*'}; + +qual(_, {{_,_,Min}, {_,_,Max}}) -> + {Min, Max}. + +%% Optional reports when running verbosely. +report(What, [F | A]) + when is_function(F) -> + report(What, apply(F, A)); +report(What, Data) -> + report(getr(verbose), What, Data). + +report(true, Tag, Data) -> + io:format("##~n## ~p ~p~n", [Tag, Data]); +report(false, _, _) -> + ok. + +%% ------------------------------------------------------------------------ +%% make_dict/1 +%% +%% Turn a parsed dictionary into an dict. + +make_dict(Parse) -> + foldl(fun(T,A) -> + report(section, T), + section(T,A) + end, + dict:new(), + Parse). + +section([{T, L} | Rest], Dict) + when T == name; + T == prefix; + T == id; + T == vendor -> + case find(T, Dict) of + [] -> + dict:store(T, [[L | Rest]], Dict); + [[Line | _]] -> + ?RETURN(duplicate_section, [T, L, Line]) + end; + +section([{T, L} | Rest], Dict) + when T == avp_types; + T == messages; + T == grouped; + T == inherits; + T == custom_types; + T == codecs; + T == avp_vendor_id; + T == enum; + T == define -> + dict:append(T, [L | Rest], Dict). + +%% =========================================================================== +%% reset/2 +%% +%% Reset sections from options. + +reset(Dict, Opts) -> + foldl([fun reset/3, Opts], Dict, [name, prefix, inherits]). + +reset(K, Dict, Opts) -> + foldl(fun opt/2, Dict, [T || {A,_} = T <- Opts, A == K]). + +opt({inherits = Key, "-"}, Dict) -> + dict:erase(Key, Dict); + +opt({inherits = Key, Mod}, Dict) -> + case lists:splitwith(fun(C) -> C /= $/ end, Mod) of + {Mod, ""} -> + dict:append(Key, [0, {word, 0, Mod}], Dict); + {From, [$/|To]} -> + dict:store(Key, + [reinherit(From, To, M) || M <- find(Key, Dict)], + Dict) + end; + +opt({Key, Val}, Dict) -> + dict:store(Key, [[0, {word, 0, Val}]], Dict); + +opt(_, Dict) -> + Dict. + +reinherit(From, To, [L, {word, _, From} = T | Avps]) -> + [L, setelement(3, T, To) | Avps]; +reinherit(_, _, T) -> + T. + +%% =========================================================================== +%% pass1/1 +%% +%% Explode sections into additional dictionary entries plus semantic +%% checks. + +pass1(Dict) -> + true = no_messages_without_id(Dict), + + foldl(fun(K,D) -> foldl([fun p1/3, K], D, find(K,D)) end, + Dict, + [id, + vendor, + avp_types, %% must precede inherits, grouped, enum + avp_vendor_id, + custom_types, + codecs, + inherits, + grouped, + messages, + enum, + define]). + +%% Multiple sections are allowed as long as their bodies don't +%% overlap. (Except enum/define.) + +p1([_Line, N], Dict, id = K) -> + true = is_uint32(N, [K]), + Dict; + +p1([_Line, Id, _Name], Dict, vendor = K) -> + true = is_uint32(Id, [K]), + Dict; + +p1([_Line, X | Body], Dict, K) + when K == avp_vendor_id; + K == custom_types; + K == codecs; + K == inherits -> + foldl([fun explode/4, X, K], Dict, Body); + +p1([_Line, X | Body], Dict, K) + when K == define; + K == enum -> + {_, L, Name} = X, + foldl([fun explode2/4, X, K], + store_new({K, Name}, + [L, Body], + Dict, + [K, Name, L], + already_declared), + Body); + +p1([_Line | Body], Dict, K) + when K == avp_types; + K == grouped; + K == messages -> + foldl([fun explode/3, K], Dict, Body). + +no_messages_without_id(Dict) -> + case find(messages, Dict) of + [] -> + true; + [[Line | _] | _] -> + [] /= find(id, Dict) orelse ?RETURN(messages_without_id, [Line]) + end. + +%% Note that the AVP's in avp_vendor_id, custom_types, codecs and +%% enum can all be inherited, as can the AVP content of messages and +%% grouped AVP's. Check that the referenced AVP's exist after +%% importing definitions. + +%% explode/4 +%% +%% {avp_vendor_id, AvpName} -> [Lineno, Id::integer()] +%% {custom_types|codecs|inherits, AvpName} -> [Lineno, Mod::string()] + +explode({_, Line, AvpName}, Dict, {_, _, X} = T, K) -> + true = K /= avp_vendor_id orelse is_uint32(T, [K]), + true = K /= inherits orelse avp_not_local(AvpName, Line, Dict), + + store_new({key(K), AvpName}, + [Line, X], + Dict, + [AvpName, Line, K], + avp_already_defined). + +%% explode2/4 + +%% {define, {Name, Key}} -> [Lineno, Value::integer(), enum|define] + +explode2([{_, Line, Key}, {_, _, Value} = T], Dict, {_, _, Name}, K) -> + true = is_uint32(T, [K, Name]), + + store_new({key(K), {Name, Key}}, + [Line, Value, K], + Dict, + [Name, Key, K, Line], + key_already_defined). + +%% key/1 +%% +%% Conflate keys that are equivalent as far as uniqueness of +%% definition goes. + +key(K) + when K == enum; + K == define -> + define; +key(K) + when K == custom_types; + K == codecs -> + custom; +key(K) -> + K. + +%% explode/3 + +%% {avp_types, AvpName} -> [Line | Toks] +%% {avp_types, {Code, IsReq}} -> [Line, AvpName] +%% +%% where AvpName = string() +%% Code = integer() +%% IsReq = boolean() + +explode([{_, Line, Name} | Toks], Dict0, avp_types = K) -> + %% Each AVP can be defined only once. + Dict = store_new({K, Name}, + [Line | Toks], + Dict0, + [Name, Line], + avp_name_already_defined), + + [{number, _, _Code} = C, {word, _, Type}, {word, _, _Flags}] = Toks, + + true = avp_type_known(Type, Name, Line), + true = is_uint32(C, [K, Name]), + + Dict; + +%% {grouped, Name} -> [Line, HeaderTok | AvpToks] +%% {grouped, {Name, AvpName}} -> [Line, Qual, Delim] +%% +%% where Name = string() +%% AvpName = string() +%% Qual = {Q, Q} | boolean() +%% Q = true | NumberTok +%% Delim = $< | ${ | $[ + +explode([{_, Line, Name}, Header | Avps], Dict0, grouped = K) -> + Dict = store_new({K, Name}, + [Line, Header | Avps], + Dict0, + [Name, Line], + group_already_defined), + + [{_,_, Code} = C, Vid] = Header, + {DefLine, {_, _, Flags}} = grouped_flags(Name, Code, Dict0, Line), + V = lists:member($V, Flags), + + true = is_uint32(C, [K, Name, "AVP code"]), + true = is_uint32(Vid, [K, Name, "vendor id"]), + false = vendor_id_mismatch(Vid, V, Name, Dict0, Line, DefLine), + + explode_avps(Avps, Dict, K, Name); + +%% {messages, Name} -> [Line, HeaderTok | AvpToks] +%% {messages, {Code, IsReq}} -> [Line, NameTok] +%% {messages, Code} -> [[Line, NameTok, IsReq]] +%% {messages, {Name, Flag}} -> [Line] +%% {messages, {Name, AvpName}} -> [Line, Qual, Delim] +%% +%% where Name = string() +%% Code = integer() +%% IsReq = boolean() +%% Flag = 'REQ' | 'PXY' +%% AvpName = string() +%% Qual = true | {Q,Q} +%% Q = true | NumberTok +%% Delim = $< | ${ | ${ + +explode([{'answer-message' = A, Line}, false = H | Avps], + Dict0, + messages = K) -> + Name = ?L(A), + Dict1 = store_new({K, Name}, + [Line, H, Avps], + Dict0, + [Name, Line], + message_name_already_defined), + + explode_avps(Avps, Dict1, K, Name); + +explode([{_, Line, MsgName} = M, Header | Avps], + Dict0, + messages = K) -> + %% There can be at most one message with a given name. + Dict1 = store_new({K, MsgName}, + [Line, Header | Avps], + Dict0, + [MsgName, Line], + message_name_already_defined), + + [{_, _, Code} = C, Bits, ApplId] = Header, + + %% Don't check any application id since it's required to be + %% the same as @id. + true = is_uint32(C, [K, MsgName]), + + %% An application id specified as part of the message definition + %% has to agree with @id. The former is parsed just because RFC + %% 3588 specifies it. + false = application_id_mismatch(ApplId, Dict1, MsgName), + + IsReq = lists:keymember('REQ', 1, Bits), + + %% For each command code, there can be at most one request and + %% one answer. + Dict2 = store_new({K, {Code, IsReq}}, + [Line, M], + Dict1, + [choose(IsReq, "Request", "Answer"), Code, Line], + message_code_already_defined), + + %% For each message, each flag can occur at most once. + Dict3 = foldl(fun({F,L},D) -> + store_new({K, {MsgName, F}}, + [L], + D, + [MsgName, ?L(F)], + message_has_duplicate_flag) + end, + Dict2, + Bits), + + dict:append({K, Code}, + [Line, M, IsReq], + explode_avps(Avps, Dict3, K, MsgName)). + +%% explode_avps/4 +%% +%% Ensure required AVP order and sane qualifiers. Can't check for AVP +%% names until after they've been imported. +%% +%% RFC 3588 allows a trailing fixed while 3588bis doesn't. Parse the +%% former. + +explode_avps(Avps, Dict, Key, Name) -> + xa("<{[<", Avps, Dict, Key, Name). + +xa(_, [], Dict, _, _) -> + Dict; + +xa(Ds, [[Qual, D, {'AVP', Line}] | Avps], Dict, Key, Name) -> + xa(Ds, [[Qual, D, {word, Line, "AVP"}] | Avps], Dict, Key, Name); + +xa([], [[_Qual, D, {_, Line, Name}] | _], _, _, _) -> + ?RETURN(invalid_avp_order, [D, Name, close(D), Line]); + +xa([D|_] = Ds, [[Qual, D, {_, Line, AvpName}] | Avps], Dict, Key, Name) -> + xa(Ds, + Avps, + store_new({Key, {Name, AvpName}}, + [Line, Qual, D], + Dict, + [Name, Line], + avp_already_referenced), + Key, + Name); + +xa([_|Ds], Avps, Dict, Key, Name) -> + xa(Ds, Avps, Dict, Key, Name). + +close($<) -> $>; +close(${) -> $}; +close($[) -> $]. + +%% is_uint32/2 + +is_uint32(false, _) -> + true; +is_uint32({Line, _, N}, Args) -> + N < 1 bsl 32 orelse ?RETURN(uint32_out_of_range, Args ++ [N, Line]). +%% Can't call diameter_types here since it may not exist yet. + +%% application_id_mismatch/3 + +application_id_mismatch({number, Line, Id}, Dict, MsgName) -> + [[_, {_, L, I}]] = dict:fetch(id, Dict), + + I /= Id andalso ?RETURN(message_application_id_mismatch, + [MsgName, Id, Line, I, L]); + +application_id_mismatch(false = No, _, _) -> + No. + +%% avp_not_local/3 + +avp_not_local(Name, Line, Dict) -> + A = find({avp_types, Name}, Dict), + + [] == A orelse ?RETURN(inherited_avp_already_defined, + [Name, Line, hd(A)]). + +%% avp_type_known/3 + +avp_type_known(Type, Name, Line) -> + false /= type(Type) + orelse ?RETURN(avp_has_unknown_type, [Name, Line, Type]). + +%% vendor_id_mismatch/6 +%% +%% Require a vendor id specified on a group to match any specified +%% in @avp_vendor_id. Note that both locations for the value are +%% equivalent, both in the value being attributed to a locally +%% defined AVP and ignored when imported from another dictionary. + +vendor_id_mismatch({_,_,_}, false, Name, _, Line, DefLine) -> + ?RETURN(grouped_vendor_id_without_flag, [Name, Line, DefLine]); + +vendor_id_mismatch({_, _, I}, true, Name, Dict, Line, _) -> + case vendor_id(Name, Dict) of + {avp_vendor_id, L, N} -> + I /= N andalso + ?RETURN(grouped_vendor_id_mismatch, [Name, Line, I, N, L]); + _ -> + false + end; + +vendor_id_mismatch(_, _, _, _, _, _) -> + false. + +%% grouped_flags/4 + +grouped_flags(Name, Code, Dict, Line) -> + case find({avp_types, Name}, Dict) of + [L, {_, _, Code}, {_, _, "Grouped"}, Flags] -> + {L, Flags}; + [_, {_, L, C}, {_, _, "Grouped"}, _Flags] -> + ?RETURN(grouped_avp_code_mismatch, [Name, Line, Code, C, L]); + [_, _Code, {_, L, T}, _] -> + ?RETURN(grouped_avp_has_wrong_type, [Name, Line, T, L]); + [] -> + ?RETURN(grouped_avp_not_defined, [Name, Line]) + end. + +%% vendor_id/2 + +%% Look for a vendor id in @avp_vendor_id, then @vendor. +vendor_id(Name, Dict) -> + case find({avp_vendor_id, Name}, Dict) of + [Line, Id] when is_integer(Id) -> + {avp_vendor_id, Line, Id}; + [] -> + vendor(Dict) + end. + +vendor(Dict) -> + case find(vendor, Dict) of + [[_Line, {_, _, Id}, {_, _, _}]] -> + {vendor, Id}; + [] -> + false + end. + +%% find/2 + +find(Key, Dict) -> + case dict:find(Key, Dict) of + {ok, L} when is_list(L) -> + L; + error -> + [] + end. + +%% store_new/5 + +store_new(Key, Value, Dict, Args, Err) -> + case dict:find(Key, Dict) of + {ok, [L | _]} -> + ?RETURN(Err, Args ++ [L]); + error -> + dict:store(Key, Value, Dict) + end. + +%% type/1 + +type("DiamIdent") -> + "DiameterIdentity"; +type("DiamURI") -> + "DiameterURI"; +type(T) + when T == "OctetString"; + T == "Integer32"; + T == "Integer64"; + T == "Unsigned32"; + T == "Unsigned64"; + T == "Float32"; + T == "Float64"; + T == "Grouped"; + T == "Enumerated"; + T == "Address"; + T == "Time"; + T == "UTF8String"; + T == "DiameterIdentity"; + T == "DiameterURI"; + T == "IPFilterRule"; + T == "QoSFilterRule" -> + T; +type(_) -> + false. + +%% =========================================================================== +%% pass2/1 +%% +%% More explosion, but that requires the previous pass to write its +%% entries. + +pass2(Dict) -> + foldl(fun(K,D) -> foldl([fun p2/3, K], D, find(K,D)) end, + Dict, + [avp_types]). + +p2([_Line | Body], Dict, avp_types) -> + foldl(fun explode_avps/2, Dict, Body); + +p2([], Dict, _) -> + Dict. + +explode_avps([{_, Line, Name} | Toks], Dict) -> + [{number, _, Code}, {word, _, _Type}, {word, _, Flags}] = Toks, + + true = avp_flags_valid(Flags, Name, Line), + + 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. + store_new({avp_types, {Code, Vid}}, + [Line, Name], + Dict, + [Code, Vid, Name, Line], + avp_code_already_defined). + +%% avp_flags_valid/3 + +avp_flags_valid(Flags, Name, Line) -> + Bad = lists:filter(fun(C) -> not lists:member(C, "MVP") end, Flags), + [] == Bad + orelse ?RETURN(avp_has_invalid_flag, [Name, Line, hd(Bad)]), + + Dup = Flags -- "MVP", + [] == Dup + orelse ?RETURN(avp_has_duplicate_flag, [Name, Line, hd(Dup)]). + +%% avp_vendor_id/4 + +avp_vendor_id(Flags, Name, Line, Dict) -> + V = lists:member($V, Flags), + + case vendor_id(Name, Dict) of + {avp_vendor_id, _, I} when V -> + I; + {avp_vendor_id, L, I} -> + ?RETURN(avp_has_vendor_id, [Name, Line, I, L]); + {vendor, I} when V -> + I; + false when V -> + ?RETURN(avp_has_no_vendor, [Name, Line]); + _ -> + false + end. + +%% =========================================================================== +%% pass3/2 +%% +%% Import AVPs. + +pass3(Dict, Opts) -> + import_enums(import_groups(import_avps(insert_codes(Dict), Opts))). + +%% insert_codes/1 +%% +%% command_codes -> [{Code, ReqNameTok, AnsNameTok}] + +insert_codes(Dict) -> + dict:store(command_codes, + dict:fold(fun make_code/3, [], Dict), + Dict). + +make_code({messages, Code}, Names, Acc) + when is_integer(Code) -> + [mk_code(Code, Names) | Acc]; +make_code(_, _, Acc) -> + Acc. + +mk_code(Code, [[_, _, false] = Ans, [_, _, true] = Req]) -> + mk_code(Code, [Req, Ans]); + +mk_code(Code, [[_, {_,_,Req}, true], [_, {_,_,Ans}, false]]) -> + {Code, Req, Ans}; + +mk_code(_Code, [[Line, _Name, IsReq]]) -> + ?RETURN(message_missing, [choose(IsReq, "Request", "Answer"), + Line, + choose(IsReq, "answer", "request")]). + +%% import_avps/2 + +import_avps(Dict, Opts) -> + Import = inherit(Dict, Opts), + report(imported, Import), + + %% pass4/1 tests that all referenced AVP's are either defined + %% or imported. + + dict:store(import_avps, + lists:map(fun({M, _, As}) -> {M, [A || {_,A} <- As]} end, + lists:reverse(Import)), + foldl(fun explode_imports/2, Dict, Import)). + +explode_imports({Mod, Line, Avps}, Dict) -> + foldl([fun xi/4, Mod, Line], Dict, Avps). + +xi({L, {Name, _Code, _Type, _Flags} = A}, Dict, Mod, Line) -> + store_new({avp_types, Name}, + [0, Mod, Line, L, A], + store_new({import, Name}, + [Line], + Dict, + [Name, Line], + duplicate_import), + [Name, Mod, Line], + imported_avp_already_defined). + +%% import_groups/1 +%% import_enums/1 +%% +%% For each inherited module, store the content of imported AVP's of +%% type grouped/enumerated in a new key. + +import_groups(Dict) -> + dict:store(import_groups, import(grouped, Dict), Dict). + +import_enums(Dict) -> + dict:store(import_enums, import(enum, Dict), Dict). + +import(Key, Dict) -> + flatmap([fun import_key/2, Key], dict:fetch(import_avps, Dict)). + +import_key({Mod, Avps}, Key) -> + As = lists:flatmap(fun(T) -> + N = element(1,T), + choose(lists:keymember(N, 1, Avps), [T], []) + end, + orddict:fetch(Key, dict(Mod))), + if As == [] -> + []; + true -> + [{Mod, As}] + end. + +%% ------------------------------------------------------------------------ +%% inherit/2 +%% +%% Return a {Mod, Line, [{Lineno, Avp}]} list, where Mod is a module +%% name, Line points to the corresponding @inherit and each Avp is +%% from Mod:dict(). Lineno is 0 if the import is implicit. + +inherit(Dict, Opts) -> + code:add_pathsa([D || {include, D} <- Opts]), + foldl(fun inherit_avps/2, [], find(inherits, Dict)). +%% Note that the module order of the returned lists is reversed +%% relative to @inherits. + +inherit_avps([Line, {_,_,M} | Names], Acc) -> + Mod = ?A(M), + report(inherit_from, Mod), + case find_avps(Names, avps_from_module(Mod)) of + {_, [{_, L, N} | _]} -> + ?RETURN(requested_avp_not_found, [Mod, Line, N, L]); + {Found, []} -> + [{Mod, Line, lists:sort(Found)} | Acc] + end. + +%% Import everything not defined locally ... +find_avps([], Avps) -> + {[{0, A} || A <- Avps], []}; + +%% ... or specified AVPs. +find_avps(Names, Avps) -> + foldl(fun acc_avp/2, {[], Names}, Avps). + +acc_avp({Name, _Code, _Type, _Flags} = A, {Found, Not} = Acc) -> + case lists:keyfind(Name, 3, Not) of + {_, Line, Name} -> + {[{Line, A} | Found], lists:keydelete(Name, 3, Not)}; + false -> + Acc + end. + +%% avps_from_module/2 + +avps_from_module(Mod) -> + orddict:fetch(avp_types, dict(Mod)). + +dict(Mod) -> + try Mod:dict() of + [?VERSION | Dict] -> + Dict; + _ -> + ?RETURN(recompile, [Mod]) + catch + error: _ -> + ?RETURN(choose(false == code:is_loaded(Mod), + not_loaded, + no_dict), + [Mod]) + end. + +%% =========================================================================== +%% pass4/1 +%% +%% Sanity checks. + +pass4(Dict) -> + dict:fold(fun(K, V, _) -> p4(K, V, Dict) end, ok, Dict), + Dict. + +%% Ensure enum AVP's have type Enumerated. +p4({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) + when (K == grouped orelse K == messages), + is_list(Name), + is_list(AvpName), + AvpName /= "AVP" -> + true = avp_is_defined(AvpName, Dict, Line); + +%% Ditto. +p4({K, AvpName}, [Line | _], Dict) + when K == avp_vendor_id; + K == custom_types; + K == codecs -> + true = avp_is_defined(AvpName, Dict, Line); + +p4(_, _, _) -> + ok. + +%% has_enumerated_type/3 + +is_enumerated_avp(Name, Dict, Line) -> + case find({avp_types, Name}, Dict) of + [_Line, _Code, {_, _, "Enumerated"}, _Flags] -> %% local + true; + [_Line, _Code, {_, L, T}, _] -> + ?RETURN(enumerated_avp_has_wrong_local_type, + [Name, Line, T, L]); + [0, _, _, _, {_Name, _Code, "Enumerated", _Flags}] -> %% inherited + true; + [0, Mod, LM, LA, {_Name, _Code, Type, _Flags}] -> + ?RETURN(enumerated_avp_has_wrong_inherited_type, + [Name, Line, Type, Mod, choose(0 == LA, LM, LA)]); + [] -> + ?RETURN(enumerated_avp_not_defined, [Name, Line]) + end. + +avp_is_defined(Name, Dict, Line) -> + case find({avp_types, Name}, Dict) of + [_Line, _Code, _Type, _Flags] -> %% local + true; + [0, _, _, _, {Name, _Code, _Type, _Flags}] -> %% inherited + true; + [] -> + ?RETURN(avp_not_defined, [Name, Line]) + end. + +%% =========================================================================== + +putr(Key, Value) -> + put({?MODULE, Key}, Value). + +getr(Key) -> + get({?MODULE, Key}). + +eraser(Key) -> + erase({?MODULE, Key}). + +choose(true, X, _) -> X; +choose(false, _, X) -> X. + +foldl(F, Acc, List) -> + lists:foldl(fun(T,A) -> eval([F,T,A]) end, Acc, List). + +flatmap(F, List) -> + lists:flatmap(fun(T) -> eval([F,T]) end, List). + +eval([[F|X] | A]) -> + eval([F | A ++ X]); +eval([F|A]) -> + apply(F,A). diff --git a/lib/diameter/src/app/diameter_exprecs.erl b/lib/diameter/src/compiler/diameter_exprecs.erl index 5e120d6f44..191f53f29d 100644 --- a/lib/diameter/src/app/diameter_exprecs.erl +++ b/lib/diameter/src/compiler/diameter_exprecs.erl @@ -96,41 +96,15 @@ -export([parse_transform/2]). -%% Form tag with line number. --define(F(T), T, ?LINE). -%% Yes, that's right. The replacement is to the first unmatched ')'. - --define(attribute, ?F(attribute)). --define(clause, ?F(clause)). --define(function, ?F(function)). --define(call, ?F(call)). --define('fun', ?F('fun')). --define(generate, ?F(generate)). --define(lc, ?F(lc)). --define(match, ?F(match)). --define(remote, ?F(remote)). --define(record, ?F(record)). --define(record_field, ?F(record_field)). --define(record_index, ?F(record_index)). --define(tuple, ?F(tuple)). - --define(ATOM(T), {atom, ?LINE, T}). --define(VAR(V), {var, ?LINE, V}). - --define(CALL(F,A), {?call, ?ATOM(F), A}). --define(APPLY(M,F,A), {?call, {?remote, ?ATOM(M), ?ATOM(F)}, A}). +-include("diameter_forms.hrl"). %% parse_transform/2 parse_transform(Forms, _Options) -> Rs = [R || {attribute, _, record, R} <- Forms], - case lists:append([E || {attribute, _, export_records, E} <- Forms]) of - [] -> - Forms; - Es -> - {H,T} = lists:splitwith(fun is_head/1, Forms), - H ++ [a_export(Es) | f_accessors(Es, Rs)] ++ T - end. + Es = lists:append([E || {attribute, _, export_records, E} <- Forms]), + {H,T} = lists:splitwith(fun is_head/1, Forms), + H ++ [a_export(Es) | f_accessors(Es, Rs)] ++ T. is_head(T) -> not lists:member(element(1,T), [function, eof]). @@ -200,7 +174,7 @@ fname(Op, Rname) -> '#info-/2'(Exports) -> {?function, fname(info), 2, - lists:map(fun 'info-'/1, Exports)}. + lists:map(fun 'info-'/1, Exports) ++ [?BADARG(2)]}. 'info-'(R) -> {?clause, [?ATOM(R), ?VAR('Info')], @@ -209,7 +183,7 @@ fname(Op, Rname) -> '#new-/1'(Exports) -> {?function, fname(new), 1, - lists:map(fun 'new-'/1, Exports)}. + lists:map(fun 'new-'/1, Exports) ++ [?BADARG(1)]}. 'new-'(R) -> {?clause, [?ATOM(R)], @@ -218,7 +192,7 @@ fname(Op, Rname) -> '#new-/2'(Exports) -> {?function, fname(new), 2, - lists:map(fun 'new--'/1, Exports)}. + lists:map(fun 'new--'/1, Exports) ++ [?BADARG(2)]}. 'new--'(R) -> {?clause, [?ATOM(R), ?VAR('Vals')], @@ -227,7 +201,7 @@ fname(Op, Rname) -> '#get-/2'(Exports) -> {?function, fname(get), 2, - lists:map(fun 'get-'/1, Exports)}. + lists:map(fun 'get-'/1, Exports) ++ [?BADARG(2)]}. 'get-'(R) -> {?clause, [?VAR('Attrs'), @@ -237,7 +211,7 @@ fname(Op, Rname) -> '#set-/2'(Exports) -> {?function, fname(set), 2, - lists:map(fun 'set-'/1, Exports)}. + lists:map(fun 'set-'/1, Exports) ++ [?BADARG(2)]}. 'set-'(R) -> {?clause, [?VAR('Vals'), {?match, {?record, R, []}, ?VAR('Rec')}], diff --git a/lib/diameter/src/compiler/diameter_forms.hrl b/lib/diameter/src/compiler/diameter_forms.hrl index d93131df34..4cd86c32aa 100644 --- a/lib/diameter/src/compiler/diameter_forms.hrl +++ b/lib/diameter/src/compiler/diameter_forms.hrl @@ -21,6 +21,13 @@ %% Macros used when building abstract code. %% +%% Generated functions that could have no generated clauses will have +%% a trailing ?BADARG clause that should never execute as called +%% by diameter. +-define(BADARG(N), {?clause, [?VAR('_') || _ <- lists:seq(1,N)], + [], + [?APPLY(erlang, error, [?ATOM(badarg)])]}). + %% Form tag with line number. -define(F(T), T, ?LINE). %% Yes, that's right. The replacement is to the first unmatched ')'. diff --git a/lib/diameter/src/compiler/diameter_make.erl b/lib/diameter/src/compiler/diameter_make.erl index 4431b88c4d..16e30c1ffb 100644 --- a/lib/diameter/src/compiler/diameter_make.erl +++ b/lib/diameter/src/compiler/diameter_make.erl @@ -18,103 +18,115 @@ %% %% -%% Driver for the encoder generator utility. +%% Module alternative to diameterc for dictionary compilation. +%% +%% Eg. 1> diameter_make:codec("mydict.dia"). +%% +%% $ erl -noinput \ +%% -boot start_clean \ +%% -eval 'ok = diameter_make:codec("mydict.dia")' \ +%% -s init stop %% -module(diameter_make). --export([spec/0, - hrl/0, - erl/0]). +-export([codec/1, + codec/2, + dict/1, + dict/2, + format/1, + reformat/1]). --spec spec() -> no_return(). --spec hrl() -> no_return(). --spec erl() -> no_return(). +-export_type([opt/0]). -spec() -> - make(spec). +-type opt() :: {include|outdir|name|prefix|inherits, string()} + | verbose + | debug. -hrl() -> - make(hrl). +%% =========================================================================== -erl() -> - make(erl). +%% codec/1-2 +%% +%% Parse a dictionary file and generate a codec module. + +-spec codec(Path, [opt()]) + -> ok + | {error, Reason} + when Path :: string(), + Reason :: string(). + +codec(File, Opts) -> + case dict(File, Opts) of + {ok, Dict} -> + make(File, + Opts, + Dict, + [spec || _ <- [1], lists:member(debug, Opts)] ++ [erl, hrl]); + {error, _} = E -> + E + end. -%% make/1 +codec(File) -> + codec(File, []). -make(Mode) -> - Args = init:get_plain_arguments(), - Opts = try options(Args) catch throw: help -> help(Mode) end, - Files = proplists:get_value(files, Opts, []), - lists:foreach(fun(F) -> from_file(F, Mode, Opts) end, Files), - halt(0). +%% 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. -%% from_file/3 +dict(File) -> + dict(File, []). -from_file(F, Mode, Opts) -> - try to_spec(F, Mode, Opts) of - Spec -> - from_spec(F, Spec, Mode, Opts) - catch - error: Reason -> - io:format("==> ~p parse failure:~n~p~n", - [F, {Reason, erlang:get_stacktrace()}]), - halt(1) - end. +%% format/1 +%% +%% Turn an orddict returned by dict/1-2 back into a dictionary file +%% in the form of an iolist(). -%% to_spec/2 +-spec format(orddict:orddict()) + -> iolist(). -%% Try to read the input as an already parsed file or else parse it. -to_spec(F, spec, Opts) -> - diameter_spec_util:parse(F, Opts); -to_spec(F, _, _) -> - {ok, [Spec]} = file:consult(F), - Spec. +format(Dict) -> + diameter_dict_util:format(Dict). -%% from_spec/4 +%% reformat/1 +%% +%% Parse a dictionary file and return its formatted equivalent. + +-spec reformat(File) + -> {ok, iolist()} + | {error, Reason} + when File :: string(), + Reason :: string(). + +reformat(File) -> + case dict(File) of + {ok, Dict} -> + {ok, format(Dict)}; + {error, _} = No -> + No + end. -from_spec(File, Spec, Mode, Opts) -> +%% =========================================================================== + +make(_, _, _, []) -> + ok; +make(File, Opts, Dict, [Mode | Rest]) -> try - diameter_codegen:from_spec(File, Spec, Opts, Mode) + ok = diameter_codegen:from_dict(File, Dict, Opts, Mode), + make(File, Opts, Dict, Rest) catch error: Reason -> - io:format("==> ~p codegen failure:~n~p~n~p~n", - [Mode, File, {Reason, erlang:get_stacktrace()}]), - halt(1) + erlang:error({Reason, Mode, erlang:get_stacktrace()}) end. - -%% options/1 - -options(["-v" | Rest]) -> - [verbose | options(Rest)]; - -options(["-o", Outdir | Rest]) -> - [{outdir, Outdir} | options(Rest)]; - -options(["-i", Incdir | Rest]) -> - [{include, Incdir} | options(Rest)]; - -options(["-h" | _]) -> - throw(help); - -options(["--" | Fs]) -> - [{files, Fs}]; - -options(["-" ++ _ = Opt | _]) -> - io:fwrite("==> unknown option: ~s~n", [Opt]), - throw(help); - -options(Fs) -> %% trailing arguments - options(["--" | Fs]). - -%% help/1 - -help(M) -> - io:fwrite("Usage: ~p ~p [Options] [--] File ...~n" - "Options:~n" - " -v verbose output~n" - " -h shows this help message~n" - " -o OutDir where to put the output files~n" - " -i IncludeDir where to search for beams to import~n", - [?MODULE, M]), - halt(1). diff --git a/lib/diameter/src/compiler/diameter_nowarn.erl b/lib/diameter/src/compiler/diameter_nowarn.erl new file mode 100644 index 0000000000..6c17af6563 --- /dev/null +++ b/lib/diameter/src/compiler/diameter_nowarn.erl @@ -0,0 +1,41 @@ +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2010-2011. 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 parse transform to work around dialyzer currently not +%% understanding nowarn_unused_function except on individual +%% functions. The include of diameter_gen.hrl by generated dictionary +%% modules contains code that may not be called depending on the +%% dictionary. (The relay dictionary for example.) +%% +%% Even called functions may contain cases that aren't used for a +%% particular dictionary. This also causes dialyzer to complain but +%% there's no way to silence it in this case. +%% + +-module(diameter_nowarn). + +-export([parse_transform/2]). + +parse_transform(Forms, _Options) -> + [{attribute, ?LINE, compile, {nowarn_unused_function, {F,A}}} + || {function, _, F, A, _} <- Forms] + ++ Forms. +%% Note that dialyzer also doesn't understand {nowarn_unused_function, FAs} +%% with FAs a list of tuples. diff --git a/lib/diameter/src/compiler/diameter_spec_scan.erl b/lib/diameter/src/compiler/diameter_spec_scan.erl deleted file mode 100644 index bc0448882a..0000000000 --- a/lib/diameter/src/compiler/diameter_spec_scan.erl +++ /dev/null @@ -1,157 +0,0 @@ -%% -%% %CopyrightBegin% -%% -%% Copyright Ericsson AB 2010-2011. 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% -%% - --module(diameter_spec_scan). - -%% -%% Functions used by the spec file parser in diameter_spec_util. -%% - --export([split/1, - split/2, - parse/1]). - -%%% ----------------------------------------------------------- -%%% # parse/1 -%%% -%%% Output: list of Token -%%% -%%% Token = '{' | '}' | '<' | '>' | '[' | ']' -%%% | '*' | '::=' | ':' | ',' | '-' -%%% | {name, string()} -%%% | {tag, atom()} -%%% | {number, integer() >= 0} -%%% -%%% Tokenize a string. Fails if the string does not parse. -%%% ----------------------------------------------------------- - -parse(S) -> - parse(S, []). - -%% parse/2 - -parse(S, Acc) -> - acc(split(S), Acc). - -acc({T, Rest}, Acc) -> - parse(Rest, [T | Acc]); -acc("", Acc) -> - lists:reverse(Acc). - -%%% ----------------------------------------------------------- -%%% # split/2 -%%% -%%% Output: {list() of Token, Rest} -%%% -%%% Extract a specified number of tokens from a string. Returns a list -%%% of length less than the specified number if there are less than -%%% this number of tokens to be parsed. -%%% ----------------------------------------------------------- - -split(Str, N) - when N >= 0 -> - split(N, Str, []). - -split(0, Str, Acc) -> - {lists:reverse(Acc), Str}; - -split(N, Str, Acc) -> - case split(Str) of - {T, Rest} -> - split(N-1, Rest, [T|Acc]); - "" = Rest -> - {lists:reverse(Acc), Rest} - end. - -%%% ----------------------------------------------------------- -%%% # split/1 -%%% -%%% Output: {Token, Rest} | "" -%%% -%%% Extract the next token from a string. -%%% ----------------------------------------------------------- - -split("" = Rest) -> - Rest; - -split("::=" ++ T) -> - {'::=', T}; - -split([H|T]) - when H == ${; H == $}; - H == $<; H == $>; - H == $[; H == $]; - H == $*; H == $:; H == $,; H == $- -> - {list_to_atom([H]), T}; - -split([H|T]) when $A =< H, H =< $Z; - $0 =< H, H =< $9 -> - {P, Rest} = splitwith(fun is_name_ch/1, [H], T), - Tok = try - {number, read_int(P)} - catch - error:_ -> - {name, P} - end, - {Tok, Rest}; - -split([H|T]) when $a =< H, H =< $z -> - {P, Rest} = splitwith(fun is_name_ch/1, [H], T), - {{tag, list_to_atom(P)}, Rest}; - -split([H|T]) when H == $\t; - H == $\s; - H == $\n -> - split(T). - -%% read_int/1 - -read_int([$0,X|S]) - when X == $X; - X == $x -> - {ok, [N], []} = io_lib:fread("~16u", S), - N; - -read_int(S) -> - list_to_integer(S). - -%% splitwith/3 - -splitwith(Fun, Acc, S) -> - split([] /= S andalso Fun(hd(S)), Fun, Acc, S). - -split(true, Fun, Acc, [H|T]) -> - splitwith(Fun, [H|Acc], T); -split(false, _, Acc, S) -> - {lists:reverse(Acc), S}. - -is_name_ch(C) -> - is_alphanum(C) orelse C == $- orelse C == $_. - -is_alphanum(C) -> - is_lower(C) orelse is_upper(C) orelse is_digit(C). - -is_lower(C) -> - $a =< C andalso C =< $z. - -is_upper(C) -> - $A =< C andalso C =< $Z. - -is_digit(C) -> - $0 =< C andalso C =< $9. diff --git a/lib/diameter/src/compiler/diameter_spec_util.erl b/lib/diameter/src/compiler/diameter_spec_util.erl deleted file mode 100644 index b60886b678..0000000000 --- a/lib/diameter/src/compiler/diameter_spec_util.erl +++ /dev/null @@ -1,1068 +0,0 @@ -%% -%% %CopyrightBegin% -%% -%% Copyright Ericsson AB 2010-2011. 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% -%% - -%% -%% This module turns a .dia (aka spec) file into the orddict that -%% diameter_codegen.erl in turn morphs into .erl and .hrl files for -%% encode and decode of Diameter messages and AVPs. -%% - --module(diameter_spec_util). - --export([parse/2]). - --define(ERROR(T), erlang:error({T, ?MODULE, ?LINE})). --define(ATOM, list_to_atom). - -%% parse/1 -%% -%% Output: orddict() - -parse(Path, Options) -> - put({?MODULE, verbose}, lists:member(verbose, Options)), - {ok, B} = file:read_file(Path), - Chunks = chunk(B), - Spec = make_spec(Chunks), - true = groups_defined(Spec), %% sanity checks - true = customs_defined(Spec), %% - Full = import_enums(import_groups(import_avps(insert_codes(Spec), - Options))), - true = enums_defined(Full), %% sanity checks - true = v_flags_set(Spec), - Full. - -%% Optional reports when running verbosely. -report(What, Data) -> - report(get({?MODULE, verbose}), What, Data). - -report(true, Tag, Data) -> - io:format("##~n## ~p ~p~n", [Tag, Data]); -report(false, _, _) -> - ok. - -%% chunk/1 - -chunk(B) -> - chunkify(normalize(binary_to_list(B))). - -%% normalize/1 -%% -%% Replace CR NL by NL, multiple NL by one, tab by space, and strip -%% comments and leading/trailing space from each line. Precludes -%% semicolons being used for any other purpose than comments. - -normalize(Str) -> - nh(Str, []). - -nh([], Acc) -> - lists:reverse(Acc); - -%% Trim leading whitespace. -nh(Str, Acc) -> - nb(trim(Str), Acc). - -%% tab -> space -nb([$\t|Rest], Acc) -> - nb(Rest, [$\s|Acc]); - -%% CR NL -> NL -nb([$\r,$\n|Rest], Acc) -> - nt(Rest, Acc); - -%% Gobble multiple newlines before starting over again. -nb([$\n|Rest], Acc) -> - nt(Rest, Acc); - -%% Comment. -nb([$;|Rest], Acc) -> - nb(lists:dropwhile(fun(C) -> C /= $\n end, Rest), Acc); - -%% Just an ordinary character. Boring ... -nb([C|Rest], Acc) -> - nb(Rest, [C|Acc]); - -nb([] = Str, Acc) -> - nt(Str, Acc). - -%% Discard a subsequent newline. -nt(T, [$\n|_] = Acc) -> - nh(T, trim(Acc)); - -%% Trim whitespace from the end of the line before continuing. -nt(T, Acc) -> - nh(T, [$\n|trim(Acc)]). - -trim(S) -> - lists:dropwhile(fun(C) -> lists:member(C, "\s\t") end, S). - -%% chunkify/1 -%% -%% Split the spec file into pieces delimited by lines starting with -%% @Tag. Returns a list of {Tag, Args, Chunk} where Chunk is the -%% string extending to the next delimiter. Note that leading -%% whitespace has already been stripped. - -chunkify(Str) -> - %% Drop characters to the start of the first chunk. - {_, Rest} = split_chunk([$\n|Str]), - chunkify(Rest, []). - -chunkify([], Acc) -> - lists:reverse(Acc); - -chunkify(Rest, Acc) -> - {H,T} = split_chunk(Rest), - chunkify(T, [split_tag(H) | Acc]). - -split_chunk(Str) -> - split_chunk(Str, []). - -split_chunk([] = Rest, Acc) -> - {lists:reverse(Acc), Rest}; -split_chunk([$@|Rest], [$\n|_] = Acc) -> - {lists:reverse(Acc), Rest}; -split_chunk([C|Rest], Acc) -> - split_chunk(Rest, [C|Acc]). - -%% Expect a tag and its arguments on a single line. -split_tag(Str) -> - {L, Rest} = get_until($\n, Str), - [{tag, Tag} | Toks] = diameter_spec_scan:parse(L), - {Tag, Toks, trim(Rest)}. - -get_until(EndT, L) -> - {H, [EndT | T]} = lists:splitwith(fun(C) -> C =/= EndT end, L), - {H,T}. - -%% ------------------------------------------------------------------------ -%% make_spec/1 -%% -%% Turn chunks into spec. - -make_spec(Chunks) -> - lists:foldl(fun(T,A) -> report(chunk, T), chunk(T,A) end, - orddict:new(), - Chunks). - -chunk({T, [X], []}, Dict) - when T == name; - T == prefix -> - store(T, atomize(X), Dict); - -chunk({id = T, [{number, I}], []}, Dict) -> - store(T, I, Dict); - -chunk({vendor = T, [{number, I}, N], []}, Dict) -> - store(T, {I, atomize(N)}, Dict); - -%% inherits -> [{Mod, [AvpName, ...]}, ...] -chunk({inherits = T, [_,_|_] = Args, []}, Acc) -> - Mods = [atomize(A) || A <- Args], - append_list(T, [{M,[]} || M <- Mods], Acc); -chunk({inherits = T, [Mod], Body}, Acc) -> - append(T, {atomize(Mod), parse_avp_names(Body)}, Acc); - -%% avp_types -> [{AvpName, Code, Type, Flags, Encr}, ...] -chunk({avp_types = T, [], Body}, Acc) -> - store(T, parse_avp_types(Body), Acc); - -%% custom_types -> [{Mod, [AvpName, ...]}, ...] -chunk({custom_types = T, [Mod], Body}, Dict) -> - [_|_] = Avps = parse_avp_names(Body), - append(T, {atomize(Mod), Avps}, Dict); - -%% messages -> [{MsgName, Code, Type, Appl, Avps}, ...] -chunk({messages = T, [], Body}, Acc) -> - store(T, parse_messages(Body), Acc); - -%% grouped -> [{AvpName, Code, Vendor, Avps}, ...] -chunk({grouped = T, [], Body}, Acc) -> - store(T, parse_groups(Body), Acc); - -%% avp_vendor_id -> [{Id, [AvpName, ...]}, ...] -chunk({avp_vendor_id = T, [{number, I}], Body}, Dict) -> - [_|_] = Names = parse_avp_names(Body), - append(T, {I, Names}, Dict); - -%% enums -> [{AvpName, [{Value, Name}, ...]}, ...] -chunk({enum, [N], Str}, Dict) -> - append(enums, {atomize(N), parse_enums(Str)}, Dict); - -%% result_codes -> [{ResultName, [{Value, Name}, ...]}, ...] -chunk({result_code, [N], Str}, Dict) -> - append(result_codes, {atomize(N), parse_enums(Str)}, Dict); - -%% commands -> [{Name, Abbrev}, ...] -chunk({commands = T, [], Body}, Dict) -> - store(T, parse_commands(Body), Dict); - -chunk(T, _) -> - ?ERROR({unknown_tag, T}). - -store(Key, Value, Dict) -> - error == orddict:find(Key, Dict) orelse ?ERROR({duplicate, Key}), - orddict:store(Key, Value, Dict). -append(Key, Value, Dict) -> - orddict:append(Key, Value, Dict). -append_list(Key, Values, Dict) -> - orddict:append_list(Key, Values, Dict). - -atomize({tag, T}) -> - T; -atomize({name, T}) -> - ?ATOM(T). - -get_value(Keys, Spec) - when is_list(Keys) -> - [get_value(K, Spec) || K <- Keys]; -get_value(Key, Spec) -> - proplists:get_value(Key, Spec, []). - -%% ------------------------------------------------------------------------ -%% enums_defined/1 -%% groups_defined/1 -%% customs_defined/1 -%% -%% Ensure that every local enum/grouped/custom is defined as an avp -%% with an appropriate type. - -enums_defined(Spec) -> - Avps = get_value(avp_types, Spec), - Import = get_value(import_enums, Spec), - lists:all(fun({N,_}) -> - true = enum_defined(N, Avps, Import) - end, - get_value(enums, Spec)). - -enum_defined(Name, Avps, Import) -> - case lists:keyfind(Name, 1, Avps) of - {Name, _, 'Enumerated', _, _} -> - true; - {Name, _, T, _, _} -> - ?ERROR({avp_has_wrong_type, Name, 'Enumerated', T}); - false -> - lists:any(fun({_,Is}) -> lists:keymember(Name, 1, Is) end, Import) - orelse ?ERROR({avp_not_defined, Name, 'Enumerated'}) - end. -%% Note that an AVP is imported only if referenced by a message or -%% grouped AVP, so the final branch will fail if an enum definition is -%% extended without this being the case. - -groups_defined(Spec) -> - Avps = get_value(avp_types, Spec), - lists:all(fun({N,_,_,_}) -> true = group_defined(N, Avps) end, - get_value(grouped, Spec)). - -group_defined(Name, Avps) -> - case lists:keyfind(Name, 1, Avps) of - {Name, _, 'Grouped', _, _} -> - true; - {Name, _, T, _, _} -> - ?ERROR({avp_has_wrong_type, Name, 'Grouped', T}); - false -> - ?ERROR({avp_not_defined, Name, 'Grouped'}) - end. - -customs_defined(Spec) -> - Avps = get_value(avp_types, Spec), - lists:all(fun(A) -> true = custom_defined(A, Avps) end, - lists:flatmap(fun last/1, get_value(custom_types, Spec))). - -custom_defined(Name, Avps) -> - case lists:keyfind(Name, 1, Avps) of - {Name, _, T, _, _} when T == 'Grouped'; - T == 'Enumerated' -> - ?ERROR({avp_has_invalid_custom_type, Name, T}); - {Name, _, _, _, _} -> - true; - false -> - ?ERROR({avp_not_defined, Name}) - end. - -last({_,Xs}) -> Xs. - -%% ------------------------------------------------------------------------ -%% v_flags_set/1 - -v_flags_set(Spec) -> - Avps = get_value(avp_types, Spec) - ++ lists:flatmap(fun last/1, get_value(import_avps, Spec)), - Vs = lists:flatmap(fun last/1, get_value(avp_vendor_id, Spec)), - - lists:all(fun(N) -> vset(N, Avps) end, Vs). - -vset(Name, Avps) -> - A = lists:keyfind(Name, 1, Avps), - false == A andalso ?ERROR({avp_not_defined, Name}), - {Name, _Code, _Type, Flags, _Encr} = A, - lists:member('V', Flags) orelse ?ERROR({v_flag_not_set, A}). - -%% ------------------------------------------------------------------------ -%% insert_codes/1 - -insert_codes(Spec) -> - [Msgs, Cmds] = get_value([messages, commands], Spec), - - %% Code -> [{Name, Flags}, ...] - Dict = lists:foldl(fun({N,C,Fs,_,_}, D) -> dict:append(C,{N,Fs},D) end, - dict:new(), - Msgs), - - %% list() of {Code, {ReqName, ReqAbbr}, {AnsName, AnsAbbr}} - %% If the name and abbreviation are the same then the 2-tuples - %% are replaced by the common atom()-valued name. - Codes = dict:fold(fun(C,Ns,A) -> [make_code(C, Ns, Cmds) | A] end, - [], - dict:erase(-1, Dict)), %% answer-message - - orddict:store(command_codes, Codes, Spec). - -make_code(Code, [_,_] = Ns, Cmds) -> - {Req, Ans} = make_names(Ns, lists:map(fun({_,Fs}) -> - lists:member('REQ', Fs) - end, - Ns)), - {Code, abbrev(Req, Cmds), abbrev(Ans, Cmds)}; - -make_code(Code, Cs, _) -> - ?ERROR({missing_request_or_answer, Code, Cs}). - -%% 3.3. Diameter Command Naming Conventions -%% -%% Diameter command names typically includes one or more English words -%% followed by the verb Request or Answer. Each English word is -%% delimited by a hyphen. A three-letter acronym for both the request -%% and answer is also normally provided. - -make_names([{Rname,_},{Aname,_}], [true, false]) -> - {Rname, Aname}; -make_names([{Aname,_},{Rname,_}], [false, true]) -> - {Rname, Aname}; -make_names([_,_] = Names, _) -> - ?ERROR({inconsistent_command_flags, Names}). - -abbrev(Name, Cmds) -> - case abbr(Name, get_value(Name, Cmds)) of - Name -> - Name; - Abbr -> - {Name, Abbr} - end. - -%% No explicit abbreviation: construct. -abbr(Name, []) -> - ?ATOM(abbr(string:tokens(atom_to_list(Name), "-"))); - -%% Abbreviation was specified. -abbr(_Name, Abbr) -> - Abbr. - -%% No hyphens: already abbreviated. -abbr([Abbr]) -> - Abbr; - -%% XX-Request/Answer ==> XXR/XXA -abbr([[_,_] = P, T]) - when T == "Request"; - T == "Answer" -> - P ++ [hd(T)]; - -%% XXX-...-YYY-Request/Answer ==> X...YR/X...YA -abbr([_,_|_] = L) -> - lists:map(fun erlang:hd/1, L). - -%% ------------------------------------------------------------------------ -%% import_avps/2 - -import_avps(Spec, Options) -> - Msgs = get_value(messages, Spec), - Groups = get_value(grouped, Spec), - - %% Messages and groups require AVP's referenced by them. - NeededAvps - = ordsets:from_list(lists:flatmap(fun({_,_,_,_,As}) -> - [avp_name(A) || A <- As] - end, - Msgs) - ++ lists:flatmap(fun({_,_,_,As}) -> - [avp_name(A) || A <- As] - end, - Groups)), - MissingAvps = missing_avps(NeededAvps, Spec), - - report(needed, NeededAvps), - report(missing, MissingAvps), - - Import = inherit(get_value(inherits, Spec), Options), - - report(imported, Import), - - ImportedAvps = lists:map(fun({N,_,_,_,_}) -> N end, - lists:flatmap(fun last/1, Import)), - - Unknown = MissingAvps -- ImportedAvps, - - [] == Unknown orelse ?ERROR({undefined_avps, Unknown}), - - orddict:store(import_avps, Import, orddict:erase(inherits, Spec)). - -%% missing_avps/2 -%% -%% Given a list of AVP names and parsed spec, return the list of -%% AVP's that aren't defined in this spec. - -missing_avps(NeededNames, Spec) -> - Avps = get_value(avp_types, Spec), - Groups = lists:map(fun({N,_,_,As}) -> - {N, [avp_name(A) || A <- As]} - end, - get_value(grouped, Spec)), - Names = ordsets:from_list(['AVP' | lists:map(fun({N,_,_,_,_}) -> N end, - Avps)]), - missing_avps(NeededNames, [], {Names, Groups}). - -avp_name({'<',A,'>'}) -> A; -avp_name({A}) -> A; -avp_name([A]) -> A; -avp_name({_, A}) -> avp_name(A). - -missing_avps(NeededNames, MissingNames, {Names, _} = T) -> - missing(ordsets:filter(fun(N) -> lists:member(N, NeededNames) end, Names), - ordsets:union(NeededNames, MissingNames), - T). - -%% Nothing found locally. -missing([], MissingNames, _) -> - MissingNames; - -%% Or not. Keep looking for for the AVP's needed by the found AVP's of -%% type Grouped. -missing(FoundNames, MissingNames, {_, Groups} = T) -> - NeededNames = lists:flatmap(fun({N,As}) -> - choose(lists:member(N, FoundNames), As, []) - end, - Groups), - missing_avps(ordsets:from_list(NeededNames), - ordsets:subtract(MissingNames, FoundNames), - T). - -%% inherit/2 - -inherit(Inherits, Options) -> - Dirs = [D || {include, D} <- Options] ++ ["."], - lists:foldl(fun(T,A) -> find_avps(T, A, Dirs) end, [], Inherits). - -find_avps({Mod, AvpNames}, Acc, Path) -> - report(inherit_from, Mod), - Avps = avps_from_beam(find_beam(Mod, Path), Mod), %% could be empty - [{Mod, lists:sort(find_avps(AvpNames, Avps))} | Acc]. - -find_avps([], Avps) -> - Avps; -find_avps(Names, Avps) -> - lists:filter(fun({N,_,_,_,_}) -> lists:member(N, Names) end, Avps). - -%% find_beam/2 - -find_beam(Mod, Dirs) - when is_atom(Mod) -> - find_beam(atom_to_list(Mod), Dirs); -find_beam(Mod, Dirs) -> - Beam = Mod ++ code:objfile_extension(), - case try_path(Dirs, Beam) of - {value, Path} -> - Path; - false -> - ?ERROR({beam_not_on_path, Beam, Dirs}) - end. - -try_path([D|Ds], Fname) -> - Path = filename:join(D, Fname), - case file:read_file_info(Path) of - {ok, _} -> - {value, Path}; - _ -> - try_path(Ds, Fname) - end; -try_path([], _) -> - false. - -%% avps_from_beam/2 - -avps_from_beam(Path, Mod) -> - report(beam, Path), - ok = load_module(code:is_loaded(Mod), Mod, Path), - orddict:fetch(avp_types, Mod:dict()). - -load_module(false, Mod, Path) -> - R = filename:rootname(Path, code:objfile_extension()), - {module, Mod} = code:load_abs(R), - ok; -load_module({file, _}, _, _) -> - ok. - -choose(true, X, _) -> X; -choose(false, _, X) -> X. - -%% ------------------------------------------------------------------------ -%% import_groups/1 -%% import_enums/1 -%% -%% For each inherited module, store the content of imported AVP's of -%% type grouped/enumerated in a new key. - -import_groups(Spec) -> - orddict:store(import_groups, import(grouped, Spec), Spec). - -import_enums(Spec) -> - orddict:store(import_enums, import(enums, Spec), Spec). - -import(Key, Spec) -> - lists:flatmap(fun(T) -> import_key(Key, T) end, - get_value(import_avps, Spec)). - -import_key(Key, {Mod, Avps}) -> - Imports = lists:flatmap(fun(T) -> - choose(lists:keymember(element(1,T), - 1, - Avps), - [T], - []) - end, - get_value(Key, Mod:dict())), - if Imports == [] -> - []; - true -> - [{Mod, Imports}] - end. - -%% ------------------------------------------------------------------------ -%% parse_enums/1 -%% -%% Enums are specified either as the integer value followed by the -%% name or vice-versa. In the former case the name of the enum is -%% taken to be the string up to the end of line, which may contain -%% whitespace. In the latter case the integer may be parenthesized, -%% specified in hex and followed by an inline comment. This is -%% historical and will likely be changed to require a precise input -%% format. -%% -%% Output: list() of {integer(), atom()} - -parse_enums(Str) -> - lists:flatmap(fun(L) -> parse_enum(trim(L)) end, string:tokens(Str, "\n")). - -parse_enum([]) -> - []; - -parse_enum(Str) -> - REs = [{"^(0[xX][0-9A-Fa-f]+|[0-9]+)\s+(.*?)\s*$", 1, 2}, - {"^(.+?)\s+(0[xX][0-9A-Fa-f]+|[0-9]+)(\s+.*)?$", 2, 1}, - {"^(.+?)\s+\\((0[xX][0-9A-Fa-f]+|[0-9]+)\\)(\s+.*)?$", 2, 1}], - parse_enum(Str, REs). - -parse_enum(Str, REs) -> - try lists:foreach(fun(R) -> enum(Str, R) end, REs) of - ok -> - ?ERROR({bad_enum, Str}) - catch - throw: {enum, T} -> - [T] - end. - -enum(Str, {Re, I, N}) -> - case re:run(Str, Re, [{capture, all_but_first, list}]) of - {match, Vs} -> - T = list_to_tuple(Vs), - throw({enum, {to_int(element(I,T)), ?ATOM(element(N,T))}}); - nomatch -> - ok - end. - -to_int([$0,X|Hex]) - when X == $x; - X == $X -> - {ok, [I], _} = io_lib:fread("~#", "16#" ++ Hex), - I; -to_int(I) -> - list_to_integer(I). - -%% ------------------------------------------------------------------------ -%% parse_messages/1 -%% -%% Parse according to the ABNF for message specifications in 3.2 of -%% RFC 3588 (shown below). We require all message and AVP names to -%% start with a digit or uppercase character, except for the base -%% answer-message, which is treated as a special case. Allowing names -%% that start with a digit is more than the RFC specifies but the name -%% doesn't affect what's sent over the wire. (Certains 3GPP standards -%% use names starting with a digit. eg 3GPP-Charging-Id in TS32.299.) - -%% -%% Sadly, not even the RFC follows this grammar. In particular, except -%% in the example in 3.2, it wraps each command-name in angle brackets -%% ('<' '>') which makes parsing a sequence of specifications require -%% lookahead: after 'optional' avps have been parsed, it's not clear -%% whether a '<' is a 'fixed' or whether it's the start of a -%% subsequent message until we see whether or not '::=' follows the -%% closing '>'. Require the grammar as specified. -%% -%% Output: list of {Name, Code, Flags, ApplId, Avps} -%% -%% Name = atom() -%% Code = integer() -%% Flags = integer() -%% ApplId = [] | [integer()] -%% Avps = see parse_avps/1 - -parse_messages(Str) -> - p_cmd(trim(Str), []). - -%% command-def = command-name "::=" diameter-message -%% -%% command-name = diameter-name -%% -%% diameter-name = ALPHA *(ALPHA / DIGIT / "-") -%% -%% diameter-message = header [ *fixed] [ *required] [ *optional] -%% [ *fixed] -%% -%% header = "<" Diameter-Header:" command-id -%% [r-bit] [p-bit] [e-bit] [application-id]">" -%% -%% The header spec (and example that follows it) is slightly mangled -%% and, given the examples in the RFC should as follows: -%% -%% header = "<" "Diameter Header:" command-id -%% [r-bit] [p-bit] [e-bit] [application-id]">" -%% -%% This is what's required/parsed below, modulo whitespace. This is -%% also what's specified in the current draft standard at -%% http://ftp.ietf.org/drafts/wg/dime. -%% -%% Note that the grammar specifies the order fixed, required, -%% optional. In practise there seems to be little difference between -%% the latter two since qualifiers can be used to change the -%% semantics. For example 1*[XXX] and *1{YYY} specify 1 or more of the -%% optional avp XXX and 0 or 1 of the required avp YYY, making the -%% iotional avp required and the required avp optional. The current -%% draft addresses this somewhat by requiring that min for a qualifier -%% on an optional avp must be 0 if present. It doesn't say anything -%% about required avps however, so specifying a min of 0 would still -%% be possible. The draft also does away with the trailing *fixed. -%% -%% What will be parsed here will treat required and optional -%% interchangeably. That is. only require that required/optional -%% follow and preceed fixed, not that optional avps must follow -%% required ones. We already have several specs for which this parsing -%% is necessary and there seems to be no harm in accepting it. - -p_cmd("", Acc) -> - lists:reverse(Acc); - -p_cmd(Str, Acc) -> - {Next, Rest} = split_def(Str), - report(command, Next), - p_cmd(Rest, [p_cmd(Next) | Acc]). - -p_cmd("answer-message" ++ Str) -> - p_header([{name, 'answer-message'} | diameter_spec_scan:parse(Str)]); - -p_cmd(Str) -> - p_header(diameter_spec_scan:parse(Str)). - -%% p_header/1 - -p_header(['<', {name, _} = N, '>' | Toks]) -> - p_header([N | Toks]); - -p_header([{name, 'answer-message' = N}, '::=', - '<', {name, "Diameter"}, {name, "Header"}, ':', {tag, code}, - ',', {name, "ERR"}, '[', {name, "PXY"}, ']', '>' - | Toks]) -> - {N, -1, ['ERR', 'PXY'], [], parse_avps(Toks)}; - -p_header([{name, Name}, '::=', - '<', {name, "Diameter"}, {name, "Header"}, ':', {number, Code} - | Toks]) -> - {Flags, Rest} = p_flags(Toks), - {ApplId, [C|_] = R} = p_appl(Rest), - '>' == C orelse ?ERROR({invalid_flag, {Name, Code, Flags, ApplId}, R}), - {?ATOM(Name), Code, Flags, ApplId, parse_avps(tl(R))}; - -p_header(Toks) -> - ?ERROR({invalid_header, Toks}). - -%% application-id = 1*DIGIT -%% -%% command-id = 1*DIGIT -%% ; The Command Code assigned to the command -%% -%% r-bit = ", REQ" -%% ; If present, the 'R' bit in the Command -%% ; Flags is set, indicating that the message -%% ; is a request, as opposed to an answer. -%% -%% p-bit = ", PXY" -%% ; If present, the 'P' bit in the Command -%% ; Flags is set, indicating that the message -%% ; is proxiable. -%% -%% e-bit = ", ERR" -%% ; If present, the 'E' bit in the Command -%% ; Flags is set, indicating that the answer -%% ; message contains a Result-Code AVP in -%% ; the "protocol error" class. - -p_flags(Toks) -> - lists:foldl(fun p_flags/2, {[], Toks}, ["REQ", "PXY", "ERR"]). - -p_flags(N, {Acc, [',', {name, N} | Toks]}) -> - {[?ATOM(N) | Acc], Toks}; - -p_flags(_, T) -> - T. - -%% The RFC doesn't specify ',' before application-id but this seems a -%% bit inconsistent. Accept a comma if it exists. -p_appl([',', {number, I} | Toks]) -> - {[I], Toks}; -p_appl([{number, I} | Toks]) -> - {[I], Toks}; -p_appl(Toks) -> - {[], Toks}. - -%% parse_avps/1 -%% -%% Output: list() of Avp | {Qual, Avp} -%% -%% Qual = '*' | {Min, '*'} | {'*', Max} | {Min, Max} -%% Avp = {'<', Name, '>'} | {Name} | [Name] -%% -%% Min, Max = integer() >= 0 - -parse_avps(Toks) -> - p_avps(Toks, ['<', '|', '<'], []). -%% The list corresponds to the delimiters expected at the front, middle -%% and back of the avp specification, '|' representing '{' and '['. - -%% fixed = [qual] "<" avp-spec ">" -%% ; Defines the fixed position of an AVP -%% -%% required = [qual] "{" avp-spec "}" -%% ; The AVP MUST be present and can appear -%% ; anywhere in the message. -%% -%% optional = [qual] "[" avp-name "]" -%% ; The avp-name in the 'optional' rule cannot -%% ; evaluate to any AVP Name which is included -%% ; in a fixed or required rule. The AVP can -%% ; appear anywhere in the message. -%% -%% qual = [min] "*" [max] -%% ; See ABNF conventions, RFC 2234 Section 6.6. -%% ; The absence of any qualifiers depends on whether -%% ; it precedes a fixed, required, or optional -%% ; rule. If a fixed or required rule has no -%% ; qualifier, then exactly one such AVP MUST -%% ; be present. If an optional rule has no -%% ; qualifier, then 0 or 1 such AVP may be -%% ; present. -%% ; -%% ; NOTE: "[" and "]" have a different meaning -%% ; than in ABNF (see the optional rule, above). -%% ; These braces cannot be used to express -%% ; optional fixed rules (such as an optional -%% ; ICV at the end). To do this, the convention -%% ; is '0*1fixed'. -%% -%% min = 1*DIGIT -%% ; The minimum number of times the element may -%% ; be present. The default value is zero. -%% -%% max = 1*DIGIT -%% ; The maximum number of times the element may -%% ; be present. The default value is infinity. A -%% ; value of zero implies the AVP MUST NOT be -%% ; present. -%% -%% avp-spec = diameter-name -%% ; The avp-spec has to be an AVP Name, defined -%% ; in the base or extended Diameter -%% ; specifications. -%% -%% avp-name = avp-spec / "AVP" -%% ; The string "AVP" stands for *any* arbitrary -%% ; AVP Name, which does not conflict with the -%% ; required or fixed position AVPs defined in -%% ; the command code definition. -%% - -p_avps([], _, Acc) -> - lists:reverse(Acc); - -p_avps(Toks, Delim, Acc) -> - {Qual, Rest} = p_qual(Toks), - {Avp, R, D} = p_avp(Rest, Delim), - T = if Qual == false -> - Avp; - true -> - {Qual, Avp} - end, - p_avps(R, D, [T | Acc]). - -p_qual([{number, Min}, '*', {number, Max} | Toks]) -> - {{Min, Max}, Toks}; -p_qual([{number, Min}, '*' = Max | Toks]) -> - {{Min, Max}, Toks}; -p_qual(['*' = Min, {number, Max} | Toks]) -> - {{Min, Max}, Toks}; -p_qual(['*' = Q | Toks]) -> - {Q, Toks}; -p_qual(Toks) -> - {false, Toks}. - -p_avp([B, {name, Name}, E | Toks], [_|_] = Delim) -> - {avp(B, ?ATOM(Name), E), - Toks, - delim(choose(B == '<', B, '|'), Delim)}; -p_avp(Toks, Delim) -> - ?ERROR({invalid_avp, Toks, Delim}). - -avp('<' = B, Name, '>' = E) -> - {B, Name, E}; -avp('{', Name, '}') -> - {Name}; -avp('[', Name, ']') -> - [Name]; -avp(B, Name, E) -> - ?ERROR({invalid_avp, B, Name, E}). - -delim(B, D) -> - if B == hd(D) -> D; true -> tl(D) end. - -%% split_def/1 -%% -%% Strip one command definition off head of a string. - -split_def(Str) -> - sdh(Str, []). - -%% Look for the "::=" starting off the definition. -sdh("", _) -> - ?ERROR({missing, '::='}); -sdh("::=" ++ Rest, Acc) -> - sdb(Rest, [$=,$:,$:|Acc]); -sdh([C|Rest], Acc) -> - sdh(Rest, [C|Acc]). - -%% Look for the "::=" starting off the following definition. -sdb("::=" ++ _ = Rest, Acc) -> - sdt(trim(Acc), Rest); -sdb("" = Rest, Acc) -> - sd(Acc, Rest); -sdb([C|Rest], Acc) -> - sdb(Rest, [C|Acc]). - -%% Put name characters of the subsequent specification back into Rest. -sdt([C|Acc], Rest) - when C /= $\n, C /= $\s -> - sdt(Acc, [C|Rest]); - -sdt(Acc, Rest) -> - sd(Acc, Rest). - -sd(Acc, Rest) -> - {trim(lists:reverse(Acc)), Rest}. -%% Note that Rest is already trimmed of leading space. - -%% ------------------------------------------------------------------------ -%% parse_groups/1 -%% -%% Parse according to the ABNF for message specifications in 4.4 of -%% RFC 3588 (shown below). Again, allow names starting with a digit -%% and also require "AVP Header" without "-" since this is what -%% the RFC uses in all examples. -%% -%% Output: list of {Name, Code, Vendor, Avps} -%% -%% Name = atom() -%% Code = integer() -%% Vendor = [] | [integer()] -%% Avps = see parse_avps/1 - -parse_groups(Str) -> - p_group(trim(Str), []). - -%% grouped-avp-def = name "::=" avp -%% -%% name-fmt = ALPHA *(ALPHA / DIGIT / "-") -%% -%% name = name-fmt -%% ; The name has to be the name of an AVP, -%% ; defined in the base or extended Diameter -%% ; specifications. -%% -%% avp = header [ *fixed] [ *required] [ *optional] -%% [ *fixed] -%% -%% header = "<" "AVP-Header:" avpcode [vendor] ">" -%% -%% avpcode = 1*DIGIT -%% ; The AVP Code assigned to the Grouped AVP -%% -%% vendor = 1*DIGIT -%% ; The Vendor-ID assigned to the Grouped AVP. -%% ; If absent, the default value of zero is -%% ; used. - -p_group("", Acc) -> - lists:reverse(Acc); - -p_group(Str, Acc) -> - {Next, Rest} = split_def(Str), - report(group, Next), - p_group(Rest, [p_group(diameter_spec_scan:parse(Next)) | Acc]). - -p_group([{name, Name}, '::=', '<', {name, "AVP"}, {name, "Header"}, - ':', {number, Code} - | Toks]) -> - {Id, [C|_] = R} = p_vendor(Toks), - C == '>' orelse ?ERROR({invalid_group_header, R}), - {?ATOM(Name), Code, Id, parse_avps(tl(R))}; - -p_group(Toks) -> - ?ERROR({invalid_group, Toks}). - -p_vendor([{number, I} | Toks]) -> - {[I], Toks}; -p_vendor(Toks) -> - {[], Toks}. - -%% ------------------------------------------------------------------------ -%% parse_avp_names/1 - -parse_avp_names(Str) -> - [p_name(N) || N <- diameter_spec_scan:parse(Str)]. - -p_name({name, N}) -> - ?ATOM(N); -p_name(T) -> - ?ERROR({invalid_avp_name, T}). - -%% ------------------------------------------------------------------------ -%% parse_avp_types/1 -%% -%% Output: list() of {Name, Code, Type, Flags, Encr} - -parse_avp_types(Str) -> - p_avp_types(Str, []). - -p_avp_types(Str, Acc) -> - p_type(diameter_spec_scan:split(Str, 3), Acc). - -p_type({[],[]}, Acc) -> - lists:reverse(Acc); - -p_type({[{name, Name}, {number, Code}, {name, Type}], Str}, Acc) -> - {Flags, Encr, Rest} = try - p_avp_flags(trim(Str), []) - catch - throw: {?MODULE, Reason} -> - ?ERROR({invalid_avp_type, Reason}) - end, - p_avp_types(Rest, [{?ATOM(Name), Code, ?ATOM(type(Type)), Flags, Encr} - | Acc]); - -p_type(T, _) -> - ?ERROR({invalid_avp_type, T}). - -p_avp_flags([C|Str], Acc) - when C == $M; - C == $P; - C == $V -> - p_avp_flags(Str, [?ATOM([C]) | Acc]); -%% Could support lowercase here if there's a use for distinguishing -%% between Must and Should in the future in deciding whether or not -%% to set a flag. - -p_avp_flags([$-|Str], Acc) -> - %% Require encr on same line as flags if specified. - {H,T} = lists:splitwith(fun(C) -> C /= $\n end, Str), - - {[{name, [$X|X]} | Toks], Rest} = diameter_spec_scan:split([$X|H], 2), - - "" == X orelse throw({?MODULE, {invalid_avp_flag, Str}}), - - Encr = case Toks of - [] -> - "-"; - [{_, E}] -> - (E == "Y" orelse E == "N") - orelse throw({?MODULE, {invalid_encr, E}}), - E - end, - - Flags = ordsets:from_list(lists:reverse(Acc)), - - {Flags, ?ATOM(Encr), Rest ++ T}; - -p_avp_flags(Str, Acc) -> - p_avp_flags([$-|Str], Acc). - -type("DiamIdent") -> "DiameterIdentity"; %% RFC 3588 -type("DiamURI") -> "DiameterURI"; %% RFC 3588 -type("IPFltrRule") -> "IPFilterRule"; %% RFC 4005 -type("QoSFltrRule") -> "QoSFilterRule"; %% RFC 4005 -type(N) - when N == "OctetString"; - N == "Integer32"; - N == "Integer64"; - N == "Unsigned32"; - N == "Unsigned64"; - N == "Float32"; - N == "Float64"; - N == "Grouped"; - N == "Enumerated"; - N == "Address"; - N == "Time"; - N == "UTF8String"; - N == "DiameterIdentity"; - N == "DiameterURI"; - N == "IPFilterRule"; - N == "QoSFilterRule" -> - N; -type(N) -> - ?ERROR({invalid_avp_type, N}). - -%% ------------------------------------------------------------------------ -%% parse_commands/1 - -parse_commands(Str) -> - p_abbr(diameter_spec_scan:parse(Str), []). - - p_abbr([{name, Name}, {name, Abbrev} | Toks], Acc) - when length(Abbrev) < length(Name) -> - p_abbr(Toks, [{?ATOM(Name), ?ATOM(Abbrev)} | Acc]); - -p_abbr([], Acc) -> - lists:reverse(Acc); - -p_abbr(T, _) -> - ?ERROR({invalid_command, T}). diff --git a/lib/diameter/src/compiler/diameter_vsn.hrl b/lib/diameter/src/compiler/diameter_vsn.hrl new file mode 100644 index 0000000000..024d047adc --- /dev/null +++ b/lib/diameter/src/compiler/diameter_vsn.hrl @@ -0,0 +1,22 @@ +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2010-2011. 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% +%% + +%% The version of the format of the return value of dict/0 in +%% generated dictionary modules. +-define(VERSION, 1). diff --git a/lib/diameter/src/depend.sed b/lib/diameter/src/depend.sed new file mode 100644 index 0000000000..8f999f646f --- /dev/null +++ b/lib/diameter/src/depend.sed @@ -0,0 +1,51 @@ +# +# %CopyrightBegin% +# +# Copyright Ericsson AB 2010-2011. 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 include dependencies from .erl files. First line of input +# is the path to the module in question (minus the .erl extension), +# the rest is the contents of the module. +# + +1{ + s@^[^/]*/@@ + h + d +} + +# Only interested in includes of diameter hrls. +/^-include/!d +/"diameter/!d + +# Extract the name of the included files in one of two forms: +# +# $(INCDIR)/diameter.hrl +# diameter_internal.hrl + +s@^-include_lib(".*/@$(INCDIR)/@ +s@^-include("@@ +s@".*@@ + +# Retrieve the path to our module from the hold space, morph it +# into a beam path and turn it into a dependency like this: +# +# $(EBIN)/diameter_service.$(EMULATOR): $(INCDIR)/diameter.hrl + +G +s@^\(.*\)\n\(.*\)@$(EBIN)/\2.$(EMULATOR): \1@ diff --git a/lib/diameter/src/dict/base_accounting.dia b/lib/diameter/src/dict/base_accounting.dia new file mode 100644 index 0000000000..ced324078c --- /dev/null +++ b/lib/diameter/src/dict/base_accounting.dia @@ -0,0 +1,69 @@ +;; +;; %CopyrightBegin% +;; +;; Copyright Ericsson AB 2010-2011. 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% +;; + +@id 3 +@name diameter_gen_base_accounting +@prefix diameter_base_accounting +@vendor 0 IETF + +@inherits diameter_gen_base_rfc3588 + +@messages + + ACR ::= < Diameter Header: 271, REQ, PXY > + < Session-Id > + { Origin-Host } + { Origin-Realm } + { Destination-Realm } + { Accounting-Record-Type } + { Accounting-Record-Number } + [ Acct-Application-Id ] + [ Vendor-Specific-Application-Id ] + [ User-Name ] + [ Accounting-Sub-Session-Id ] + [ Acct-Session-Id ] + [ Acct-Multi-Session-Id ] + [ Acct-Interim-Interval ] + [ Accounting-Realtime-Required ] + [ Origin-State-Id ] + [ Event-Timestamp ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + ACA ::= < Diameter Header: 271, PXY > + < Session-Id > + { Result-Code } + { Origin-Host } + { Origin-Realm } + { Accounting-Record-Type } + { Accounting-Record-Number } + [ Acct-Application-Id ] + [ Vendor-Specific-Application-Id ] + [ User-Name ] + [ Accounting-Sub-Session-Id ] + [ Acct-Session-Id ] + [ Acct-Multi-Session-Id ] + [ Error-Reporting-Host ] + [ Acct-Interim-Interval ] + [ Accounting-Realtime-Required ] + [ Origin-State-Id ] + [ Event-Timestamp ] + * [ Proxy-Info ] + * [ AVP ] diff --git a/lib/diameter/src/dict/base_rfc3588.dia b/lib/diameter/src/dict/base_rfc3588.dia new file mode 100644 index 0000000000..acd7fffd00 --- /dev/null +++ b/lib/diameter/src/dict/base_rfc3588.dia @@ -0,0 +1,461 @@ +;; +;; %CopyrightBegin% +;; +;; Copyright Ericsson AB 2010-2011. 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% +;; + +@id 0 +@name diameter_gen_base_rfc3588 +@prefix diameter_base +@vendor 0 IETF + +@avp_types + + Acct-Interim-Interval 85 Unsigned32 M + Accounting-Realtime-Required 483 Enumerated M + Acct-Multi-Session-Id 50 UTF8String M + Accounting-Record-Number 485 Unsigned32 M + Accounting-Record-Type 480 Enumerated M + Acct-Session-Id 44 OctetString M + Accounting-Sub-Session-Id 287 Unsigned64 M + Acct-Application-Id 259 Unsigned32 M + Auth-Application-Id 258 Unsigned32 M + Auth-Request-Type 274 Enumerated M + Authorization-Lifetime 291 Unsigned32 M + Auth-Grace-Period 276 Unsigned32 M + Auth-Session-State 277 Enumerated M + Re-Auth-Request-Type 285 Enumerated M + Class 25 OctetString M + Destination-Host 293 DiamIdent M + Destination-Realm 283 DiamIdent M + Disconnect-Cause 273 Enumerated M + E2E-Sequence 300 Grouped M + Error-Message 281 UTF8String - + Error-Reporting-Host 294 DiamIdent - + Event-Timestamp 55 Time M + Experimental-Result 297 Grouped M + Experimental-Result-Code 298 Unsigned32 M + Failed-AVP 279 Grouped M + Firmware-Revision 267 Unsigned32 - + Host-IP-Address 257 Address M + Inband-Security-Id 299 Unsigned32 M + Multi-Round-Time-Out 272 Unsigned32 M + Origin-Host 264 DiamIdent M + Origin-Realm 296 DiamIdent M + Origin-State-Id 278 Unsigned32 M + Product-Name 269 UTF8String - + Proxy-Host 280 DiamIdent M + Proxy-Info 284 Grouped M + Proxy-State 33 OctetString M + Redirect-Host 292 DiamURI M + Redirect-Host-Usage 261 Enumerated M + Redirect-Max-Cache-Time 262 Unsigned32 M + Result-Code 268 Unsigned32 M + Route-Record 282 DiamIdent M + Session-Id 263 UTF8String M + Session-Timeout 27 Unsigned32 M + Session-Binding 270 Unsigned32 M + Session-Server-Failover 271 Enumerated M + Supported-Vendor-Id 265 Unsigned32 M + Termination-Cause 295 Enumerated M + User-Name 1 UTF8String M + Vendor-Id 266 Unsigned32 M + Vendor-Specific-Application-Id 260 Grouped M + +@messages + + CER ::= < Diameter Header: 257, REQ > + { Origin-Host } + { Origin-Realm } + 1* { Host-IP-Address } + { Vendor-Id } + { Product-Name } + [ Origin-State-Id ] + * [ Supported-Vendor-Id ] + * [ Auth-Application-Id ] + * [ Inband-Security-Id ] + * [ Acct-Application-Id ] + * [ Vendor-Specific-Application-Id ] + [ Firmware-Revision ] + * [ AVP ] + + CEA ::= < Diameter Header: 257 > + { Result-Code } + { Origin-Host } + { Origin-Realm } + 1* { Host-IP-Address } + { Vendor-Id } + { Product-Name } + [ Origin-State-Id ] + [ Error-Message ] + * [ Failed-AVP ] + * [ Supported-Vendor-Id ] + * [ Auth-Application-Id ] + * [ Inband-Security-Id ] + * [ Acct-Application-Id ] + * [ Vendor-Specific-Application-Id ] + [ Firmware-Revision ] + * [ AVP ] + + DPR ::= < Diameter Header: 282, REQ > + { Origin-Host } + { Origin-Realm } + { Disconnect-Cause } + + DPA ::= < Diameter Header: 282 > + { Result-Code } + { Origin-Host } + { Origin-Realm } + [ Error-Message ] + * [ Failed-AVP ] + + DWR ::= < Diameter Header: 280, REQ > + { Origin-Host } + { Origin-Realm } + [ Origin-State-Id ] + + DWA ::= < Diameter Header: 280 > + { Result-Code } + { Origin-Host } + { Origin-Realm } + [ Error-Message ] + * [ Failed-AVP ] + [ Origin-State-Id ] + + answer-message ::= < Diameter Header: code, ERR [PXY] > + 0*1 < Session-Id > + { Origin-Host } + { Origin-Realm } + { Result-Code } + [ Origin-State-Id ] + [ Error-Reporting-Host ] + [ Proxy-Info ] + * [ AVP ] + + RAR ::= < Diameter Header: 258, REQ, PXY > + < Session-Id > + { Origin-Host } + { Origin-Realm } + { Destination-Realm } + { Destination-Host } + { Auth-Application-Id } + { Re-Auth-Request-Type } + [ User-Name ] + [ Origin-State-Id ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + RAA ::= < Diameter Header: 258, PXY > + < Session-Id > + { Result-Code } + { Origin-Host } + { Origin-Realm } + [ User-Name ] + [ Origin-State-Id ] + [ Error-Message ] + [ Error-Reporting-Host ] + * [ Failed-AVP ] + * [ Redirect-Host ] + [ Redirect-Host-Usage ] + [ Redirect-Max-Cache-Time ] + * [ Proxy-Info ] + * [ AVP ] + + STR ::= < Diameter Header: 275, REQ, PXY > + < Session-Id > + { Origin-Host } + { Origin-Realm } + { Destination-Realm } + { Auth-Application-Id } + { Termination-Cause } + [ User-Name ] + [ Destination-Host ] + * [ Class ] + [ Origin-State-Id ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + STA ::= < Diameter Header: 275, PXY > + < Session-Id > + { Result-Code } + { Origin-Host } + { Origin-Realm } + [ User-Name ] + * [ Class ] + [ Error-Message ] + [ Error-Reporting-Host ] + * [ Failed-AVP ] + [ Origin-State-Id ] + * [ Redirect-Host ] + [ Redirect-Host-Usage ] + [ Redirect-Max-Cache-Time ] + * [ Proxy-Info ] + * [ AVP ] + + ASR ::= < Diameter Header: 274, REQ, PXY > + < Session-Id > + { Origin-Host } + { Origin-Realm } + { Destination-Realm } + { Destination-Host } + { Auth-Application-Id } + [ User-Name ] + [ Origin-State-Id ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + ASA ::= < Diameter Header: 274, PXY > + < Session-Id > + { Result-Code } + { Origin-Host } + { Origin-Realm } + [ User-Name ] + [ Origin-State-Id ] + [ Error-Message ] + [ Error-Reporting-Host ] + * [ Failed-AVP ] + * [ Redirect-Host ] + [ Redirect-Host-Usage ] + [ Redirect-Max-Cache-Time ] + * [ Proxy-Info ] + * [ AVP ] + + ACR ::= < Diameter Header: 271, REQ, PXY > + < Session-Id > + { Origin-Host } + { Origin-Realm } + { Destination-Realm } + { Accounting-Record-Type } + { Accounting-Record-Number } + [ Acct-Application-Id ] + [ Vendor-Specific-Application-Id ] + [ User-Name ] + [ Accounting-Sub-Session-Id ] + [ Acct-Session-Id ] + [ Acct-Multi-Session-Id ] + [ Acct-Interim-Interval ] + [ Accounting-Realtime-Required ] + [ Origin-State-Id ] + [ Event-Timestamp ] + * [ Proxy-Info ] + * [ Route-Record ] + * [ AVP ] + + ACA ::= < Diameter Header: 271, PXY > + < Session-Id > + { Result-Code } + { Origin-Host } + { Origin-Realm } + { Accounting-Record-Type } + { Accounting-Record-Number } + [ Acct-Application-Id ] + [ Vendor-Specific-Application-Id ] + [ User-Name ] + [ Accounting-Sub-Session-Id ] + [ Acct-Session-Id ] + [ Acct-Multi-Session-Id ] + [ Error-Reporting-Host ] + [ Acct-Interim-Interval ] + [ Accounting-Realtime-Required ] + [ Origin-State-Id ] + [ Event-Timestamp ] + * [ Proxy-Info ] + * [ AVP ] + +@enum Disconnect-Cause + + REBOOTING 0 + BUSY 1 + DO_NOT_WANT_TO_TALK_TO_YOU 2 + +@enum Redirect-Host-Usage + + DONT_CACHE 0 + ALL_SESSION 1 + ALL_REALM 2 + REALM_AND_APPLICATION 3 + ALL_APPLICATION 4 + ALL_HOST 5 + ALL_USER 6 + +@enum Auth-Request-Type + + AUTHENTICATE_ONLY 1 + AUTHORIZE_ONLY 2 + AUTHORIZE_AUTHENTICATE 3 + +@enum Auth-Session-State + + STATE_MAINTAINED 0 + NO_STATE_MAINTAINED 1 + +@enum Re-Auth-Request-Type + + AUTHORIZE_ONLY 0 + AUTHORIZE_AUTHENTICATE 1 + +@enum Termination-Cause + + LOGOUT 1 + SERVICE_NOT_PROVIDED 2 + BAD_ANSWER 3 + ADMINISTRATIVE 4 + LINK_BROKEN 5 + AUTH_EXPIRED 6 + USER_MOVED 7 + SESSION_TIMEOUT 8 + +@enum Session-Server-Failover + + REFUSE_SERVICE 0 + TRY_AGAIN 1 + ALLOW_SERVICE 2 + TRY_AGAIN_ALLOW_SERVICE 3 + +@enum Accounting-Record-Type + + EVENT_RECORD 1 + START_RECORD 2 + INTERIM_RECORD 3 + STOP_RECORD 4 + +@enum Accounting-Realtime-Required + + DELIVER_AND_GRANT 1 + GRANT_AND_STORE 2 + GRANT_AND_LOSE 3 + +@define Result-Code + + ;; 7.1.1. Informational + MULTI_ROUND_AUTH 1001 + + ;; 7.1.2. Success + SUCCESS 2001 + LIMITED_SUCCESS 2002 + + ;; 7.1.3. Protocol Errors + COMMAND_UNSUPPORTED 3001 + UNABLE_TO_DELIVER 3002 + REALM_NOT_SERVED 3003 + TOO_BUSY 3004 + LOOP_DETECTED 3005 + REDIRECT_INDICATION 3006 + APPLICATION_UNSUPPORTED 3007 + INVALID_HDR_BITS 3008 + INVALID_AVP_BITS 3009 + UNKNOWN_PEER 3010 + + ;; 7.1.4. Transient Failures + AUTHENTICATION_REJECTED 4001 + OUT_OF_SPACE 4002 + ELECTION_LOST 4003 + + ;; 7.1.5. Permanent Failures + AVP_UNSUPPORTED 5001 + UNKNOWN_SESSION_ID 5002 + AUTHORIZATION_REJECTED 5003 + INVALID_AVP_VALUE 5004 + MISSING_AVP 5005 + RESOURCES_EXCEEDED 5006 + CONTRADICTING_AVPS 5007 + AVP_NOT_ALLOWED 5008 + AVP_OCCURS_TOO_MANY_TIMES 5009 + NO_COMMON_APPLICATION 5010 + UNSUPPORTED_VERSION 5011 + UNABLE_TO_COMPLY 5012 + INVALID_BIT_IN_HEADER 5013 + INVALID_AVP_LENGTH 5014 + INVALID_MESSAGE_LENGTH 5015 + INVALID_AVP_BIT_COMBO 5016 + NO_COMMON_SECURITY 5017 + + ;; With a prefix for backwards compatibility. + DIAMETER_MULTI_ROUND_AUTH 1001 + DIAMETER_SUCCESS 2001 + DIAMETER_LIMITED_SUCCESS 2002 + DIAMETER_COMMAND_UNSUPPORTED 3001 + DIAMETER_UNABLE_TO_DELIVER 3002 + DIAMETER_REALM_NOT_SERVED 3003 + DIAMETER_TOO_BUSY 3004 + DIAMETER_LOOP_DETECTED 3005 + DIAMETER_REDIRECT_INDICATION 3006 + DIAMETER_APPLICATION_UNSUPPORTED 3007 + DIAMETER_INVALID_HDR_BITS 3008 + DIAMETER_INVALID_AVP_BITS 3009 + DIAMETER_UNKNOWN_PEER 3010 + DIAMETER_AUTHENTICATION_REJECTED 4001 + DIAMETER_OUT_OF_SPACE 4002 + DIAMETER_ELECTION_LOST 4003 + DIAMETER_AVP_UNSUPPORTED 5001 + DIAMETER_UNKNOWN_SESSION_ID 5002 + DIAMETER_AUTHORIZATION_REJECTED 5003 + DIAMETER_INVALID_AVP_VALUE 5004 + DIAMETER_MISSING_AVP 5005 + DIAMETER_RESOURCES_EXCEEDED 5006 + DIAMETER_CONTRADICTING_AVPS 5007 + DIAMETER_AVP_NOT_ALLOWED 5008 + DIAMETER_AVP_OCCURS_TOO_MANY_TIMES 5009 + DIAMETER_NO_COMMON_APPLICATION 5010 + DIAMETER_UNSUPPORTED_VERSION 5011 + DIAMETER_UNABLE_TO_COMPLY 5012 + DIAMETER_INVALID_BIT_IN_HEADER 5013 + DIAMETER_INVALID_AVP_LENGTH 5014 + DIAMETER_INVALID_MESSAGE_LENGTH 5015 + DIAMETER_INVALID_AVP_BIT_COMBO 5016 + DIAMETER_NO_COMMON_SECURITY 5017 + +@grouped + + Proxy-Info ::= < AVP Header: 284 > + { Proxy-Host } + { Proxy-State } + * [ AVP ] + + Failed-AVP ::= < AVP Header: 279 > + 1* {AVP} + + Experimental-Result ::= < AVP Header: 297 > + { Vendor-Id } + { Experimental-Result-Code } + + Vendor-Specific-Application-Id ::= < AVP Header: 260 > + 1* { Vendor-Id } + [ Auth-Application-Id ] + [ Acct-Application-Id ] + +;; The E2E-Sequence AVP is defined in RFC 3588 as Grouped, but +;; there is no definition of the group - only an informal text stating +;; that there should be a nonce (an OctetString) and a counter +;; (integer) +;; + E2E-Sequence ::= <AVP Header: 300 > + 2* { AVP } + +;; Backwards compatibility. +@define Termination-Cause + + DIAMETER_LOGOUT 1 + DIAMETER_SERVICE_NOT_PROVIDED 2 + DIAMETER_BAD_ANSWER 3 + DIAMETER_ADMINISTRATIVE 4 + DIAMETER_LINK_BROKEN 5 + DIAMETER_AUTH_EXPIRED 6 + DIAMETER_USER_MOVED 7 + DIAMETER_SESSION_TIMEOUT 8 diff --git a/lib/diameter/src/app/diameter_gen_relay.dia b/lib/diameter/src/dict/relay.dia index d86446e368..294014b093 100644 --- a/lib/diameter/src/app/diameter_gen_relay.dia +++ b/lib/diameter/src/dict/relay.dia @@ -18,7 +18,6 @@ ;; @id 0xFFFFFFFF +@name diameter_gen_relay @prefix diameter_relay @vendor 0 IETF - -@inherits diameter_gen_base_rfc3588 diff --git a/lib/diameter/src/gen/.gitignore b/lib/diameter/src/gen/.gitignore new file mode 100644 index 0000000000..3f32313f56 --- /dev/null +++ b/lib/diameter/src/gen/.gitignore @@ -0,0 +1,2 @@ +/diameter_dict_parser.erl +/diameter_gen*rl diff --git a/lib/diameter/src/modules.mk b/lib/diameter/src/modules.mk new file mode 100644 index 0000000000..01f9284881 --- /dev/null +++ b/lib/diameter/src/modules.mk @@ -0,0 +1,105 @@ +#-*-makefile-*- ; force emacs to enter makefile-mode + +# %CopyrightBegin% +# +# Copyright Ericsson AB 2010-2012. 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% + +# Runtime dictionary files in ./dict. Modules will be generated from +# these are included in the app file. +DICTS = \ + base_rfc3588 \ + base_accounting \ + relay + +# The yecc grammar for the dictionary parser. +DICT_YRL = \ + diameter_dict_parser + +# Handwritten (runtime) modules included in the app file. +RT_MODULES = \ + base/diameter \ + base/diameter_app \ + base/diameter_callback \ + base/diameter_capx \ + base/diameter_config \ + base/diameter_codec \ + base/diameter_dict \ + base/diameter_lib \ + base/diameter_misc_sup \ + base/diameter_peer \ + base/diameter_peer_fsm \ + base/diameter_peer_fsm_sup \ + base/diameter_reg \ + base/diameter_service \ + base/diameter_service_sup \ + base/diameter_session \ + base/diameter_stats \ + base/diameter_sup \ + base/diameter_sync \ + base/diameter_types \ + base/diameter_watchdog \ + base/diameter_watchdog_sup \ + transport/diameter_etcp \ + transport/diameter_etcp_sup \ + transport/diameter_tcp \ + transport/diameter_tcp_sup \ + transport/diameter_sctp \ + transport/diameter_sctp_sup \ + transport/diameter_transport \ + transport/diameter_transport_sup + +# Handwritten (compile time) modules not included in the app file. +CT_MODULES = \ + base/diameter_dbg \ + base/diameter_info \ + compiler/diameter_codegen \ + compiler/diameter_exprecs \ + compiler/diameter_nowarn \ + compiler/diameter_dict_scanner \ + compiler/diameter_dict_util \ + compiler/diameter_make + +# Released hrl files in ../include intended for public consumption. +EXTERNAL_HRLS = \ + diameter.hrl \ + diameter_gen.hrl + +# Released hrl files intended for private use. +INTERNAL_HRLS = \ + base/diameter_internal.hrl \ + compiler/diameter_forms.hrl \ + compiler/diameter_vsn.hrl + +# Released files relative to ../bin. +BINS = \ + diameterc + +# Released files relative to ../examples. +EXAMPLES = \ + code/GNUmakefile \ + code/peer.erl \ + code/client.erl \ + code/client_cb.erl \ + code/server.erl \ + code/server_cb.erl \ + code/relay.erl \ + code/relay_cb.erl \ + dict/rfc4004_mip.dia \ + dict/rfc4005_nas.dia \ + dict/rfc4006_cc.dia \ + dict/rfc4072_eap.dia \ + dict/rfc4590_digest.dia \ + dict/rfc4740_sip.dia diff --git a/lib/diameter/src/transport/.gitignore b/lib/diameter/src/transport/.gitignore deleted file mode 100644 index d9f072e262..0000000000 --- a/lib/diameter/src/transport/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ - -/depend.mk - diff --git a/lib/diameter/src/transport/Makefile b/lib/diameter/src/transport/Makefile deleted file mode 100644 index 4b53100fd2..0000000000 --- a/lib/diameter/src/transport/Makefile +++ /dev/null @@ -1,141 +0,0 @@ -# -# %CopyrightBegin% -# -# Copyright Ericsson AB 2010-2011. 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% -# -# - -ifneq ($(ERL_TOP),) -include $(ERL_TOP)/make/target.mk -EBIN = ../../ebin -include $(ERL_TOP)/make/$(TARGET)/otp.mk -else -include $(DIAMETER_TOP)/make/target.mk -EBIN = ../../ebin -include $(DIAMETER_TOP)/make/$(TARGET)/rules.mk -endif - - -# ---------------------------------------------------- -# Application version -# ---------------------------------------------------- - -include ../../vsn.mk -VSN=$(DIAMETER_VSN) - -# ---------------------------------------------------- -# Release directory specification -# ---------------------------------------------------- - -RELSYSDIR = $(RELEASE_PATH)/lib/diameter-$(VSN) - -INCDIR = ../../include - -# ---------------------------------------------------- -# Target Specs -# ---------------------------------------------------- - -include modules.mk - -ERL_FILES = \ - $(MODULES:%=%.erl) - -TARGET_FILES = \ - $(MODULES:%=$(EBIN)/%.$(EMULATOR)) - -# ---------------------------------------------------- -# FLAGS -# ---------------------------------------------------- - -ifeq ($(TYPE),debug) -ERL_COMPILE_FLAGS += -Ddebug -endif - -include ../app/diameter.mk - -ERL_COMPILE_FLAGS += \ - $(DIAMETER_ERL_COMPILE_FLAGS) \ - -I$(INCDIR) - -# ---------------------------------------------------- -# Targets -# ---------------------------------------------------- - -debug: - @${MAKE} TYPE=debug opt - -opt: $(TARGET_FILES) - -clean: - rm -f $(TARGET_FILES) - rm -f errs core *~ - rm -f depend.mk - -docs: - -info: - @echo "" - @echo "ERL_FILES = $(ERL_FILES)" - @echo "HRL_FILES = $(HRL_FILES)" - @echo "" - @echo "TARGET_FILES = $(TARGET_FILES)" - @echo "" - -# ---------------------------------------------------- -# Special Build Targets -# ---------------------------------------------------- - -# Invoked from ../app to add modules to the app file. -$(APP_TARGET): force - M=`echo $(MODULES) | sed -e 's/^ *//' -e 's/ *$$//' -e 'y/ /,/'`; \ - echo "/%TRANSPORT_MODULES%/s//$$M/;w;q" | tr ';' '\n' \ - | ed -s $@ - -# ---------------------------------------------------- -# Release Target -# ---------------------------------------------------- -ifneq ($(ERL_TOP),) -include $(ERL_TOP)/make/otp_release_targets.mk -else -include $(DIAMETER_TOP)/make/release_targets.mk -endif - -release_spec: opt - $(INSTALL_DIR) $(RELSYSDIR)/ebin - $(INSTALL_DATA) $(TARGET_FILES) $(RELSYSDIR)/ebin - $(INSTALL_DIR) $(RELSYSDIR)/src/transport - $(INSTALL_DATA) $(ERL_FILES) $(HRL_FILES) $(RELSYSDIR)/src/transport - -release_docs_spec: - -force: - -# ---------------------------------------------------- -# Dependencies -# ---------------------------------------------------- - -depend: depend.mk - -# Generate dependencies makefile. -depend.mk: ../app/depend.sed $(ERL_FILES) Makefile - for f in $(MODULES); do \ - sed -f $< $$f.erl | sed "s@/@/$$f@"; \ - done \ - > $@ - --include depend.mk - -.PHONY: clean debug depend docs force info opt release_docs_spec release_spec diff --git a/lib/diameter/src/transport/diameter_etcp.erl b/lib/diameter/src/transport/diameter_etcp.erl index d925d62545..cd62cf34fa 100644 --- a/lib/diameter/src/transport/diameter_etcp.erl +++ b/lib/diameter/src/transport/diameter_etcp.erl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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 @@ -36,7 +36,9 @@ send/2, close/1, setopts/2, - port/1]). + sockname/1, + peername/1, + getstat/1]). %% child start -export([start_link/1]). @@ -113,10 +115,20 @@ close(Pid) -> setopts(_, _) -> ok. -%% port/1 +%% sockname/1 -port(_) -> - 3868. %% We have no local port: fake it. +sockname(_) -> + {error, ?MODULE}. + +%% peername/1 + +peername(_) -> + {error, ?MODULE}. + +%% getstat/1 + +getstat(_) -> + {error, ?MODULE}. %% start_link/1 diff --git a/lib/diameter/src/transport/diameter_sctp.erl b/lib/diameter/src/transport/diameter_sctp.erl index 46473e7bf1..79b8b851fb 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-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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,9 +37,18 @@ code_change/3, terminate/2]). +-export([info/1]). %% service_info callback + +-export([ports/0, + ports/1]). + -include_lib("kernel/include/inet_sctp.hrl"). -include_lib("diameter/include/diameter.hrl"). +%% Keys into process dictionary. +-define(INFO_KEY, info). +-define(REF_KEY, ref). + -define(ERROR(T), erlang:error({T, ?MODULE, ?LINE})). %% The default port for a listener. @@ -59,6 +68,7 @@ -record(transport, {parent :: pid(), mode :: {accept, pid()} + | accept | {connect, {list(inet:ip_address()), uint(), list()}} %% {RAs, RP, Errors} | connect, @@ -118,8 +128,8 @@ s({accept, Ref} = A, Addrs, Opts) -> %% gen_sctp in order to be able to accept a new association only %% *after* an accepting transport has been spawned. -s({connect = C, _}, Addrs, Opts) -> - diameter_sctp_sup:start_child({C, self(), Opts, Addrs}). +s({connect = C, Ref}, Addrs, Opts) -> + diameter_sctp_sup:start_child({C, self(), Opts, Addrs, Ref}). %% start_link/1 @@ -131,6 +141,24 @@ start_link(T) -> diameter_lib:spawn_opts(server, [])). %% --------------------------------------------------------------------------- +%% # info/1 +%% --------------------------------------------------------------------------- + +info({gen_sctp, Sock}) -> + lists:flatmap(fun(K) -> info(K, Sock) end, + [{socket, sockname}, + {peer, peername}, + {statistics, getstat}]). + +info({K,F}, Sock) -> + case inet:F(Sock) of + {ok, V} -> + [{K,V}]; + _ -> + [] + end. + +%% --------------------------------------------------------------------------- %% # init/1 %% --------------------------------------------------------------------------- @@ -149,28 +177,36 @@ i({listen, Ref, {Opts, Addrs}}) -> socket = Sock}); %% A connecting transport. -i({connect, Pid, Opts, Addrs}) -> +i({connect, Pid, Opts, Addrs, Ref}) -> {[As, Ps], Rest} = proplists:split(Opts, [raddr, rport]), RAs = [diameter_lib:ipaddr(A) || {raddr, A} <- As], [RP] = [P || {rport, P} <- Ps] ++ [P || P <- [?DEFAULT_PORT], [] == Ps], {LAs, Sock} = open(Addrs, Rest, 0), + putr(?REF_KEY, Ref), proc_lib:init_ack({ok, self(), LAs}), erlang:monitor(process, Pid), #transport{parent = Pid, mode = {connect, connect(Sock, RAs, RP, [])}, socket = Sock}; +i({connect, _, _, _} = T) -> %% from old code + x(T); %% An accepting transport spawned by diameter. -i({accept, Pid, LPid, Sock}) -> +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), #transport{parent = Pid, mode = {accept, LPid}, socket = Sock}; +i({accept, _, _, _} = T) -> %% from old code + x(T); %% An accepting transport spawned at association establishment. i({accept, Ref, LPid, Sock, Id}) -> + putr(?REF_KEY, Ref), proc_lib:init_ack({ok, self()}), MRef = erlang:monitor(process, LPid), %% Wait for a signal that the transport has been started before @@ -250,13 +286,33 @@ gen_opts(Opts) -> [binary, {active, once} | Opts]. %% --------------------------------------------------------------------------- +%% # ports/0-1 +%% --------------------------------------------------------------------------- + +ports() -> + Ts = diameter_reg:match({?MODULE, '_', '_'}), + [{type(T), N, Pid} || {{?MODULE, T, {_, {_, S}}}, Pid} <- Ts, + {ok, N} <- [inet:port(S)]]. + +ports(Ref) -> + Ts = diameter_reg:match({?MODULE, '_', {Ref, '_'}}), + [{type(T), N, Pid} || {{?MODULE, T, {R, {_, S}}}, Pid} <- Ts, + R == Ref, + {ok, N} <- [inet:port(S)]]. + +type(listener) -> + listen; +type(T) -> + T. + +%% --------------------------------------------------------------------------- %% # handle_call/3 %% --------------------------------------------------------------------------- handle_call({{accept, Ref}, Pid}, _, #listener{ref = Ref, count = N} = S) -> - {TPid, NewS} = accept(Pid, S), + {TPid, NewS} = accept(Ref, Pid, S), {reply, {ok, TPid}, NewS#listener{count = N+1}}; handle_call(_, _, State) -> @@ -294,6 +350,11 @@ terminate(_, #transport{assoc_id = undefined}) -> ok; terminate(_, #transport{socket = Sock, + mode = accept, + assoc_id = Id}) -> + close(Sock, Id); + +terminate(_, #transport{socket = Sock, mode = {accept, _}, assoc_id = Id}) -> close(Sock, Id); @@ -306,6 +367,12 @@ terminate(_, #listener{socket = Sock}) -> %% --------------------------------------------------------------------------- +putr(Key, Val) -> + put({?MODULE, Key}, Val). + +getr(Key) -> + get({?MODULE, Key}). + %% start_timer/1 start_timer(#listener{count = 0} = S) -> @@ -319,13 +386,16 @@ start_timer(S) -> %% Incoming message from SCTP. l({sctp, Sock, _RA, _RP, Data} = Msg, #listener{socket = Sock} = S) -> - setopts(Sock), - case find(Data, S) of + Id = assoc_id(Data), + + try find(Id, Data, S) of {TPid, NewS} -> - TPid ! Msg, + TPid ! {peeloff, peeloff(Sock, Id, TPid), Msg}, NewS; false -> S + after + setopts(Sock) end; %% Transport is asking message to be sent. See send/3 for why the send @@ -393,15 +463,19 @@ t(T,S) -> %% transition/2 -%% Incoming message. -transition({sctp, Sock, _RA, _RP, Data}, #transport{socket = Sock, - mode = {accept, _}} - = S) -> - recv(Data, S); +%% Listening process is transfering ownership of an association. +transition({peeloff, Sock, {sctp, LSock, _RA, _RP, _Data} = Msg}, + #transport{mode = {accept, _}, + socket = LSock} + = S) -> + transition(Msg, S#transport{socket = Sock}); -transition({sctp, Sock, _RA, _RP, Data}, #transport{socket = Sock} = S) -> +%% Incoming message. +transition({sctp, _Sock, _RA, _RP, Data}, #transport{socket = Sock} = S) -> setopts(Sock), recv(Data, S); +%% Don't match on Sock since in R15B01 it can be the listening socket +%% in the (peeled-off) accept case, which is likely a bug. %% Outgoing message. transition({diameter, {send, Msg}}, S) -> @@ -411,27 +485,46 @@ transition({diameter, {send, Msg}}, S) -> transition({diameter, {close, Pid}}, #transport{parent = Pid}) -> stop; -%% Listener process has died. -transition({'DOWN', _, process, Pid, _}, #transport{mode = {accept, Pid}}) -> +%% TLS over SCTP is described in RFC 3436 but has limitations as +%% described in RFC 6083. The latter describes DTLS over SCTP, which +%% addresses these limitations, DTLS itself being described in RFC +%% 4347. TLS is primarily used over TCP, which the current RFC 3588 +%% draft acknowledges by equating TLS with TLS/TCP and DTLS/SCTP. +transition({diameter, {tls, _Ref, _Type, _Bool}}, _) -> stop; %% Parent process has died. transition({'DOWN', _, process, Pid, _}, #transport{parent = Pid}) -> - stop. + stop; + +%% Listener process has died. +transition({'DOWN', _, process, Pid, _}, #transport{mode = {accept, Pid}}) -> + stop; + +%% Ditto but we have ownership of the association. It might be that +%% we'll go down anyway though. +transition({'DOWN', _, process, _Pid, _}, #transport{mode = accept}) -> + ok; + +%% Request for the local port number. +transition({resolve_port, Pid}, #transport{socket = Sock}) + when is_pid(Pid) -> + Pid ! inet:port(Sock), + ok. %% Crash on anything unexpected. -%% accept/2 +%% accept/3 %% %% Start a new transport process or use one that's already been %% started as a consequence of association establishment. %% No pending associations: spawn a new transport. -accept(Pid, #listener{socket = Sock, - tmap = T, - pending = {0,_} = Q} - = S) -> - Arg = {accept, Pid, self(), Sock}, +accept(Ref, Pid, #listener{socket = Sock, + tmap = T, + pending = {0,_} = Q} + = S) -> + Arg = {accept, Pid, self(), Sock, Ref}, {ok, TPid} = diameter_sctp_sup:start_child(Arg), MRef = erlang:monitor(process, TPid), ets:insert(T, [{MRef, TPid}, {TPid, MRef}]), @@ -442,12 +535,12 @@ accept(Pid, #listener{socket = Sock, %% Accepting transport has died. This can happen if a new transport is %% started before the DOWN has arrived. -accept(Pid, #listener{pending = [TPid | {0,_} = Q]} = S) -> +accept(Ref, Pid, #listener{pending = [TPid | {0,_} = Q]} = S) -> false = is_process_alive(TPid), %% assert - accept(Pid, S#listener{pending = Q}); + accept(Ref, Pid, S#listener{pending = Q}); %% Pending associations: attach to the first in the queue. -accept(Pid, #listener{ref = Ref, pending = {N,Q}} = S) -> +accept(_, Pid, #listener{ref = Ref, pending = {N,Q}} = S) -> TPid = ets:first(Q), TPid ! {Ref, Pid}, ets:delete(Q, TPid), @@ -470,14 +563,6 @@ send(Bin, #transport{streams = {_, OS}, %% send/3 -%% Messages have to be sent from the controlling process, which is -%% probably a bug. Sending from here causes an inet_reply, Sock, -%% Status} message to be sent to the controlling process while -%% gen_sctp:send/4 here hangs. -send(StreamId, Bin, #transport{assoc_id = AId, - mode = {accept, LPid}}) -> - LPid ! {send, AId, StreamId, Bin}; - send(StreamId, Bin, #transport{socket = Sock, assoc_id = AId}) -> send(Sock, AId, StreamId, Bin). @@ -495,17 +580,22 @@ send(Sock, AssocId, Stream, Bin) -> %% recv/2 %% Association established ... -recv({[], #sctp_assoc_change{state = comm_up, - outbound_streams = OS, - inbound_streams = IS, - assoc_id = Id}}, - #transport{assoc_id = undefined} +recv({_, #sctp_assoc_change{state = comm_up, + outbound_streams = OS, + inbound_streams = IS, + assoc_id = Id}}, + #transport{assoc_id = undefined, + mode = {T, _}, + socket = Sock} = S) -> + Ref = getr(?REF_KEY), + is_reference(Ref) %% started in new code + andalso publish(T, Ref, Id, Sock), up(S#transport{assoc_id = Id, streams = {IS, OS}}); %% ... or not: try the next address. -recv({[], #sctp_assoc_change{} = E}, +recv({_, #sctp_assoc_change{} = E}, #transport{assoc_id = undefined, socket = Sock, mode = {connect = C, {[RA|RAs], RP, Es}}} @@ -513,7 +603,7 @@ recv({[], #sctp_assoc_change{} = E}, S#transport{mode = {C, connect(Sock, RAs, RP, [{RA,E} | Es])}}; %% Lost association after establishment. -recv({[], #sctp_assoc_change{}}, _) -> +recv({_, #sctp_assoc_change{}}, _) -> stop; %% Inbound Diameter message. @@ -523,7 +613,7 @@ recv({[#sctp_sndrcvinfo{stream = Id}], Bin}, #transport{parent = Pid}) bin = Bin}), ok; -recv({[], #sctp_shutdown_event{assoc_id = Id}}, +recv({_, #sctp_shutdown_event{assoc_id = Id}}, #transport{assoc_id = Id}) -> stop; @@ -536,12 +626,16 @@ recv({[], #sctp_shutdown_event{assoc_id = Id}}, %% disabled by default so don't handle it. We could simply disable %% events we don't react to but don't. -recv({[], #sctp_paddr_change{}}, _) -> +recv({_, #sctp_paddr_change{}}, _) -> ok; -recv({[], #sctp_pdapi_event{}}, _) -> +recv({_, #sctp_pdapi_event{}}, _) -> ok. +publish(T, Ref, Id, Sock) -> + true = diameter_reg:add_new({?MODULE, T, {Ref, {Id, Sock}}}), + putr(?INFO_KEY, {gen_sctp, Sock}). %% for info/1 + %% up/1 up(#transport{parent = Pid, @@ -551,21 +645,15 @@ up(#transport{parent = Pid, S#transport{mode = C}; up(#transport{parent = Pid, - mode = {accept, _}} + mode = {accept = A, _}} = S) -> diameter_peer:up(Pid), - S. + S#transport{mode = A}. -%% find/2 +%% find/3 -find({[#sctp_sndrcvinfo{assoc_id = Id}], _} - = Data, - #listener{tmap = T} - = S) -> - f(ets:lookup(T, Id), Data, S); - -find({_, Rec} = Data, #listener{tmap = T} = S) -> - f(ets:lookup(T, assoc_id(Rec)), Data, S). +find(Id, Data, #listener{tmap = T} = S) -> + f(ets:lookup(T, Id), Data, S). %% New association and a transport waiting for one: use it. f([], @@ -606,17 +694,29 @@ f([], _, _) -> %% assoc_id/1 -assoc_id(#sctp_shutdown_event{assoc_id = Id}) -> +assoc_id({[#sctp_sndrcvinfo{assoc_id = Id}], _}) -> + Id; +assoc_id({_, Rec}) -> + id(Rec). + +id(#sctp_shutdown_event{assoc_id = Id}) -> Id; -assoc_id(#sctp_assoc_change{assoc_id = Id}) -> +id(#sctp_assoc_change{assoc_id = Id}) -> Id; -assoc_id(#sctp_sndrcvinfo{assoc_id = Id}) -> +id(#sctp_sndrcvinfo{assoc_id = Id}) -> Id; -assoc_id(#sctp_paddr_change{assoc_id = Id}) -> +id(#sctp_paddr_change{assoc_id = Id}) -> Id; -assoc_id(#sctp_adaptation_event{assoc_id = Id}) -> +id(#sctp_adaptation_event{assoc_id = Id}) -> Id. +%% peeloff/3 + +peeloff(LSock, Id, TPid) -> + {ok, Sock} = gen_sctp:peeloff(LSock, Id), + ok = gen_sctp:controlling_process(Sock, TPid), + Sock. + %% connect/4 connect(_, [], _, Reasons) -> diff --git a/lib/diameter/src/transport/diameter_tcp.erl b/lib/diameter/src/transport/diameter_tcp.erl index 653c114471..f3fbbee609 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-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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,14 +37,26 @@ code_change/3, terminate/2]). +-export([info/1]). %% service_info callback + +-export([ports/0, + ports/1]). + -include_lib("diameter/include/diameter.hrl"). +%% Keys into process dictionary. +-define(INFO_KEY, info). +-define(REF_KEY, ref). + -define(ERROR(T), erlang:error({T, ?MODULE, ?LINE})). -define(DEFAULT_PORT, 3868). %% RFC 3588, ch 2.1 -define(LISTENER_TIMEOUT, 30000). -define(FRAGMENT_TIMEOUT, 1000). +%% cb_info passed to ssl. +-define(TCP_CB(Mod), {Mod, tcp, tcp_closed, tcp_error}). + %% The same gen_server implementation supports three different kinds %% of processes: an actual transport process, one that will club it to %% death should the parent die before a connection is established, and @@ -68,11 +80,11 @@ %% Accepting/connecting transport process state. -record(transport, - {socket :: inet:socket(), %% accept or connect socket + {socket :: inet:socket() | ssl:sslsock(), %% accept or connect socket parent :: pid(), %% of process that started us module :: module(), %% gen_tcp-like module - frag = <<>> :: binary() | {tref(), frag()}}). %% message fragment - + frag = <<>> :: binary() | {tref(), frag()}, %% message fragment + ssl :: boolean() | [term()]}). %% ssl options %% The usual transport using gen_tcp can be replaced by anything %% sufficiently gen_tcp-like by passing a 'module' option as the first %% (for simplicity) transport option. The transport_module diameter_etcp @@ -105,6 +117,33 @@ start_link(T) -> diameter_lib:spawn_opts(server, [])). %% --------------------------------------------------------------------------- +%% # info/1 +%% --------------------------------------------------------------------------- + +info({Mod, Sock}) -> + lists:flatmap(fun(K) -> info(Mod, K, Sock) end, + [{socket, fun sockname/2}, + {peer, fun peername/2}, + {statistics, fun getstat/2} + | ssl_info(Mod, Sock)]). + +info(Mod, {K,F}, Sock) -> + case F(Mod, Sock) of + {ok, V} -> + [{K,V}]; + _ -> + [] + end. + +ssl_info(ssl = M, Sock) -> + [{M, ssl_info(Sock)}]; +ssl_info(_, _) -> + []. + +ssl_info(Sock) -> + [{peercert, C} || {ok, C} <- [ssl:peercert(Sock)]]. + +%% --------------------------------------------------------------------------- %% # init/1 %% --------------------------------------------------------------------------- @@ -122,12 +161,18 @@ i({T, Ref, Mod, Pid, Opts, Addrs}) %% that does nothing but kill us with the parent until call %% returns. {ok, MPid} = diameter_tcp_sup:start_child(#monitor{parent = Pid}), - Sock = i(T, Ref, Mod, Pid, Opts, Addrs), + {SslOpts, Rest} = ssl(Opts), + Sock = i(T, Ref, Mod, Pid, SslOpts, Rest, Addrs), MPid ! {stop, self()}, %% tell the monitor to die - setopts(Mod, Sock), + M = if SslOpts -> ssl; true -> Mod end, + setopts(M, Sock), + putr(?REF_KEY, Ref), #transport{parent = Pid, - module = Mod, - socket = Sock}; + module = M, + socket = Sock, + ssl = SslOpts}; +%% Put the reference in the process dictionary since we now use it +%% advertise the ssl socket after TLS upgrade. %% A monitor process to kill the transport if the parent dies. i(#monitor{parent = Pid, transport = TPid} = S) -> @@ -146,30 +191,58 @@ i({listen, LRef, APid, {Mod, Opts, Addrs}}) -> LAddr = get_addr(LA, Addrs), LPort = get_port(LP), {ok, LSock} = Mod:listen(LPort, gen_opts(LAddr, Rest)), + true = diameter_reg:add_new({?MODULE, listener, {LRef, {LAddr, LSock}}}), proc_lib:init_ack({ok, self(), {LAddr, LSock}}), erlang:monitor(process, APid), - true = diameter_reg:add_new({?MODULE, listener, {LRef, {LAddr, LSock}}}), start_timer(#listener{socket = LSock}). -%% i/6 +ssl(Opts) -> + {[SslOpts], Rest} = proplists:split(Opts, [ssl_options]), + {ssl_opts(SslOpts), Rest}. + +ssl_opts([]) -> + false; +ssl_opts([{ssl_options, true}]) -> + true; +ssl_opts([{ssl_options, Opts}]) + when is_list(Opts) -> + Opts; +ssl_opts(L) -> + ?ERROR({ssl_options, L}). + +%% i/7 + +%% Establish a TLS connection before capabilities exchange ... +i(Type, Ref, Mod, Pid, true, Opts, Addrs) -> + i(Type, Ref, ssl, Pid, [{cb_info, ?TCP_CB(Mod)} | Opts], Addrs); -i(accept, Ref, Mod, Pid, Opts, Addrs) -> +%% ... or not. +i(Type, Ref, Mod, Pid, _, Opts, Addrs) -> + i(Type, Ref, Mod, Pid, Opts, Addrs). + +i(accept = T, Ref, Mod, Pid, Opts, Addrs) -> {LAddr, LSock} = listener(Ref, {Mod, Opts, Addrs}), proc_lib:init_ack({ok, self(), [LAddr]}), Sock = ok(accept(Mod, LSock)), + publish(Mod, T, Ref, Sock), diameter_peer:up(Pid), Sock; -i(connect, _, Mod, Pid, Opts, Addrs) -> +i(connect = T, Ref, Mod, Pid, Opts, Addrs) -> {[LA, RA, RP], Rest} = proplists:split(Opts, [ip, raddr, rport]), LAddr = get_addr(LA, Addrs), RAddr = get_addr(RA, []), RPort = get_port(RP), proc_lib:init_ack({ok, self(), [LAddr]}), Sock = ok(connect(Mod, RAddr, RPort, gen_opts(LAddr, Rest))), + publish(Mod, T, Ref, Sock), diameter_peer:up(Pid, {RAddr, RPort}), Sock. +publish(Mod, T, Ref, Sock) -> + true = diameter_reg:add_new({?MODULE, T, {Ref, Sock}}), + putr(?INFO_KEY, {Mod, Sock}). %% for info/1 + ok({ok, T}) -> T; ok(No) -> @@ -227,6 +300,43 @@ gen_opts(LAddr, Opts) -> | Opts]. %% --------------------------------------------------------------------------- +%% # ports/1 +%% --------------------------------------------------------------------------- + +ports() -> + Ts = diameter_reg:match({?MODULE, '_', '_'}), + [{type(T), resolve(T,S), Pid} || {{?MODULE, T, {_,S}}, Pid} <- Ts]. + +ports(Ref) -> + Ts = diameter_reg:match({?MODULE, '_', {Ref, '_'}}), + [{type(T), resolve(T,S), Pid} || {{?MODULE, T, {R,S}}, Pid} <- Ts, + R == Ref]. + +type(listener) -> + listen; +type(T) -> + T. + +sock(listener, {_LAddr, Sock}) -> + Sock; +sock(_, Sock) -> + Sock. + +resolve(Type, S) -> + Sock = sock(Type, S), + try + ok(portnr(Sock)) + catch + _:_ -> Sock + end. + +portnr(Sock) + when is_port(Sock) -> + portnr(gen_tcp, Sock); +portnr(Sock) -> + portnr(ssl, Sock). + +%% --------------------------------------------------------------------------- %% # handle_call/3 %% --------------------------------------------------------------------------- @@ -258,6 +368,8 @@ handle_info(T, #monitor{} = S) -> %% # code_change/3 %% --------------------------------------------------------------------------- +code_change(_, {transport, _, _, _, _} = S, _) -> + {ok, #transport{} = list_to_tuple(tuple_to_list(S) ++ [false])}; code_change(_, State, _) -> {ok, State}. @@ -270,6 +382,12 @@ terminate(_, _) -> %% --------------------------------------------------------------------------- +putr(Key, Val) -> + put({?MODULE, Key}, Val). + +getr(Key) -> + get({?MODULE, Key}). + %% start_timer/1 start_timer(#listener{count = 0} = S) -> @@ -332,17 +450,56 @@ t(T,S) -> %% transition/2 +%% Initial incoming message when we might need to upgrade to TLS: +%% don't request another message until we know. +transition({tcp, Sock, Bin}, #transport{socket = Sock, + parent = Pid, + frag = Head, + module = M, + ssl = Opts} + = S) + when is_list(Opts) -> + case recv1(Head, Bin) of + {Msg, B} when is_binary(Msg) -> + diameter_peer:recv(Pid, Msg), + S#transport{frag = B}; + Frag -> + setopts(M, Sock), + S#transport{frag = Frag} + end; + %% Incoming message. -transition({tcp, Sock, Data}, #transport{socket = Sock, - module = M} - = S) -> +transition({P, Sock, Bin}, #transport{socket = Sock, + module = M, + ssl = B} + = S) + when P == tcp, not B; + P == ssl, B -> setopts(M, Sock), - recv(Data, S); + recv(Bin, S); + +%% Capabilties exchange has decided on whether or not to run over TLS. +transition({diameter, {tls, Ref, Type, B}}, #transport{parent = Pid} + = S) -> + #transport{socket = Sock, + module = M} + = NS + = tls_handshake(Type, B, S), + Pid ! {diameter, {tls, Ref}}, + setopts(M, Sock), + NS#transport{ssl = B}; -transition({tcp_closed, Sock}, #transport{socket = Sock}) -> +transition({C, Sock}, #transport{socket = Sock, + ssl = B}) + when C == tcp_closed, not B; + C == ssl_closed, B -> stop; -transition({tcp_error, Sock, _Reason} = T, #transport{socket = Sock} = S) -> +transition({E, Sock, _Reason} = T, #transport{socket = Sock, + ssl = B} + = S) + when E == tcp_error, not B; + E == ssl_error, B -> ?ERROR({T,S}); %% Outgoing message. @@ -367,10 +524,10 @@ transition({timeout, TRef, flush}, S) -> flush(TRef, S); %% Request for the local port number. -transition({resolve_port, RPid}, #transport{socket = Sock, - module = M}) - when is_pid(RPid) -> - RPid ! lport(M, Sock), +transition({resolve_port, Pid}, #transport{socket = Sock, + module = M}) + when is_pid(Pid) -> + Pid ! portnr(M, Sock), ok; %% Parent process has died. @@ -379,80 +536,122 @@ transition({'DOWN', _, process, Pid, _}, #transport{parent = Pid}) -> %% Crash on anything unexpected. +%% tls_handshake/3 +%% +%% In the case that no tls message is received (eg. the service hasn't +%% been configured to advertise TLS support) we will simply never ask +%% for another TCP message, which will force the watchdog to +%% eventually take us down. + +%% TLS has already been established with the connection. +tls_handshake(_, _, #transport{ssl = true} = S) -> + S; + +%% Capabilities exchange negotiated TLS but transport was not +%% configured with an options list. +tls_handshake(_, true, #transport{ssl = false}) -> + ?ERROR(no_ssl_options); + +%% Capabilities exchange negotiated TLS: upgrade the connection. +tls_handshake(Type, true, #transport{socket = Sock, + module = M, + ssl = Opts} + = S) -> + {ok, SSock} = tls(Type, Sock, [{cb_info, ?TCP_CB(M)} | Opts]), + Ref = getr(?REF_KEY), + is_reference(Ref) %% started in new code + andalso + (true = diameter_reg:add_new({?MODULE, Type, {Ref, SSock}})), + S#transport{socket = SSock, + module = ssl}; + +%% Capabilities exchange has not negotiated TLS. +tls_handshake(_, false, S) -> + S. + +tls(connect, Sock, Opts) -> + ssl:connect(Sock, Opts); +tls(accept, Sock, Opts) -> + ssl:ssl_accept(Sock, Opts). + %% recv/2 %% %% Reassemble fragmented messages and extract multple message sent %% using Nagle. recv(Bin, #transport{parent = Pid, frag = Head} = S) -> - S#transport{frag = recv(Pid, Head, Bin)}. + case recv1(Head, Bin) of + {Msg, B} when is_binary(Msg) -> + diameter_peer:recv(Pid, Msg), + recv(B, S#transport{frag = <<>>}); + Frag -> + S#transport{frag = Frag} + end. -%% recv/3 +%% recv1/2 %% No previous fragment. -recv(Pid, <<>>, Bin) -> - rcv(Pid, Bin); +recv1(<<>>, Bin) -> + rcv(Bin); -recv(Pid, {TRef, Head}, Bin) -> +recv1({TRef, Head}, Bin) -> erlang:cancel_timer(TRef), - rcv(Pid, Head, Bin). + rcv(Head, Bin). -%% rcv/3 +%% rcv/2 %% Not even the first four bytes of the header. -rcv(Pid, Head, Bin) +rcv(Head, Bin) when is_binary(Head) -> - rcv(Pid, <<Head/binary, Bin/binary>>); + rcv(<<Head/binary, Bin/binary>>); %% Or enough to know how many bytes to extract. -rcv(Pid, {Len, N, Head, Acc}, Bin) -> - rcv(Pid, Len, N + size(Bin), Head, [Bin | Acc]). +rcv({Len, N, Head, Acc}, Bin) -> + rcv(Len, N + size(Bin), Head, [Bin | Acc]). -%% rcv/5 +%% rcv/4 %% Extract a message for which we have all bytes. -rcv(Pid, Len, N, Head, Acc) +rcv(Len, N, Head, Acc) when Len =< N -> - rcv(Pid, rcv1(Pid, Len, bin(Head, Acc))); + rcv1(Len, bin(Head, Acc)); %% Wait for more packets. -rcv(_, Len, N, Head, Acc) -> +rcv(Len, N, Head, Acc) -> {start_timer(), {Len, N, Head, Acc}}. %% rcv/2 %% Nothing left. -rcv(_, <<>> = Bin) -> +rcv(<<>> = Bin) -> Bin; %% Well, this isn't good. Chances are things will go south from here %% but if we're lucky then the bytes we have extend to an intended %% message boundary and we can recover by simply discarding them, %% which is the result of receiving them. -rcv(Pid, <<_:1/binary, Len:24, _/binary>> = Bin) +rcv(<<_:1/binary, Len:24, _/binary>> = Bin) when Len < 20 -> - diameter_peer:recv(Pid, Bin), - <<>>; + {Bin, <<>>}; %% Enough bytes to extract a message. -rcv(Pid, <<_:1/binary, Len:24, _/binary>> = Bin) +rcv(<<_:1/binary, Len:24, _/binary>> = Bin) when Len =< size(Bin) -> - rcv(Pid, rcv1(Pid, Len, Bin)); + rcv1(Len, Bin); %% Or not: wait for more packets. -rcv(_, <<_:1/binary, Len:24, _/binary>> = Head) -> +rcv(<<_:1/binary, Len:24, _/binary>> = Head) -> {start_timer(), {Len, size(Head), Head, []}}; %% Not even 4 bytes yet. -rcv(_, Head) -> +rcv(Head) -> {start_timer(), Head}. -%% rcv1/3 +%% rcv1/2 -rcv1(Pid, Len, Bin) -> +rcv1(Len, Bin) -> <<Msg:Len/binary, Rest/binary>> = Bin, - diameter_peer:recv(Pid, Msg), - Rest. + {Msg, Rest}. %% bin/[12] @@ -489,15 +688,18 @@ flush(_, S) -> %% accept/2 -accept(gen_tcp, LSock) -> - gen_tcp:accept(LSock); +accept(ssl, LSock) -> + case ssl:transport_accept(LSock) of + {ok, Sock} -> + {ssl:ssl_accept(Sock), Sock}; + {error, _} = No -> + No + end; accept(Mod, LSock) -> Mod:accept(LSock). %% connect/4 -connect(gen_tcp, Host, Port, Opts) -> - gen_tcp:connect(Host, Port, Opts); connect(Mod, Host, Port, Opts) -> Mod:connect(Host, Port, Opts). @@ -505,6 +707,8 @@ connect(Mod, Host, Port, Opts) -> send(gen_tcp, Sock, Bin) -> gen_tcp:send(Sock, Bin); +send(ssl, Sock, Bin) -> + ssl:send(Sock, Bin); send(M, Sock, Bin) -> M:send(Sock, Bin). @@ -512,6 +716,8 @@ send(M, Sock, Bin) -> setopts(gen_tcp, Sock, Opts) -> inet:setopts(Sock, Opts); +setopts(ssl, Sock, Opts) -> + ssl:setopts(Sock, Opts); setopts(M, Sock, Opts) -> M:setopts(Sock, Opts). @@ -523,9 +729,36 @@ setopts(M, Sock) -> X -> x({setopts, M, Sock, X}) %% possibly on peer disconnect end. -%% lport/2 +%% portnr/2 -lport(gen_tcp, Sock) -> +portnr(gen_tcp, Sock) -> inet:port(Sock); -lport(M, Sock) -> - M:port(Sock). +portnr(M, Sock) -> + case M:sockname(Sock) of + {ok, {_Addr, PortNr}} -> + {ok, PortNr}; + {error, _} = No -> + No + end. + +%% sockname/2 + +sockname(gen_tcp, Sock) -> + inet:sockname(Sock); +sockname(M, Sock) -> + M:sockname(Sock). + +%% peername/2 + +peername(gen_tcp, Sock) -> + inet:peername(Sock); +peername(M, Sock) -> + M:peername(Sock). + +%% getstat/2 + +getstat(gen_tcp, Sock) -> + inet:getstat(Sock); +getstat(M, Sock) -> + M:getstat(Sock). +%% Note that ssl:getstat/1 doesn't yet exist in R15B01. diff --git a/lib/diameter/src/transport/diameter_transport.erl b/lib/diameter/src/transport/diameter_transport.erl new file mode 100644 index 0000000000..ff4b6bbc6d --- /dev/null +++ b/lib/diameter/src/transport/diameter_transport.erl @@ -0,0 +1,55 @@ +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2012. 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% +%% + +-module(diameter_transport). + +%% +%% This module implements a transport start function that +%% evaluates its config argument. +%% + +%% Transport start functions +-export([start/3, + select/3, + eval/3]). + +%% start/3 + +%% Call a start function in this module ... +start(T, Svc, {F,A}) -> + start(T, Svc, {?MODULE, F, [A]}); + +%% ... or some other. +start(T, Svc, F) -> + diameter_lib:eval([F, T, Svc]). + +%% select/3 +%% +%% A start function that whose config argument is expected to return a +%% new start function. + +select(T, Svc, F) -> + start(T, Svc, diameter_lib:eval([F, T, Svc])). + +%% eval/3 +%% +%% A start function that simply evaluates its config argument. + +eval(_, _, F) -> + diameter_lib:eval(F). diff --git a/lib/diameter/src/transport/modules.mk b/lib/diameter/src/transport/modules.mk deleted file mode 100644 index a0dc3cf2c0..0000000000 --- a/lib/diameter/src/transport/modules.mk +++ /dev/null @@ -1,29 +0,0 @@ -#-*-makefile-*- ; force emacs to enter makefile-mode - -# %CopyrightBegin% -# -# Copyright Ericsson AB 2010-2011. 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% - -MODULES = \ - diameter_etcp \ - diameter_etcp_sup \ - diameter_tcp \ - diameter_tcp_sup \ - diameter_sctp \ - diameter_sctp_sup \ - diameter_transport_sup - -HRL_FILES = diff --git a/lib/diameter/test/Makefile b/lib/diameter/test/Makefile index dba1f126dc..866d135bd9 100644 --- a/lib/diameter/test/Makefile +++ b/lib/diameter/test/Makefile @@ -1,7 +1,7 @@ # # %CopyrightBegin% # -# Copyright Ericsson AB 2010-2011. All Rights Reserved. +# Copyright Ericsson AB 2010-2012. 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 @@ -16,15 +16,8 @@ # # %CopyrightEnd% -ifeq ($(ERL_TOP),) -TOP = $(DIAMETER_TOP) -else -TOP = $(ERL_TOP) -DIAMETER_TOP = $(TOP)/lib/diameter -endif - -include $(TOP)/make/target.mk -include $(TOP)/make/$(TARGET)/otp.mk +include $(ERL_TOP)/make/target.mk +include $(ERL_TOP)/make/$(TARGET)/otp.mk # ---------------------------------------------------- # Application version @@ -46,38 +39,39 @@ RELSYSDIR = $(RELEASE_PATH)/diameter_test include modules.mk -EBIN = . - -HRL_FILES = $(INTERNAL_HRL_FILES) -ERL_FILES = $(MODULES:%=%.erl) - -SOURCE = $(HRL_FILES) $(ERL_FILES) +ERL_FILES = $(MODULES:%=%.erl) TARGET_FILES = $(MODULES:%=%.$(EMULATOR)) SUITE_MODULES = $(filter diameter_%_SUITE, $(MODULES)) -SUITES = $(SUITE_MODULES:diameter_%_SUITE=%) +SUITES = $(SUITE_MODULES:diameter_%_SUITE=%) -RELTEST_FILES = $(TEST_SPEC_FILE) $(COVER_SPEC_FILE) $(SOURCE) +DATA_DIRS = $(sort $(dir $(DATA))) # ---------------------------------------------------- # FLAGS # ---------------------------------------------------- -include ../src/app/diameter.mk - # This is only used to compile suite locally when running with a # target like 'all' below. Target release_tests only installs source. -ERL_COMPILE_FLAGS += $(DIAMETER_ERL_COMPILE_FLAGS) \ - -DDIAMETER_CT=true \ - -I $(DIAMETER_TOP)/src/app +ERL_COMPILE_FLAGS += +warn_export_vars \ + +warn_unused_vars \ + -I ../include \ + -I ../src/gen # ---------------------------------------------------- # Targets # ---------------------------------------------------- -all: $(SUITES) +# Require success ... +all: opt -tests debug opt: $(TARGET_FILES) +# ... or not. +any: opt + $(MAKE) -i $(SUITES) + +run: $(SUITES) + +debug opt: $(TARGET_FILES) clean: rm -f $(TARGET_FILES) @@ -85,66 +79,56 @@ clean: realclean: clean rm -rf log - rm -f errs core *~ - -.PHONY: all tests debug opt clean realclean docs: +list = echo $(1):; echo $($(1)) | tr ' ' '\n' | sort | sed 's@^@ @' + info: - @echo "TARGET_FILES = $(TARGET_FILES)" + @echo ======================================== + @$(call list,MODULES) @echo - @echo "ERL_COMPILE_FLAGS = $(ERL_COMPILE_FLAGS)" - @echo "ERL = $(ERL)" - @echo "ERLC = $(ERLC)" - @echo - @echo "HRL_FILES = $(HRL_FILES)" - @echo "ERL_FILES = $(ERL_FILES)" - @echo "TARGET_FILES = $(TARGET_FILES)" - @echo - @echo "SUITE_MODULES = $(SUITE_MODULES)" - @echo "SUITES = $(SUITES)" + @$(call list,HRL_FILES) @echo + @$(call list,SUITES) + @echo ======================================== help: + @echo ======================================== + @echo "Useful targets:" @echo - @echo "Targets:" + @echo " all:" + @echo " Compile all test suites." @echo - @echo " all" - @echo " Run all test suites." + @echo " run:" + @echo " Compile and run all test suites." @echo - @echo " $(SUITES)" - @echo " Run a specific test suite." + @echo " $(SUITES):" + @echo " Compile and run a specific test suite." @echo - @echo " tests" - @echo " Compile all test-code." - @echo - @echo " clean | realclean" + @echo " clean | realclean:" @echo " Remove generated files." @echo - @echo " info" - @echo " Prints various environment variables." - @echo " May be useful when debugging this Makefile." - @echo - @echo " help" - @echo " Print this info." - @echo + @echo " info:" + @echo " Echo some relevant variables." + @echo ======================================== -.PHONY: docs info help +.PHONY: all any run clean debug docs help info opt realclean # ---------------------------------------------------- # Special Targets # ---------------------------------------------------- # Exit with a non-zero status if the output looks to indicate failure. -# diameter_ct:run/1 itself can't tell (it seems). -$(SUITES): log tests - $(ERL) -noshell \ - -pa $(DIAMETER_TOP)/ebin \ - -sname diameter_test_$@ \ - -s diameter_ct run diameter_$@_SUITE \ - -s init stop \ - | awk '1{rc=0} {print} / FAILED /{rc=1} END{exit rc}' +# diameter_ct:run/1 itself can't tell (it seems). The absolute -pa is +# because ct will change directories. +$(SUITES): log opt + $(ERL) -noinput \ + -pa $(realpath ../ebin) \ + -sname diameter_test_$@ \ + -s diameter_ct run diameter_$@_SUITE \ + -s init stop \ + | awk '{print} / FAILED /{rc=1} END{exit rc}' rc=0 # Shorter in sed but requires a GNU extension (ie. Q). log: @@ -156,17 +140,34 @@ log: # Release Targets # ---------------------------------------------------- -include $(TOP)/make/otp_release_targets.mk +/%: % force + sed -f release.sed $< > "$(RELSYSDIR)$@" -release_spec: +include $(ERL_TOP)/make/otp_release_targets.mk -release_docs_spec: +release_spec release_docs_spec: release_tests_spec: - $(INSTALL_DIR) $(RELSYSDIR) - $(INSTALL_DATA) $(RELTEST_FILES) $(RELSYSDIR) + $(INSTALL_DIR) "$(RELSYSDIR)" + $(INSTALL_DATA) $(TEST_SPEC_FILE) \ + $(COVER_SPEC_FILE) \ + $(HRL_FILES) \ + "$(RELSYSDIR)" + $(MAKE) $(DATA_DIRS:%/=release_data_%) + $(MAKE) $(ERL_FILES:%=/%) + +$(DATA_DIRS:%/=release_data_%): release_data_%: + $(INSTALL_DIR) "$(RELSYSDIR)/$*" + $(INSTALL_DATA) $(filter $*/%, $(DATA)) "$(RELSYSDIR)/$*" + +force: .PHONY: release_spec release_docs_spec release_test_specs +.PHONY: force +.PHONY: $(DATA_DIRS:%/=release_data_%) + +# Can't just make $(ERL_FILES:%=/%) phony since then implicit rule +# searching is skipped. # ---------------------------------------------------- @@ -175,7 +176,7 @@ depend: depend.mk # Generate dependencies makefile. depend.mk: depend.sed $(MODULES:%=%.erl) Makefile (for f in $(MODULES); do \ - sed -f $< $$f.erl | sed "s@/@/$$f@"; \ + (echo $$f; cat $$f.erl) | sed -f $<; \ done) \ > $@ diff --git a/lib/diameter/test/depend.sed b/lib/diameter/test/depend.sed index a399eb45f0..95dca44984 100644 --- a/lib/diameter/test/depend.sed +++ b/lib/diameter/test/depend.sed @@ -18,14 +18,24 @@ # # -# Extract local include dependencies from .erl files. The output is massaged -# further in Makefile. +# Extract local include dependencies from an .erl file. The first +# input line is the module name. # -/^-include/!d +# Store the module name in the hold space. +1{ + h + d +} + +# Throw away everything but local includes. /^-include_lib/d +/^-include/!d /diameter_gen/d +/diameter\./d +# Output a dependency of the beam on the included file. s@^-include("@@ s@".*@@ -s@^@$(EBIN)/.$(EMULATOR): @ +G +s@^\(.*\)\n\(.*\)@$(EBIN)/\2.$(EMULATOR): \1@ diff --git a/lib/diameter/test/diameter_app_SUITE.erl b/lib/diameter/test/diameter_app_SUITE.erl index 104785b4e6..53332af626 100644 --- a/lib/diameter/test/diameter_app_SUITE.erl +++ b/lib/diameter/test/diameter_app_SUITE.erl @@ -41,6 +41,19 @@ -define(A, list_to_atom). +%% Modules not in the app and that should not have dependencies on it +%% for build reasons. +-define(COMPILER_MODULES, [diameter_codegen, + diameter_dict_scanner, + diameter_dict_parser, + diameter_dict_util, + diameter_exprecs, + diameter_nowarn, + diameter_make]). + +-define(HELP_MODULES, [diameter_dbg, + diameter_info]). + %% =========================================================================== suite() -> @@ -93,13 +106,8 @@ vsn(Config) -> modules(Config) -> Mods = fetch(modules, fetch(app, Config)), Installed = code_mods(), - Help = [diameter_callback, - diameter_codegen, - diameter_dbg, - diameter_exprecs, - diameter_info, - diameter_spec_scan, - diameter_spec_util], + Help = lists:sort(?HELP_MODULES ++ ?COMPILER_MODULES), + {[], Help} = {Mods -- Installed, lists:sort(Installed -- Mods)}. code_mods() -> @@ -133,13 +141,16 @@ release(Config) -> Rel = {release, {"diameter test release", fetch(vsn, App)}, {erts, erlang:system_info(version)}, - [{A, appvsn(A)} || A <- fetch(applications, App)]}, + [{A, appvsn(A)} || A <- [sasl | fetch(applications, App)]]}, Dir = fetch(priv_dir, Config), ok = write_file(filename:join([Dir, "diameter_test.rel"]), Rel), {ok, _, []} = systools:make_script("diameter_test", [{path, [Dir]}, {outdir, Dir}, silent]). +%% sasl need to be included to avoid a missing_sasl warning, error +%% in the case of relup/1. + appvsn(Name) -> [{application, Name, App}] = diameter_util:consult(Name, app), fetch(vsn, App). @@ -147,14 +158,13 @@ appvsn(Name) -> %% =========================================================================== %% # xref/1 %% -%% Ensure that no function in our application calls an undefined function. +%% Ensure that no function in our application calls an undefined function +%% or one in an application we haven't specified as a dependency. (Almost.) %% =========================================================================== xref(Config) -> App = fetch(app, Config), - Mods = fetch(modules, App) -- [diameter_codegen, diameter_dbg], - %% Skip modules that aren't required at runtime and that have - %% dependencies beyond those applications listed in the app file. + Mods = fetch(modules, App), {ok, XRef} = xref:start(make_name(xref_test_name)), ok = xref:set_default(XRef, [{verbose, false}, {warnings, false}]), @@ -164,16 +174,35 @@ xref(Config) -> %% stop xref from complaining about calls to module erlang, which %% was previously in kernel. Erts isn't an application however, in %% the sense that there's no .app file, and isn't listed in - %% applications. Seems less than ideal. + %% applications. ok = lists:foreach(fun(A) -> add_application(XRef, A) end, [?APP, erts | fetch(applications, App)]), {ok, Undefs} = xref:analyze(XRef, undefined_function_calls), + {ok, Called} = xref:analyze(XRef, {module_call, ?COMPILER_MODULES}), xref:stop(XRef), %% Only care about calls from our own application. - [] = lists:filter(fun({{M,_,_},_}) -> lists:member(M, Mods) end, Undefs). + [] = lists:filter(fun({{F,_,_},{T,_,_}}) -> + lists:member(F, Mods) + andalso {F,T} /= {diameter_tcp, ssl} + end, + Undefs), + %% 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). + +%% 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). add_application(XRef, App) -> add_application(XRef, App, code:lib_dir(App)). @@ -201,7 +230,7 @@ relup(Config) -> App = fetch(app, Config), Rel = [{erts, erlang:system_info(version)} - | [{A, appvsn(A)} || A <- fetch(applications, App)]], + | [{A, appvsn(A)} || A <- [sasl | fetch(applications, App)]]], Dir = fetch(priv_dir, Config), @@ -209,12 +238,15 @@ relup(Config) -> UpFrom = acc_rel(Dir, Rel, Up), DownTo = acc_rel(Dir, Rel, Down), - {[Name], [Name], UpFrom, DownTo} %% no intersections + {[Name], [Name], [], []} %% no current in up/down and go both ways = {[Name] -- UpFrom, [Name] -- DownTo, UpFrom -- DownTo, DownTo -- UpFrom}, + [[], []] = [S -- sets:to_list(sets:from_list(S)) + || S <- [UpFrom, DownTo]], + {ok, _, _, []} = systools:make_relup(Name, UpFrom, DownTo, [{path, [Dir]}, {outdir, Dir}, silent]). diff --git a/lib/diameter/test/diameter_capx_SUITE.erl b/lib/diameter/test/diameter_capx_SUITE.erl new file mode 100644 index 0000000000..ae128b8203 --- /dev/null +++ b/lib/diameter/test/diameter_capx_SUITE.erl @@ -0,0 +1,420 @@ +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2010-2012. 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% +%% + +%% +%% Tests of capabilities exchange between Diameter nodes. In +%% particular, of error and event handling. +%% + +-module(diameter_capx_SUITE). + +-export([suite/0, + all/0, + groups/0, + init_per_testcase/2, + end_per_testcase/2]). + +%% testcases +-export([start/1, + start_services/1, + add_listeners/1, + s_no_common_application/1, + c_no_common_application/1, + s_no_common_security/1, + c_no_common_security/1, + s_unknown_peer/1, + c_unknown_peer/1, + s_unable/1, + c_unable/1, + s_client_reject/1, + c_client_reject/1, + remove_listeners/1, + stop_services/1, + stop/1]). + +%% diameter callbacks +-export([peer_up/4, + peer_down/4]). + +-include("diameter.hrl"). +-include("diameter_gen_base_rfc3588.hrl"). + +%% =========================================================================== + +-define(util, diameter_util). + +-define(CLIENT, client). +-define(SERVER, server). + +-define(ADDR, {127,0,0,1}). + +-define(REALM, "erlang.org"). +-define(HOST(Name), Name ++ "." ++ ?REALM). + +%% Config for diameter:start_service/2. +-define(SERVICE(Name), + [{'Origin-Realm', ?REALM}, + {'Host-IP-Address', [?ADDR]}, + {'Vendor-Id', 12345}, + {'Product-Name', "OTP/diameter"}, + {'Auth-Application-Id', [?DIAMETER_APP_ID_COMMON]}, + {'Acct-Application-Id', [?DIAMETER_APP_ID_ACCOUNTING]} + | [{application, [{alias, A}, + {dictionary, D}, + {module, [?MODULE, A]}]} + || {A,D} <- [{common, ?DIAMETER_DICT_COMMON}, + {accounting, ?DIAMETER_DICT_ACCOUNTING}]]]). + +-define(A, list_to_atom). +-define(L, atom_to_list). + +-define(event, #diameter_event). +-define(caps, #diameter_caps). +-define(packet, #diameter_packet). + +-define(cea, #diameter_base_CEA). +-define(answer_message, #'diameter_base_answer-message'). + +-define(fail(T), erlang:error({T, process_info(self(), messages)})). + +-define(TIMEOUT, 10000). + +%% =========================================================================== + +suite() -> + [{timetrap, {seconds, 60}}]. + +all() -> [start, + start_services, + add_listeners, + {group, all}, + {group, all, [parallel]}, + remove_listeners, + stop_services, + stop]. + +groups() -> + [{all, [], lists:flatmap(fun tc/1, tc())}]. + +%% 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]. + +end_per_testcase(N, _) + when N == start; + N == start_services; + N == add_listeners; + N == remove_listeners; + N == stop_services; + N == stop -> + ok; +end_per_testcase(Name, Config) -> + CRef = ?util:read_priv(Config, Name), + ok = diameter:remove_transport(?CLIENT, CRef). + +%% Testcases all come in two flavours, client and server. +tc(Name) -> + [?A([C,$_|?L(Name)]) || C <- "cs"]. + +tc() -> + [no_common_application, + no_common_security, + unknown_peer, + unable, + client_reject]. + +%% =========================================================================== +%% start/stop testcases + +start(_Config) -> + ok = diameter:start(). + +start_services(_Config) -> + ok = diameter:start_service(?SERVER, ?SERVICE(?SERVER)), + ok = diameter:start_service(?CLIENT, ?SERVICE(?CLIENT)). + +%% One server that responds only to base accounting, one that responds +%% to both this and the common application. Share a common service just +%% to simplify config, and because we can. +add_listeners(Config) -> + Acct = listen(?SERVER, + [{capabilities, [{'Origin-Host', ?HOST("acct-srv")}, + {'Auth-Application-Id', []}]}, + {applications, [accounting]}, + {capabilities_cb, [fun server_capx/3, acct]}]), + Base = listen(?SERVER, + [{capabilities, [{'Origin-Host', ?HOST("base-srv")}]}, + {capabilities_cb, [fun server_capx/3, base]}]), + ?util:write_priv(Config, ?MODULE, {Base, Acct}). %% lref/2 reads + +remove_listeners(_Config) -> + ok = diameter:remove_transport(?SERVER, true). + +stop_services(_Config) -> + ok = diameter:stop_service(?CLIENT), + ok = diameter:stop_service(?SERVER). + +stop(_Config) -> + ok = diameter:stop(). + +%% =========================================================================== +%% All the testcases come in pairs, one for receiving an event on the +%% client side, one on the server side. Note that testcases will +%% receive events resulting from other testcases when running in +%% parallel since the events are per service. The unique client +%% Origin-Host for each testcase plus transport references are used to +%% ensure that only the relevant event is extracted from the mailbox. +%% Don't bother extracting events that aren't relevant. + +%% ==================== +%% Ask the accounting server to speak the common application and expect +%% DIAMETER_NO_COMMON_APPLICATION = 5010. + +s_no_common_application(Config) -> + server_closed(Config, fun no_common_application/1, 5010). + +c_no_common_application(Config) -> + client_closed(Config, "acct-srv", fun no_common_application/1, 5010). + +no_common_application(Config) -> + connect(Config, acct, [{capabilities, [{'Acct-Application-Id', []}]}, + {applications, [common]}]). + +%% ==================== +%% Ask the base server to speak accounting with an unknown security +%% method and expect DIAMETER_NO_COMMON_SECURITY = 5017. + +s_no_common_security(Config) -> + server_closed(Config, fun no_common_security/1, 5017). + +c_no_common_security(Config) -> + client_closed(Config, "base-srv", fun no_common_security/1, 5017). + +no_common_security(Config) -> + connect(Config, base, [{capabilities, [{'Acct-Application-Id', []}, + {'Inband-Security-Id', [17, 18]}]}, + {applications, [common]}]). + +%% ==================== +%% Have the base server reject a decent CER with the protocol error +%% DIAMETER_UNKNOWN_PEER = 3010. + +s_unknown_peer(Config) -> + server_reject(Config, fun base/1, 3010). + +c_unknown_peer(Config) -> + true = diameter:subscribe(?CLIENT), + OH = ?HOST("base-srv"), + + {CRef, _} = base(Config), + + {'CEA', ?caps{}, + ?packet{msg = ?answer_message{'Origin-Host' = OH, + 'Result-Code' = 3010}}} + = client_recv(CRef). + +base(Config) -> + connect(Config, base, []). + +%% ==================== +%% Have the base server reject a decent CER with the non-protocol +%% error DIAMETER_UNABLE_TO_COMPLY = 5012. + +s_unable(Config) -> + server_reject(Config, fun base/1, 5012). + +c_unable(Config) -> + client_closed(Config, "base-srv", fun base/1, 5012). + +%% ==================== +%% Have the client reject a decent CEA. + +s_client_reject(Config) -> + true = diameter:subscribe(?SERVER), + OH = host(Config), + + {_, LRef} = client_reject(Config), + + receive + ?event{service = ?SERVER, + info = {up, LRef, + {_, ?caps{origin_host = {_, OH}}}, + {listen, _}, + ?packet{}}} + = Info -> + Info + after ?TIMEOUT -> + ?fail({LRef, OH}) + end. + +c_client_reject(Config) -> + true = diameter:subscribe(?CLIENT), + OH = ?HOST("acct-srv"), + + {CRef, _} = client_reject(Config), + + {'CEA', {capabilities_cb, _, discard}, + ?caps{origin_host = {_, OH}}, + ?packet{msg = ?cea{'Result-Code' = 2001}}} + = client_recv(CRef). + +client_reject(Config) -> + connect(Config, acct, [{capabilities_cb, fun client_capx/2}]). + +%% =========================================================================== + +%% server_closed/3 + +server_closed(Config, F, RC) -> + true = diameter:subscribe(?SERVER), + OH = host(Config), + + {_, LRef} = F(Config), + + receive + ?event{service = ?SERVER, + info = {closed, LRef, + {'CER', RC, + ?caps{origin_host = {_, OH}}, + ?packet{}} + = Reason, + {listen, _}}} -> + Reason + after ?TIMEOUT -> + ?fail({LRef, OH}) + end. + +%% server_reject/3 + +server_reject(Config, F, RC) -> + true = diameter:subscribe(?SERVER), + OH = host(Config), + + {_, LRef} = F(Config), + + receive + ?event{service = ?SERVER, + info = {closed, LRef, + {'CER', {capabilities_cb, _, RC}, + ?caps{origin_host = {_, OH}}, + ?packet{}} + = Reason, + {listen, _}}} -> + Reason + after ?TIMEOUT -> + ?fail({LRef, OH}) + end. + +%% cliient_closed/4 + +client_closed(Config, Host, F, RC) -> + true = diameter:subscribe(?CLIENT), + OH = ?HOST(Host), + + {CRef, _} = F(Config), + + {'CEA', RC, ?caps{origin_host = {_, OH}}, ?packet{}} + = client_recv(CRef). + +%% client_recv/1 + +client_recv(CRef) -> + receive + ?event{service = ?CLIENT, + info = {closed, CRef, Reason, {connect, _}}} -> + Reason + after ?TIMEOUT -> + ?fail(CRef) + end. + +%% server_capx/3 + +server_capx(_, ?caps{origin_host = {_, [_,$_|"unknown_peer." ++ _]}}, _) -> + unknown; + +server_capx(_, ?caps{origin_host = {_, [_,$_|"unable." ++ _]}}, _) -> + 5012; %% DIAMETER_UNABLE_TO_COMPLY + +server_capx(_, ?caps{origin_host = {OH,DH}}, _) -> + io:format("connection: ~p -> ~p~n", [DH,OH]), + ok. + +%% client_capx/2 + +client_capx(_, ?caps{origin_host = {[_,$_|"client_reject." ++ _], _}}) -> + discard. + +%% =========================================================================== + +host(Config) -> + {_, H} = lists:keyfind(host, 1, Config), + ?HOST(H). + +listen(Name, Opts) -> + ?util:listen(Name, tcp, Opts). + +connect(Config, T, Opts) -> + {_, H} = lists:keyfind(host, 1, Config), + LRef = lref(Config, T), + CRef = connect(LRef, [{capabilities, [{'Origin-Host', ?HOST(H)}]} + | Opts]), + Name = lists:takewhile(fun(C) -> C /= $. end, H), + ?util:write_priv(Config, Name, CRef), %% end_per_testcase reads + {CRef, LRef}. + +connect(LRef, Opts) -> + [PortNr] = ?util:lport(tcp, LRef, 20), + {ok, CRef} = diameter:add_transport(?CLIENT, + {connect, opts(PortNr, Opts)}), + CRef. + +opts(PortNr, Opts) -> + [{transport_module, diameter_tcp}, + {transport_config, [{raddr, ?ADDR}, + {rport, PortNr}, + {ip, ?ADDR}, + {port, 0}]} + | Opts]. + +lref(Config, T) -> + case ?util:read_priv(Config, ?MODULE) of + {LRef, _} when T == base -> + LRef; + {_, LRef} when T == acct -> + LRef + end. + +%% =========================================================================== +%% diameter callbacks + +peer_up(?SERVER, + {_, ?caps{origin_host = {"acct-srv." ++ _, + [_,$_|"client_reject." ++ _]}}}, + State, + _) -> + State. + +peer_down(?SERVER, + {_, ?caps{origin_host = {"acct-srv." ++ _, + [_,$_|"client_reject." ++ _]}}}, + State, + _) -> + State. diff --git a/lib/diameter/test/diameter_codec_SUITE.erl b/lib/diameter/test/diameter_codec_SUITE.erl index 30c60be8e9..2e219bbb10 100644 --- a/lib/diameter/test/diameter_codec_SUITE.erl +++ b/lib/diameter/test/diameter_codec_SUITE.erl @@ -35,7 +35,8 @@ %% testcases -export([base/1, gen/1, - lib/1]). + lib/1, + unknown/1]). -include("diameter_ct.hrl"). @@ -47,7 +48,7 @@ suite() -> [{timetrap, {seconds, 10}}]. all() -> - [base, gen, lib]. + [base, gen, lib, unknown]. init_per_testcase(gen, Config) -> [{application, ?APP, App}] = diameter_util:consult(?APP, app), @@ -74,3 +75,26 @@ gen([{dicts, Ms} | _]) -> lib(_Config) -> diameter_codec_test:lib(). + +%% Have a separate AVP dictionary just to exercise more code. +unknown(Config) -> + Priv = proplists:get_value(priv_dir, Config), + Data = proplists:get_value(data_dir, Config), + ok = make(Data, "recv.dia"), + ok = make(Data, "avps.dia"), + {ok, _, _} = compile("diameter_test_avps.erl"), + ok = make(Data, "send.dia"), + {ok, _, _} = compile("diameter_test_send.erl"), + {ok, _, _} = compile("diameter_test_recv.erl"), + {ok, _, _} = compile(filename:join([Data, "diameter_test_unknown.erl"]), + [{i, Priv}]), + diameter_test_unknown:run(). + +make(Dir, File) -> + diameter_make:codec(filename:join([Dir, File])). + +compile(File) -> + compile(File, []). + +compile(File, Opts) -> + compile:file(File, [return | Opts]). diff --git a/lib/diameter/test/diameter_codec_SUITE_data/avps.dia b/lib/diameter/test/diameter_codec_SUITE_data/avps.dia new file mode 100644 index 0000000000..c9d80a37a9 --- /dev/null +++ b/lib/diameter/test/diameter_codec_SUITE_data/avps.dia @@ -0,0 +1,25 @@ +;; +;; %CopyrightBegin% +;; +;; Copyright Ericsson AB 2010-2011. 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% +;; + +@name diameter_test_avps + +@avp_types + + XXX 111 Unsigned32 M + YYY 222 Unsigned32 - diff --git a/lib/diameter/test/diameter_codec_SUITE_data/diameter_test_unknown.erl b/lib/diameter/test/diameter_codec_SUITE_data/diameter_test_unknown.erl new file mode 100644 index 0000000000..bce3d78a37 --- /dev/null +++ b/lib/diameter/test/diameter_codec_SUITE_data/diameter_test_unknown.erl @@ -0,0 +1,76 @@ +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2010-2011. 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% +%% + +-module(diameter_test_unknown). + +-compile(export_all). + +%% +%% Test reception of unknown AVP's. +%% + +-include_lib("diameter/include/diameter.hrl"). +-include("diameter_test_send.hrl"). +-include("diameter_test_recv.hrl"). + +-define(HOST, "test.erlang.org"). +-define(REALM, "erlang.org"). + +%% Patterns to match decoded AVP's. +-define(MANDATORY_XXX, #diameter_avp{code = 111}). +-define(NOT_MANDATORY_YYY, #diameter_avp{code = 222}). + +%% Ensure that an unknown AVP with an M flag is regarded as an error +%% while one without an M flag is returned as 'AVP'. + +run() -> + H = #diameter_header{version = 1, + end_to_end_id = 1, + hop_by_hop_id = 1}, + Vs = [{'Origin-Host', ?HOST}, + {'Origin-Realm', ?REALM}, + {'XXX', [0]}, + {'YYY', [1]}], + Pkt = #diameter_packet{header = H, + msg = Vs}, + + [] = diameter_util:run([{?MODULE, [run, M, enc(M, Pkt)]} + || M <- ['AR','BR']]). + +enc(M, #diameter_packet{msg = Vs} = P) -> + diameter_codec:encode(diameter_test_send, + P#diameter_packet{msg = [M|Vs]}). + +run(M, Pkt) -> + dec(M, diameter_codec:decode(diameter_test_recv, Pkt)). +%% Note that the recv dictionary defines neither XXX nor YYY. + +dec('AR', #diameter_packet + {msg = #recv_AR{'Origin-Host' = ?HOST, + 'Origin-Realm' = ?REALM, + 'AVP' = [?NOT_MANDATORY_YYY]}, + errors = [{5001, ?MANDATORY_XXX}]}) -> + ok; + +dec('BR', #diameter_packet + {msg = #recv_BR{'Origin-Host' = ?HOST, + 'Origin-Realm' = ?REALM}, + errors = [{5008, ?NOT_MANDATORY_YYY}, + {5001, ?MANDATORY_XXX}]}) -> + ok. diff --git a/lib/diameter/test/diameter_codec_SUITE_data/recv.dia b/lib/diameter/test/diameter_codec_SUITE_data/recv.dia new file mode 100644 index 0000000000..15fec5a5dd --- /dev/null +++ b/lib/diameter/test/diameter_codec_SUITE_data/recv.dia @@ -0,0 +1,51 @@ +;; +;; %CopyrightBegin% +;; +;; Copyright Ericsson AB 2010-2011. 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% +;; + +@id 17 +@name diameter_test_recv +@prefix recv + +@inherits diameter_gen_base_rfc3588 + + Origin-Host + Origin-Realm + Result-Code + +@messages + + AR ::= < Diameter Header: 123, REQ > + { Origin-Host } + { Origin-Realm } + * [ AVP ] + + AA ::= < Diameter Header: 123 > + { Result-Code } + { Origin-Host } + { Origin-Realm } + * [ AVP ] + + BR ::= < Diameter Header: 124, REQ > + { Origin-Host } + { Origin-Realm } + + BA ::= < Diameter Header: 124 > + { Result-Code } + { Origin-Host } + { Origin-Realm } + * [ AVP ] diff --git a/lib/diameter/test/diameter_codec_SUITE_data/send.dia b/lib/diameter/test/diameter_codec_SUITE_data/send.dia new file mode 100644 index 0000000000..1472f146ae --- /dev/null +++ b/lib/diameter/test/diameter_codec_SUITE_data/send.dia @@ -0,0 +1,56 @@ +;; +;; %CopyrightBegin% +;; +;; Copyright Ericsson AB 2010-2011. 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% +;; + +@id 17 +@name diameter_test_send +@prefix send + +@inherits diameter_gen_base_rfc3588 + + Origin-Host + Origin-Realm + Result-Code + +@inherits diameter_test_avps + +@messages + + AR ::= < Diameter Header: 123, REQ > + { Origin-Host } + { Origin-Realm } + [ XXX ] + [ YYY ] + + AA ::= < Diameter Header: 123 > + { Result-Code } + { Origin-Host } + { Origin-Realm } + * [ AVP ] + + BR ::= < Diameter Header: 124, REQ > + { Origin-Host } + { Origin-Realm } + [ XXX ] + [ YYY ] + + BA ::= < Diameter Header: 124 > + { Result-Code } + { Origin-Host } + { Origin-Realm } + * [ AVP ] diff --git a/lib/diameter/test/diameter_codec_test.erl b/lib/diameter/test/diameter_codec_test.erl index aab7ab35cc..fbd38067a8 100644 --- a/lib/diameter/test/diameter_codec_test.erl +++ b/lib/diameter/test/diameter_codec_test.erl @@ -25,11 +25,14 @@ %% Test encode/decode of dictionary-related modules. %% --include_lib("diameter/include/diameter.hrl"). +-include("diameter.hrl"). -define(BASE, diameter_gen_base_rfc3588). -define(BOOL, [true, false]). +-define(A, list_to_atom). +-define(S, atom_to_list). + %% =========================================================================== %% Interface. @@ -42,7 +45,7 @@ gen(Mod) -> command_codes, avp_types, grouped, - enums, + enum, import_avps, import_groups, import_enums]]). @@ -133,7 +136,7 @@ types() -> gen(M, T) -> [] = run(lists:map(fun(X) -> {?MODULE, [gen, M, T, X]} end, - fetch(T, M:dict()))). + fetch(T, dict(M)))). fetch(T, Spec) -> case orddict:find(T, Spec) of @@ -143,6 +146,10 @@ fetch(T, Spec) -> [] end. +gen(M, messages = T, {Name, Code, Flags, ApplId, Avps}) + when is_list(Name) -> + gen(M, T, {?A(Name), Code, Flags, ApplId, Avps}); + gen(M, messages, {Name, Code, Flags, _, _}) -> Rname = M:msg2rec(Name), Name = M:rec2msg(Rname), @@ -156,22 +163,16 @@ gen(M, messages, {Name, Code, Flags, _, _}) -> end, [] = arity(M, Name, Rname); -gen(M, command_codes = T, {Code, {Req, Abbr}, Ans}) -> - Rname = M:msg2rec(Req), - Rname = M:msg2rec(Abbr), - gen(M, T, {Code, Req, Ans}); - -gen(M, command_codes = T, {Code, Req, {Ans, Abbr}}) -> - Rname = M:msg2rec(Ans), - Rname = M:msg2rec(Abbr), - gen(M, T, {Code, Req, Ans}); - gen(M, command_codes, {Code, Req, Ans}) -> - Msgs = orddict:fetch(messages, M:dict()), + Msgs = orddict:fetch(messages, dict(M)), {_, Code, _, _, _} = lists:keyfind(Req, 1, Msgs), {_, Code, _, _, _} = lists:keyfind(Ans, 1, Msgs); -gen(M, avp_types, {Name, Code, Type, _Flags, _Encr}) -> +gen(M, avp_types = T, {Name, Code, Type, Flags}) + when is_list(Name) -> + gen(M, T, {?A(Name), Code, ?A(Type), Flags}); + +gen(M, avp_types, {Name, Code, Type, _Flags}) -> {Code, Flags, VendorId} = M:avp_header(Name), 0 = Flags band 2#00011111, V = undefined /= VendorId, @@ -181,11 +182,19 @@ gen(M, avp_types, {Name, Code, Type, _Flags, _Encr}) -> B = z(B), [] = avp_decode(M, Type, Name); +gen(M, grouped = T, {Name, Code, Vid, Avps}) + when is_list(Name) -> + gen(M, T, {?A(Name), Code, Vid, Avps}); + gen(M, grouped, {Name, _, _, _}) -> Rname = M:name2rec(Name), [] = arity(M, Name, Rname); -gen(M, enums, {Name, ED}) -> +gen(M, enum = T, {Name, ED}) + when is_list(Name) -> + 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]); gen(M, Tag, {_Mod, L}) -> @@ -253,17 +262,17 @@ arity(M, Name, AvpName, Rec) -> %% enum/3 -enum(M, Name, {E,_}) -> +enum(M, Name, {_,E}) -> B = <<E:32/integer>>, B = M:avp(encode, E, Name), E = M:avp(decode, B, Name). retag(import_avps) -> avp_types; retag(import_groups) -> grouped; -retag(import_enums) -> enums; +retag(import_enums) -> enum; retag(avp_types) -> import_avps; -retag(enums) -> import_enums. +retag(enum) -> import_enums. %% =========================================================================== @@ -370,8 +379,8 @@ values('Time') -> %% wrapped as for values/1. values('Enumerated', Name, Mod) -> - {_Name, Vals} = lists:keyfind(Name, 1, types(enums, Mod)), - lists:map(fun({N,_}) -> N end, Vals); + {_Name, Vals} = lists:keyfind(?S(Name), 1, types(enum, Mod)), + lists:map(fun({_,N}) -> N end, Vals); values('Grouped', Name, Mod) -> Rname = Mod:name2rec(Name), @@ -400,8 +409,8 @@ values('AVP', _) -> values(Name, Mod) -> Avps = types(avp_types, Mod), - {Name, _Code, Type, _Flags, _Encr} = lists:keyfind(Name, 1, Avps), - b(values(Type, Name, Mod)). + {_Name, _Code, Type, _Flags} = lists:keyfind(?S(Name), 1, Avps), + b(values(?A(Type), Name, Mod)). %% group/5 %% @@ -467,7 +476,7 @@ types(T, Mod) -> types(T, retag(T), Mod). types(T, IT, Mod) -> - Dict = Mod:dict(), + Dict = dict(Mod), fetch(T, Dict) ++ lists:flatmap(fun({_,As}) -> As end, fetch(IT, Dict)). %% random/[12] @@ -498,3 +507,8 @@ flatten({_, {{badmatch, [{_, {{badmatch, _}, _}} | _] = L}, _}}) -> L; flatten(T) -> [T]. + +%% dict/1 + +dict(Mod) -> + tl(Mod:dict()). diff --git a/lib/diameter/test/diameter_compiler_SUITE.erl b/lib/diameter/test/diameter_compiler_SUITE.erl new file mode 100644 index 0000000000..79bf9d32db --- /dev/null +++ b/lib/diameter/test/diameter_compiler_SUITE.erl @@ -0,0 +1,483 @@ +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2010-2012. 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% +%% + +%% +%% Tests of the dictionary file compiler. +%% + +-module(diameter_compiler_SUITE). + +-export([suite/0, + all/0, + init_per_suite/1, + end_per_suite/1]). + +%% testcases +-export([format/1, format/2, + replace/1, replace/2, + generate/1, generate/4, + examples/1]). + +-export([dict/0]). %% fake dictionary module + +-define(base, "base_rfc3588.dia"). +-define(util, diameter_util). +-define(S, atom_to_list). +-define(L, integer_to_list). + +%% =========================================================================== + +%% 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. +-define(REPLACE, + [{ok, + "", + ""}, + {scan, + "@id 0", + "@id \\&"}, + {scan, + "@name ", + "&'"}, + {parse, + "@id 0", + "@id @id"}, + {avp_code_already_defined, + "480", + "485"}, + {uint32_out_of_range, + "@id 0", + "@id 4294967296"}, + {uint32_out_of_range, + "@vendor 0", + "@vendor 4294967296"}, + {uint32_out_of_range, + [{"^ *Failed-AVP .*$", "&V"}, + {"@avp_types", "@avp_vendor_id 4294967296 Failed-AVP\n&"}]}, + {imported_avp_already_defined, + "@avp_types", + "@inherits diameter_gen_base_rfc3588 &"}, + {duplicate_import, + [{"@avp_types", "@inherits diameter_gen_base_rfc3588 Class\n&"}, + {"@avp_types", "@inherits diameter_gen_base_rfc3588\n&"}, + {"^@avp_types[^@]*", ""}, + {"^@enum[^&]*", ""}]}, + {duplicate_section, + "@prefix", + "@name"}, + {already_declared, + "@enum Termination-Cause", + "& XXX 0\n &"}, + {already_declared, + "@define Result-Code", + "& XXX 1000 &"}, + {inherited_avp_already_defined, + "@id", + "@inherits nomod Origin-Host &"}, + {avp_already_defined, + "@avp_types", + "@inherits m XXX\nXXX\n&"}, + {avp_already_defined, + "@avp_types", + "@inherits mod1 XXX\n@inherits mod2 XXX\n&"}, + {key_already_defined, + "DIAMETER_SUCCESS", + "& 2001\n&"}, + {messages_without_id, + "@id 0", + ""}, + {avp_name_already_defined, + "Class", + "& 666 Time M\n&"}, + {avp_has_unknown_type, + "Enumerated", + "Enum"}, + {avp_has_invalid_flag, + " -", + " X"}, + {avp_has_duplicate_flag, + " -", + " MM"}, + {avp_has_vendor_id, + "@avp_types", + "@avp_vendor_id 667 Class\n&"}, + {avp_has_no_vendor, + [{"^ *Class .*$", "&V"}, + {"@vendor .*", ""}]}, + {group_already_defined, + "@grouped", + "& Failed-AVP ::= < AVP Header: 279 > " "{AVP}\n&"}, + {grouped_avp_code_mismatch, + "(Failed-AVP ::= [^0-9]*27)9", + "&8"}, + {grouped_avp_has_wrong_type, + "(Failed-AVP *279 *)Grouped", + "\\1Time"}, + {grouped_avp_not_defined, + "Failed-AVP *.*", + ""}, + {grouped_vendor_id_without_flag, + "(Failed-AVP .*)>", + "\\1 668>"}, + {grouped_vendor_id_mismatch, + [{"(Failed-AVP .*)>", "\\1 17>"}, + {"^ *Failed-AVP .*$", "&V"}, + {"@avp_types", "@avp_vendor_id 18 Failed-AVP\n&"}]}, + {ok, + [{"(Failed-AVP .*)>", "\\1 17>"}, + {"^ *Failed-AVP .*$", "&V"}]}, + {message_name_already_defined, + "CEA ::= .*:", + "& 257 > {Result-Code}\n&"}, + {message_code_already_defined, + "CEA( ::= .*)", + "XXX\\1 {Result-Code}\n&"}, + {message_has_duplicate_flag, + "(CER ::=.*)>", + "\\1, REQ>"}, + {message_application_id_mismatch, + "(CER ::=.*)>", + "\\1 1>"}, + {invalid_avp_order, + "CEA ::=", + "{Result-Code} &"}, + {ok, + "{ Product-Name", + "* &"}, + {required_avp_has_zero_max_arity, + "{ Product-Name", + "*0 &"}, + {required_avp_has_zero_min_arity, + "{ Product-Name", + "0* &"}, + {required_avp_has_zero_min_arity, + "{ Product-Name", + "0*0 &"}, + {ok, + "{ Product-Name", + "*1 &"}, + {ok, + "{ Product-Name", + "1* &"}, + {ok, + "{ Product-Name", + "1*1 &"}, + {ok, + "{ Product-Name", + "2* &"}, + {ok, + "{ Product-Name", + "*2 &"}, + {ok, + "{ Product-Name", + "2*2 &"}, + {ok, + "{ Product-Name", + "2*3 &"}, + {qualifier_has_min_greater_than_max, + "{ Product-Name", + "3*2 &"}, + {ok, + "\\[ Origin-State-Id", + "* &"}, + {ok, + "\\[ Origin-State-Id", + "0* &"}, + {ok, + "\\[ Origin-State-Id", + "*0 &"}, + {ok, + "\\[ Origin-State-Id", + "0*0 &"}, + {ok, + "\\[ Origin-State-Id", + "0*1 &"}, + {ok, + "\\[ Origin-State-Id", + "0*2 &"}, + {ok, + "\\[ Origin-State-Id", + "*1 &"}, + {optional_avp_has_nonzero_min_arity, + "\\[ Origin-State-Id", + "1* &"}, + {optional_avp_has_nonzero_min_arity, + "\\[ Origin-State-Id", + "1*1 &"}, + {ok, + "\\[ Origin-State-Id", + "*2 &"}, + {optional_avp_has_nonzero_min_arity, + "\\[ Origin-State-Id", + "2* &"}, + {optional_avp_has_nonzero_min_arity, + "\\[ Origin-State-Id", + "2*2 &"}, + {optional_avp_has_nonzero_min_arity, + "\\[ Origin-State-Id", + "2*3 &"}, + {optional_avp_has_nonzero_min_arity, + "\\[ Origin-State-Id", + "3*2 &"}, + {ok, + "^ *< Session-Id", + "* &"}, + {ok, + "^ *< Session-Id", + "*0 &"}, + {ok, + "^ *< Session-Id", + "0* &"}, + {ok, + "^ *< Session-Id", + "0*0 &"}, + {ok, + "^ *< Session-Id", + "0*1 &"}, + {ok, + "^ *< Session-Id", + "0*2 &"}, + {ok, + "^ *< Session-Id", + "*1 &"}, + {ok, + "^ *< Session-Id", + "1* &"}, + {ok, + "^ *< Session-Id", + "1*1 &"}, + {ok, + "^ *< Session-Id", + "*2 &"}, + {ok, + "^ *< Session-Id", + "2* &"}, + {ok, + "^ *< Session-Id", + "2*2 &"}, + {ok, + "^ *< Session-Id", + "2*3 &"}, + {qualifier_has_min_greater_than_max, + "^ *< Session-Id", + "3*2 &"}, + {avp_already_referenced, + "CER ::=.*", + "& {Origin-Host}"}, + {message_missing, + "CER ::=", + "XXR ::= < Diameter-Header: 666, REQ > {Origin-Host} &"}, + {requested_avp_not_found, + [{"@id", "@inherits diameter_gen_base_rfc3588 XXX &"}, + {"CEA ::=", "<XXX> &"}]}, + {requested_avp_not_found, + [{"@id", "@inherits diameter_gen_base_rfc3588 'X X X' &"}, + {"CEA ::=", "<'X X X'> &"}]}, + {enumerated_avp_has_wrong_local_type, + "Enumerated", + "Time"}, + {enumerated_avp_not_defined, + [{"{ Disconnect-Cause }", ""}, + {"^ *Disconnect-Cause .*", ""}]}, + {avp_not_defined, + "CEA ::=", + "<XXX> &"}, + {not_loaded, + [{"@avp_types", "@inherits nomod XXX &"}, + {"CEA ::=", "<XXX> &"}]}, + {recompile, + [{"@avp_types", "@inherits " ++ ?S(?MODULE) ++ " XXX &"}, + {"CEA ::=", "<XXX> &"}]}, + {no_dict, + [{"@avp_types", "@inherits diameter XXX &"}, + {"CEA ::=", "<XXX> &"}]}, + {ok, + "@avp_types", + "@end & bad syntax"}, + {parse, + "@avp_types", + "& bad syntax"}, + {ok, + [{"@avp_types", "& 3XXX 666 Time M 'X X X' 667 Time -"}, + {"^ *Class .*", "@avp_types"}, + {"^ *Failed-AVP ", "@avp_types &"}, + {"@grouped", "&&"}, + {"^ *Failed-AVP ::=", "@grouped &"}, + {"CEA ::=", "<'Class'> &"}, + {"@avp_types", "@inherits diameter_gen_base_rfc3588 Class\n&"}, + {"@avp_types", "@custom_types mymod " + "Product-Name Firmware-Revision\n" + "@codecs mymod " + "Origin-Host Origin-Realm\n&"}]}]). + +%% Standard dictionaries in examples/dict. +-define(EXAMPLES, [rfc4004_mip, + rfc4005_nas, + rfc4006_cc, + rfc4072_eap, + rfc4590_digest, + rfc4740_sip]). + +%% =========================================================================== + +suite() -> + [{timetrap, {minutes, 10}}]. + +all() -> + [format, + replace, + generate, + examples]. + +%% Error handling testcases will make an erroneous dictionary out of +%% the base dictionary and check that the expected error results. +%% ?REPLACE encodes the modifications and expected error. +init_per_suite(Config) -> + Path = filename:join([code:lib_dir(diameter, src), "dict", ?base]), + {ok, Bin} = file:read_file(Path), + [{base, Bin} | Config]. + +end_per_suite(_Config) -> + ok. + +%% =========================================================================== +%% format/1 +%% +%% Ensure that parse o format is the identity map. + +format(Config) -> + Bin = proplists:get_value(base, Config), + [] = ?util:run([{?MODULE, [format, M, Bin]} + || E <- ?REPLACE, + {ok, M} <- [norm(E)]]). + +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), []), + {Dict, Dict} = {Dict, D}. + +%% =========================================================================== +%% replace/1 +%% +%% Ensure the expected success/error when parsing a morphed common +%% dictionary. + +replace(Config) -> + Bin = proplists:get_value(base, Config), + [] = ?util:run([{?MODULE, [replace, N, Bin]} + || E <- ?REPLACE, + N <- [norm(E)]]). + +replace({E, Mods}, Bin) -> + B = modify(Bin, Mods), + case {E, diameter_dict_util: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 + end. + +re({RE, Repl}, Bin) -> + re:replace(Bin, RE, Repl, [multiline]). + +%% =========================================================================== +%% generate/1 +%% +%% Ensure success when generating code and compiling. + +generate(Config) -> + Bin = proplists:get_value(base, Config), + Rs = lists:zip(?REPLACE, lists:seq(1, length(?REPLACE))), + [] = ?util:run([{?MODULE, [generate, M, Bin, N, T]} + || {E,N} <- Rs, + {ok, M} <- [norm(E)], + T <- [erl, hrl, spec]]). + +generate(Mods, Bin, N, Mode) -> + B = modify(Bin, Mods ++ [{"@name .*", "@name dict" ++ ?L(N)}]), + {ok, Dict} = diameter_dict_util: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])). + +%% =========================================================================== +%% examples/1 +%% +%% Compile dictionaries extracted from various standards. + +examples(_Config) -> + Dir = filename:join([code:lib_dir(diameter, examples), "dict"]), + [D || D <- ?EXAMPLES, _ <- [examples(?S(D), Dir)]]. + +examples(Dict, Dir) -> + {Name, Pre} = make_name(Dict), + ok = diameter_make:codec(filename:join([Dir, Dict ++ ".dia"]), + [{name, Name}, + {prefix, Pre}, + inherits("rfc3588_base") + | opts(Dict)]), + {ok, _, _} = compile:file(Name ++ ".erl", [return]). + +opts(M) + when M == "rfc4006_cc"; + M == "rfc4072_eap" -> + [inherits("rfc4005_nas")]; +opts("rfc4740_sip") -> + [inherits("rfc4590_digest")]; +opts(_) -> + []. + +inherits(File) -> + {Name, _} = make_name(File), + {inherits, File ++ "/" ++ Name}. + +make_name(File) -> + {R, [$_|N]} = lists:splitwith(fun(C) -> C /= $_ end, File), + {string:join(["diameter_gen", N, R], "_"), "diameter_" ++ N}. + +%% =========================================================================== + +modify(Bin, Mods) -> + lists:foldl(fun re/2, Bin, Mods). + +norm({E, RE, Repl}) -> + {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)). + +dict() -> + [0 | orddict:new()]. diff --git a/lib/diameter/test/diameter_ct.erl b/lib/diameter/test/diameter_ct.erl index f8ee3dc1d7..ded50bf6c5 100644 --- a/lib/diameter/test/diameter_ct.erl +++ b/lib/diameter/test/diameter_ct.erl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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,15 +25,14 @@ -export([run/1]). -%% ct:run_test/1 is currently documented as returning a list of test -%% results ... but no. Instead it returns 'ok' regardless of whether -%% or not the suite in question has failed testcases. +%% The makefile looks for signs of failure so ignore the ct:run_test/1 +%% return value. run([Suite]) -> Start = info(), - ok = ct:run_test([{suite, Suite}, - {logdir, "./log"}, - {auto_compile, false}]), + ct:run_test([{suite, Suite}, + {logdir, "./log"}, + {auto_compile, false}]), info(Start , info()). info() -> diff --git a/lib/diameter/test/diameter_dict_SUITE.erl b/lib/diameter/test/diameter_dict_SUITE.erl index 87bb9727fe..3cc65c0257 100644 --- a/lib/diameter/test/diameter_dict_SUITE.erl +++ b/lib/diameter/test/diameter_dict_SUITE.erl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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,9 +25,7 @@ -export([suite/0, all/0, - groups/0, - init_per_group/2, - end_per_group/2]). + groups/0]). %% testcases -export([append/1, @@ -50,13 +48,14 @@ %% =========================================================================== suite() -> - [{timetrap, {seconds, 10}}]. + [{timetrap, {seconds, 60}}]. all() -> - [{group, all} | tc()]. + [{group, all}, + {group, all, [parallel]}]. groups() -> - [{all, [parallel], tc()}]. + [{all, [], tc()}]. tc() -> [append, @@ -71,12 +70,6 @@ tc() -> update, update_counter]. -init_per_group(_, Config) -> - Config. - -end_per_group(_, _) -> - ok. - %% =========================================================================== -define(KV100, [{N,[N]} || N <- lists:seq(1,100)]). diff --git a/lib/diameter/test/diameter_dpr_SUITE.erl b/lib/diameter/test/diameter_dpr_SUITE.erl new file mode 100644 index 0000000000..9252650bf7 --- /dev/null +++ b/lib/diameter/test/diameter_dpr_SUITE.erl @@ -0,0 +1,196 @@ +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2012. 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% +%% + +%% +%% Tests of the disconnect_cb configuration. +%% + +-module(diameter_dpr_SUITE). + +-export([suite/0, + all/0, + groups/0, + init_per_group/2, + end_per_group/2]). + +%% testcases +-export([start/1, + connect/1, + remove_transport/1, + stop_service/1, + check/1, + stop/1]). + +%% disconnect_cb +-export([disconnect/5]). + +-include("diameter.hrl"). + +%% =========================================================================== + +-define(util, diameter_util). + +-define(ADDR, {127,0,0,1}). + +-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}, + {'Origin-Realm', "erlang.org"}, + {'Host-IP-Address', [?ADDR]}, + {'Vendor-Id', hd(Host)}, %% match this in disconnect/5 + {'Product-Name', "OTP/diameter"}, + {'Acct-Application-Id', [?APP_ID]}, + {restrict_connections, false}, + {application, [{dictionary, ?DICT_COMMON}, + {module, #diameter_callback{_ = false}}]}]). + +%% Disconnect reasons that diameter passes as the first argument of a +%% function configured as disconnect_cb. +-define(REASONS, [transport, service, application]). + +%% 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. +-define(RETURNS, + [[close, {dpr, [{cause, invalid}]}], [ignore, close], []] + ++ [[{dpr, [{timeout, 5000}, {cause, T}]}] || T <- ?CAUSES]). + +%% =========================================================================== + +suite() -> + [{timetrap, {seconds, 60}}]. + +all() -> + [{group, R} || R <- ?REASONS]. + +%% The group determines how transports are terminated: by remove_transport, +%% stop_service or application stop. +groups() -> + Ts = tc(), + [{R, [], Ts} || R <- ?REASONS]. + +init_per_group(Name, Config) -> + [{group, Name} | Config]. + +end_per_group(_, _) -> + ok. + +tc() -> + [start, connect, remove_transport, stop_service, check, stop]. + +%% =========================================================================== +%% start/stop testcases + +start(_Config) -> + ok = diameter:start(), + ok = diameter:start_service(?SERVER, ?SERVICE(?SERVER)), + ok = diameter:start_service(?CLIENT, ?SERVICE(?CLIENT)). + +connect(Config) -> + Pid = spawn(fun init/0), %% process for disconnect_cb to bang + Grp = group(Config), + LRef = ?util:listen(?SERVER, tcp), + Refs = [?util:connect(?CLIENT, tcp, LRef, opts(RCs, {Grp, Pid})) + || RCs <- ?RETURNS], + ?util:write_priv(Config, config, [Pid | Refs]). + +%% Remove all the client transports only in the transport group. +remove_transport(Config) -> + transport == group(Config) + andalso (ok = diameter:remove_transport(?CLIENT, true)). + +%% Stop the service only in the service group. +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(Config) -> + Grp = group(Config), + [Pid | Refs] = ?util:read_priv(Config, config), + Pid ! self(), %% ask for dictionary + Dict = receive {Pid, D} -> D end, %% get it + check(Refs, ?RETURNS, Grp, Dict). %% check for callbacks + +stop(_Config) -> + ok = diameter:stop(). + +%% Whether or not there are callbacks after diameter:stop() depends on +%% timing as long as the server runs on the same node: a server +%% transport could close the connection before the client has chance +%% to apply its callback. Therefore, just check that there haven't +%% been any callbacks yet. +check(_, _, application, Dict) -> + [] = dict:to_list(Dict); + +check([], [], _, _) -> + ok; + +check([Ref | Refs], CBs, Grp, Dict) -> + check1(Ref, hd(CBs), Grp, Dict), + check(Refs, tl(CBs), Grp, Dict). + +check1(Ref, [ignore | RCs], Reason, Dict) -> + check1(Ref, RCs, Reason, Dict); + +check1(Ref, [_|_], Reason, Dict) -> + {ok, Reason} = dict:find(Ref, Dict); %% callback with expected reason + +check1(Ref, [], _, Dict) -> + error = dict:find(Ref, Dict). %% no callback + +%% ---------------------------------------- + +group(Config) -> + {group, Grp} = lists:keyfind(group, 1, Config), + Grp. + +%% Configure the callback with the group name (= disconnect reason) as +%% extra argument. +opts(RCs, T) -> + [{disconnect_cb, {?MODULE, disconnect, [T, RC]}} || RC <- RCs]. + +%% Match the group name with the disconnect reason to ensure the +%% callback is being called as expected. +disconnect(Reason, Ref, Peer, {Reason, Pid}, RC) -> + io:format("disconnect: ~p ~p~n", [Ref, Reason]), + {_, #diameter_caps{vendor_id = {$C,$S}}} = Peer, + Pid ! {Reason, Ref}, + RC. + +init() -> + exit(recv(dict:new())). + +recv(Dict) -> + receive + Pid when is_pid(Pid) -> + Pid ! {self(), Dict}; + {Reason, Ref} -> + recv(dict:store(Ref, Reason, Dict)) + end. diff --git a/lib/diameter/test/diameter_failover_SUITE.erl b/lib/diameter/test/diameter_failover_SUITE.erl new file mode 100644 index 0000000000..ed31670031 --- /dev/null +++ b/lib/diameter/test/diameter_failover_SUITE.erl @@ -0,0 +1,237 @@ +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2010-2012. 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% +%% + +%% +%% Tests of traffic between six Diameter nodes in three realms, +%% connected as follows. +%% +%% ----- SERVER1.REALM2 +%% / +%% / ----- SERVER2.REALM2 +%% | / +%% CLIENT.REALM1 ------ SERVER3.REALM2 +%% | \ +%% | \ +%% \ ---- SERVER1.REALM3 +%% \ +%% ----- SERVER2.REALM3 +%% + +-module(diameter_failover_SUITE). + +-export([suite/0, + all/0]). + +%% testcases +-export([start/1, + start_services/1, + connect/1, + send_ok/1, + send_nok/1, + stop_services/1, + stop/1]). + +%% diameter callbacks +-export([pick_peer/4, + prepare_request/3, + handle_answer/4, + handle_request/3]). + +-include("diameter.hrl"). +-include("diameter_gen_base_rfc3588.hrl"). + +%% =========================================================================== + +-define(util, diameter_util). + +-define(ADDR, {127,0,0,1}). + +-define(CLIENT, "CLIENT.REALM1"). +-define(SERVER1, "SERVER1.REALM2"). +-define(SERVER2, "SERVER2.REALM2"). +-define(SERVER3, "SERVER3.REALM2"). +-define(SERVER4, "SERVER1.REALM3"). +-define(SERVER5, "SERVER2.REALM3"). + +-define(SERVICES, [?CLIENT, ?SERVER1, ?SERVER2, ?SERVER3, ?SERVER4, ?SERVER5]). + +-define(DICT_COMMON, ?DIAMETER_DICT_COMMON). + +-define(APP_ALIAS, the_app). +-define(APP_ID, ?DICT_COMMON:id()). + +%% Config for diameter:start_service/2. +-define(SERVICE(Host, Dict), + [{'Origin-Host', Host}, + {'Origin-Realm', realm(Host)}, + {'Host-IP-Address', [?ADDR]}, + {'Vendor-Id', 12345}, + {'Product-Name', "OTP/diameter"}, + {'Acct-Application-Id', [Dict:id()]}, + {application, [{alias, ?APP_ALIAS}, + {dictionary, Dict}, + {module, #diameter_callback + {peer_up = false, + peer_down = false, + handle_error = false, + prepare_retransmit = false, + default = ?MODULE}}, + {answer_errors, callback}]}]). + +-define(SUCCESS, 2001). + +-define(LOGOUT, ?'DIAMETER_BASE_TERMINATION-CAUSE_DIAMETER_LOGOUT'). + +%% =========================================================================== + +suite() -> + [{timetrap, {seconds, 60}}]. + +all() -> + [start, + start_services, + connect, + send_ok, + send_nok, + stop_services, + stop]. + +%% =========================================================================== +%% start/stop testcases + +start(_Config) -> + ok = diameter:start(). + +start_services(_Config) -> + S = [server(N, ?DICT_COMMON) || N <- tl(?SERVICES)], + + ok = diameter:start_service(?CLIENT, ?SERVICE(?CLIENT, ?DICT_COMMON)), + + {save_config, [{?CLIENT, S}]}. + +connect(Config) -> + {_, Conns} = proplists:get_value(saved_config, Config), + + lists:foreach(fun({CN,Ss}) -> connect(CN, Ss) end, Conns). + +stop_services(_Config) -> + [] = [{H,T} || H <- ?SERVICES, + T <- [diameter:stop_service(H)], + T /= ok]. + +stop(_Config) -> + ok = diameter:stop(). + +%% ---------------------------------------- + +server(Name, Dict) -> + ok = diameter:start_service(Name, ?SERVICE(Name, Dict)), + {Name, ?util:listen(Name, tcp)}. + +connect(Name, Refs) -> + [{{Name, ?util:connect(Name, tcp, LRef)}, T} || {_, LRef} = T <- Refs]. + +%% =========================================================================== +%% traffic testcases + +%% Send an STR and expect success after SERVER3 answers after a couple +%% of failovers. +send_ok(_Config) -> + Req = ['STR', {'Destination-Realm', realm(?SERVER1)}, + {'Termination-Cause', ?LOGOUT}, + {'Auth-Application-Id', ?APP_ID}], + #diameter_base_STA{'Result-Code' = ?SUCCESS, + 'Origin-Host' = ?SERVER3} + = call(Req, [{filter, realm}]). + +%% Send an STR and expect failure when both servers fail. +send_nok(_Config) -> + Req = ['STR', {'Destination-Realm', realm(?SERVER4)}, + {'Termination-Cause', ?LOGOUT}, + {'Auth-Application-Id', ?APP_ID}], + {error, failover} = call(Req, [{filter, realm}]). + +%% =========================================================================== + +realm(Host) -> + tl(lists:dropwhile(fun(C) -> C /= $. end, Host)). + +call(Req, Opts) -> + diameter:call(?CLIENT, ?APP_ALIAS, Req, Opts). + +set([H|T], Vs) -> + [H | Vs ++ T]. + +%% =========================================================================== +%% diameter callbacks + +%% pick_peer/4 + +%% Choose a server other than SERVER3 or SERVER5 if possible. +pick_peer(Peers, _, ?CLIENT, _State) -> + case lists:partition(fun({_, #diameter_caps{origin_host = {_, OH}}}) -> + OH /= ?SERVER3 andalso OH /= ?SERVER5 + end, + Peers) + of + {[], [Peer]} -> + {ok, Peer}; + {[Peer | _], _} -> + {ok, Peer} + end. + +%% prepare_request/3 + +prepare_request(Pkt, ?CLIENT, {_Ref, Caps}) -> + {send, prepare(Pkt, Caps)}. + +prepare(#diameter_packet{msg = Req}, Caps) -> + #diameter_caps{origin_host = {OH, _}, + origin_realm = {OR, _}} + = Caps, + set(Req, [{'Session-Id', diameter:session_id(OH)}, + {'Origin-Host', OH}, + {'Origin-Realm', OR}]). + +%% handle_answer/4 + +handle_answer(Pkt, _Req, ?CLIENT, _Peer) -> + #diameter_packet{msg = Rec, errors = []} = Pkt, + Rec. + +%% handle_request/3 + +%% Only SERVER3 actually answers. +handle_request(Pkt, ?SERVER3, {_, Caps}) -> + #diameter_packet{msg = #diameter_base_STR{'Session-Id' = SId, + 'Origin-Host' = ?CLIENT}} + = Pkt, + #diameter_caps{origin_host = {OH, _}, + origin_realm = {OR, _}} + = Caps, + + {reply, #diameter_base_STA{'Result-Code' = ?SUCCESS, + 'Session-Id' = SId, + 'Origin-Host' = OH, + 'Origin-Realm' = OR}}; + +%% Others kill the transport to force failover. +handle_request(_, _, {TPid, _}) -> + exit(TPid, kill), + discard. diff --git a/lib/diameter/test/diameter_gen_sctp_SUITE.erl b/lib/diameter/test/diameter_gen_sctp_SUITE.erl new file mode 100644 index 0000000000..2fde7b9fdb --- /dev/null +++ b/lib/diameter/test/diameter_gen_sctp_SUITE.erl @@ -0,0 +1,367 @@ +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2010-2012. 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% +%% + +%% +%% Some gen_sctp-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_transport_SUITE testcases to fail. +%% + +-module(diameter_gen_sctp_SUITE). + +-export([suite/0, + all/0, + init_per_suite/1, + end_per_suite/1]). + +%% testcases +-export([send_not_from_controlling_process/1, + send_from_multiple_clients/1, + receive_what_was_sent/1]). + +-include_lib("kernel/include/inet_sctp.hrl"). + +%% Message from gen_sctp are of this form. +-define(SCTP(Sock, Data), {sctp, Sock, _, _, Data}). + +%% Open sockets on the loopback address. +-define(ADDR, {127,0,0,1}). + +%% Snooze, nap, siesta. +-define(SLEEP(T), receive after T -> ok end). + +%% An indescribably long number of milliseconds after which everthing +%% that should have happened has. +-define(FOREVER, 2000). + +%% The first byte in each message we send as a simple guard against +%% not receiving what was sent. +-define(MAGIC, 42). + +%% =========================================================================== + +suite() -> + [{timetrap, {minutes, 2}}]. + +all() -> + [send_not_from_controlling_process, + send_from_multiple_clients, + receive_what_was_sent]. + +init_per_suite(Config) -> + case gen_sctp:open() of + {ok, Sock} -> + gen_sctp:close(Sock), + Config; + {error, E} when E == eprotonosupport; + E == esocktnosupport -> + {skip, no_sctp} + end. + +end_per_suite(_Config) -> + ok. + +%% =========================================================================== + +%% send_not_from_controlling_process/1 +%% +%% This testcase failing shows gen_sctp:send/4 hanging when called +%% outside the controlling process of the socket in question. + +send_not_from_controlling_process(_) -> + Pids = send_not_from_controlling_process(), + ?SLEEP(?FOREVER), + try + [] = [{P,I} || P <- Pids, I <- [process_info(P)], I /= undefined] + after + lists:foreach(fun(P) -> exit(P, kill) end, Pids) + end. + +%% send_not_from_controlling_process/0 +%% +%% Returns the pids of three spawned processes: a listening process, a +%% connecting process and a sending process. +%% +%% The expected behaviour is that all three processes exit: +%% +%% - The listening process exits upon receiving an SCTP message +%% sent by the sending process. +%% - The connecting process exits upon listening process exit. +%% - The sending process exits upon gen_sctp:send/4 return. +%% +%% The observed behaviour is that all three processes remain alive +%% indefinitely: +%% +%% - The listening process never receives the SCTP message sent +%% by the sending process. +%% - The connecting process has an inet_reply message in its mailbox +%% as a consequence of the call to gen_sctp:send/4 call from the +%% sending process. +%% - The call to gen_sctp:send/4 in the sending process doesn't return, +%% hanging in prim_inet:getopts/2. + +send_not_from_controlling_process() -> + FPid = self(), + {L, MRef} = spawn_monitor(fun() -> listen(FPid) end),%% listening process + receive + {?MODULE, C, S} -> + erlang:demonitor(MRef, [flush]), + [L,C,S]; + {'DOWN', MRef, process, _, _} = T -> + error(T) + end. + +%% listen/1 + +listen(FPid) -> + {ok, Sock} = open(), + ok = gen_sctp:listen(Sock, true), + {ok, PortNr} = inet:port(Sock), + 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. + +%% connect1/3 + +connect1(PortNr, FPid, LPid) -> + {ok, Sock} = open(), + ok = gen_sctp:connect_init(Sock, ?ADDR, PortNr, []), + Id = assoc(Sock), + FPid ! {?MODULE, + self(), + spawn(fun() -> send(Sock, Id) end)}, %% sending process + MRef = erlang:monitor(process, LPid), + down(MRef). %% Waits with this as current_function. + +%% down/1 + +down(MRef) -> + receive {'DOWN', MRef, process, _, Reason} -> Reason end. + +%% send/2 + +send(Sock, Id) -> + ok = gen_sctp:send(Sock, Id, 0, <<0:32>>). + +%% =========================================================================== + +%% send_from_multiple_clients/0 +%% +%% Demonstrates sluggish delivery of messages. + +send_from_multiple_clients(_) -> + {S, Rs} = T = send_from_multiple_clients(8, 1024), + Max = ?FOREVER*1000, + {false, [], _} = {Max < S, + Rs -- [OI || {O,_} = OI <- Rs, is_integer(O)], + T}. + +%% send_from_multiple_clients/2 +%% +%% Opens a listening socket and then spawns a specified number of +%% processes, each of which connects to the listening socket. Each +%% connecting process then sends a message, whose size in bytes is +%% passed as an argument, the listening process sends a reply +%% containing the time at which the message was received, and the +%% connecting process then exits upon reception of this reply. +%% +%% Returns the elapsed time for all connecting process to exit +%% together with a list of exit reasons for the connecting processes. +%% In the successful case a connecting process exits with the +%% outbound/inbound transit times for the sent/received message as +%% reason. +%% +%% The observed behaviour is that some outbound messages (that is, +%% from a connecting process to the listening process) can take an +%% unexpectedly long time to complete their journey. The more +%% connecting processes, the longer the possible delay it seems. +%% +%% eg. (With F = fun send_from_multiple_clients/2.) +%% +%% 5> F(2, 1024). +%% {875,[{128,116},{113,139}]} +%% 6> F(4, 1024). +%% {2995290,[{2994022,250},{2994071,80},{200,130},{211,113}]} +%% 7> F(8, 1024). +%% {8997461,[{8996161,116}, +%% {2996471,86}, +%% {2996278,116}, +%% {2996360,95}, +%% {246,112}, +%% {213,159}, +%% {373,173}, +%% {376,118}]} +%% 8> F(8, 1024). +%% {21001891,[{20999968,128}, +%% {8997891,172}, +%% {8997927,91}, +%% {2995716,164}, +%% {2995860,87}, +%% {134,100}, +%% {117,98}, +%% {149,125}]} +%% +%% This turns out to have been due to SCTP resends as a consequence of +%% the listener having an insufficient recbuf. Increasing the size +%% solves the problem. +%% + +send_from_multiple_clients(N, Sz) + when is_integer(N), 0 < N, is_integer(Sz), 0 < Sz -> + timer:tc(fun listen/2, [N, <<?MAGIC, 0:Sz/unit:8>>]). + +%% listen/2 + +listen(N, Bin) -> + {ok, Sock} = open(), + ok = gen_sctp:listen(Sock, true), + {ok, PortNr} = inet:port(Sock), + + %% Spawn a middleman that in turn spawns N connecting processes, + %% collects a list of exit reasons and then exits with the list as + %% reason. loop/3 returns when we receive this list from the + %% middleman's 'DOWN'. + + Self = self(), + Fun = fun() -> exit(connect2(Self, PortNr, Bin)) end, + {_, MRef} = spawn_monitor(fun() -> exit(fold(N, Fun)) end), + loop(Sock, MRef, Bin). + +%% fold/2 +%% +%% Spawn N processes and collect their exit reasons in a list. + +fold(N, Fun) -> + start(N, Fun), + acc(N, []). + +start(0, _) -> + ok; +start(N, Fun) -> + spawn_monitor(Fun), + start(N-1, Fun). + +acc(0, Acc) -> + Acc; +acc(N, Acc) -> + receive + {'DOWN', _MRef, process, _, RC} -> + acc(N-1, [RC | Acc]) + end. + +%% loop/3 + +loop(Sock, MRef, Bin) -> + receive + ?SCTP(Sock, {[#sctp_sndrcvinfo{assoc_id = Id}], B}) -> + Sz = size(Bin), + {Sz, Bin} = {size(B), B}, %% assert + ok = send(Sock, Id, mark(Bin)), + loop(Sock, MRef, Bin); + ?SCTP(Sock, _) -> + loop(Sock, MRef, Bin); + {'DOWN', MRef, process, _, Reason} -> + Reason + end. + +%% connect2/3 + +connect2(Pid, PortNr, Bin) -> + erlang:monitor(process, Pid), + + {ok, Sock} = open(), + ok = gen_sctp:connect_init(Sock, ?ADDR, PortNr, []), + Id = assoc(Sock), + + %% T1 = time before send + %% T2 = time after listening process received our message + %% T3 = time after reply is received + + T1 = now(), + ok = send(Sock, Id, Bin), + T2 = unmark(recv(Sock, Id)), + T3 = now(), + {timer:now_diff(T2, T1), timer:now_diff(T3, T2)}. %% {Outbound, Inbound} + +%% recv/2 + +recv(Sock, Id) -> + receive + ?SCTP(Sock, {[#sctp_sndrcvinfo{assoc_id = Id}], Bin}) -> + Bin; + T -> %% eg. 'DOWN' + exit(T) + end. + +%% send/3 + +send(Sock, Id, Bin) -> + gen_sctp:send(Sock, Id, 0, Bin). + +%% mark/1 + +mark(Bin) -> + Info = term_to_binary(now()), + <<Info/binary, Bin/binary>>. + +%% unmark/1 + +unmark(Bin) -> + {_,_,_} = binary_to_term(Bin). + +%% =========================================================================== + +%% receive_what_was_sent/1 +%% +%% Demonstrates reception of a message that differs from that sent. + +receive_what_was_sent(_Config) -> + send_from_multiple_clients(1, 1024*32). %% fails + +%% =========================================================================== + +%% open/0 + +open() -> + open([]). + +%% open/1 + +open(Opts) -> + gen_sctp:open([{ip, ?ADDR}, {port, 0}, {active, true}, binary, + {recbuf, 1 bsl 16}, {sndbuf, 1 bsl 16} + | Opts]). + +%% assoc/1 + +assoc(Sock) -> + receive + ?SCTP(Sock, {[], #sctp_assoc_change{state = S, + assoc_id = Id}}) -> + comm_up = S, %% assert + Id + end. diff --git a/lib/diameter/test/diameter_reg_SUITE.erl b/lib/diameter/test/diameter_reg_SUITE.erl index ade824c9dd..4939019f7a 100644 --- a/lib/diameter/test/diameter_reg_SUITE.erl +++ b/lib/diameter/test/diameter_reg_SUITE.erl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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 @@ -26,8 +26,6 @@ -export([suite/0, all/0, groups/0, - init_per_group/2, - end_per_group/2, init_per_suite/1, end_per_suite/1]). @@ -45,13 +43,14 @@ %% =========================================================================== suite() -> - [{timetrap, {seconds, 10}}]. + [{timetrap, {seconds, 60}}]. all() -> - [{group, all} | tc()]. + [{group, all}, + {group, all, [parallel]}]. groups() -> - [{all, [parallel], tc()}]. + [{all, [], tc()}]. tc() -> [add, @@ -61,12 +60,6 @@ tc() -> terms, pids]. -init_per_group(_, Config) -> - Config. - -end_per_group(_, _) -> - ok. - init_per_suite(Config) -> ok = diameter:start(), Config. diff --git a/lib/diameter/test/diameter_relay_SUITE.erl b/lib/diameter/test/diameter_relay_SUITE.erl index d3d1fe690a..f10d82bdf8 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-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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,44 +35,38 @@ -export([suite/0, all/0, - groups/0, - init_per_group/2, - end_per_group/2, - init_per_suite/1, - end_per_suite/1]). + groups/0]). %% testcases --export([send1/1, +-export([start/1, + start_services/1, + connect/1, + send1/1, send2/1, send3/1, send4/1, send_loop/1, send_timeout_1/1, send_timeout_2/1, - remove_transports/1, - stop_services/1]). + info/1, + disconnect/1, + stop_services/1, + stop/1]). %% diameter callbacks --export([peer_up/3, - peer_down/3, - pick_peer/4, +-export([pick_peer/4, prepare_request/3, prepare_retransmit/3, handle_answer/4, - handle_error/4, handle_request/3]). --ifdef(DIAMETER_CT). +-include("diameter.hrl"). -include("diameter_gen_base_rfc3588.hrl"). --else. --include_lib("diameter/include/diameter_gen_base_rfc3588.hrl"). --endif. - --include_lib("diameter/include/diameter.hrl"). --include("diameter_ct.hrl"). %% =========================================================================== +-define(util, diameter_util). + -define(ADDR, {127,0,0,1}). -define(CLIENT, "CLIENT.REALM1"). @@ -83,6 +77,10 @@ -define(SERVER3, "SERVER1.REALM3"). -define(SERVER4, "SERVER2.REALM3"). +-define(SERVICES, [?CLIENT, + ?RELAY1, ?RELAY2, + ?SERVER1, ?SERVER2, ?SERVER3, ?SERVER4]). + -define(DICT_COMMON, ?DIAMETER_DICT_COMMON). -define(DICT_RELAY, ?DIAMETER_DICT_RELAY). @@ -99,22 +97,12 @@ {'Acct-Application-Id', [Dict:id()]}, {application, [{alias, ?APP_ALIAS}, {dictionary, Dict}, - {module, ?MODULE}, + {module, #diameter_callback{peer_up = false, + peer_down = false, + handle_error = false, + default = ?MODULE}}, {answer_errors, callback}]}]). -%% Config for diameter:add_transport/2. In the listening case, listen -%% on a free port that we then lookup using the implementation detail -%% that diameter_tcp registers the port with diameter_reg. --define(CONNECT(PortNr), - {connect, [{transport_module, diameter_tcp}, - {transport_config, [{raddr, ?ADDR}, - {rport, PortNr}, - {ip, ?ADDR}, - {port, 0}]}]}). --define(LISTEN, - {listen, [{transport_module, diameter_tcp}, - {transport_config, [{ip, ?ADDR}, {port, 0}]}]}). - -define(SUCCESS, 2001). -define(LOOP_DETECTED, 3005). -define(UNABLE_TO_DELIVER, 3002). @@ -122,55 +110,25 @@ -define(LOGOUT, ?'DIAMETER_BASE_TERMINATION-CAUSE_DIAMETER_LOGOUT'). -define(AUTHORIZE_ONLY, ?'DIAMETER_BASE_RE-AUTH-REQUEST-TYPE_AUTHORIZE_ONLY'). --define(A, list_to_atom). --define(L, atom_to_list). - %% =========================================================================== suite() -> - [{timetrap, {seconds, 10}}]. + [{timetrap, {seconds, 60}}]. all() -> - [{group, N} || {N, _, _} <- groups()] - ++ [remove_transports, stop_services]. + [start, + start_services, + connect, + {group, all}, + {group, all, [parallel]}, + disconnect, + stop_services, + stop]. groups() -> - Ts = tc(), - [{all, [], Ts}, - {p, [parallel], Ts}]. - -init_per_group(_, Config) -> - Config. - -end_per_group(_, _) -> - ok. - -init_per_suite(Config) -> - ok = diameter:start(), - [S1,S2,S3,S4] = S = [server(N, ?DICT_COMMON) || N <- [?SERVER1, - ?SERVER2, - ?SERVER3, - ?SERVER4]], - [R1,R2] = R = [server(N, ?DICT_RELAY) || N <- [?RELAY1, ?RELAY2]], - - ok = diameter:start_service(?CLIENT, ?SERVICE(?CLIENT, ?DICT_COMMON)), + [{all, [], tc()}]. - true = diameter:subscribe(?RELAY1), - true = diameter:subscribe(?RELAY2), - true = diameter:subscribe(?CLIENT), - - [C1,C2] = connect(?RELAY1, [S1,S2]), - [C3,C4] = connect(?RELAY2, [S3,S4]), - [C5,C6] = connect(?CLIENT, [R1,R2]), - - C7 = connect(?RELAY1, R2), - - [{transports, {S, R, [C1,C2,C3,C4,C5,C6,C7]}} | Config]. - -end_per_suite(_Config) -> - ok = diameter:stop(). - -%% Testcases to run when services are started and connections +%% Traffic cases run when services are started and connections %% established. tc() -> [send1, @@ -179,45 +137,59 @@ tc() -> send4, send_loop, send_timeout_1, - send_timeout_2]. - -server(Host, Dict) -> - ok = diameter:start_service(Host, ?SERVICE(Host, Dict)), - {ok, LRef} = diameter:add_transport(Host, ?LISTEN), - {LRef, portnr(LRef)}. - -connect(Host, {_LRef, PortNr}) -> - {ok, Ref} = diameter:add_transport(Host, ?CONNECT(PortNr)), - ok = receive - #diameter_event{service = Host, - info = {up, Ref, _, _, #diameter_packet{}}} -> - ok - after 2000 -> - false - end, - Ref; -connect(Host, Ports) -> - [connect(Host, P) || P <- Ports]. - -portnr(LRef) -> - portnr(LRef, 20). - -portnr(LRef, N) - when 0 < N -> - case diameter_reg:match({diameter_tcp, listener, {LRef, '_'}}) of - [{T, _Pid}] -> - {_, _, {LRef, {_Addr, LSock}}} = T, - {ok, PortNr} = inet:port(LSock), - PortNr; - [] -> - receive after 50 -> ok end, - portnr(LRef, N-1) - end. + send_timeout_2, + info]. -realm(Host) -> - tl(lists:dropwhile(fun(C) -> C /= $. end, Host)). +%% =========================================================================== +%% start/stop testcases + +start(_Config) -> + ok = diameter:start(). + +start_services(_Config) -> + [S1,S2,S3,S4] = [server(N, ?DICT_COMMON) || N <- [?SERVER1, + ?SERVER2, + ?SERVER3, + ?SERVER4]], + [R1,R2] = [server(N, ?DICT_RELAY) || N <- [?RELAY1, ?RELAY2]], + + ok = diameter:start_service(?CLIENT, ?SERVICE(?CLIENT, ?DICT_COMMON)), + + {save_config, [{?RELAY1, [S1,S2,R2]}, + {?RELAY2, [S3,S4]}, + {?CLIENT, [R1,R2]}]}. + +connect(Config) -> + {_, Conns} = proplists:get_value(saved_config, Config), + + ?util:write_priv(Config, + "cfg", + lists:flatmap(fun({CN,Ss}) -> connect(CN, Ss) end, + Conns)). + +disconnect(Config) -> + lists:foreach(fun({{CN,CR},{SN,SR}}) -> ?util:disconnect(CN,CR,SN,SR) end, + ?util:read_priv(Config, "cfg")). + +stop_services(_Config) -> + [] = [{H,T} || H <- ?SERVICES, + T <- [diameter:stop_service(H)], + T /= ok]. + +stop(_Config) -> + ok = diameter:stop(). + +%% ---------------------------------------- + +server(Name, Dict) -> + ok = diameter:start_service(Name, ?SERVICE(Name, Dict)), + {Name, ?util:listen(Name, tcp)}. + +connect(Name, Refs) -> + [{{Name, ?util:connect(Name, tcp, LRef)}, T} || {_, LRef} = T <- Refs]. %% =========================================================================== +%% traffic testcases %% Send an STR intended for a specific server and expect success. send1(_Config) -> @@ -254,40 +226,14 @@ send_timeout(Tmo) -> {'Re-Auth-Request-Type', ?AUTHORIZE_ONLY}], call(Req, [{filter, realm}, {timeout, Tmo}]). -%% Remove the client transports and expect the corresponding server -%% transport to go down. -remove_transports(Config) -> - {[S1,S2,S3,S4], [R1,R2], [C1,C2,C3,C4,C5,C6,C7]} - = proplists:get_value(transports, Config), - - true = diameter:subscribe(?SERVER1), - true = diameter:subscribe(?SERVER2), - true = diameter:subscribe(?SERVER3), - true = diameter:subscribe(?SERVER4), - true = diameter:subscribe(?RELAY1), - true = diameter:subscribe(?RELAY2), - - disconnect(S1, ?RELAY1, C1), - disconnect(S2, ?RELAY1, C2), - disconnect(S3, ?RELAY2, C3), - disconnect(S4, ?RELAY2, C4), - disconnect(R1, ?CLIENT, C5), - disconnect(R2, ?CLIENT, C6), - disconnect(R2, ?RELAY1, C7). - -disconnect({LRef, _PortNr}, Client, CRef) -> - ok = diameter:remove_transport(Client, CRef), - ok = receive #diameter_event{info = {down, LRef, _, _}} -> ok - after 2000 -> false - end. - -stop_services(_Config) -> - S = [?CLIENT, ?RELAY1, ?RELAY2, ?SERVER1, ?SERVER2, ?SERVER3, ?SERVER4], - Ok = [ok || _ <- S], - Ok = [diameter:stop_service(H) || H <- S]. +info(_Config) -> + [] = ?util:info(). %% =========================================================================== +realm(Host) -> + tl(lists:dropwhile(fun(C) -> C /= $. end, Host)). + call(Server) -> Realm = realm(Server), Req = ['STR', {'Destination-Realm', Realm}, @@ -301,29 +247,19 @@ call(Server) -> call(Req, Opts) -> diameter:call(?CLIENT, ?APP_ALIAS, Req, Opts). - + set([H|T], Vs) -> [H | Vs ++ T]. %% =========================================================================== %% diameter callbacks -%% peer_up/3 - -peer_up(_SvcName, _Peer, State) -> - State. - -%% peer_down/3 - -peer_down(_SvcName, _Peer, State) -> - State. - %% pick_peer/4 pick_peer([Peer | _], _, Svc, _State) when Svc == ?RELAY1; Svc == ?RELAY2; - Svc == ?CLIENT-> + Svc == ?CLIENT -> {ok, Peer}. %% prepare_request/3 @@ -361,11 +297,6 @@ handle_answer(Pkt, _Req, ?CLIENT, _Peer) -> #diameter_packet{msg = Rec, errors = []} = Pkt, Rec. -%% handle_error/4 - -handle_error(Reason, _Req, _Svc, _Peer) -> - {error, Reason}. - %% handle_request/3 handle_request(Pkt, OH, {_Ref, #diameter_caps{origin_host = {OH,_}} = Caps}) diff --git a/lib/diameter/test/diameter_stats_SUITE.erl b/lib/diameter/test/diameter_stats_SUITE.erl index e50a0050a6..8b7d8cb1b6 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-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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 @@ -26,38 +26,34 @@ -export([suite/0, all/0, groups/0, - init_per_group/2, - end_per_group/2, init_per_suite/1, end_per_suite/1]). %% testcases --export([an/1, - twa/1]). +-export([reg/1, + incr/1, + read/1, + flush/1]). -define(stat, diameter_stats). --define(util, diameter_util). %% =========================================================================== suite() -> - [{timetrap, {seconds, 10}}]. + [{timetrap, {seconds, 60}}]. all() -> - [{group, all} | tc()]. + [{group, all}, + {group, all, [parallel]}]. groups() -> - [{all, [parallel], tc()}]. + [{all, [], tc()}]. tc() -> - [an, - twa]. - -init_per_group(_, Config) -> - Config. - -end_per_group(_, _) -> - ok. + [reg, + incr, + read, + flush]. init_per_suite(Config) -> ok = diameter:start(), @@ -68,25 +64,62 @@ end_per_suite(_Config) -> %% =========================================================================== -an(_) -> - Ref = {'_', make_ref()}, +reg(_) -> + Ref = '$1', true = ?stat:reg(Ref), - true = ?stat:reg(Ref), %% duplicate - ok = ?stat:incr(x), - ok = ?stat:incr(x, Ref), - ok = ?stat:incr(y, 2), - ok = ?stat:incr(y, Ref), - %% Flushing a pid flushes even stats on the registered reference. - [{x,2},{y,3}] = lists:sort(?stat:flush()), - [] = ?stat:flush(Ref), - [] = ?stat:flush(). - -twa(_) -> + false = ?stat:reg(Ref). %% duplicate + +incr(_) -> + Ref = '_', + Ctr = x, + false = ?stat:incr(Ctr), %% not registered, + 1 = ?stat:incr(Ctr, Ref, 1), %% only pids need register + true = ?stat:reg(Ref), + spawn(fun() -> + true = ?stat:reg(Ref), + 2 = ?stat:incr(Ctr, self(), 2) + end), + ok = fold(Ctr, Ref, 3), %% folded + ?stat:flush([self(), Ref]). + +read(_) -> Ref = make_ref(), - ok = ?stat:incr(x, 8), - ok = ?stat:incr(x, Ref, 7), - %% Flushing a reference doesn't affect registered pids. - [{x,7}] = ?stat:flush(Ref), - [] = ?stat:flush(Ref), - [{x,8}] = ?stat:flush(), - [] = ?stat:flush(). + C1 = {a,b}, + C2 = {b,a}, + true = ?stat:reg(Ref), + 1 = ?stat:incr(C1), + 1 = ?stat:incr(C2), + 2 = ?stat:incr(C1), + 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([]), + [] = ?stat:read([make_ref()]), + ?stat:flush([self(), Ref, make_ref()]). + +flush(_) -> + Ref = make_ref(), + Ctr = '_', + true = ?stat:reg(Ref), + 1 = ?stat:incr(Ctr), + 3 = ?stat:incr(Ctr, self(), 2), + 2 = ?stat:incr(Ctr, Ref, 2), + Self = self(), + [{Self, [{Ctr, 3}]}] = ?stat:flush([self()]), + 1 = ?stat:incr(Ctr), + [{Ref, [{Ctr, 2}]}] = ?stat:flush([Ref]), + [{Self, [{Ctr, 1}]}] = ?stat:flush([self()]), + [] = ?stat:flush([self(), Ref]). + +%% =========================================================================== + +%% Keep incremented until a fold results in the specified value. +fold(Ctr, Ref, N) -> + case ?stat:incr(Ctr, Ref, 0) of + N -> + ok; + M when M < N -> + erlang:yield(), + fold(Ctr, Ref, N) + end. diff --git a/lib/diameter/test/diameter_sync_SUITE.erl b/lib/diameter/test/diameter_sync_SUITE.erl index 84f77b6066..457efab8ae 100644 --- a/lib/diameter/test/diameter_sync_SUITE.erl +++ b/lib/diameter/test/diameter_sync_SUITE.erl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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 @@ -26,8 +26,6 @@ -export([suite/0, all/0, groups/0, - init_per_group/2, - end_per_group/2, init_per_suite/1, end_per_suite/1]). @@ -45,13 +43,14 @@ %% =========================================================================== suite() -> - [{timetrap, {seconds, 10}}]. + [{timetrap, {seconds, 60}}]. all() -> - [{group, all} | tc()]. + [{group, all}, + {group, all, [parallel]}]. groups() -> - [{all, [parallel], tc()}]. + [{all, [], tc()}]. tc() -> [call, @@ -59,12 +58,6 @@ tc() -> timeout, flush]. -init_per_group(_, Config) -> - Config. - -end_per_group(_, _) -> - ok. - init_per_suite(Config) -> ok = diameter:start(), Config. diff --git a/lib/diameter/test/diameter_tls_SUITE.erl b/lib/diameter/test/diameter_tls_SUITE.erl new file mode 100644 index 0000000000..6cc34b20c5 --- /dev/null +++ b/lib/diameter/test/diameter_tls_SUITE.erl @@ -0,0 +1,385 @@ +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2010-2012. 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% +%% + +%% +%% Tests of traffic between six Diameter nodes connected as follows. +%% +%% ---- SERVER.REALM1 (TLS after capabilities exchange) +%% / +%% / ---- SERVER.REALM2 (ditto) +%% | / +%% CLIENT.REALM0 ----- SERVER.REALM3 (no security) +%% | \ +%% \ ---- SERVER.REALM4 (TLS at connection establishment) +%% \ +%% ---- SERVER.REALM5 (ditto) +%% + +-module(diameter_tls_SUITE). + +-export([suite/0, + all/0, + groups/0, + init_per_suite/1, + end_per_suite/1]). + +%% testcases +-export([start_ssl/1, + start_diameter/1, + make_certs/1, make_certs/0, + start_services/1, + add_transports/1, + send1/1, + send2/1, + send3/1, + send4/1, + send5/1, + remove_transports/1, + stop_services/1, + stop_diameter/1, + stop_ssl/1]). + +%% diameter callbacks +-export([prepare_request/3, + prepare_retransmit/3, + handle_answer/4, + handle_request/3]). + +-include("diameter.hrl"). +-include("diameter_gen_base_rfc3588.hrl"). + +%% =========================================================================== + +-define(util, diameter_util). + +-define(ADDR, {127,0,0,1}). + +-define(CLIENT, "CLIENT.REALM0"). +-define(SERVER1, "SERVER.REALM1"). +-define(SERVER2, "SERVER.REALM2"). +-define(SERVER3, "SERVER.REALM3"). +-define(SERVER4, "SERVER.REALM4"). +-define(SERVER5, "SERVER.REALM5"). + +-define(SERVERS, [?SERVER1, ?SERVER2, ?SERVER3, ?SERVER4, ?SERVER5]). + +-define(DICT_COMMON, ?DIAMETER_DICT_COMMON). + +-define(APP_ALIAS, the_app). +-define(APP_ID, ?DICT_COMMON:id()). + +-define(NO_INBAND_SECURITY, 0). +-define(TLS, 1). + +%% Config for diameter:start_service/2. +-define(SERVICE(Host, Dict), + [{'Origin-Host', Host}, + {'Origin-Realm', realm(Host)}, + {'Host-IP-Address', [?ADDR]}, + {'Vendor-Id', 12345}, + {'Product-Name', "OTP/diameter"}, + {'Inband-Security-Id', [?NO_INBAND_SECURITY]}, + {'Auth-Application-Id', [Dict:id()]}, + {application, [{alias, ?APP_ALIAS}, + {dictionary, Dict}, + {module, #diameter_callback{peer_up = false, + peer_down = false, + pick_peer = false, + handle_error = false, + default = ?MODULE}}, + {answer_errors, callback}]}]). + +%% Config for diameter:add_transport/2. In the listening case, listen +%% on a free port that we then lookup using the implementation detail +%% that diameter_tcp registers the port with diameter_reg. +-define(CONNECT(PortNr, Caps, Opts), + {connect, [{transport_module, diameter_tcp}, + {transport_config, [{raddr, ?ADDR}, + {rport, PortNr}, + {ip, ?ADDR}, + {port, 0} + | Opts]}, + {capabilities, Caps}]}). +-define(LISTEN(Caps, Opts), + {listen, [{transport_module, diameter_tcp}, + {transport_config, [{ip, ?ADDR}, {port, 0} | Opts]}, + {capabilities, Caps}]}). + +-define(SUCCESS, 2001). +-define(LOGOUT, ?'DIAMETER_BASE_TERMINATION-CAUSE_DIAMETER_LOGOUT'). + +%% =========================================================================== + +suite() -> + [{timetrap, {seconds, 60}}]. + +all() -> + [start_ssl, + start_diameter, + make_certs, + start_services, + add_transports, + {group, all}, + {group, all, [parallel]}, + remove_transports, + stop_services, + stop_diameter, + stop_ssl]. + +groups() -> + [{all, [], tc()}]. + +%% Shouldn't really have to know about crypto here but 'ok' from +%% ssl:start() isn't enough to guarantee that TLS is available. +init_per_suite(Config) -> + try + false /= os:find_executable("openssl") + orelse throw({?MODULE, no_openssl}), + ok == (catch crypto:start()) + orelse throw({?MODULE, no_crypto}), + Config + catch + {?MODULE, E} -> + {skip, E} + end. + +end_per_suite(_Config) -> + crypto:stop(). + +%% Testcases to run when services are started and connections +%% established. +tc() -> + [send1, + send2, + send3, + send4, + send5]. + +%% =========================================================================== +%% testcases + +start_ssl(_Config) -> + ok = ssl:start(). + +start_diameter(_Config) -> + ok = diameter:start(). + +make_certs() -> + [{timetrap, {seconds, 30}}]. + +make_certs(Config) -> + Dir = proplists:get_value(priv_dir, Config), + + [] = ?util:run([[fun make_cert/2, Dir, B] || B <- ["server1", + "server2", + "server4", + "server5", + "client"]]). + +start_services(Config) -> + Dir = proplists:get_value(priv_dir, Config), + Servers = [server(S, sopts(S, Dir)) || S <- ?SERVERS], + + ok = diameter:start_service(?CLIENT, ?SERVICE(?CLIENT, ?DICT_COMMON)), + + {save_config, [Dir | Servers]}. + +add_transports(Config) -> + {_, [Dir | Servers]} = proplists:get_value(saved_config, Config), + + true = diameter:subscribe(?CLIENT), + + Opts = ssl_options(Dir, "client"), + Connections = [connect(?CLIENT, S, copts(N, Opts)) + || {S,N} <- lists:zip(Servers, ?SERVERS)], + + ?util:write_priv(Config, "cfg", lists:zip(Servers, Connections)). + + +%% Remove the client transports and expect the corresponding server +%% transport to go down. +remove_transports(Config) -> + Ts = ?util:read_priv(Config, "cfg"), + [] = [T || S <- ?SERVERS, T <- [diameter:subscribe(S)], T /= true], + lists:map(fun disconnect/1, Ts). + +stop_services(_Config) -> + [] = [{H,T} || H <- [?CLIENT | ?SERVERS], + T <- [diameter:stop_service(H)], + T /= ok]. + +stop_diameter(_Config) -> + ok = diameter:stop(). + +stop_ssl(_Config) -> + ok = ssl:stop(). + +%% Send an STR intended for a specific server and expect success. +send1(_Config) -> + call(?SERVER1). +send2(_Config) -> + call(?SERVER2). +send3(_Config) -> + call(?SERVER3). +send4(_Config) -> + call(?SERVER4). +send5(_Config) -> + call(?SERVER5). + +%% =========================================================================== +%% diameter callbacks + +%% prepare_request/3 + +prepare_request(#diameter_packet{msg = Req}, + ?CLIENT, + {_Ref, Caps}) -> + #diameter_caps{origin_host = {OH, _}, + origin_realm = {OR, _}} + = Caps, + + {send, set(Req, [{'Session-Id', diameter:session_id(OH)}, + {'Origin-Host', OH}, + {'Origin-Realm', OR}])}. + +%% prepare_retransmit/3 + +prepare_retransmit(_Pkt, false, _Peer) -> + discard. + +%% handle_answer/4 + +handle_answer(Pkt, _Req, ?CLIENT, _Peer) -> + #diameter_packet{msg = Rec, errors = []} = Pkt, + Rec. + +%% handle_request/3 + +handle_request(#diameter_packet{msg = #diameter_base_STR{'Session-Id' = SId}}, + OH, + {_Ref, #diameter_caps{origin_host = {OH,_}, + origin_realm = {OR, _}}}) + when OH /= ?CLIENT -> + {reply, #diameter_base_STA{'Result-Code' = ?SUCCESS, + 'Session-Id' = SId, + 'Origin-Host' = OH, + 'Origin-Realm' = OR}}. + +%% =========================================================================== +%% support functions + +call(Server) -> + Realm = realm(Server), + Req = ['STR', {'Destination-Realm', Realm}, + {'Termination-Cause', ?LOGOUT}, + {'Auth-Application-Id', ?APP_ID}], + #diameter_base_STA{'Result-Code' = ?SUCCESS, + 'Origin-Host' = Server, + 'Origin-Realm' = Realm} + = call(Req, [{filter, realm}]). + +call(Req, Opts) -> + diameter:call(?CLIENT, ?APP_ALIAS, Req, Opts). + +set([H|T], Vs) -> + [H | Vs ++ T]. + +disconnect({{LRef, _PortNr}, CRef}) -> + ok = diameter:remove_transport(?CLIENT, CRef), + ok = receive #diameter_event{info = {down, LRef, _, _}} -> ok + after 2000 -> false + end. + +realm(Host) -> + tl(lists:dropwhile(fun(C) -> C /= $. end, Host)). + +inband_security(Ids) -> + [{'Inband-Security-Id', Ids}]. + +ssl_options(Dir, Base) -> + Root = filename:join([Dir, Base]), + [{ssl_options, [{certfile, Root ++ "_ca.pem"}, + {keyfile, Root ++ "_key.pem"}]}]. + +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]], + + 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"]), + + %% Hope for the best and only check that files are written. + os:cmd(KCmd), + os:cmd(CCmd), + + [_,_] = [T || P <- Paths, {ok, T} <- [file:read_file_info(P)]], + + {K,C}. + +join(Strs) -> + string:join(Strs, " "). + +%% server/2 + +server(Host, {Caps, Opts}) -> + ok = diameter:start_service(Host, ?SERVICE(Host, ?DICT_COMMON)), + {ok, LRef} = diameter:add_transport(Host, ?LISTEN(Caps, Opts)), + {LRef, hd([_] = ?util:lport(tcp, LRef, 20))}. + +sopts(?SERVER1, Dir) -> + {inband_security([?TLS]), + ssl_options(Dir, "server1")}; +sopts(?SERVER2, Dir) -> + {inband_security([?NO_INBAND_SECURITY, ?TLS]), + ssl_options(Dir, "server2")}; +sopts(?SERVER3, _) -> + {[], []}; +sopts(?SERVER4, Dir) -> + {[], ssl(ssl_options(Dir, "server4"))}; +sopts(?SERVER5, Dir) -> + {[], ssl(ssl_options(Dir, "server5"))}. + +ssl([{ssl_options = T, Opts}]) -> + [{T, true} | Opts]. + +%% connect/3 + +connect(Host, {_LRef, PortNr}, {Caps, Opts}) -> + {ok, Ref} = diameter:add_transport(Host, ?CONNECT(PortNr, Caps, Opts)), + ok = receive + #diameter_event{service = Host, + info = {up, Ref, _, _, #diameter_packet{}}} -> + ok + after 2000 -> + false + end, + Ref. + +copts(S, Opts) + when S == ?SERVER1; + S == ?SERVER2; + S == ?SERVER3 -> + {inband_security([?NO_INBAND_SECURITY, ?TLS]), Opts}; +copts(S, Opts) + when S == ?SERVER4; + S == ?SERVER5 -> + {[], ssl(Opts)}. diff --git a/lib/diameter/test/diameter_tls_SUITE_data/Makefile.ca b/lib/diameter/test/diameter_tls_SUITE_data/Makefile.ca new file mode 100644 index 0000000000..3f2645add0 --- /dev/null +++ b/lib/diameter/test/diameter_tls_SUITE_data/Makefile.ca @@ -0,0 +1,43 @@ +# -*- makefile -*- +# %CopyrightBegin% +# +# Copyright Ericsson AB 2011. 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% + +# +# Certificates are now generated from the suite itself but the +# makefile itself is still useful. +# + +KEYS = $(HOSTS:%=%_key.pem) +CERTS = $(HOSTS:%=%_ca.pem) + +all: $(CERTS) + +%_ca.pem: %_key.pem + openssl req -new -x509 -key $< -out $@ -days 1095 \ + -subj '/C=SE/ST=./L=Stockholm/CN=www.erlang.org' + +%_key.pem: + openssl genrsa -out $@ 2048 + +clean: + rm -f $(CERTS) + +realclean: clean + rm -f $(KEYS) + +.PRECIOUS: $(KEYS) +.PHONY: all clean realclean diff --git a/lib/diameter/test/diameter_traffic_SUITE.erl b/lib/diameter/test/diameter_traffic_SUITE.erl index 8c85323222..142b28a4c2 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-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 @@ -26,16 +26,20 @@ -export([suite/0, all/0, groups/0, - init_per_suite/1, - end_per_suite/1, init_per_group/2, end_per_group/2, init_per_testcase/2, end_per_testcase/2]). %% testcases --export([result_codes/1, +-export([start/1, + start_services/1, + add_transports/1, + result_codes/1, send_ok/1, + send_nok/1, + send_eval/1, + send_bad_answer/1, send_arbitrary/1, send_unknown/1, send_unknown_mandatory/1, @@ -73,29 +77,27 @@ send_multiple_filters_3/1, send_anything/1, remove_transports/1, - stop_services/1]). + stop_services/1, + stop/1]). %% diameter callbacks -export([peer_up/3, peer_down/3, - pick_peer/5, pick_peer/6, - prepare_request/4, prepare_request/5, - prepare_retransmit/4, - handle_answer/5, handle_answer/6, - handle_error/5, + pick_peer/6, pick_peer/7, + prepare_request/5, prepare_request/6, + prepare_retransmit/5, + handle_answer/6, handle_answer/7, + handle_error/6, handle_request/3]). --ifdef(DIAMETER_CT). +-include("diameter.hrl"). -include("diameter_gen_base_rfc3588.hrl"). --else. --include_lib("diameter/include/diameter_gen_base_rfc3588.hrl"). --endif. - --include_lib("diameter/include/diameter.hrl"). --include("diameter_ct.hrl"). +-include("diameter_gen_base_accounting.hrl"). %% =========================================================================== +-define(util, diameter_util). + -define(ADDR, {127,0,0,1}). -define(CLIENT, "CLIENT"). @@ -103,11 +105,23 @@ -define(REALM, "erlang.org"). -define(HOST(Host, Realm), Host ++ [$.|Realm]). --define(APP_ALIAS, base). -define(EXTRA, an_extra_argument). + +-define(BASE, ?DIAMETER_DICT_COMMON). +-define(ACCT, ?DIAMETER_DICT_ACCOUNTING). + +%% Sequence mask for End-to-End and Hop-by-Hop identifiers. +-define(CLIENT_MASK, {1,26}). %% 1 in top 6 bits + +%% Run tests cases in different encoding variants. Send outgoing +%% messages as lists or records. -define(ENCODINGS, [list, record]). --define(DICT, ?DIAMETER_DICT_COMMON). +%% Identifers for client connections. +-define(CONNECTIONS, [c1,c2,c3]). + +%% Not really what we should be setting unless the message is sent in +%% the common application but diameter doesn't care. -define(APP_ID, ?DIAMETER_APP_ID_COMMON). %% Config for diameter:start_service/2. @@ -117,24 +131,13 @@ {'Host-IP-Address', [?ADDR]}, {'Vendor-Id', 12345}, {'Product-Name', "OTP/diameter"}, - {'Acct-Application-Id', [?DIAMETER_APP_ID_COMMON]}, - {application, [{alias, ?APP_ALIAS}, - {dictionary, ?DIAMETER_DICT_COMMON}, - {module, ?MODULE}, - {answer_errors, callback}]}]). - -%% Config for diameter:add_transport/2. In the listening case, listen -%% on a free port that we then lookup using the implementation detail -%% that diameter_tcp registers the port with diameter_reg. --define(CONNECT(PortNr), - {connect, [{transport_module, diameter_tcp}, - {transport_config, [{raddr, ?ADDR}, - {rport, PortNr}, - {ip, ?ADDR}, - {port, 0}]}]}). --define(LISTEN, - {listen, [{transport_module, diameter_tcp}, - {transport_config, [{ip, ?ADDR}, {port, 0}]}]}). + {'Auth-Application-Id', [?DIAMETER_APP_ID_COMMON]}, + {'Acct-Application-Id', [?DIAMETER_APP_ID_ACCOUNTING]}, + {restrict_connections, false} + | [{application, [{dictionary, D}, + {module, ?MODULE}, + {answer_errors, callback}]} + || D <- [?BASE, ?ACCT]]]). -define(SUCCESS, ?'DIAMETER_BASE_RESULT-CODE_DIAMETER_SUCCESS'). @@ -146,6 +149,8 @@ ?'DIAMETER_BASE_RESULT-CODE_DIAMETER_APPLICATION_UNSUPPORTED'). -define(INVALID_HDR_BITS, ?'DIAMETER_BASE_RESULT-CODE_DIAMETER_INVALID_HDR_BITS'). +-define(INVALID_AVP_BITS, + ?'DIAMETER_BASE_RESULT-CODE_DIAMETER_INVALID_AVP_BITS'). -define(AVP_UNSUPPORTED, ?'DIAMETER_BASE_RESULT-CODE_DIAMETER_AVP_UNSUPPORTED'). -define(UNSUPPORTED_VERSION, @@ -169,47 +174,27 @@ -define(A, list_to_atom). -define(L, atom_to_list). --define(P(N), ?A("p_" ++ ?L(N))). + +-define(NAME(A,B), ?A(?L(A) ++ "," ++ ?L(B))). %% =========================================================================== suite() -> - [{timetrap, {seconds, 10}}]. + [{timetrap, {seconds, 60}}]. all() -> - [result_codes | [{group, N} || {N, _, _} <- groups()]] - ++ [remove_transports, stop_services]. + [start, start_services, add_transports, result_codes] + ++ [{group, ?util:name([E,C]), P} || E <- ?ENCODINGS, + C <- ?CONNECTIONS, + P <- [[], [parallel]]] + ++ [remove_transports, stop_services, stop]. groups() -> Ts = tc(), - [{E, [], Ts} || E <- ?ENCODINGS] - ++ [{?P(E), [parallel], Ts} || E <- ?ENCODINGS]. - -init_per_suite(Config) -> - ok = diameter:start(), - ok = diameter:start_service(?SERVER, ?SERVICE(?SERVER)), - ok = diameter:start_service(?CLIENT, ?SERVICE(?CLIENT)), - {ok, LRef} = diameter:add_transport(?SERVER, ?LISTEN), - true = diameter:subscribe(?CLIENT), - {ok, CRef} = diameter:add_transport(?CLIENT, ?CONNECT(portnr())), - {up, CRef, _Peer, _Config, #diameter_packet{}} - = receive #diameter_event{service = ?CLIENT, info = I} -> I - after 2000 -> false - end, - true = diameter:unsubscribe(?CLIENT), - [{transports, {LRef, CRef}} | Config]. - -end_per_suite(_Config) -> - ok = diameter:stop(). + [{?util:name([E,C]), [], Ts} || E <- ?ENCODINGS, C <- ?CONNECTIONS]. init_per_group(Name, Config) -> - E = case ?L(Name) of - "p_" ++ Rest -> - ?A(Rest); - _ -> - Name - end, - [{encode, E} | Config]. + [{group, Name} | Config]. end_per_group(_, _) -> ok. @@ -224,6 +209,9 @@ end_per_testcase(_, _) -> %% established. tc() -> [send_ok, + send_nok, + send_eval, + send_bad_answer, send_arbitrary, send_unknown, send_unknown_mandatory, @@ -261,26 +249,42 @@ tc() -> send_multiple_filters_3, send_anything]. -portnr() -> - portnr(20). - -portnr(N) - when 0 < N -> - case diameter_reg:match({diameter_tcp, listener, '_'}) of - [{T, _Pid}] -> - {_, _, {_LRef, {_Addr, LSock}}} = T, - {ok, PortNr} = inet:port(LSock), - PortNr; - [] -> - receive after 50 -> ok end, - portnr(N-1) - end. +%% =========================================================================== +%% start/stop testcases + +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)]). + +add_transports(Config) -> + LRef = ?util:listen(?SERVER, tcp, [{capabilities_cb, fun capx/2}]), + Cs = [?util:connect(?CLIENT, tcp, LRef, [{id, C}]) || C <- ?CONNECTIONS], + ?util:write_priv(Config, "transport", [LRef | Cs]). + +remove_transports(Config) -> + [LRef | Cs] = ?util:read_priv(Config, "transport"), + [?util:disconnect(?CLIENT, C, ?SERVER, LRef) || C <- Cs]. + +stop_services(_Config) -> + ok = diameter:stop_service(?CLIENT), + ok = diameter:stop_service(?SERVER). + +stop(_Config) -> + ok = diameter:stop(). + +capx(_, #diameter_caps{origin_host = {OH,DH}}) -> + io:format("connection: ~p -> ~p~n", [DH,OH]), + ok. %% =========================================================================== %% Ensure that result codes have the expected values. result_codes(_Config) -> - {2001, 3001, 3002, 3003, 3004, 3007, 3008, 5001, 5011} + {2001, 3001, 3002, 3003, 3004, 3007, 3008, 3009, 5001, 5011} = {?SUCCESS, ?COMMAND_UNSUPPORTED, ?UNABLE_TO_DELIVER, @@ -288,6 +292,7 @@ result_codes(_Config) -> ?TOO_BUSY, ?APPLICATION_UNSUPPORTED, ?INVALID_HDR_BITS, + ?INVALID_AVP_BITS, ?AVP_UNSUPPORTED, ?UNSUPPORTED_VERSION}. @@ -295,9 +300,34 @@ result_codes(_Config) -> send_ok(Config) -> Req = ['ACR', {'Accounting-Record-Type', ?EVENT_RECORD}, {'Accounting-Record-Number', 1}], - #diameter_base_ACA{'Result-Code' = ?SUCCESS} + + #diameter_base_accounting_ACA{'Result-Code' = ?SUCCESS} = call(Config, Req). +%% Send an accounting ACR that the server answers badly to. +send_nok(Config) -> + Req = ['ACR', {'Accounting-Record-Type', ?EVENT_RECORD}, + {'Accounting-Record-Number', 0}], + + #'diameter_base_answer-message'{'Result-Code' = ?INVALID_AVP_BITS} + = call(Config, Req). + +%% Send an ACR and expect success. +send_eval(Config) -> + Req = ['ACR', {'Accounting-Record-Type', ?EVENT_RECORD}, + {'Accounting-Record-Number', 3}], + + #diameter_base_accounting_ACA{'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. +send_bad_answer(Config) -> + Req = ['ACR', {'Accounting-Record-Type', ?EVENT_RECORD}, + {'Accounting-Record-Number', 2}], + {error, timeout} = call(Config, Req). + %% Send an ASR with an arbitrary AVP and expect success and the same %% AVP in the reply. send_arbitrary(Config) -> @@ -347,7 +377,7 @@ send_unsupported(Config) -> #'diameter_base_answer-message'{'Result-Code' = ?COMMAND_UNSUPPORTED} = call(Config, Req). -%% Send an unsupported command and expect 3007. +%% Send an unsupported application and expect 3007. send_unsupported_app(Config) -> Req = ['STR', {'Termination-Cause', ?BAD_ANSWER}], #'diameter_base_answer-message'{'Result-Code' = ?APPLICATION_UNSUPPORTED} @@ -528,24 +558,9 @@ send_multiple_filters(Config, Fs) -> %% Ensure that we can pass a request in any form to diameter:call/4, %% only the return value from the prepare_request callback being %% significant. -send_anything(Config) -> +send_anything(Config) -> #diameter_base_STA{'Result-Code' = ?SUCCESS} = call(Config, anything). - -%% Remove the client transport and expect the server transport to -%% go down. -remove_transports(Config) -> - {LRef, CRef} = proplists:get_value(transports, Config), - true = diameter:subscribe(?SERVER), - ok = diameter:remove_transport(?CLIENT, CRef), - {down, LRef, _, _} - = receive #diameter_event{service = ?SERVER, info = I} -> I - after 2000 -> false - end. - -stop_services(_Config) -> - {ok, ok} = {diameter:stop_service(?CLIENT), - diameter:stop_service(?SERVER)}. %% =========================================================================== @@ -554,32 +569,44 @@ call(Config, Req) -> call(Config, Req, Opts) -> Name = proplists:get_value(testcase, Config), - Enc = proplists:get_value(encode, Config), + [Encoding, Client] = ?util:name(proplists:get_value(group, Config)), diameter:call(?CLIENT, - ?APP_ALIAS, - msg(Req, Enc), - [{extra, [Name]} | Opts]). - -msg([_|_] = L, list) -> - L; -msg([H|T], record) -> - ?DICT:'#new-'(?DICT:msg2rec(H), T); -msg(T, _) -> + dict(Req), + req(Req, Encoding), + [{extra, [Name, Client]} | Opts]). + +req(['ACR' = H | T], record) -> + ?ACCT:'#new-'(?ACCT:msg2rec(H), T); +req([H|T], record) -> + ?BASE:'#new-'(?BASE:msg2rec(H), T); +req(T, _) -> T. +dict(['ACR' | _]) -> + ?ACCT; +dict(_) -> + ?BASE. + %% Set only values that aren't already. set([H|T], Vs) -> [H | Vs ++ T]; +set(#diameter_base_accounting_ACR{} = Rec, Vs) -> + set(Rec, Vs, ?ACCT); set(Rec, Vs) -> - lists:foldl(fun({F,_} = FV, A) -> set(?DICT:'#get-'(F, A), FV, A) end, + set(Rec, Vs, ?BASE). + +set(Rec, Vs, Dict) -> + lists:foldl(fun({F,_} = FV, A) -> + set(Dict, Dict:'#get-'(F, A), FV, A) + end, Rec, Vs). -set(E, FV, Rec) +set(Dict, E, FV, Rec) when E == undefined; E == [] -> - ?DICT:'#set-'(FV, Rec); -set(_, _, Rec) -> + Dict:'#set-'(FV, Rec); +set(_, _, _, Rec) -> Rec. %% =========================================================================== @@ -595,41 +622,53 @@ peer_up(_SvcName, _Peer, State) -> peer_down(_SvcName, _Peer, State) -> State. -%% pick_peer/5/6 +%% pick_peer/6-7 -pick_peer([Peer], _, ?CLIENT, _State, Name) +pick_peer(Peers, _, ?CLIENT, _State, Name, Id) when Name /= send_detach -> - {ok, Peer}. + find(Id, Peers). -pick_peer([_Peer], _, ?CLIENT, _State, send_nopeer, ?EXTRA) -> +pick_peer(_Peers, _, ?CLIENT, _State, send_nopeer, _, ?EXTRA) -> false; -pick_peer([Peer], _, ?CLIENT, _State, send_detach, {_,_}) -> - {ok, Peer}. +pick_peer(Peers, _, ?CLIENT, _State, send_detach, Id, {_,_}) -> + find(Id, Peers). + +find(Id, Peers) -> + [P] = [P || P <- Peers, id(Id, P)], + {ok, P}. + +id(Id, {Pid, _Caps}) -> + [{ref, _}, {type, _}, {options, Opts} | _] + = diameter:service_info(?CLIENT, Pid), + lists:member({id, Id}, Opts). -%% prepare_request/4/5 +%% prepare_request/5-6 -prepare_request(_Pkt, ?CLIENT, {_Ref, _Caps}, send_discard) -> +prepare_request(_Pkt, ?CLIENT, {_Ref, _Caps}, send_discard, _) -> {discard, unprepared}; -prepare_request(Pkt, ?CLIENT, {_Ref, Caps}, Name) -> +prepare_request(Pkt, ?CLIENT, {_Ref, Caps}, Name, _) -> {send, prepare(Pkt, Caps, Name)}. -prepare_request(Pkt, ?CLIENT, {_Ref, Caps}, send_detach, _) -> - {send, prepare(Pkt, Caps)}. +prepare_request(Pkt, ?CLIENT, {_Ref, Caps}, send_detach, _, _) -> + {eval_packet, {send, prepare(Pkt, Caps)}, [fun log/2, detach]}. + +log(#diameter_packet{} = P, T) -> + io:format("~p: ~p~n", [T,P]). prepare(Pkt, Caps, send_unsupported) -> Req = prepare(Pkt, Caps), #diameter_packet{bin = <<H:5/binary, _CmdCode:3/binary, T/binary>>} = E - = diameter_codec:encode(?DICT, Pkt#diameter_packet{msg = Req}), + = diameter_codec:encode(?BASE, Pkt#diameter_packet{msg = Req}), E#diameter_packet{bin = <<H/binary, 42:24/integer, T/binary>>}; prepare(Pkt, Caps, send_unsupported_app) -> Req = prepare(Pkt, Caps), #diameter_packet{bin = <<H:8/binary, _ApplId:4/binary, T/binary>>} = E - = diameter_codec:encode(?DICT, Pkt#diameter_packet{msg = Req}), + = diameter_codec:encode(?BASE, Pkt#diameter_packet{msg = Req}), E#diameter_packet{bin = <<H/binary, 42:32/integer, T/binary>>}; prepare(Pkt, Caps, send_error_bit) -> @@ -650,7 +689,7 @@ prepare(Pkt, Caps, _Name) -> prepare(Pkt, Caps). prepare(#diameter_packet{msg = Req}, Caps) - when is_record(Req, diameter_base_ACR); + when is_record(Req, diameter_base_accounting_ACR); 'ACR' == hd(Req) -> #diameter_caps{origin_host = {OH, _}, origin_realm = {OR, DR}} @@ -699,25 +738,25 @@ prepare(#diameter_packet{msg = Req}, Caps) {'Destination-Realm', DR}, {'Auth-Application-Id', ?APP_ID}]). -%% prepare_retransmit/4 +%% prepare_retransmit/5 -prepare_retransmit(_Pkt, false, _Peer, _Name) -> +prepare_retransmit(_Pkt, false, _Peer, _Name, _Id) -> discard. -%% handle_answer/5/6 +%% handle_answer/6-7 -handle_answer(Pkt, Req, ?CLIENT, Peer, Name) -> +handle_answer(Pkt, Req, ?CLIENT, Peer, Name, _Id) -> answer(Pkt, Req, Peer, Name). -handle_answer(Pkt, _Req, ?CLIENT, _Peer, send_detach, {Pid, Ref}) -> +handle_answer(Pkt, _Req, ?CLIENT, _Peer, send_detach, _Id, {Pid, Ref}) -> Pid ! {Ref, Pkt}. answer(#diameter_packet{msg = Rec, errors = []}, _Req, _Peer, _) -> Rec. -%% handle_error/5 +%% handle_error/6 -handle_error(Reason, _Req, ?CLIENT, _Peer, _Name) -> +handle_error(Reason, _Req, ?CLIENT, _Peer, _Name, _Id) -> {error, Reason}. %% handle_request/3 @@ -725,13 +764,54 @@ handle_error(Reason, _Req, ?CLIENT, _Peer, _Name) -> %% Note that diameter will set Result-Code and Failed-AVPs if %% #diameter_packet.errors is non-null. -handle_request(Pkt, ?SERVER, {_Ref, Caps}) -> - request(Pkt, Caps). - -request(#diameter_packet{msg - = #diameter_base_ACR{'Session-Id' = SId, - 'Accounting-Record-Type' = RT, - 'Accounting-Record-Number' = RN}}, +handle_request(#diameter_packet{header = H, msg = M}, ?SERVER, {_Ref, Caps}) -> + #diameter_header{end_to_end_id = EI, + hop_by_hop_id = HI} + = H, + {V,B} = ?CLIENT_MASK, + V = EI bsr B, %% assert + V = HI bsr B, %% + request(M, Caps). + +%% send_nok +request(#diameter_base_accounting_ACR{'Accounting-Record-Number' = 0}, + _) -> + {eval_packet, {protocol_error, ?INVALID_AVP_BITS}, [fun log/2, invalid]}; + +%% send_bad_answer +request(#diameter_base_accounting_ACR{'Session-Id' = SId, + 'Accounting-Record-Type' = RT, + 'Accounting-Record-Number' = 2 = RN}, + #diameter_caps{origin_host = {OH, _}, + origin_realm = {OR, _}}) -> + Ans = ['ACA', {'Result-Code', ?SUCCESS}, + {'Session-Id', SId}, + {'Origin-Host', OH}, + {'Origin-Realm', OR}, + {'Accounting-Record-Type', RT}, + {'Accounting-Record-Number', RN}], + + {reply, #diameter_packet{header = #diameter_header{is_error = true},%% not + msg = Ans}}; + +%% send_eval +request(#diameter_base_accounting_ACR{'Session-Id' = SId, + 'Accounting-Record-Type' = RT, + 'Accounting-Record-Number' = 3 = RN}, + #diameter_caps{origin_host = {OH, _}, + origin_realm = {OR, _}}) -> + Ans = ['ACA', {'Result-Code', ?SUCCESS}, + {'Session-Id', SId}, + {'Origin-Host', OH}, + {'Origin-Realm', OR}, + {'Accounting-Record-Type', RT}, + {'Accounting-Record-Number', RN}], + {eval, {reply, Ans}, {erlang, now, []}}; + +%% send_ok +request(#diameter_base_accounting_ACR{'Session-Id' = SId, + 'Accounting-Record-Type' = RT, + 'Accounting-Record-Number' = 1 = RN}, #diameter_caps{origin_host = {OH, _}, origin_realm = {OR, _}}) -> {reply, ['ACA', {'Result-Code', ?SUCCESS}, @@ -741,8 +821,8 @@ request(#diameter_packet{msg {'Accounting-Record-Type', RT}, {'Accounting-Record-Number', RN}]}; -request(#diameter_packet{msg = #diameter_base_ASR{'Session-Id' = SId, - 'AVP' = Avps}}, +request(#diameter_base_ASR{'Session-Id' = SId, + 'AVP' = Avps}, #diameter_caps{origin_host = {OH, _}, origin_realm = {OR, _}}) -> {reply, #diameter_base_ASA{'Result-Code' = ?SUCCESS, @@ -751,22 +831,25 @@ request(#diameter_packet{msg = #diameter_base_ASR{'Session-Id' = SId, 'Origin-Realm' = OR, 'AVP' = Avps}}; -request(#diameter_packet{msg = #diameter_base_STR{'Termination-Cause' = T}}, +%% send_noreply +request(#diameter_base_STR{'Termination-Cause' = T}, _Caps) when T /= ?LOGOUT -> discard; -request(#diameter_packet{msg = #diameter_base_STR{'Destination-Realm'= R}}, +%% send_destination_5 +request(#diameter_base_STR{'Destination-Realm'= R}, #diameter_caps{origin_realm = {OR, _}}) when R /= undefined, R /= OR -> {protocol_error, ?REALM_NOT_SERVED}; -request(#diameter_packet{msg = #diameter_base_STR{'Destination-Host'= [H]}}, +%% send_destination_6 +request(#diameter_base_STR{'Destination-Host'= [H]}, #diameter_caps{origin_host = {OH, _}}) when H /= OH -> {protocol_error, ?UNABLE_TO_DELIVER}; -request(#diameter_packet{msg = #diameter_base_STR{'Session-Id' = SId}}, +request(#diameter_base_STR{'Session-Id' = SId}, #diameter_caps{origin_host = {OH, _}, origin_realm = {OR, _}}) -> {reply, #diameter_base_STA{'Result-Code' = ?SUCCESS, @@ -774,6 +857,7 @@ request(#diameter_packet{msg = #diameter_base_STR{'Session-Id' = SId}}, 'Origin-Host' = OH, 'Origin-Realm' = OR}}; -request(#diameter_packet{msg = #diameter_base_RAR{}}, _Caps) -> +%% send_error +request(#diameter_base_RAR{}, _Caps) -> receive after 2000 -> ok end, {protocol_error, ?TOO_BUSY}. diff --git a/lib/diameter/test/diameter_transport_SUITE.erl b/lib/diameter/test/diameter_transport_SUITE.erl index d545859fe8..893b7ba2f9 100644 --- a/lib/diameter/test/diameter_transport_SUITE.erl +++ b/lib/diameter/test/diameter_transport_SUITE.erl @@ -27,24 +27,23 @@ -export([suite/0, all/0, groups/0, - init_per_group/2, - end_per_group/2, init_per_suite/1, end_per_suite/1]). %% testcases --export([tcp_accept/1, +-export([start/1, + tcp_accept/1, tcp_connect/1, sctp_accept/1, - sctp_connect/1]). + sctp_connect/1, + stop/1]). -export([accept/1, connect/1, init/2]). -include_lib("kernel/include/inet_sctp.hrl"). --include_lib("diameter/include/diameter.hrl"). --include("diameter_ct.hrl"). +-include("diameter.hrl"). -define(util, diameter_util). @@ -67,16 +66,6 @@ = #diameter_caps{host_ip_address = Addrs}}). -%% The term diameter_tcp/sctp registers after opening a listening -%% socket. This is an implementation detail that should probably be -%% replaced by some documented way of getting at the port number of -%% the listening socket, which is what we're after since we specify -%% port 0 to get something unused. --define(TCP_LISTENER(Ref, Addr, LSock), - {diameter_tcp, listener, {Ref, {Addr, LSock}}}). --define(SCTP_LISTENER(Ref, Addr, LSock), - {diameter_sctp, listener, {Ref, {[Addr], LSock}}}). - %% The term we register after open a listening port with gen_tcp. -define(TEST_LISTENER(Ref, PortNr), {?MODULE, listen, Ref, PortNr}). @@ -101,10 +90,13 @@ suite() -> [{timetrap, {minutes, 2}}]. all() -> - [{group, all} | tc()]. + [start, + {group, all}, + {group, all, [parallel]}, + stop]. groups() -> - [{all, [parallel], tc()}]. + [{all, [], tc()}]. tc() -> [tcp_accept, @@ -112,17 +104,18 @@ tc() -> sctp_accept, sctp_connect]. -init_per_group(_, Config) -> - Config. - -end_per_group(_, _) -> - ok. - init_per_suite(Config) -> - ok = diameter:start(), [{sctp, have_sctp()} | Config]. end_per_suite(_Config) -> + ok. + +%% =========================================================================== + +start(_Config) -> + ok = diameter:start(). + +stop(_Config) -> ok = diameter:stop(). %% =========================================================================== @@ -177,12 +170,12 @@ connect(Prot) -> %% have_sctp/0 have_sctp() -> - try gen_sctp:open() of + case gen_sctp:open() of {ok, Sock} -> gen_sctp:close(Sock), - true - catch - error: badarg -> + true; + {error, E} when E == eprotonosupport; + E == esocktnosupport -> %% fail on any other reason false end. @@ -216,10 +209,10 @@ init(accept, {Prot, Ref}) -> init(gen_connect, {Prot, Ref}) -> %% Lookup the peer's listening socket. - {ok, PortNr} = inet:port(lsock(Prot, Ref)), + [PortNr] = ?util:lport(Prot, Ref, 20), %% Connect, send a message and receive it back. - {ok, Sock} = gen_connect(Prot, PortNr, Ref), + {ok, Sock} = gen_connect(Prot, PortNr), Bin = make_msg(), ok = gen_send(Prot, Sock, Bin), Bin = gen_recv(Prot, Sock); @@ -253,22 +246,16 @@ init(connect, {Prot, Ref}) -> MRef = erlang:monitor(process, TPid), ?RECV({'DOWN', MRef, process, _, _}). -lsock(sctp, Ref) -> - [{?SCTP_LISTENER(_ , _, LSock), _}] - = match(?SCTP_LISTENER(Ref, ?ADDR, '_')), - LSock; -lsock(tcp, Ref) -> - [{?TCP_LISTENER(_ , _, LSock), _}] - = match(?TCP_LISTENER(Ref, ?ADDR, '_')), - LSock. - match(Pat) -> - case diameter_reg:match(Pat) of - [] -> + match(Pat, 20). + +match(Pat, T) -> + L = diameter_reg:match(Pat), + if [] /= L orelse 1 == T -> + L; + true -> ?WAIT(50), - match(Pat); - L -> - L + match(Pat, T-1) end. bin(sctp, #diameter_packet{bin = Bin}) -> @@ -332,7 +319,7 @@ start_accept(Prot, Ref) -> %% Configure the same port number for transports on the same %% reference. - PortNr = portnr(Prot, Ref), + [PortNr | _] = ?util:lport(Prot, Ref) ++ [0], {Mod, Opts} = tmod(Prot), try @@ -362,39 +349,9 @@ tmod(sctp) -> tmod(tcp) -> {diameter_tcp, []}. -portnr(sctp, Ref) -> - case diameter_reg:match(?SCTP_LISTENER(Ref, ?ADDR, '_')) of - [{?SCTP_LISTENER(_, _, LSock), _}] -> - {ok, N} = inet:port(LSock), - N; - [] -> - 0 - end; -portnr(tcp, Ref) -> - case diameter_reg:match(?TCP_LISTENER(Ref, ?ADDR, '_')) of - [{?TCP_LISTENER(_, _, LSock), _}] -> - {ok, N} = inet:port(LSock), - N; - [] -> - 0 - end. - %% =========================================================================== -%% gen_connect/3 - -gen_connect(Prot, PortNr, Ref) -> - Pid = sync(connect, Ref), - - %% Stagger connect attempts to avoid the situation that no - %% transport process is accepting yet. - receive after 250 -> ok end, - - try - gen_connect(Prot, PortNr) - after - Pid ! Ref - end. +%% gen_connect/2 gen_connect(sctp = P, PortNr) -> {ok, Sock} = Ok = gen_sctp:open([{ip, ?ADDR}, {port, 0} | ?SCTP_OPTS]), diff --git a/lib/diameter/test/diameter_util.erl b/lib/diameter/test/diameter_util.erl index 99f4fa1977..5af4ad9ba5 100644 --- a/lib/diameter/test/diameter_util.erl +++ b/lib/diameter/test/diameter_util.erl @@ -1,7 +1,7 @@ %% %% %CopyrightBegin% %% -%% Copyright Ericsson AB 2010-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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,15 +23,45 @@ %% Utility functions. %% --export([consult/2, +%% generic +-export([name/1, + consult/2, run/1, fold/3, foldl/3, - scramble/1, - ps/0]). + scramble/1]). + +%% diameter-specific +-export([lport/2, + lport/3, + listen/2, listen/3, + connect/3, connect/4, + disconnect/4, + info/0]). + +%% common_test-specific +-export([write_priv/3, + read_priv/2, + map_priv/3]). -define(L, atom_to_list). + +%% --------------------------------------------------------------------------- +%% name/2 +%% +%% Contruct and deconstruct lists of atoms as atoms to work around +%% group names in common_test being restricted to atoms. + +name(Names) + when is_list(Names) -> + list_to_atom(string:join([atom_to_list(A) || A <- Names], ",")); + +name(A) + when is_atom(A) -> + [list_to_atom(S) || S <- string:tokens(atom_to_list(A), ",")]. + +%% --------------------------------------------------------------------------- %% consult/2 %% %% Extract info from the app/appup file (presumably) of the named @@ -56,6 +86,7 @@ consult(Path) -> %% Name/Path in the return value distinguish the errors and allow for %% a useful badmatch. +%% --------------------------------------------------------------------------- %% run/1 %% %% Evaluate functions in parallel and return a list of those that @@ -71,6 +102,7 @@ cons(true, _, _, Acc) -> cons(false, F, RC, Acc) -> [{F, RC} | Acc]. +%% --------------------------------------------------------------------------- %% fold/3 %% %% Parallel fold. Results are folded in the order received. @@ -116,6 +148,7 @@ down(MRef) -> down() -> receive {'DOWN', MRef, process, _, Reason} -> {MRef, Reason} end. +%% --------------------------------------------------------------------------- %% foldl/3 %% %% Parallel fold. Results are folded in order of the function list. @@ -131,6 +164,7 @@ recvl([{MRef, F} | L], Ref, Fun, Acc) -> R = down(MRef), recvl(L, Ref, Fun, acc(R, Ref, F, Fun, Acc)). +%% --------------------------------------------------------------------------- %% scramble/1 %% %% Sort a list into random order. @@ -150,12 +184,10 @@ s(Acc, L) -> {H, [T|Rest]} = lists:split(random:uniform(length(L)) - 1, L), s([T|Acc], H ++ Rest). -%% ps/0 - -ps() -> - [{P, process_info(P)} || P <- erlang:processes()]. - +%% --------------------------------------------------------------------------- %% eval/1 +%% +%% Evaluate a function in one of a number of forms. eval({M,[F|A]}) when is_atom(F) -> @@ -175,3 +207,157 @@ eval(L) eval(F) when is_function(F,0) -> F(). + +%% --------------------------------------------------------------------------- +%% write_priv/3 +%% +%% Write an arbitrary term to a named file. + +write_priv(Config, Name, Term) -> + write(path(Config, Name), Term). + +write(Path, Term) -> + ok = file:write_file(Path, term_to_binary(Term)). + +%% read_priv/2 +%% +%% Read a term from a file. + +read_priv(Config, Name) -> + read(path(Config, Name)). + +read(Path) -> + {ok, Bin} = file:read_file(Path), + binary_to_term(Bin). + +%% map_priv/3 +%% +%% Modify a term in a file and return both old and new values. + +map_priv(Config, Name, Fun1) -> + map(path(Config, Name), Fun1). + +map(Path, Fun1) -> + T0 = read(Path), + T1 = Fun1(T0), + write(Path, T1), + {T0, T1}. + +path(Config, Name) + when is_atom(Name) -> + path(Config, ?L(Name)); +path(Config, Name) -> + Dir = proplists:get_value(priv_dir, Config), + filename:join([Dir, Name]). + +%% --------------------------------------------------------------------------- +%% lport/2-3 +%% +%% Lookup the port number of a tcp/sctp listening transport. + +lport(M, Ref) -> + lport(M, Ref, 1). + +lport(M, Ref, Tries) -> + lp(tmod(M), Ref, Tries). + +lp(M, Ref, T) -> + L = [N || {listen, N, _} <- M:ports(Ref)], + if [] /= L orelse T =< 1 -> + L; + true -> + receive after 50 -> ok end, + lp(M, Ref, T-1) + end. + +%% --------------------------------------------------------------------------- +%% listen/2-3 +%% +%% Add a listening transport on the loopback address and a free port. + +listen(SvcName, Prot) -> + listen(SvcName, Prot, []). + +listen(SvcName, Prot, Opts) -> + SvcName = diameter:service_info(SvcName, name), %% assert + Ref = add_transport(SvcName, {listen, opts(Prot, listen) ++ Opts}), + true = transport(SvcName, Ref), %% assert + Ref. + +%% --------------------------------------------------------------------------- +%% connect/2-3 +%% +%% Add a connecting transport on and connect to a listening transport +%% with the specified reference. + +connect(Client, Prot, LRef) -> + connect(Client, Prot, LRef, []). + +connect(Client, Prot, LRef, Opts) -> + [PortNr] = lport(Prot, LRef, 20), + Client = diameter:service_info(Client, name), %% assert + true = diameter:subscribe(Client), + 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, + Ref. + +transport(SvcName, Ref) -> + [Ref] == [R || [{ref, R} | _] <- diameter:service_info(SvcName, transport), + R == Ref]. + +%% --------------------------------------------------------------------------- +%% disconnect/4 +%% +%% Remove the client transport and expect the server transport to go +%% down. + +disconnect(Client, Ref, Server, LRef) -> + true = diameter:subscribe(Server), + ok = diameter:remove_transport(Client, Ref), + ok = receive + {diameter_event, Server, {down, LRef, _, _}} -> ok + after 10000 -> + {Client, Ref, Server, LRef, process_info(self(), messages)} + end. + +%% --------------------------------------------------------------------------- + +-define(ADDR, {127,0,0,1}). + +add_transport(SvcName, T) -> + {ok, Ref} = diameter:add_transport(SvcName, T), + Ref. + +tmod(tcp) -> + diameter_tcp; +tmod(sctp) -> + diameter_sctp. + +opts(Prot, T) -> + [{transport_module, tmod(Prot)}, + {transport_config, [{ip, ?ADDR}, {port, 0} | opts(T)]}]. + +opts(listen) -> + []; +opts(PortNr) -> + [{raddr, ?ADDR}, {rport, PortNr}]. + +%% --------------------------------------------------------------------------- +%% info/0 + +info() -> + [_|_] = Svcs = diameter:services(), %% assert + run([[fun info/1, S] || S <- Svcs]). + +info(S) -> + [_|_] = Keys = diameter:service_info(S, keys), + [] = run([[fun info/2, K, S] || K <- Keys]). + +info(Key, SvcName) -> + [{Key, _}] = diameter:service_info(SvcName, [Key]). diff --git a/lib/diameter/test/diameter_watchdog_SUITE.erl b/lib/diameter/test/diameter_watchdog_SUITE.erl index dec307529a..7ce09e93ca 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-2011. All Rights Reserved. +%% Copyright Ericsson AB 2010-2012. 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,46 +30,44 @@ end_per_suite/1]). %% testcases --export([reopen/1, reopen/4]). +-export([reopen/1, reopen/4, reopen/7]). --export([start/3, %% diameter_transport callback - id/1, %% jitter callback - run/1]). +-export([id/1, %% jitter callback + run1/1]). --include_lib("diameter/include/diameter.hrl"). +%% diameter_app callbacks +-export([peer_up/3, + peer_down/3]). + +%% gen_tcp-ish interface +-export([listen/2, + accept/1, + connect/3, + send/2, + setopts/2]). + +-include("diameter.hrl"). -include("diameter_ct.hrl"). %% =========================================================================== -define(util, diameter_util). --define(BASE, diameter_gen_base_rfc3588). --define(APPL_ID, diameter_gen_base_rfc3588:id()). --define(SUCCESS, 2001). %% DIAMETER_SUCCESS - -%% Addresses for the local and remote diameter nodes. The values don't -%% matter since we're faking transport. --define(LOCALHOST, {127,0,0,1}). --define(REMOTEHOST, {10,0,0,1}). - --define(CAPS, #diameter_caps{origin_host = "node.innan.com", - origin_realm = "innan.com", - host_ip_address = [?LOCALHOST], - vendor_id = 1022, - product_name = "remote", - auth_application_id = [?APPL_ID]}). - --define(APPL, #diameter_app{alias = ?MODULE, - dictionary = ?BASE, - module = [?MODULE], - init_state = now(), - id = ?APPL_ID, - mutable = false}). - -%% Service record maintained by our faked service process. --define(SERVICE, #diameter_service{pid = self(), - capabilities = ?CAPS, - applications = [?APPL]}). +-define(BASE, ?DIAMETER_DICT_COMMON). +-define(REALM, "erlang.org"). +-define(ADDR, {127,0,0,1}). + +%% Config for diameter:start_service/2. +-define(SERVICE(Name), + [{'Origin-Host', Name ++ "." ++ ?REALM}, + {'Origin-Realm', ?REALM}, + {'Host-IP-Address', [?ADDR]}, + {'Vendor-Id', 42}, + {'Product-Name', "OTP/diameter"}, + {'Auth-Application-Id', [?DIAMETER_APP_ID_COMMON]}, + {application, [{alias, Name}, + {dictionary, ?BASE}, + {module, ?MODULE}]}]). %% Watchdog timer as a callback. -define(WD(T), {?MODULE, id, [T]}). @@ -82,28 +80,28 @@ F_ <- [fun(T__) -> T__ end, fun(T__) -> ?WD(T__) end]]]). -%% Transport types. --define(TRANSPORTS, [connect, accept]). +%% Watchdog timer of the misbehaving peer. +-define(PEER_WD, 10000). -%% Message over the transport interface. --define(TMSG(T), {diameter, T}). - -%% Receive a message within a specified time. --define(RECV(T, Timeout), - receive T -> now() - after Timeout -> ?ERROR({timeout, Timeout}) +%% Receive a watchdog event within a specified time. +-define(EVENT(T, Tmo), + receive #diameter_event{info = T} -> now() + after Tmo -> ?ERROR({timeout, Tmo}) end). -%% Receive a message in a given number of watchdogs, plus or minus +%% Receive an event in a given number of watchdogs, plus or minus %% half. Note that the call to now_diff assumes left to right %% evaluation order. --define(RECV(T, N, WdL, WdH), +-define(EVENT(T, N, WdL, WdH), [?ERROR({received, _Elapsed_, _LowerBound_, N, WdL}) || _UpperBound_ <- [(N)*(WdH) + (WdH) div 2], - _Elapsed_ <- [now_diff(now(), ?RECV(T, _UpperBound_))], + _Elapsed_ <- [now_diff(now(), ?EVENT(T, _UpperBound_))], _LowerBound_ <- [(N)*(WdL) - (WdL) div 2], _Elapsed_ =< _LowerBound_*1000]). +-define(EVENT(T, N, Wd), + ?EVENT(T, N, Wd, Wd)). + %% A timeout that ensures one watchdog. The ensure only one watchdog %% requires (Wd + 2000) + 1000 < 2*(Wd - 2000) ==> 7000 < Wd for the %% case with random jitter. @@ -112,7 +110,7 @@ %% =========================================================================== suite() -> - [{timetrap, {minutes, 6}}].%% enough for 11 watchdogs @ 30 sec plus jitter + [{timetrap, {minutes, 10}}].%% enough for 17 watchdogs @ 30 sec plus jitter all() -> [reopen]. @@ -134,52 +132,97 @@ end_per_suite(_Config) -> %% implement a transport process that plays the role of the peer %% Diameter node. +%reopen(_) -> +% reopen(connect, ?WD(10000), 1, 'DWR'); + reopen(_) -> - [] = ?util:run([{?MODULE, [run, [reopen, Wd, T, N, M]]} - || Wd <- ?WD_TIMERS, - T <- ?TRANSPORTS, - N <- [0,1,2], - M <- ['DWR', 'DWA', other]]). + [] = run([[reopen, T, Wd, N, M] + || Wd <- ?WD_TIMERS, %% watchdog_timer value + T <- [listen, connect], %% watchdog to test + N <- [0,1,2], %% DWR's to answer before ignoring + M <- ['DWR', 'DWA', 'RAA']]). %% how to induce failback -reopen(Wd, Type, N, What) -> - Ref = make_ref(), +reopen(Type, Wd, N, M) -> + Server = start_service(), + Client = start_service(), - %% The maker of transport processes. - TPid = start({N, Wd, What, Ref}), + %% The peer to the transport whose watchdog is tested is given a + %% long watchdog timeout so that it doesn't send DWR of its own. + {Node, Peer} = {{[], Wd}, {[{module, ?MODULE}], ?WD(?PEER_WD)}}, - %% Act like diameter_service and start the watchdog process, which - %% in turn starts a peer_fsm process, which in turn starts a - %% transport process by way of start/3. Messages received by the - %% testcase are those sent by diameter_watchdog to the service - %% process (= process starting the watchdog). - WPid1 = watchdog(Type, Ref, TPid, Wd), + {{LH,LW},{CH,CW}} = case Type of + listen -> {Node, Peer}; + connect -> {Peer, Node} + end, - %% Low/high watchdog timeouts. - WdL = jitter(Wd, -2000), - WdH = jitter(Wd, 2000), + LO = [{transport_module, diameter_tcp}, + {transport_config, LH ++ [{ip, ?ADDR}, {port, 0}]}, + {watchdog_timer, LW}], + + {ok, LRef} = diameter:add_transport(Server, {listen, LO}), + + [LP] = ?util:lport(tcp, LRef, 20), + + CO = [{transport_module, diameter_tcp}, + {transport_config, CH ++ [{ip, ?ADDR}, {port, 0}, + {raddr, ?ADDR}, {rport, LP}]}, + {watchdog_timer, CW}], + + %% Use a temporary process to ensure the connecting transport is + %% added only once events from the listening transport are + %% subscribed to. + Pid = spawn(fun() -> receive _ -> ok end end), + + [] = run([[reopen, Type, T, LRef, Pid, Wd, N, M] + || T <- [{listen, Server}, {connect, Client, CO}]]). + +%% start_service/1 + +start_service() -> + Name = hostname(), + ok = diameter:start_service(Name, [{monitor, self()} | ?SERVICE(Name)]), + Name. + +%% reopen/7 +reopen(Type, {listen = T, SvcName}, Ref, Pid, Wd, N, M) -> + diameter:subscribe(SvcName), + Pid ! ok, + recv(Type, T, SvcName, Ref, Wd, N, M); + +reopen(Type, {connect = T, SvcName, Opts}, _, Pid, Wd, N, M) -> + diameter:subscribe(SvcName), + MRef = erlang:monitor(process, Pid), + receive {'DOWN', MRef, process, _, _} -> ok end, + {ok, Ref} = diameter:add_transport(SvcName, {T, Opts}), + recv(Type, T, SvcName, Ref, Wd, N, M). + +%% recv/7 + +%% The watchdog to be tested. +recv(Type, Type, _SvcName, Ref, Wd, N, M) -> %% Connection should come up immediately as a consequence of %% starting the watchdog process. In the accepting case this %% results in a new watchdog on a transport waiting for a new %% connection. - ?RECV({connection_up, WPid1, _}, 1000), - WPid2 = case Type of - connect -> - WPid1; - accept -> - watchdog(Type, Ref, TPid, Wd) - end, + ?EVENT({watchdog, Ref, _, {initial, okay}, _}, 2000), + ?EVENT({up, Ref, _, _, #diameter_packet{}}, 0), + + %% Low/high watchdog timeouts. + WdL = jitter(Wd, -2000), + WdH = jitter(Wd, 2000), %% OKAY Timer expires & Failover() %% Pending SetWatchdog() SUSPECT %% - %% Since our transport is replying to N DWR's before becoming - %% silent, we should go down after N+2 watchdog_timer expirations: - %% that is, after the first unanswered DWR. Knowing the min/max - %% watchdog timeout values gives the time interval in which the - %% down message is expected. - ?RECV({connection_down, WPid1}, N+2, WdL, WdH), + %% The peer replies to N DWR's before becoming silent, we should + %% go down after N+2 watchdog_timer expirations: that is, after + %% the first unanswered DWR. Knowing the min/max watchdog timeout + %% values gives the time interval in which the event is expected. + + ?EVENT({watchdog, Ref, _, {okay, suspect}, _}, N+2, WdL, WdH), + ?EVENT({down, Ref, _, _}, 0), %% SUSPECT Receive DWA Pending = FALSE %% Failback() @@ -188,9 +231,11 @@ reopen(Wd, Type, N, What) -> %% SUSPECT Receive non-DWA Failback() %% SetWatchdog() OKAY %% - %% The transport receives a message before the expiry of another - %% watchdog to induce failback. - ?RECV({connection_up, WPid1}, WdH), + %% The peer sends a message before the expiry of another watchdog + %% to induce failback. + + ?EVENT({watchdog, Ref, _, {suspect, okay}, _}, WdH + 2000), + ?EVENT({up, Ref, _, _}, 0), %% OKAY Timer expires & SendWatchdog() %% !Pending SetWatchdog() @@ -199,30 +244,35 @@ reopen(Wd, Type, N, What) -> %% OKAY Timer expires & Failover() %% Pending SetWatchdog() SUSPECT %% - %% The transport is still not responding to watchdogs so the - %% connection should go back down after either one or two watchdog - %% expiries, depending on whether or not DWA restored the connection. - F = choose(What == 'DWA', 2, 1), - ?RECV({connection_down, WPid1}, F, WdL, WdH), + %% The peer is now ignoring all watchdogs so the connection goes + %% back down after either one or two watchdog expiries, depending + %% on whether or not DWA restored the connection. + + F = choose(M == 'DWA', 2, 1), + ?EVENT({watchdog, Ref, _, {okay, suspect}, _}, F, WdL, WdH), + ?EVENT({down, Ref, _, _}, 0), %% SUSPECT Timer expires CloseConnection() %% SetWatchdog() DOWN %% + %% Non-response brings the connection down after another timeout. + + ?EVENT({watchdog, Ref, _, {suspect, down}, _}, 1, WdL, WdH), + %% DOWN Timer expires AttemptOpen() %% SetWatchdog() DOWN %% - %% Our transport tells us when the fake connection is - %% reestablished, which should happen after another couple of - %% watchdog expiries, the first bringing the watchdog to state - %% DOWN, the second triggering an attempt to reopen the - %% connection. - ?RECV({reopen, Ref}, 2, WdL, WdH), - %% DOWN Connection up NumDWA = 0 %% SendWatchdog() %% SetWatchdog() %% Pending = TRUE REOPEN %% + %% The connection is reestablished after another timeout. + + recv_reopen(Type, Ref, WdL, WdH), + + %% REOPEN Receive non-DWA Throwaway() REOPEN + %% %% REOPEN Receive DWA & Pending = FALSE %% NumDWA < 2 NumDWA++ REOPEN %% @@ -230,311 +280,259 @@ reopen(Wd, Type, N, What) -> %% NumDWA == 2 NumDWA++ %% Failback() OKAY %% - %% Now the watchdog should require three received DWA's before - %% taking the connection back up. The first DWR is sent directly - %% after capabilities exchange so it should take no more than two - %% watchdog expiries. - ?RECV({connection_up, WPid2, _}, 2, WdL, WdH). + %% REOPEN Timer expires & SendWatchdog() + %% !Pending SetWatchdog() + %% Pending = TRUE REOPEN + %% + %% An exchange of 3 watchdogs (the first directly after + %% capabilities exchange) brings the connection back up. -%% =========================================================================== + ?EVENT({watchdog, Ref, _, {reopen, okay}, _}, 2, WdL, WdH), + ?EVENT({up, Ref, _, _, #diameter_packet{}}, 0), -%% Start the fake transport process. From diameter's point of view -%% it's started when diameter calls start/3. We start it before this -%% happens since we use the same fake transport each time diameter -%% calls start/3. The process lives and dies with the test case. -start(Config) -> - Pid = self(), - spawn(fun() -> loop(init(Pid, Config)) end). - -%% Transport start from diameter. This may be called multiple times -%% depending on the testcase. -start({Type, _Ref}, #diameter_service{}, Pid) -> - Ref = make_ref(), - MRef = erlang:monitor(process, Pid), - Pid ! {start, self(), Type, Ref}, - {Ref, TPid} = receive - {Ref, _} = T -> - T; - {'DOWN', MRef, process, _, _} = T -> - T - end, - erlang:demonitor(MRef, [flush]), - {ok, TPid}. + %% Non-response brings it down again. -%% id/1 + ?EVENT({watchdog, Ref, _, {okay, suspect}, _}, 2, WdL, WdH), + ?EVENT({down, Ref, _, _}, 0), + ?EVENT({watchdog, Ref, _, {suspect, down}, _}, 1, WdL, WdH), -id(T) -> - T. + %% Reestablish after another watchdog. -%% =========================================================================== + recv_reopen(Type, Ref, WdL, WdH), -choose(true, X, _) -> X; -choose(false, _, X) -> X. + %% REOPEN Timer expires & NumDWA = -1 + %% Pending & SetWatchdog() + %% NumDWA >= 0 REOPEN + %% + %% REOPEN Timer expires & CloseConnection() + %% Pending & SetWatchdog() + %% NumDWA < 0 DOWN + %% + %% Peer is now ignoring all watchdogs go down again after 2 + %% timeouts. -%% run/1 -%% -%% A more useful badmatch in case of failure. + ?EVENT({watchdog, Ref, _, {reopen, down}, _}, 2, WdL, WdH); -run([F|A]) -> - ok = try - apply(?MODULE, F, A), - ok - catch - E:R -> - {A, E, R, erlang:get_stacktrace()} - end. +%% The misbehaving peer. +recv(_, Type, SvcName, Ref, Wd, N, M) -> + %% First transport process. + ?EVENT({watchdog, Ref, _, {initial, okay}, _}, 1000), + ?EVENT({up, Ref, _, _, #diameter_packet{}}, 0), + reg(Type, Ref, SvcName, {SvcName, {Wd,N,M}}), + ?EVENT({watchdog, Ref, _, {okay, down}, _}, infinity), -%% now_diff/2 + %% Second transport process. + ?EVENT({watchdog, Ref, _, {_, reopen}, _}, infinity), + reg(Type, Ref, SvcName, 3), + ?EVENT({watchdog, Ref, _, {_, down}, _}, infinity), -now_diff(T1, T2) -> - timer:now_diff(T2, T1). + %% Third transport process. + ?EVENT({watchdog, Ref, _, {_, reopen}, _}, infinity), + reg(Type, Ref, SvcName, 0), + ?EVENT({watchdog, Ref, _, {_, down}, _}, infinity), -%% jitter/2 + ok. -jitter(?WD(T), _) -> - T; -jitter(T,D) -> - T+D. +%% recv_reopen/4 -%% watchdog/4 -%% -%% Fake the call from diameter_service. The watchdog process will send -%% messages to the calling "service" process so our tests are that the -%% watchdog responds as expected. +recv_reopen(connect, Ref, WdL, WdH) -> + ?EVENT({watchdog, Ref, _, {_, reopen}, _}, 1, WdL, WdH), + ?EVENT({reconnect, Ref, _}, 0); -watchdog(Type, Ref, TPid, Wd) -> - Opts = [{transport_module, ?MODULE}, - {transport_config, TPid}, - {watchdog_timer, Wd}], - monitor(diameter_watchdog:start({Type, Ref}, - {false, Opts, false, ?SERVICE})). +recv_reopen(listen, Ref, _, _) -> + ?EVENT({watchdog, Ref, _, {_, reopen}, _}, 1, ?PEER_WD). -monitor(Pid) -> - erlang:monitor(process, Pid), - Pid. +%% reg/4 +%% +%% Lookup the pid of the transport process and publish a term for +%% send/2 to lookup. +reg(Type, Ref, SvcName, T) -> + TPid = tpid(Type, Ref, diameter:service_info(SvcName, transport)), + true = diameter_reg:add_new({?MODULE, TPid, T}). + +%% tpid/3 + +tpid(connect, Ref, [[{ref, Ref}, + {type, connect}, + {options, _}, + {watchdog, _}, + {peer, _}, + {apps, _}, + {caps, _}, + {port, [{owner, TPid} | _]} + | _]]) -> + TPid; + +tpid(listen, Ref, [[{ref, Ref}, + {type, listen}, + {options, _}, + {accept, As} + | _]]) -> + [[{watchdog, _}, + {peer, _}, + {apps, _}, + {caps, _}, + {port, [{owner, TPid} | _]} + | _]] + = lists:filter(fun([{watchdog, {_,_,S}} | _]) -> + S == okay orelse S == reopen + end, + As), + TPid. %% =========================================================================== -%% Transport process implmentation. Fakes reception of messages by -%% sending fakes to the parent (peer fsm) process that called start/3. - --record(transport, - {type, %% connect | accept | manager - parent, %% pid() of peer_fsm/ervice process - open = false, %% done with capabilities exchange? - config}).%% testcase-specific config - -%% init/2 - -%% Testcase starting the manager. -init(SvcPid, {_,_,_,_} = Config) -> - putr(peer, [{'Origin-Host', hostname() ++ ".utan.com"}, - {'Origin-Realm', "utan.com"}]), - #transport{type = manager, - parent = monitor(SvcPid), - config = Config}; - -%% Manager starting a transport. -init(_, {Type, ParentPid, SvcPid, TwinPid, Peer, {N,_,_,_} = Config}) -> - putr(peer, Peer), - putr(service, SvcPid), - putr(count, init(Type, ParentPid, TwinPid, N)),%% number of DWR's to answer - #transport{type = Type, - parent = monitor(ParentPid), - config = Config}. - -init(Type, ParentPid, undefined, N) -> - connected(ParentPid, Type), - N; -init(_, _, TPid, _) -> - monitor(TPid), - 3. - -%% Generate a unique hostname for the faked peer. -hostname() -> - lists:flatten(io_lib:format("~p-~p-~p", tuple_to_list(now()))). - -%% loop/1 - -loop(S) -> - loop(msg(receive T -> T end, S)). - -msg(T,S) -> - case transition(T,S) of - ok -> - S; - #transport{} = NS -> - NS; - {stop, Reason} -> - x(Reason) - end. - -x(Reason) -> - exit(Reason). - -%% transition/2 - -%% Manager is being asked for a new transport process. -transition({start, Pid, Type, Ref}, #transport{type = manager, - parent = SvcPid, - config = Config}) -> - TPid = start({Type, Pid, SvcPid, getr(transport), getr(peer), Config}), - Pid ! {Ref, TPid}, - putr(transport, TPid), +listen(PortNr, Opts) -> + gen_tcp:listen(PortNr, Opts). + +accept(LSock) -> + gen_tcp:accept(LSock). + +connect(Addr, Port, Opts) -> + gen_tcp:connect(Addr, Port, Opts). + +setopts(Sock, Opts) -> + inet:setopts(Sock, Opts). + +send(Sock, Bin) -> + send(getr(config), Sock, Bin). + +%% send/3 + +%% First outgoing message from a new transport process is CER/CEA. +%% Remaining outgoing messages are either DWR or DWA. +send(undefined, Sock, Bin) -> + putr(config, init), + gen_tcp:send(Sock, Bin); + +%% Outgoing DWR: fake reception of DWA. Use the fact that AVP values +%% are ignored. This is to ensure that the peer's watchdog state +%% transitions are only induced by responses to messages it sends. +send(_, Sock, <<_:32, 1:1, _:7, 280:24, _:32, EId:32, HId:32, _/binary>>) -> + Pkt = #diameter_packet{header = #diameter_header{version = 1, + end_to_end_id = EId, + hop_by_hop_id = HId}, + msg = ['DWA', {'Result-Code', 2001}, + {'Origin-Host', "XXX"}, + {'Origin-Realm', ?REALM}]}, + #diameter_packet{bin = Bin} = diameter_codec:encode(?BASE, Pkt), + self() ! {tcp, Sock, Bin}, ok; -%% Peer fsm or testcase process has died. -transition({'DOWN', _, process, Pid, _} = T, #transport{parent = Pid}) -> - {stop, T}; - -%% Twin transport process has gone down. In the connect case, the -%% transport isn't started until this happens in the first place so -%% connect immediately. In the accept case, fake the peer reconnecting -%% only after another watchdog expiry. -transition({'DOWN', _, process, _, _}, #transport{type = Type, - config = {_, Wd, _, _}}) -> - Tmo = case Type of - connect -> - 0; - accept -> - ?ONE_WD(Wd) - end, - erlang:send_after(Tmo, self(), reconnect), +%% First outgoing DWA. +send(init, Sock, Bin) -> + [{{?MODULE, _, T}, _}] = diameter_reg:wait({?MODULE, self(), '_'}), + putr(config, T), + send(Sock, Bin); + +%% First transport process. +send({SvcName, {_,_,_} = T}, Sock, Bin) -> + [{'Origin-Host', _} = OH, {'Origin-Realm', _} = OR | _] + = ?SERVICE(SvcName), + putr(origin, [OH, OR]), + putr(config, T), + send(Sock, Bin); + +%% Discard DWA, failback after another timeout in the peer. +send({Wd, 0 = No, Msg}, Sock, Bin) -> + Origin = getr(origin), + spawn(fun() -> failback(?ONE_WD(Wd), Msg, Sock, Bin, Origin) end), + putr(config, No), ok; -transition(reconnect, #transport{type = Type, - parent = Pid, - config = {_,_,_,Ref}}) -> - getr(service) ! {reopen, Ref}, - connected(Pid, Type), - ok; +%% Send DWA while we're in the mood (aka 0 < N). +send({Wd, N, Msg}, Sock, Bin) -> + putr(config, {Wd, N-1, Msg}), + gen_tcp:send(Sock, Bin); -%% Peer fsm process is sending CER: fake the peer's CEA. -transition(?TMSG({send, Bin}), #transport{type = connect, - open = false, - parent = Pid} - = S) -> - {Code, Flags, _} = ?BASE:msg_header('CER'), - <<_:32, Flags:8, Code:24, _:96, _/binary>> = Bin, - Hdr = make_header(Bin), - recv(Pid, {Hdr, make_cea()}), - S#transport{open = true}; - -%% Peer fsm process is sending CEA. -transition(?TMSG({send, Bin}), #transport{type = accept, - open = false} - = S) -> - {Code, Flags, _} = ?BASE:msg_header('CEA'), - <<_:32, Flags:8, Code:24, _:96, _/binary>> = Bin, - S#transport{open = true}; - -%% Watchdog is sending DWR or DWA. -transition(?TMSG({send, Bin}), #transport{open = true} = S) -> - {Code, _, _} = ?BASE:msg_header('DWR'), - {Code, _, _} = ?BASE:msg_header('DWA'), - <<_:32, R:1, 0:7, Code:24, _:96, _/binary>> = Bin, - Hdr = make_header(Bin), - dwa(1 == R, S, Hdr), +%% Discard DWA. +send(0, _Sock, _Bin) -> ok; -%% We're telling ourselves to fake a received message. -transition({recv, Msg}, #transport{parent = Pid}) -> - recv(Pid, Msg), - ok; +%% Send DWA. +send(N, Sock, <<_:32, 0:1, _:7, 280:24, _/binary>> = Bin) -> + putr(config, N-1), + gen_tcp:send(Sock, Bin). -%% We're telling ourselves to receive a message to induce failback. -transition(failback = T, #transport{parent = Pid}) -> - recv(Pid, eraser(T)), - ok. +failback(Tmo, Msg, Sock, Bin, Origin) -> + timer:sleep(Tmo), + ok = gen_tcp:send(Sock, msg(Msg, Bin, Origin)). -make_header(Bin) -> - #diameter_header{end_to_end_id = E, - hop_by_hop_id = H} - = diameter_codec:decode_header(Bin), - #diameter_header{end_to_end_id = E, - hop_by_hop_id = H}. - -recv(Pid, Msg) -> - Pid ! ?TMSG({recv, encode(Msg)}). - -%% Replace the end-to-end/hop-by-hop identifiers with those from an -%% incoming request to which we're constructing a reply. -encode({Hdr, [_|_] = Msg}) -> - #diameter_header{hop_by_hop_id = HBH, - end_to_end_id = E2E} - = Hdr, - #diameter_packet{bin = Bin} = diameter_codec:encode(?BASE, Msg), - <<H:12/binary, _:64, T/binary>> = Bin, - <<H/binary, HBH:32, E2E:32, T/binary>>; - -encode([_|_] = Msg) -> - #diameter_packet{bin = Bin} = diameter_codec:encode(?BASE, Msg), +%% msg/2 + +msg('DWA', Bin, _Origin) -> + Bin; +msg(Msg, _Bin, Origin) -> + #diameter_packet{bin = Bin} + = diameter_codec:encode(?BASE, msg(Msg, Origin)), Bin. -connected(Pid, connect) -> - Pid ! ?TMSG({self(), connected, make_ref()}); -connected(Pid, accept) -> - Pid ! ?TMSG({self(), connected}), - recv(Pid, make_cer()). +msg('DWR' = M, T) -> + [M | T]; -make_cer() -> - ['CER' | getr(peer)] ++ [{'Host-IP-Address', [?REMOTEHOST]}, - {'Vendor-Id', 1028}, - {'Product-Name', "Utan"}, - {'Auth-Application-Id', [?APPL_ID]}]. +msg('RAA', T) -> + ['RAA', {'Session-Id', diameter:session_id("abc")}, + {'Result-Code', 2001} + | T]. +%% An unexpected answer is discarded after passing through the +%% watchdog state machine. -make_cea() -> - ['CER' | Rest] = make_cer(), - ['CEA', {'Result-Code', ?SUCCESS} | Rest]. +%% =========================================================================== -make_dwr() -> - ['DWR' | getr(peer)]. +peer_up(_SvcName, _Peer, S) -> + S. -make_dwa() -> - ['DWR' | Rest] = make_dwr(), - ['DWA', {'Result-Code', ?SUCCESS} | Rest]. +peer_down(_SvcName, _Peer, S) -> + S. -dwa(false, _, _) -> %% outgoing was DWA ... - ok; -dwa(true, S, Hdr) -> %% ... or DWR - dwa(getr(count), Hdr, S); - -%% React to the DWR only after another watchdog expiry. We shouldn't -%% get another DWR while the answer is pending. -dwa(0, Hdr, #transport{config = {_, Wd, What, _}}) -> - erlang:send_after(?ONE_WD(Wd), self(), failback), - putr(failback, make_msg(What, Hdr)), - eraser(count); - -dwa(undefined, _, _) -> - undefined = getr(failback), %% ensure this is after failback - ok; +%% =========================================================================== -%% Reply with DWA. -dwa(N, Hdr, #transport{parent = Pid}) -> - putr(count, N-1), - recv(Pid, {Hdr, make_dwa()}). +choose(true, X, _) -> X; +choose(false, _, X) -> X. -%% Answer to received DWR. -make_msg('DWA', Hdr) -> - {Hdr, make_dwa()}; +%% id/1 +%% +%% Jitter callback. -%% DWR from peer. -make_msg('DWR', _) -> - make_dwr(); +id(T) -> + T. -%% An unexpected answer is discarded after passing through the -%% watchdog state machine. -make_msg(other, _) -> - ['RAA', {'Session-Id', diameter:session_id("abc")}, - {'Result-Code', 2001} - | getr(peer)]. +%% run/1 +%% +%% A more useful badmatch in case of failure. + +run(Fs) -> + ?util:run([{?MODULE, [run1, F]} || F <- Fs]). + +run1([F|A]) -> + ok = try + apply(?MODULE, F, A), + ok + catch + E:R -> + S = erlang:get_stacktrace(), + io:format("~p~n", [{A, E, R, S}]), + S + end. + +%% now_diff/2 + +now_diff(T1, T2) -> + timer:now_diff(T2, T1). + +%% jitter/2 + +jitter(?WD(T), _) -> + T; +jitter(T,D) -> + T+D. + +%% Generate a unique hostname for the faked peer. +hostname() -> + lists:flatten(io_lib:format("~p-~p-~p", tuple_to_list(now()))). putr(Key, Val) -> put({?MODULE, Key}, Val). getr(Key) -> get({?MODULE, Key}). - -eraser(Key) -> - erase({?MODULE, Key}). diff --git a/lib/diameter/test/modules.mk b/lib/diameter/test/modules.mk index c6f709dc36..5898e125ae 100644 --- a/lib/diameter/test/modules.mk +++ b/lib/diameter/test/modules.mk @@ -2,7 +2,7 @@ # %CopyrightBegin% # -# Copyright Ericsson AB 2010-2011. All Rights Reserved. +# Copyright Ericsson AB 2010-2012. 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,6 +24,7 @@ MODULES = \ diameter_ct \ diameter_util \ diameter_enum \ + diameter_compiler_SUITE \ diameter_codec_SUITE \ diameter_codec_test \ diameter_app_SUITE \ @@ -32,9 +33,20 @@ MODULES = \ diameter_sync_SUITE \ diameter_stats_SUITE \ diameter_watchdog_SUITE \ + diameter_gen_sctp_SUITE \ diameter_transport_SUITE \ + diameter_capx_SUITE \ diameter_traffic_SUITE \ - diameter_relay_SUITE + diameter_relay_SUITE \ + diameter_tls_SUITE \ + diameter_failover_SUITE \ + diameter_dpr_SUITE -INTERNAL_HRL_FILES = \ +HRL_FILES = \ diameter_ct.hrl + +DATA = \ + diameter_codec_SUITE_data/avps.dia \ + diameter_codec_SUITE_data/send.dia \ + diameter_codec_SUITE_data/recv.dia \ + diameter_codec_SUITE_data/diameter_test_unknown.erl diff --git a/lib/diameter/src/compiler/modules.mk b/lib/diameter/test/release.sed index 17a311dacf..2720b778f2 100644 --- a/lib/diameter/src/compiler/modules.mk +++ b/lib/diameter/test/release.sed @@ -1,27 +1,35 @@ -#-*-makefile-*- ; force emacs to enter makefile-mode - +# # %CopyrightBegin% -# +# # Copyright Ericsson AB 2010-2011. 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% +# -MODULES = \ - diameter_codegen \ - diameter_spec_scan \ - diameter_spec_util +# +# This bit of gymnastics is to replace the include of diameter's +# public hrls by include_lib when releasing testsuites, so that they +# compile both in the development filesystem (where generated hrls +# aren't in diameter/include) and with common_test's autocompilation +# on an installed release. Solving the problem by installing generated +# hrls to ../include is anathema: that directory is for handwritten +# source.) +# -HRL_FILES = \ - diameter_forms.hrl +/^-include("/!b +/"diameter_gen_/b s +/"diameter\./!b +:s +s@("@_lib&diameter/include/@ diff --git a/lib/diameter/vsn.mk b/lib/diameter/vsn.mk index c783450c9f..7b2208137b 100644 --- a/lib/diameter/vsn.mk +++ b/lib/diameter/vsn.mk @@ -2,7 +2,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 @@ -18,7 +18,7 @@ # %CopyrightEnd% APPLICATION = diameter -DIAMETER_VSN = 0.10 +DIAMETER_VSN = 1.3.1 PRE_VSN = APP_VSN = "$(APPLICATION)-$(DIAMETER_VSN)$(PRE_VSN)" |